peerconnection.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "peerconnection.hpp"
  19. #include "certificate.hpp"
  20. #include "dtlstransport.hpp"
  21. #include "icetransport.hpp"
  22. #include "include.hpp"
  23. #include "sctptransport.hpp"
  24. #include <iostream>
  25. #ifdef _WIN32
  26. #include <winsock2.h>
  27. #endif
  28. namespace rtc {
  29. using namespace std::placeholders;
  30. using std::shared_ptr;
  31. using std::weak_ptr;
  32. PeerConnection::PeerConnection() : PeerConnection(Configuration()) {
  33. #ifdef _WIN32
  34. WSADATA wsaData;
  35. if (WSAStartup(MAKEWORD(2, 2), &wsaData))
  36. throw std::runtime_error("WSAStartup failed, error=" + std::to_string(WSAGetLastError()));
  37. #endif
  38. }
  39. PeerConnection::PeerConnection(const Configuration &config)
  40. : mConfig(config), mCertificate(make_certificate("libdatachannel")), mState(State::New) {}
  41. PeerConnection::~PeerConnection() {
  42. changeState(State::Destroying);
  43. close();
  44. mSctpTransport.reset();
  45. mDtlsTransport.reset();
  46. mIceTransport.reset();
  47. #ifdef _WIN32
  48. WSACleanup();
  49. #endif
  50. }
  51. void PeerConnection::close() {
  52. // Close DataChannels
  53. closeDataChannels();
  54. // Close Transports
  55. for (int i = 0; i < 2; ++i) { // Make sure a transport wasn't spawn behind our back
  56. if (auto transport = std::atomic_load(&mSctpTransport))
  57. transport->stop();
  58. if (auto transport = std::atomic_load(&mDtlsTransport))
  59. transport->stop();
  60. if (auto transport = std::atomic_load(&mIceTransport))
  61. transport->stop();
  62. }
  63. changeState(State::Closed);
  64. }
  65. const Configuration *PeerConnection::config() const { return &mConfig; }
  66. PeerConnection::State PeerConnection::state() const { return mState; }
  67. PeerConnection::GatheringState PeerConnection::gatheringState() const { return mGatheringState; }
  68. std::optional<Description> PeerConnection::localDescription() const {
  69. std::lock_guard lock(mLocalDescriptionMutex);
  70. return mLocalDescription;
  71. }
  72. std::optional<Description> PeerConnection::remoteDescription() const {
  73. std::lock_guard lock(mRemoteDescriptionMutex);
  74. return mRemoteDescription;
  75. }
  76. void PeerConnection::setRemoteDescription(Description description) {
  77. description.hintType(localDescription() ? Description::Type::Answer : Description::Type::Offer);
  78. auto remoteCandidates = description.extractCandidates();
  79. std::lock_guard lock(mRemoteDescriptionMutex);
  80. mRemoteDescription.emplace(std::move(description));
  81. auto iceTransport = std::atomic_load(&mIceTransport);
  82. if (!iceTransport)
  83. iceTransport = initIceTransport(Description::Role::ActPass);
  84. iceTransport->setRemoteDescription(*mRemoteDescription);
  85. if (mRemoteDescription->type() == Description::Type::Offer) {
  86. // This is an offer and we are the answerer.
  87. processLocalDescription(iceTransport->getLocalDescription(Description::Type::Answer));
  88. iceTransport->gatherLocalCandidates();
  89. } else {
  90. // This is an answer and we are the offerer.
  91. auto sctpTransport = std::atomic_load(&mSctpTransport);
  92. if (!sctpTransport && iceTransport->role() == Description::Role::Active) {
  93. // Since we assumed passive role during DataChannel creation, we need to shift the
  94. // stream numbers by one to shift them from odd to even.
  95. std::unique_lock lock(mDataChannelsMutex);
  96. decltype(mDataChannels) newDataChannels;
  97. auto it = mDataChannels.begin();
  98. while (it != mDataChannels.end()) {
  99. auto channel = it->second.lock();
  100. if (channel->stream() % 2 == 1)
  101. channel->mStream -= 1;
  102. newDataChannels.emplace(channel->stream(), channel);
  103. ++it;
  104. }
  105. std::swap(mDataChannels, newDataChannels);
  106. }
  107. }
  108. for (const auto &candidate : remoteCandidates)
  109. addRemoteCandidate(candidate);
  110. }
  111. void PeerConnection::addRemoteCandidate(Candidate candidate) {
  112. std::lock_guard lock(mRemoteDescriptionMutex);
  113. auto iceTransport = std::atomic_load(&mIceTransport);
  114. if (!mRemoteDescription || !iceTransport)
  115. throw std::logic_error("Remote candidate set without remote description");
  116. mRemoteDescription->addCandidate(candidate);
  117. if (candidate.resolve(Candidate::ResolveMode::Simple)) {
  118. iceTransport->addRemoteCandidate(candidate);
  119. } else {
  120. // OK, we might need a lookup, do it asynchronously
  121. weak_ptr<IceTransport> weakIceTransport{iceTransport};
  122. std::thread t([weakIceTransport, candidate]() mutable {
  123. if (candidate.resolve(Candidate::ResolveMode::Lookup))
  124. if (auto iceTransport = weakIceTransport.lock())
  125. iceTransport->addRemoteCandidate(candidate);
  126. });
  127. t.detach();
  128. }
  129. }
  130. std::optional<string> PeerConnection::localAddress() const {
  131. auto iceTransport = std::atomic_load(&mIceTransport);
  132. return iceTransport ? iceTransport->getLocalAddress() : nullopt;
  133. }
  134. std::optional<string> PeerConnection::remoteAddress() const {
  135. auto iceTransport = std::atomic_load(&mIceTransport);
  136. return iceTransport ? iceTransport->getRemoteAddress() : nullopt;
  137. }
  138. shared_ptr<DataChannel> PeerConnection::createDataChannel(const string &label,
  139. const string &protocol,
  140. const Reliability &reliability) {
  141. // RFC 5763: The answerer MUST use either a setup attribute value of setup:active or
  142. // setup:passive. [...] Thus, setup:active is RECOMMENDED.
  143. // See https://tools.ietf.org/html/rfc5763#section-5
  144. // Therefore, we assume passive role when we are the offerer.
  145. auto iceTransport = std::atomic_load(&mIceTransport);
  146. auto role = iceTransport ? iceTransport->role() : Description::Role::Passive;
  147. auto channel = emplaceDataChannel(role, label, protocol, reliability);
  148. if (!iceTransport) {
  149. // RFC 5763: The endpoint that is the offerer MUST use the setup attribute value of
  150. // setup:actpass.
  151. // See https://tools.ietf.org/html/rfc5763#section-5
  152. iceTransport = initIceTransport(Description::Role::ActPass);
  153. processLocalDescription(iceTransport->getLocalDescription(Description::Type::Offer));
  154. iceTransport->gatherLocalCandidates();
  155. } else {
  156. if (auto transport = std::atomic_load(&mSctpTransport))
  157. if (transport->state() == SctpTransport::State::Connected)
  158. channel->open(transport);
  159. }
  160. return channel;
  161. }
  162. void PeerConnection::onDataChannel(
  163. std::function<void(shared_ptr<DataChannel> dataChannel)> callback) {
  164. mDataChannelCallback = callback;
  165. }
  166. void PeerConnection::onLocalDescription(
  167. std::function<void(const Description &description)> callback) {
  168. mLocalDescriptionCallback = callback;
  169. }
  170. void PeerConnection::onLocalCandidate(std::function<void(const Candidate &candidate)> callback) {
  171. mLocalCandidateCallback = callback;
  172. }
  173. void PeerConnection::onStateChange(std::function<void(State state)> callback) {
  174. mStateChangeCallback = callback;
  175. }
  176. void PeerConnection::onGatheringStateChange(std::function<void(GatheringState state)> callback) {
  177. mGatheringStateChangeCallback = callback;
  178. }
  179. shared_ptr<IceTransport> PeerConnection::initIceTransport(Description::Role role) {
  180. try {
  181. std::lock_guard lock(mInitMutex);
  182. if (auto transport = std::atomic_load(&mIceTransport))
  183. return transport;
  184. auto transport = std::make_shared<IceTransport>(
  185. mConfig, role, std::bind(&PeerConnection::processLocalCandidate, this, _1),
  186. [this](IceTransport::State state) {
  187. switch (state) {
  188. case IceTransport::State::Connecting:
  189. changeState(State::Connecting);
  190. break;
  191. case IceTransport::State::Failed:
  192. changeState(State::Failed);
  193. break;
  194. case IceTransport::State::Connected:
  195. initDtlsTransport();
  196. break;
  197. case IceTransport::State::Disconnected:
  198. changeState(State::Disconnected);
  199. break;
  200. default:
  201. // Ignore
  202. break;
  203. }
  204. },
  205. [this](IceTransport::GatheringState state) {
  206. switch (state) {
  207. case IceTransport::GatheringState::InProgress:
  208. changeGatheringState(GatheringState::InProgress);
  209. break;
  210. case IceTransport::GatheringState::Complete:
  211. endLocalCandidates();
  212. changeGatheringState(GatheringState::Complete);
  213. break;
  214. default:
  215. // Ignore
  216. break;
  217. }
  218. });
  219. std::atomic_store(&mIceTransport, transport);
  220. return transport;
  221. } catch (const std::exception &e) {
  222. PLOG_ERROR << e.what();
  223. changeState(State::Failed);
  224. throw std::runtime_error("ICE transport initialization failed");
  225. }
  226. }
  227. shared_ptr<DtlsTransport> PeerConnection::initDtlsTransport() {
  228. try {
  229. std::lock_guard lock(mInitMutex);
  230. if (auto transport = std::atomic_load(&mDtlsTransport))
  231. return transport;
  232. auto lower = std::atomic_load(&mIceTransport);
  233. auto transport = std::make_shared<DtlsTransport>(
  234. lower, mCertificate, std::bind(&PeerConnection::checkFingerprint, this, _1),
  235. [this](DtlsTransport::State state) {
  236. switch (state) {
  237. case DtlsTransport::State::Connected:
  238. initSctpTransport();
  239. break;
  240. case DtlsTransport::State::Failed:
  241. changeState(State::Failed);
  242. break;
  243. case DtlsTransport::State::Disconnected:
  244. changeState(State::Disconnected);
  245. break;
  246. default:
  247. // Ignore
  248. break;
  249. }
  250. });
  251. std::atomic_store(&mDtlsTransport, transport);
  252. return transport;
  253. } catch (const std::exception &e) {
  254. PLOG_ERROR << e.what();
  255. changeState(State::Failed);
  256. throw std::runtime_error("DTLS transport initialization failed");
  257. }
  258. }
  259. shared_ptr<SctpTransport> PeerConnection::initSctpTransport() {
  260. try {
  261. std::lock_guard lock(mInitMutex);
  262. if (auto transport = std::atomic_load(&mSctpTransport))
  263. return transport;
  264. uint16_t sctpPort = remoteDescription()->sctpPort().value_or(DEFAULT_SCTP_PORT);
  265. auto lower = std::atomic_load(&mDtlsTransport);
  266. auto transport = std::make_shared<SctpTransport>(
  267. lower, sctpPort, std::bind(&PeerConnection::forwardMessage, this, _1),
  268. std::bind(&PeerConnection::forwardBufferedAmount, this, _1, _2),
  269. [this](SctpTransport::State state) {
  270. switch (state) {
  271. case SctpTransport::State::Connected:
  272. changeState(State::Connected);
  273. openDataChannels();
  274. break;
  275. case SctpTransport::State::Failed:
  276. remoteCloseDataChannels();
  277. changeState(State::Failed);
  278. break;
  279. case SctpTransport::State::Disconnected:
  280. remoteCloseDataChannels();
  281. changeState(State::Disconnected);
  282. break;
  283. default:
  284. // Ignore
  285. break;
  286. }
  287. });
  288. std::atomic_store(&mSctpTransport, transport);
  289. return transport;
  290. } catch (const std::exception &e) {
  291. PLOG_ERROR << e.what();
  292. changeState(State::Failed);
  293. throw std::runtime_error("SCTP transport initialization failed");
  294. }
  295. }
  296. void PeerConnection::endLocalCandidates() {
  297. std::lock_guard lock(mLocalDescriptionMutex);
  298. if (mLocalDescription)
  299. mLocalDescription->endCandidates();
  300. }
  301. bool PeerConnection::checkFingerprint(const std::string &fingerprint) const {
  302. std::lock_guard lock(mRemoteDescriptionMutex);
  303. if (auto expectedFingerprint =
  304. mRemoteDescription ? mRemoteDescription->fingerprint() : nullopt) {
  305. return *expectedFingerprint == fingerprint;
  306. }
  307. return false;
  308. }
  309. void PeerConnection::forwardMessage(message_ptr message) {
  310. if (!message) {
  311. remoteCloseDataChannels();
  312. return;
  313. }
  314. auto channel = findDataChannel(message->stream);
  315. auto iceTransport = std::atomic_load(&mIceTransport);
  316. auto sctpTransport = std::atomic_load(&mSctpTransport);
  317. if (!iceTransport || !sctpTransport)
  318. return;
  319. if (!channel) {
  320. const byte dataChannelOpenMessage{0x03};
  321. unsigned int remoteParity = (iceTransport->role() == Description::Role::Active) ? 1 : 0;
  322. if (message->type == Message::Control && *message->data() == dataChannelOpenMessage &&
  323. message->stream % 2 == remoteParity) {
  324. channel =
  325. std::make_shared<DataChannel>(shared_from_this(), sctpTransport, message->stream);
  326. channel->onOpen(std::bind(&PeerConnection::triggerDataChannel, this,
  327. weak_ptr<DataChannel>{channel}));
  328. mDataChannels.insert(std::make_pair(message->stream, channel));
  329. } else {
  330. // Invalid, close the DataChannel by resetting the stream
  331. sctpTransport->reset(message->stream);
  332. return;
  333. }
  334. }
  335. channel->incoming(message);
  336. }
  337. void PeerConnection::forwardBufferedAmount(uint16_t stream, size_t amount) {
  338. if (auto channel = findDataChannel(stream))
  339. channel->triggerBufferedAmount(amount);
  340. }
  341. shared_ptr<DataChannel> PeerConnection::emplaceDataChannel(Description::Role role,
  342. const string &label,
  343. const string &protocol,
  344. const Reliability &reliability) {
  345. // The active side must use streams with even identifiers, whereas the passive side must use
  346. // streams with odd identifiers.
  347. // See https://tools.ietf.org/html/draft-ietf-rtcweb-data-protocol-09#section-6
  348. std::unique_lock lock(mDataChannelsMutex);
  349. unsigned int stream = (role == Description::Role::Active) ? 0 : 1;
  350. while (mDataChannels.find(stream) != mDataChannels.end()) {
  351. stream += 2;
  352. if (stream >= 65535)
  353. throw std::runtime_error("Too many DataChannels");
  354. }
  355. auto channel =
  356. std::make_shared<DataChannel>(shared_from_this(), stream, label, protocol, reliability);
  357. mDataChannels.emplace(std::make_pair(stream, channel));
  358. return channel;
  359. }
  360. shared_ptr<DataChannel> PeerConnection::findDataChannel(uint16_t stream) {
  361. std::shared_lock lock(mDataChannelsMutex);
  362. shared_ptr<DataChannel> channel;
  363. if (auto it = mDataChannels.find(stream); it != mDataChannels.end()) {
  364. channel = it->second.lock();
  365. if (!channel || channel->isClosed()) {
  366. mDataChannels.erase(it);
  367. channel.reset();
  368. }
  369. }
  370. return channel;
  371. }
  372. void PeerConnection::iterateDataChannels(
  373. std::function<void(shared_ptr<DataChannel> channel)> func) {
  374. std::shared_lock lock(mDataChannelsMutex);
  375. auto it = mDataChannels.begin();
  376. while (it != mDataChannels.end()) {
  377. auto channel = it->second.lock();
  378. if (!channel || channel->isClosed()) {
  379. it = mDataChannels.erase(it);
  380. continue;
  381. }
  382. func(channel);
  383. ++it;
  384. }
  385. }
  386. void PeerConnection::openDataChannels() {
  387. if (auto transport = std::atomic_load(&mSctpTransport))
  388. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->open(transport); });
  389. }
  390. void PeerConnection::closeDataChannels() {
  391. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->close(); });
  392. }
  393. void PeerConnection::remoteCloseDataChannels() {
  394. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->remoteClose(); });
  395. }
  396. void PeerConnection::processLocalDescription(Description description) {
  397. std::optional<uint16_t> remoteSctpPort;
  398. if (auto remote = remoteDescription())
  399. remoteSctpPort = remote->sctpPort();
  400. std::lock_guard lock(mLocalDescriptionMutex);
  401. mLocalDescription.emplace(std::move(description));
  402. mLocalDescription->setFingerprint(mCertificate->fingerprint());
  403. mLocalDescription->setSctpPort(remoteSctpPort.value_or(DEFAULT_SCTP_PORT));
  404. mLocalDescription->setMaxMessageSize(LOCAL_MAX_MESSAGE_SIZE);
  405. mLocalDescriptionCallback(*mLocalDescription);
  406. }
  407. void PeerConnection::processLocalCandidate(Candidate candidate) {
  408. std::lock_guard lock(mLocalDescriptionMutex);
  409. if (!mLocalDescription)
  410. throw std::logic_error("Got a local candidate without local description");
  411. mLocalDescription->addCandidate(candidate);
  412. mLocalCandidateCallback(candidate);
  413. }
  414. void PeerConnection::triggerDataChannel(weak_ptr<DataChannel> weakDataChannel) {
  415. auto dataChannel = weakDataChannel.lock();
  416. if (!dataChannel)
  417. return;
  418. mDataChannelCallback(dataChannel);
  419. }
  420. void PeerConnection::changeState(State state) {
  421. State current;
  422. do {
  423. current = mState.load();
  424. if (current == state || current == State::Destroying)
  425. return;
  426. } while (!mState.compare_exchange_weak(current, state));
  427. if (state != State::Destroying)
  428. mStateChangeCallback(state);
  429. }
  430. void PeerConnection::changeGatheringState(GatheringState state) {
  431. if (mGatheringState.exchange(state) != state)
  432. mGatheringStateChangeCallback(state);
  433. }
  434. } // namespace rtc
  435. std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::State &state) {
  436. using State = rtc::PeerConnection::State;
  437. std::string str;
  438. switch (state) {
  439. case State::New:
  440. str = "new";
  441. break;
  442. case State::Connecting:
  443. str = "connecting";
  444. break;
  445. case State::Connected:
  446. str = "connected";
  447. break;
  448. case State::Disconnected:
  449. str = "disconnected";
  450. break;
  451. case State::Failed:
  452. str = "failed";
  453. break;
  454. case State::Closed:
  455. str = "closed";
  456. break;
  457. case State::Destroying:
  458. str = "destroying";
  459. break;
  460. default:
  461. str = "unknown";
  462. break;
  463. }
  464. return out << str;
  465. }
  466. std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::GatheringState &state) {
  467. using GatheringState = rtc::PeerConnection::GatheringState;
  468. std::string str;
  469. switch (state) {
  470. case GatheringState::New:
  471. str = "new";
  472. break;
  473. case GatheringState::InProgress:
  474. str = "in_progress";
  475. break;
  476. case GatheringState::Complete:
  477. str = "complete";
  478. break;
  479. default:
  480. str = "unknown";
  481. break;
  482. }
  483. return out << str;
  484. }