peerconnection.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. #include <thread>
  26. namespace rtc {
  27. using namespace std::placeholders;
  28. using std::shared_ptr;
  29. using std::weak_ptr;
  30. template <typename F, typename T, typename... Args> auto weak_bind(F &&f, T *t, Args &&... _args) {
  31. return [bound = std::bind(f, t, _args...), weak_this = t->weak_from_this()](auto &&... args) {
  32. if (auto shared_this = weak_this.lock())
  33. bound(args...);
  34. };
  35. }
  36. template <typename F, typename T, typename... Args>
  37. auto weak_bind_verifier(F &&f, T *t, Args &&... _args) {
  38. return [bound = std::bind(f, t, _args...), weak_this = t->weak_from_this()](auto &&... args) {
  39. if (auto shared_this = weak_this.lock())
  40. return bound(args...);
  41. else
  42. return false;
  43. };
  44. }
  45. PeerConnection::PeerConnection() : PeerConnection(Configuration()) {}
  46. PeerConnection::PeerConnection(const Configuration &config)
  47. : mConfig(config), mCertificate(make_certificate("libdatachannel")), mState(State::New) {}
  48. PeerConnection::~PeerConnection() { close(); }
  49. void PeerConnection::close() {
  50. closeDataChannels();
  51. closeTransports();
  52. }
  53. const Configuration *PeerConnection::config() const { return &mConfig; }
  54. PeerConnection::State PeerConnection::state() const { return mState; }
  55. PeerConnection::GatheringState PeerConnection::gatheringState() const { return mGatheringState; }
  56. std::optional<Description> PeerConnection::localDescription() const {
  57. std::lock_guard lock(mLocalDescriptionMutex);
  58. return mLocalDescription;
  59. }
  60. std::optional<Description> PeerConnection::remoteDescription() const {
  61. std::lock_guard lock(mRemoteDescriptionMutex);
  62. return mRemoteDescription;
  63. }
  64. void PeerConnection::setRemoteDescription(Description description) {
  65. description.hintType(localDescription() ? Description::Type::Answer : Description::Type::Offer);
  66. auto remoteCandidates = description.extractCandidates();
  67. std::lock_guard lock(mRemoteDescriptionMutex);
  68. mRemoteDescription.emplace(std::move(description));
  69. auto iceTransport = std::atomic_load(&mIceTransport);
  70. if (!iceTransport)
  71. iceTransport = initIceTransport(Description::Role::ActPass);
  72. iceTransport->setRemoteDescription(*mRemoteDescription);
  73. if (mRemoteDescription->type() == Description::Type::Offer) {
  74. // This is an offer and we are the answerer.
  75. processLocalDescription(iceTransport->getLocalDescription(Description::Type::Answer));
  76. iceTransport->gatherLocalCandidates();
  77. } else {
  78. // This is an answer and we are the offerer.
  79. auto sctpTransport = std::atomic_load(&mSctpTransport);
  80. if (!sctpTransport && iceTransport->role() == Description::Role::Active) {
  81. // Since we assumed passive role during DataChannel creation, we need to shift the
  82. // stream numbers by one to shift them from odd to even.
  83. std::unique_lock lock(mDataChannelsMutex); // we are going to swap the container
  84. decltype(mDataChannels) newDataChannels;
  85. auto it = mDataChannels.begin();
  86. while (it != mDataChannels.end()) {
  87. auto channel = it->second.lock();
  88. if (channel->stream() % 2 == 1)
  89. channel->mStream -= 1;
  90. newDataChannels.emplace(channel->stream(), channel);
  91. ++it;
  92. }
  93. std::swap(mDataChannels, newDataChannels);
  94. }
  95. }
  96. for (const auto &candidate : remoteCandidates)
  97. addRemoteCandidate(candidate);
  98. }
  99. void PeerConnection::addRemoteCandidate(Candidate candidate) {
  100. std::lock_guard lock(mRemoteDescriptionMutex);
  101. auto iceTransport = std::atomic_load(&mIceTransport);
  102. if (!mRemoteDescription || !iceTransport)
  103. throw std::logic_error("Remote candidate set without remote description");
  104. mRemoteDescription->addCandidate(candidate);
  105. if (candidate.resolve(Candidate::ResolveMode::Simple)) {
  106. iceTransport->addRemoteCandidate(candidate);
  107. } else {
  108. // OK, we might need a lookup, do it asynchronously
  109. weak_ptr<IceTransport> weakIceTransport{iceTransport};
  110. std::thread t([weakIceTransport, candidate]() mutable {
  111. if (candidate.resolve(Candidate::ResolveMode::Lookup))
  112. if (auto iceTransport = weakIceTransport.lock())
  113. iceTransport->addRemoteCandidate(candidate);
  114. });
  115. t.detach();
  116. }
  117. }
  118. std::optional<string> PeerConnection::localAddress() const {
  119. auto iceTransport = std::atomic_load(&mIceTransport);
  120. return iceTransport ? iceTransport->getLocalAddress() : nullopt;
  121. }
  122. std::optional<string> PeerConnection::remoteAddress() const {
  123. auto iceTransport = std::atomic_load(&mIceTransport);
  124. return iceTransport ? iceTransport->getRemoteAddress() : nullopt;
  125. }
  126. shared_ptr<DataChannel> PeerConnection::createDataChannel(const string &label,
  127. const string &protocol,
  128. const Reliability &reliability) {
  129. // RFC 5763: The answerer MUST use either a setup attribute value of setup:active or
  130. // setup:passive. [...] Thus, setup:active is RECOMMENDED.
  131. // See https://tools.ietf.org/html/rfc5763#section-5
  132. // Therefore, we assume passive role when we are the offerer.
  133. auto iceTransport = std::atomic_load(&mIceTransport);
  134. auto role = iceTransport ? iceTransport->role() : Description::Role::Passive;
  135. auto channel = emplaceDataChannel(role, label, protocol, reliability);
  136. if (!iceTransport) {
  137. // RFC 5763: The endpoint that is the offerer MUST use the setup attribute value of
  138. // setup:actpass.
  139. // See https://tools.ietf.org/html/rfc5763#section-5
  140. iceTransport = initIceTransport(Description::Role::ActPass);
  141. processLocalDescription(iceTransport->getLocalDescription(Description::Type::Offer));
  142. iceTransport->gatherLocalCandidates();
  143. } else {
  144. if (auto transport = std::atomic_load(&mSctpTransport))
  145. if (transport->state() == SctpTransport::State::Connected)
  146. channel->open(transport);
  147. }
  148. return channel;
  149. }
  150. void PeerConnection::onDataChannel(
  151. std::function<void(shared_ptr<DataChannel> dataChannel)> callback) {
  152. mDataChannelCallback = callback;
  153. }
  154. void PeerConnection::onLocalDescription(
  155. std::function<void(const Description &description)> callback) {
  156. mLocalDescriptionCallback = callback;
  157. }
  158. void PeerConnection::onLocalCandidate(std::function<void(const Candidate &candidate)> callback) {
  159. mLocalCandidateCallback = callback;
  160. }
  161. void PeerConnection::onStateChange(std::function<void(State state)> callback) {
  162. mStateChangeCallback = callback;
  163. }
  164. void PeerConnection::onGatheringStateChange(std::function<void(GatheringState state)> callback) {
  165. mGatheringStateChangeCallback = callback;
  166. }
  167. shared_ptr<IceTransport> PeerConnection::initIceTransport(Description::Role role) {
  168. try {
  169. if (auto transport = std::atomic_load(&mIceTransport))
  170. return transport;
  171. auto transport = std::make_shared<IceTransport>(
  172. mConfig, role, weak_bind(&PeerConnection::processLocalCandidate, this, _1),
  173. [this](IceTransport::State state) {
  174. switch (state) {
  175. case IceTransport::State::Connecting:
  176. changeState(State::Connecting);
  177. break;
  178. case IceTransport::State::Failed:
  179. changeState(State::Failed);
  180. break;
  181. case IceTransport::State::Connected:
  182. initDtlsTransport();
  183. break;
  184. case IceTransport::State::Disconnected:
  185. changeState(State::Disconnected);
  186. break;
  187. default:
  188. // Ignore
  189. break;
  190. }
  191. },
  192. [this](IceTransport::GatheringState state) {
  193. switch (state) {
  194. case IceTransport::GatheringState::InProgress:
  195. changeGatheringState(GatheringState::InProgress);
  196. break;
  197. case IceTransport::GatheringState::Complete:
  198. endLocalCandidates();
  199. changeGatheringState(GatheringState::Complete);
  200. break;
  201. default:
  202. // Ignore
  203. break;
  204. }
  205. });
  206. std::atomic_store(&mIceTransport, transport);
  207. if (mState == State::Closed) {
  208. mIceTransport.reset();
  209. transport->stop();
  210. throw std::runtime_error("Connection is closed");
  211. }
  212. return transport;
  213. } catch (const std::exception &e) {
  214. PLOG_ERROR << e.what();
  215. changeState(State::Failed);
  216. throw std::runtime_error("ICE transport initialization failed");
  217. }
  218. }
  219. shared_ptr<DtlsTransport> PeerConnection::initDtlsTransport() {
  220. try {
  221. if (auto transport = std::atomic_load(&mDtlsTransport))
  222. return transport;
  223. auto lower = std::atomic_load(&mIceTransport);
  224. auto transport = std::make_shared<DtlsTransport>(
  225. lower, mCertificate, weak_bind_verifier(&PeerConnection::checkFingerprint, this, _1),
  226. [this](DtlsTransport::State state) {
  227. switch (state) {
  228. case DtlsTransport::State::Connected:
  229. initSctpTransport();
  230. break;
  231. case DtlsTransport::State::Failed:
  232. changeState(State::Failed);
  233. break;
  234. case DtlsTransport::State::Disconnected:
  235. changeState(State::Disconnected);
  236. break;
  237. default:
  238. // Ignore
  239. break;
  240. }
  241. });
  242. std::atomic_store(&mDtlsTransport, transport);
  243. if (mState == State::Closed) {
  244. mDtlsTransport.reset();
  245. transport->stop();
  246. throw std::runtime_error("Connection is closed");
  247. }
  248. return transport;
  249. } catch (const std::exception &e) {
  250. PLOG_ERROR << e.what();
  251. changeState(State::Failed);
  252. throw std::runtime_error("DTLS transport initialization failed");
  253. }
  254. }
  255. shared_ptr<SctpTransport> PeerConnection::initSctpTransport() {
  256. try {
  257. if (auto transport = std::atomic_load(&mSctpTransport))
  258. return transport;
  259. uint16_t sctpPort = remoteDescription()->sctpPort().value_or(DEFAULT_SCTP_PORT);
  260. auto lower = std::atomic_load(&mDtlsTransport);
  261. auto transport = std::make_shared<SctpTransport>(
  262. lower, sctpPort, weak_bind(&PeerConnection::forwardMessage, this, _1),
  263. weak_bind(&PeerConnection::forwardBufferedAmount, this, _1, _2),
  264. [this](SctpTransport::State state) {
  265. switch (state) {
  266. case SctpTransport::State::Connected:
  267. changeState(State::Connected);
  268. openDataChannels();
  269. break;
  270. case SctpTransport::State::Failed:
  271. remoteCloseDataChannels();
  272. changeState(State::Failed);
  273. break;
  274. case SctpTransport::State::Disconnected:
  275. remoteCloseDataChannels();
  276. changeState(State::Disconnected);
  277. break;
  278. default:
  279. // Ignore
  280. break;
  281. }
  282. });
  283. std::atomic_store(&mSctpTransport, transport);
  284. if (mState == State::Closed) {
  285. mSctpTransport.reset();
  286. transport->stop();
  287. throw std::runtime_error("Connection is closed");
  288. }
  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::closeTransports() {
  297. // Change state to sink state Closed to block init methods
  298. changeState(State::Closed);
  299. // Reset callbacks now that state is changed
  300. resetCallbacks();
  301. // Pass the references to a thread, allowing to terminate a transport from its own thread
  302. auto sctp = std::atomic_exchange(&mSctpTransport, decltype(mSctpTransport)(nullptr));
  303. auto dtls = std::atomic_exchange(&mDtlsTransport, decltype(mDtlsTransport)(nullptr));
  304. auto ice = std::atomic_exchange(&mIceTransport, decltype(mIceTransport)(nullptr));
  305. if (sctp || dtls || ice) {
  306. std::thread t([sctp, dtls, ice]() mutable {
  307. if (sctp)
  308. sctp->stop();
  309. if (dtls)
  310. dtls->stop();
  311. if (ice)
  312. ice->stop();
  313. sctp.reset();
  314. dtls.reset();
  315. ice.reset();
  316. });
  317. t.detach();
  318. }
  319. }
  320. void PeerConnection::endLocalCandidates() {
  321. std::lock_guard lock(mLocalDescriptionMutex);
  322. if (mLocalDescription)
  323. mLocalDescription->endCandidates();
  324. }
  325. bool PeerConnection::checkFingerprint(const std::string &fingerprint) const {
  326. std::lock_guard lock(mRemoteDescriptionMutex);
  327. if (auto expectedFingerprint =
  328. mRemoteDescription ? mRemoteDescription->fingerprint() : nullopt) {
  329. return *expectedFingerprint == fingerprint;
  330. }
  331. return false;
  332. }
  333. void PeerConnection::forwardMessage(message_ptr message) {
  334. if (!message) {
  335. remoteCloseDataChannels();
  336. return;
  337. }
  338. auto channel = findDataChannel(message->stream);
  339. auto iceTransport = std::atomic_load(&mIceTransport);
  340. auto sctpTransport = std::atomic_load(&mSctpTransport);
  341. if (!iceTransport || !sctpTransport)
  342. return;
  343. if (!channel) {
  344. const byte dataChannelOpenMessage{0x03};
  345. unsigned int remoteParity = (iceTransport->role() == Description::Role::Active) ? 1 : 0;
  346. if (message->type == Message::Control && *message->data() == dataChannelOpenMessage &&
  347. message->stream % 2 == remoteParity) {
  348. channel =
  349. std::make_shared<DataChannel>(shared_from_this(), sctpTransport, message->stream);
  350. channel->onOpen(weak_bind(&PeerConnection::triggerDataChannel, this,
  351. weak_ptr<DataChannel>{channel}));
  352. mDataChannels.insert(std::make_pair(message->stream, channel));
  353. } else {
  354. // Invalid, close the DataChannel by resetting the stream
  355. sctpTransport->reset(message->stream);
  356. return;
  357. }
  358. }
  359. channel->incoming(message);
  360. }
  361. void PeerConnection::forwardBufferedAmount(uint16_t stream, size_t amount) {
  362. if (auto channel = findDataChannel(stream))
  363. channel->triggerBufferedAmount(amount);
  364. }
  365. shared_ptr<DataChannel> PeerConnection::emplaceDataChannel(Description::Role role,
  366. const string &label,
  367. const string &protocol,
  368. const Reliability &reliability) {
  369. // The active side must use streams with even identifiers, whereas the passive side must use
  370. // streams with odd identifiers.
  371. // See https://tools.ietf.org/html/draft-ietf-rtcweb-data-protocol-09#section-6
  372. std::unique_lock lock(mDataChannelsMutex); // we are going to emplace
  373. unsigned int stream = (role == Description::Role::Active) ? 0 : 1;
  374. while (mDataChannels.find(stream) != mDataChannels.end()) {
  375. stream += 2;
  376. if (stream >= 65535)
  377. throw std::runtime_error("Too many DataChannels");
  378. }
  379. auto channel =
  380. std::make_shared<DataChannel>(shared_from_this(), stream, label, protocol, reliability);
  381. mDataChannels.emplace(std::make_pair(stream, channel));
  382. return channel;
  383. }
  384. shared_ptr<DataChannel> PeerConnection::findDataChannel(uint16_t stream) {
  385. std::shared_lock lock(mDataChannelsMutex); // read-only
  386. if (auto it = mDataChannels.find(stream); it != mDataChannels.end())
  387. if (auto channel = it->second.lock())
  388. return channel;
  389. return nullptr;
  390. }
  391. void PeerConnection::iterateDataChannels(
  392. std::function<void(shared_ptr<DataChannel> channel)> func) {
  393. // Iterate
  394. {
  395. std::shared_lock lock(mDataChannelsMutex); // read-only
  396. auto it = mDataChannels.begin();
  397. while (it != mDataChannels.end()) {
  398. auto channel = it->second.lock();
  399. if (channel && !channel->isClosed())
  400. func(channel);
  401. ++it;
  402. }
  403. }
  404. // Cleanup
  405. {
  406. std::unique_lock lock(mDataChannelsMutex); // we are going to erase
  407. auto it = mDataChannels.begin();
  408. while (it != mDataChannels.end()) {
  409. if (!it->second.lock()) {
  410. it = mDataChannels.erase(it);
  411. continue;
  412. }
  413. ++it;
  414. }
  415. }
  416. }
  417. void PeerConnection::openDataChannels() {
  418. if (auto transport = std::atomic_load(&mSctpTransport))
  419. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->open(transport); });
  420. }
  421. void PeerConnection::closeDataChannels() {
  422. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->close(); });
  423. }
  424. void PeerConnection::remoteCloseDataChannels() {
  425. iterateDataChannels([&](shared_ptr<DataChannel> channel) { channel->remoteClose(); });
  426. }
  427. void PeerConnection::processLocalDescription(Description description) {
  428. std::optional<uint16_t> remoteSctpPort;
  429. if (auto remote = remoteDescription())
  430. remoteSctpPort = remote->sctpPort();
  431. std::lock_guard lock(mLocalDescriptionMutex);
  432. mLocalDescription.emplace(std::move(description));
  433. mLocalDescription->setFingerprint(mCertificate->fingerprint());
  434. mLocalDescription->setSctpPort(remoteSctpPort.value_or(DEFAULT_SCTP_PORT));
  435. mLocalDescription->setMaxMessageSize(LOCAL_MAX_MESSAGE_SIZE);
  436. mLocalDescriptionCallback(*mLocalDescription);
  437. }
  438. void PeerConnection::processLocalCandidate(Candidate candidate) {
  439. std::lock_guard lock(mLocalDescriptionMutex);
  440. if (!mLocalDescription)
  441. throw std::logic_error("Got a local candidate without local description");
  442. mLocalDescription->addCandidate(candidate);
  443. mLocalCandidateCallback(candidate);
  444. }
  445. void PeerConnection::triggerDataChannel(weak_ptr<DataChannel> weakDataChannel) {
  446. auto dataChannel = weakDataChannel.lock();
  447. if (!dataChannel)
  448. return;
  449. mDataChannelCallback(dataChannel);
  450. }
  451. bool PeerConnection::changeState(State state) {
  452. State current;
  453. do {
  454. current = mState.load();
  455. if (current == state)
  456. return true;
  457. if (current == State::Closed)
  458. return false;
  459. } while (!mState.compare_exchange_weak(current, state));
  460. mStateChangeCallback(state);
  461. return true;
  462. }
  463. bool PeerConnection::changeGatheringState(GatheringState state) {
  464. if (mGatheringState.exchange(state) != state)
  465. mGatheringStateChangeCallback(state);
  466. return true;
  467. }
  468. void PeerConnection::resetCallbacks() {
  469. // Unregister all callbacks
  470. mDataChannelCallback = nullptr;
  471. mLocalDescriptionCallback = nullptr;
  472. mLocalCandidateCallback = nullptr;
  473. mStateChangeCallback = nullptr;
  474. mGatheringStateChangeCallback = nullptr;
  475. }
  476. } // namespace rtc
  477. std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::State &state) {
  478. using State = rtc::PeerConnection::State;
  479. std::string str;
  480. switch (state) {
  481. case State::New:
  482. str = "new";
  483. break;
  484. case State::Connecting:
  485. str = "connecting";
  486. break;
  487. case State::Connected:
  488. str = "connected";
  489. break;
  490. case State::Disconnected:
  491. str = "disconnected";
  492. break;
  493. case State::Failed:
  494. str = "failed";
  495. break;
  496. case State::Closed:
  497. str = "closed";
  498. break;
  499. default:
  500. str = "unknown";
  501. break;
  502. }
  503. return out << str;
  504. }
  505. std::ostream &operator<<(std::ostream &out, const rtc::PeerConnection::GatheringState &state) {
  506. using GatheringState = rtc::PeerConnection::GatheringState;
  507. std::string str;
  508. switch (state) {
  509. case GatheringState::New:
  510. str = "new";
  511. break;
  512. case GatheringState::InProgress:
  513. str = "in_progress";
  514. break;
  515. case GatheringState::Complete:
  516. str = "complete";
  517. break;
  518. default:
  519. str = "unknown";
  520. break;
  521. }
  522. return out << str;
  523. }