sctptransport.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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 "sctptransport.hpp"
  19. #include "dtlstransport.hpp"
  20. #include "logcounter.hpp"
  21. #include <chrono>
  22. #include <exception>
  23. #include <iostream>
  24. #include <thread>
  25. #include <vector>
  26. // The IETF draft says:
  27. // SCTP MUST support performing Path MTU discovery without relying on ICMP or ICMPv6 as specified in
  28. // [RFC4821] using probing messages specified in [RFC4820].
  29. // See https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-13#section-5
  30. //
  31. // However, usrsctp does not implement Path MTU discovery, so we need to disable it for now.
  32. // See https://github.com/sctplab/usrsctp/issues/205
  33. #define USE_PMTUD 0
  34. // TODO: When Path MTU discovery is supported, it needs to be enabled with libjuice as ICE backend
  35. // on all platforms except Mac OS where the Don't Fragment (DF) flag can't be set:
  36. /*
  37. #if !USE_NICE
  38. #ifndef __APPLE__
  39. // libjuice enables Linux path MTU discovery or sets the DF flag
  40. #define USE_PMTUD 1
  41. #else
  42. // Setting the DF flag is not available on Mac OS
  43. #define USE_PMTUD 0
  44. #endif
  45. #else // USE_NICE == 1
  46. #define USE_PMTUD 0
  47. #endif
  48. */
  49. using namespace std::chrono_literals;
  50. using namespace std::chrono;
  51. namespace rtc {
  52. static LogCounter COUNTER_UNKNOWN_PPID(plog::warning,
  53. "Number of SCTP packets received with an unknown PPID");
  54. static LogCounter
  55. COUNTER_BAD_NOTIF_LEN(plog::warning,
  56. "Number of SCTP packets received with an bad notification length");
  57. static LogCounter COUNTER_BAD_SCTP_STATUS(plog::warning,
  58. "Number of SCTP packets received with a bad status");
  59. std::unordered_set<SctpTransport *> SctpTransport::Instances;
  60. std::shared_mutex SctpTransport::InstancesMutex;
  61. void SctpTransport::Init() {
  62. usrsctp_init(0, &SctpTransport::WriteCallback, nullptr);
  63. usrsctp_sysctl_set_sctp_ecn_enable(0);
  64. usrsctp_sysctl_set_sctp_init_rtx_max_default(5);
  65. usrsctp_sysctl_set_sctp_path_rtx_max_default(5);
  66. usrsctp_sysctl_set_sctp_assoc_rtx_max_default(5); // single path
  67. usrsctp_sysctl_set_sctp_rto_min_default(1 * 1000); // ms
  68. usrsctp_sysctl_set_sctp_rto_max_default(10 * 1000); // ms
  69. usrsctp_sysctl_set_sctp_rto_initial_default(1 * 1000); // ms
  70. usrsctp_sysctl_set_sctp_init_rto_max_default(10 * 1000); // ms
  71. usrsctp_sysctl_set_sctp_heartbeat_interval_default(10 * 1000); // ms
  72. usrsctp_sysctl_set_sctp_max_chunks_on_queue(10 * 1024);
  73. // Change congestion control from the default TCP Reno (RFC 2581) to H-TCP
  74. usrsctp_sysctl_set_sctp_default_cc_module(SCTP_CC_HTCP);
  75. // Enable Partial Reliability Extension (RFC 3758)
  76. usrsctp_sysctl_set_sctp_pr_enable(1);
  77. // Enable Non-Renegable Selective Acknowledgments (NR-SACKs)
  78. usrsctp_sysctl_set_sctp_nrsack_enable(1);
  79. // Increase the initial window size to 10 MTUs (RFC 6928)
  80. usrsctp_sysctl_set_sctp_initial_cwnd(10);
  81. // Reduce SACK delay from the default 200ms to 20ms
  82. usrsctp_sysctl_set_sctp_delayed_sack_time_default(20); // ms
  83. }
  84. void SctpTransport::Cleanup() {
  85. while (usrsctp_finish() != 0)
  86. std::this_thread::sleep_for(100ms);
  87. }
  88. SctpTransport::SctpTransport(std::shared_ptr<Transport> lower, uint16_t port,
  89. std::optional<size_t> mtu, message_callback recvCallback,
  90. amount_callback bufferedAmountCallback,
  91. state_callback stateChangeCallback)
  92. : Transport(lower, std::move(stateChangeCallback)), mPort(port),
  93. mSendQueue(0, message_size_func), mBufferedAmountCallback(std::move(bufferedAmountCallback)) {
  94. onRecv(recvCallback);
  95. PLOG_DEBUG << "Initializing SCTP transport";
  96. usrsctp_register_address(this);
  97. {
  98. std::unique_lock lock(InstancesMutex);
  99. Instances.insert(this);
  100. }
  101. mSock = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP, nullptr, nullptr, 0, nullptr);
  102. if (!mSock)
  103. throw std::runtime_error("Could not create SCTP socket, errno=" + std::to_string(errno));
  104. usrsctp_set_upcall(mSock, &SctpTransport::UpcallCallback, this);
  105. if (usrsctp_set_non_blocking(mSock, 1))
  106. throw std::runtime_error("Unable to set non-blocking mode, errno=" + std::to_string(errno));
  107. // SCTP must stop sending after the lower layer is shut down, so disable linger
  108. struct linger sol = {};
  109. sol.l_onoff = 1;
  110. sol.l_linger = 0;
  111. if (usrsctp_setsockopt(mSock, SOL_SOCKET, SO_LINGER, &sol, sizeof(sol)))
  112. throw std::runtime_error("Could not set socket option SO_LINGER, errno=" +
  113. std::to_string(errno));
  114. struct sctp_assoc_value av = {};
  115. av.assoc_id = SCTP_ALL_ASSOC;
  116. av.assoc_value = 1;
  117. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET, &av, sizeof(av)))
  118. throw std::runtime_error("Could not set socket option SCTP_ENABLE_STREAM_RESET, errno=" +
  119. std::to_string(errno));
  120. int on = 1;
  121. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_RECVRCVINFO, &on, sizeof(on)))
  122. throw std::runtime_error("Could set socket option SCTP_RECVRCVINFO, errno=" +
  123. std::to_string(errno));
  124. struct sctp_event se = {};
  125. se.se_assoc_id = SCTP_ALL_ASSOC;
  126. se.se_on = 1;
  127. se.se_type = SCTP_ASSOC_CHANGE;
  128. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_EVENT, &se, sizeof(se)))
  129. throw std::runtime_error("Could not subscribe to event SCTP_ASSOC_CHANGE, errno=" +
  130. std::to_string(errno));
  131. se.se_type = SCTP_SENDER_DRY_EVENT;
  132. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_EVENT, &se, sizeof(se)))
  133. throw std::runtime_error("Could not subscribe to event SCTP_SENDER_DRY_EVENT, errno=" +
  134. std::to_string(errno));
  135. se.se_type = SCTP_STREAM_RESET_EVENT;
  136. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_EVENT, &se, sizeof(se)))
  137. throw std::runtime_error("Could not subscribe to event SCTP_STREAM_RESET_EVENT, errno=" +
  138. std::to_string(errno));
  139. // The sender SHOULD disable the Nagle algorithm (see RFC1122) to minimize the latency.
  140. // See https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-13#section-6.6
  141. int nodelay = 1;
  142. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_NODELAY, &nodelay, sizeof(nodelay)))
  143. throw std::runtime_error("Could not set socket option SCTP_NODELAY, errno=" +
  144. std::to_string(errno));
  145. struct sctp_paddrparams spp = {};
  146. // Enable SCTP heartbeats
  147. spp.spp_flags = SPP_HB_ENABLE;
  148. // RFC 8261 5. DTLS considerations:
  149. // If path MTU discovery is performed by the SCTP layer and IPv4 is used as the network-layer
  150. // protocol, the DTLS implementation SHOULD allow the DTLS user to enforce that the
  151. // corresponding IPv4 packet is sent with the Don't Fragment (DF) bit set. If controlling the DF
  152. // bit is not possible (for example, due to implementation restrictions), a safe value for the
  153. // path MTU has to be used by the SCTP stack. It is RECOMMENDED that the safe value not exceed
  154. // 1200 bytes.
  155. // See https://tools.ietf.org/html/rfc8261#section-5
  156. #if USE_PMTUD
  157. if (!mtu.has_value()) {
  158. #else
  159. if (false) {
  160. #endif
  161. // Enable SCTP path MTU discovery
  162. spp.spp_flags |= SPP_PMTUD_ENABLE;
  163. PLOG_VERBOSE << "Path MTU discovery enabled";
  164. } else {
  165. // Fall back to a safe MTU value.
  166. spp.spp_flags |= SPP_PMTUD_DISABLE;
  167. // The MTU value provided specifies the space available for chunks in the
  168. // packet, so we also subtract the SCTP header size.
  169. size_t pmtu = mtu.value_or(DEFAULT_IPV4_MTU + 20) - 12 - 37 - 8 - 40; // SCTP/DTLS/UDP/IPv6
  170. spp.spp_pathmtu = uint32_t(pmtu);
  171. PLOG_VERBOSE << "Path MTU discovery disabled, SCTP MTU set to " << pmtu;
  172. }
  173. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &spp, sizeof(spp)))
  174. throw std::runtime_error("Could not set socket option SCTP_PEER_ADDR_PARAMS, errno=" +
  175. std::to_string(errno));
  176. // The IETF draft recommends the number of streams negotiated during SCTP association to be
  177. // 65535.
  178. // See https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-13#section-6.2
  179. struct sctp_initmsg sinit = {};
  180. sinit.sinit_num_ostreams = 65535;
  181. sinit.sinit_max_instreams = 65535;
  182. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_INITMSG, &sinit, sizeof(sinit)))
  183. throw std::runtime_error("Could not set socket option SCTP_INITMSG, errno=" +
  184. std::to_string(errno));
  185. // Prevent fragmented interleave of messages (i.e. level 0), see RFC 6458 8.1.20.
  186. // Unless the user has set the fragmentation interleave level to 0, notifications
  187. // may also be interleaved with partially delivered messages.
  188. int level = 0;
  189. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_FRAGMENT_INTERLEAVE, &level, sizeof(level)))
  190. throw std::runtime_error("Could not disable SCTP fragmented interleave, errno=" +
  191. std::to_string(errno));
  192. // The default send and receive window size of usrsctp is 256KiB, which is too small for
  193. // realistic RTTs, therefore we increase it to 1MiB for better performance.
  194. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1051685
  195. int bufferSize = 1024 * 1024;
  196. if (usrsctp_setsockopt(mSock, SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize)))
  197. throw std::runtime_error("Could not set SCTP recv buffer size, errno=" +
  198. std::to_string(errno));
  199. if (usrsctp_setsockopt(mSock, SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize)))
  200. throw std::runtime_error("Could not set SCTP send buffer size, errno=" +
  201. std::to_string(errno));
  202. }
  203. SctpTransport::~SctpTransport() {
  204. stop();
  205. close();
  206. usrsctp_deregister_address(this);
  207. {
  208. std::unique_lock lock(InstancesMutex);
  209. Instances.erase(this);
  210. }
  211. }
  212. void SctpTransport::start() {
  213. Transport::start();
  214. registerIncoming();
  215. connect();
  216. }
  217. bool SctpTransport::stop() {
  218. // Transport::stop() will unregister incoming() from the lower layer, therefore we need to make
  219. // sure the thread from lower layers is not blocked in incoming() by the WrittenOnce condition.
  220. mWrittenOnce = true;
  221. mWrittenCondition.notify_all();
  222. if (!Transport::stop())
  223. return false;
  224. mSendQueue.stop();
  225. flush();
  226. shutdown();
  227. onRecv(nullptr);
  228. return true;
  229. }
  230. void SctpTransport::close() {
  231. if (mSock) {
  232. mProcessor.join();
  233. usrsctp_close(mSock);
  234. mSock = nullptr;
  235. }
  236. }
  237. void SctpTransport::connect() {
  238. if (!mSock)
  239. throw std::logic_error("Attempted SCTP connect with closed socket");
  240. PLOG_DEBUG << "SCTP connecting";
  241. changeState(State::Connecting);
  242. struct sockaddr_conn sconn = {};
  243. sconn.sconn_family = AF_CONN;
  244. sconn.sconn_port = htons(mPort);
  245. sconn.sconn_addr = this;
  246. #ifdef HAVE_SCONN_LEN
  247. sconn.sconn_len = sizeof(sconn);
  248. #endif
  249. if (usrsctp_bind(mSock, reinterpret_cast<struct sockaddr *>(&sconn), sizeof(sconn)))
  250. throw std::runtime_error("Could not bind usrsctp socket, errno=" + std::to_string(errno));
  251. // According to the IETF draft, both endpoints must initiate the SCTP association, in a
  252. // simultaneous-open manner, irrelevent to the SDP setup role.
  253. // See https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-9.3
  254. int ret = usrsctp_connect(mSock, reinterpret_cast<struct sockaddr *>(&sconn), sizeof(sconn));
  255. if (ret && errno != EINPROGRESS)
  256. throw std::runtime_error("Connection attempt failed, errno=" + std::to_string(errno));
  257. }
  258. void SctpTransport::shutdown() {
  259. if (!mSock)
  260. return;
  261. PLOG_DEBUG << "SCTP shutdown";
  262. if (usrsctp_shutdown(mSock, SHUT_RDWR) != 0 && errno != ENOTCONN) {
  263. PLOG_WARNING << "SCTP shutdown failed, errno=" << errno;
  264. }
  265. close();
  266. PLOG_INFO << "SCTP disconnected";
  267. changeState(State::Disconnected);
  268. mWrittenCondition.notify_all();
  269. }
  270. bool SctpTransport::send(message_ptr message) {
  271. std::lock_guard lock(mSendMutex);
  272. if (!message)
  273. return trySendQueue();
  274. PLOG_VERBOSE << "Send size=" << message->size();
  275. // Flush the queue, and if nothing is pending, try to send directly
  276. if (trySendQueue() && trySendMessage(message))
  277. return true;
  278. mSendQueue.push(message);
  279. updateBufferedAmount(uint16_t(message->stream), long(message_size_func(message)));
  280. return false;
  281. }
  282. bool SctpTransport::flush() {
  283. try {
  284. std::lock_guard lock(mSendMutex);
  285. trySendQueue();
  286. return true;
  287. } catch (const std::exception &e) {
  288. PLOG_WARNING << "SCTP flush: " << e.what();
  289. return false;
  290. }
  291. }
  292. void SctpTransport::closeStream(unsigned int stream) {
  293. send(make_message(0, Message::Reset, uint16_t(stream)));
  294. }
  295. void SctpTransport::incoming(message_ptr message) {
  296. // There could be a race condition here where we receive the remote INIT before the local one is
  297. // sent, which would result in the connection being aborted. Therefore, we need to wait for data
  298. // to be sent on our side (i.e. the local INIT) before proceeding.
  299. if (!mWrittenOnce) { // test the atomic boolean is not set first to prevent a lock contention
  300. std::unique_lock lock(mWriteMutex);
  301. mWrittenCondition.wait(lock, [&]() { return mWrittenOnce.load(); });
  302. }
  303. if (!message) {
  304. PLOG_INFO << "SCTP disconnected";
  305. changeState(State::Disconnected);
  306. recv(nullptr);
  307. return;
  308. }
  309. PLOG_VERBOSE << "Incoming size=" << message->size();
  310. // TODO: There seems to be a possible data race between usrsctp_sendv() and usrsctp_conninput()
  311. // As a mitigation, lock the send mutex before calling usrsctp_conninput()
  312. std::lock_guard lock(mSendMutex);
  313. usrsctp_conninput(this, message->data(), message->size(), 0);
  314. }
  315. bool SctpTransport::outgoing(message_ptr message) {
  316. // Set recommended medium-priority DSCP value
  317. // See https://tools.ietf.org/html/draft-ietf-tsvwg-rtcweb-qos-18
  318. message->dscp = 10; // AF11: Assured Forwarding class 1, low drop probability
  319. return Transport::outgoing(std::move(message));
  320. }
  321. void SctpTransport::doRecv() {
  322. std::lock_guard lock(mRecvMutex);
  323. --mPendingRecvCount;
  324. try {
  325. while (state() != State::Disconnected && state() != State::Failed) {
  326. const size_t bufferSize = 65536;
  327. byte buffer[bufferSize];
  328. socklen_t fromlen = 0;
  329. struct sctp_rcvinfo info = {};
  330. socklen_t infolen = sizeof(info);
  331. unsigned int infotype = 0;
  332. int flags = 0;
  333. ssize_t len = usrsctp_recvv(mSock, buffer, bufferSize, nullptr, &fromlen, &info,
  334. &infolen, &infotype, &flags);
  335. if (len < 0) {
  336. if (errno == EWOULDBLOCK || errno == EAGAIN || errno == ECONNRESET)
  337. break;
  338. else
  339. throw std::runtime_error("SCTP recv failed, errno=" + std::to_string(errno));
  340. }
  341. PLOG_VERBOSE << "SCTP recv, len=" << len;
  342. // SCTP_FRAGMENT_INTERLEAVE does not seem to work as expected for messages > 64KB,
  343. // therefore partial notifications and messages need to be handled separately.
  344. if (flags & MSG_NOTIFICATION) {
  345. // SCTP event notification
  346. mPartialNotification.insert(mPartialNotification.end(), buffer, buffer + len);
  347. if (flags & MSG_EOR) {
  348. // Notification is complete, process it
  349. auto notification =
  350. reinterpret_cast<union sctp_notification *>(mPartialNotification.data());
  351. processNotification(notification, mPartialNotification.size());
  352. mPartialNotification.clear();
  353. }
  354. } else {
  355. // SCTP message
  356. mPartialMessage.insert(mPartialMessage.end(), buffer, buffer + len);
  357. if (flags & MSG_EOR) {
  358. // Message is complete, process it
  359. if (infotype != SCTP_RECVV_RCVINFO)
  360. throw std::runtime_error("Missing SCTP recv info");
  361. processData(std::move(mPartialMessage), info.rcv_sid,
  362. PayloadId(ntohl(info.rcv_ppid)));
  363. mPartialMessage.clear();
  364. }
  365. }
  366. }
  367. } catch (const std::exception &e) {
  368. PLOG_WARNING << e.what();
  369. }
  370. }
  371. void SctpTransport::doFlush() {
  372. std::lock_guard lock(mSendMutex);
  373. --mPendingFlushCount;
  374. try {
  375. trySendQueue();
  376. } catch (const std::exception &e) {
  377. PLOG_WARNING << e.what();
  378. }
  379. }
  380. bool SctpTransport::trySendQueue() {
  381. // Requires mSendMutex to be locked
  382. while (auto next = mSendQueue.peek()) {
  383. message_ptr message = std::move(*next);
  384. if (!trySendMessage(message))
  385. return false;
  386. mSendQueue.pop();
  387. updateBufferedAmount(uint16_t(message->stream), -long(message_size_func(message)));
  388. }
  389. return true;
  390. }
  391. bool SctpTransport::trySendMessage(message_ptr message) {
  392. // Requires mSendMutex to be locked
  393. if (!mSock || state() != State::Connected)
  394. return false;
  395. uint32_t ppid;
  396. switch (message->type) {
  397. case Message::String:
  398. ppid = !message->empty() ? PPID_STRING : PPID_STRING_EMPTY;
  399. break;
  400. case Message::Binary:
  401. ppid = !message->empty() ? PPID_BINARY : PPID_BINARY_EMPTY;
  402. break;
  403. case Message::Control:
  404. ppid = PPID_CONTROL;
  405. break;
  406. case Message::Reset:
  407. sendReset(uint16_t(message->stream));
  408. return true;
  409. default:
  410. // Ignore
  411. return true;
  412. }
  413. PLOG_VERBOSE << "SCTP try send size=" << message->size();
  414. // TODO: Implement SCTP ndata specification draft when supported everywhere
  415. // See https://tools.ietf.org/html/draft-ietf-tsvwg-sctp-ndata-08
  416. const Reliability reliability = message->reliability ? *message->reliability : Reliability();
  417. struct sctp_sendv_spa spa = {};
  418. // set sndinfo
  419. spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
  420. spa.sendv_sndinfo.snd_sid = uint16_t(message->stream);
  421. spa.sendv_sndinfo.snd_ppid = htonl(ppid);
  422. spa.sendv_sndinfo.snd_flags |= SCTP_EOR; // implicit here
  423. // set prinfo
  424. spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
  425. if (reliability.unordered)
  426. spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
  427. switch (reliability.type) {
  428. case Reliability::Type::Rexmit:
  429. spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
  430. spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
  431. spa.sendv_prinfo.pr_value = uint32_t(std::get<int>(reliability.rexmit));
  432. break;
  433. case Reliability::Type::Timed:
  434. spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
  435. spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
  436. spa.sendv_prinfo.pr_value = uint32_t(std::get<milliseconds>(reliability.rexmit).count());
  437. break;
  438. default:
  439. spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_NONE;
  440. break;
  441. }
  442. ssize_t ret;
  443. if (!message->empty()) {
  444. ret = usrsctp_sendv(mSock, message->data(), message->size(), nullptr, 0, &spa, sizeof(spa),
  445. SCTP_SENDV_SPA, 0);
  446. } else {
  447. const char zero = 0;
  448. ret = usrsctp_sendv(mSock, &zero, 1, nullptr, 0, &spa, sizeof(spa), SCTP_SENDV_SPA, 0);
  449. }
  450. if (ret < 0) {
  451. if (errno == EWOULDBLOCK || errno == EAGAIN) {
  452. PLOG_VERBOSE << "SCTP sending not possible";
  453. return false;
  454. }
  455. PLOG_ERROR << "SCTP sending failed, errno=" << errno;
  456. throw std::runtime_error("Sending failed, errno=" + std::to_string(errno));
  457. }
  458. PLOG_VERBOSE << "SCTP sent size=" << message->size();
  459. if (message->type == Message::Type::Binary || message->type == Message::Type::String)
  460. mBytesSent += message->size();
  461. return true;
  462. }
  463. void SctpTransport::updateBufferedAmount(uint16_t streamId, long delta) {
  464. // Requires mSendMutex to be locked
  465. auto it = mBufferedAmount.insert(std::make_pair(streamId, 0)).first;
  466. size_t amount = size_t(std::max(long(it->second) + delta, long(0)));
  467. if (amount == 0)
  468. mBufferedAmount.erase(it);
  469. else
  470. it->second = amount;
  471. // Synchronously call the buffered amount callback
  472. triggerBufferedAmount(streamId, amount);
  473. }
  474. void SctpTransport::triggerBufferedAmount(uint16_t streamId, size_t amount) {
  475. try {
  476. mBufferedAmountCallback(streamId, amount);
  477. } catch (const std::exception &e) {
  478. PLOG_WARNING << "SCTP buffered amount callback: " << e.what();
  479. }
  480. }
  481. void SctpTransport::sendReset(uint16_t streamId) {
  482. // Requires mSendMutex to be locked
  483. if (!mSock || state() != State::Connected)
  484. return;
  485. PLOG_DEBUG << "SCTP resetting stream " << streamId;
  486. using srs_t = struct sctp_reset_streams;
  487. const size_t len = sizeof(srs_t) + sizeof(uint16_t);
  488. byte buffer[len] = {};
  489. srs_t &srs = *reinterpret_cast<srs_t *>(buffer);
  490. srs.srs_flags = SCTP_STREAM_RESET_OUTGOING;
  491. srs.srs_number_streams = 1;
  492. srs.srs_stream_list[0] = streamId;
  493. mWritten = false;
  494. if (usrsctp_setsockopt(mSock, IPPROTO_SCTP, SCTP_RESET_STREAMS, &srs, len) == 0) {
  495. std::unique_lock lock(mWriteMutex); // locking before setsockopt might deadlock usrsctp...
  496. mWrittenCondition.wait_for(lock, 1000ms,
  497. [&]() { return mWritten || state() != State::Connected; });
  498. } else if (errno == EINVAL) {
  499. PLOG_DEBUG << "SCTP stream " << streamId << " already reset";
  500. } else {
  501. PLOG_WARNING << "SCTP reset stream " << streamId << " failed, errno=" << errno;
  502. }
  503. }
  504. void SctpTransport::handleUpcall() {
  505. if (!mSock)
  506. return;
  507. PLOG_VERBOSE << "Handle upcall";
  508. int events = usrsctp_get_events(mSock);
  509. if (events & SCTP_EVENT_READ && mPendingRecvCount == 0) {
  510. ++mPendingRecvCount;
  511. mProcessor.enqueue(&SctpTransport::doRecv, this);
  512. }
  513. if (events & SCTP_EVENT_WRITE && mPendingFlushCount == 0) {
  514. ++mPendingFlushCount;
  515. mProcessor.enqueue(&SctpTransport::doFlush, this);
  516. }
  517. }
  518. int SctpTransport::handleWrite(byte *data, size_t len, uint8_t /*tos*/, uint8_t /*set_df*/) {
  519. try {
  520. std::unique_lock lock(mWriteMutex);
  521. PLOG_VERBOSE << "Handle write, len=" << len;
  522. if (!outgoing(make_message(data, data + len)))
  523. return -1;
  524. mWritten = true;
  525. mWrittenOnce = true;
  526. mWrittenCondition.notify_all();
  527. } catch (const std::exception &e) {
  528. PLOG_ERROR << "SCTP write: " << e.what();
  529. return -1;
  530. }
  531. return 0; // success
  532. }
  533. void SctpTransport::processData(binary &&data, uint16_t sid, PayloadId ppid) {
  534. PLOG_VERBOSE << "Process data, size=" << data.size();
  535. // The usage of the PPIDs "WebRTC String Partial" and "WebRTC Binary Partial" is deprecated.
  536. // See https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-13#section-6.6
  537. // We handle them at reception for compatibility reasons but should never send them.
  538. switch (ppid) {
  539. case PPID_CONTROL:
  540. recv(make_message(std::move(data), Message::Control, sid));
  541. break;
  542. case PPID_STRING_PARTIAL: // deprecated
  543. mPartialStringData.insert(mPartialStringData.end(), data.begin(), data.end());
  544. break;
  545. case PPID_STRING:
  546. if (mPartialStringData.empty()) {
  547. mBytesReceived += data.size();
  548. recv(make_message(std::move(data), Message::String, sid));
  549. } else {
  550. mPartialStringData.insert(mPartialStringData.end(), data.begin(), data.end());
  551. mBytesReceived += mPartialStringData.size();
  552. recv(make_message(std::move(mPartialStringData), Message::String, sid));
  553. mPartialStringData.clear();
  554. }
  555. break;
  556. case PPID_STRING_EMPTY:
  557. recv(make_message(std::move(mPartialStringData), Message::String, sid));
  558. mPartialStringData.clear();
  559. break;
  560. case PPID_BINARY_PARTIAL: // deprecated
  561. mPartialBinaryData.insert(mPartialBinaryData.end(), data.begin(), data.end());
  562. break;
  563. case PPID_BINARY:
  564. if (mPartialBinaryData.empty()) {
  565. mBytesReceived += data.size();
  566. recv(make_message(std::move(data), Message::Binary, sid));
  567. } else {
  568. mPartialBinaryData.insert(mPartialBinaryData.end(), data.begin(), data.end());
  569. mBytesReceived += mPartialBinaryData.size();
  570. recv(make_message(std::move(mPartialBinaryData), Message::Binary, sid));
  571. mPartialBinaryData.clear();
  572. }
  573. break;
  574. case PPID_BINARY_EMPTY:
  575. recv(make_message(std::move(mPartialBinaryData), Message::Binary, sid));
  576. mPartialBinaryData.clear();
  577. break;
  578. default:
  579. // Unknown
  580. COUNTER_UNKNOWN_PPID++;
  581. PLOG_VERBOSE << "Unknown PPID: " << uint32_t(ppid);
  582. return;
  583. }
  584. }
  585. void SctpTransport::processNotification(const union sctp_notification *notify, size_t len) {
  586. if (len != size_t(notify->sn_header.sn_length)) {
  587. COUNTER_BAD_NOTIF_LEN++;
  588. return;
  589. }
  590. auto type = notify->sn_header.sn_type;
  591. PLOG_VERBOSE << "Processing notification, type=" << type;
  592. switch (type) {
  593. case SCTP_ASSOC_CHANGE: {
  594. const struct sctp_assoc_change &assoc_change = notify->sn_assoc_change;
  595. if (assoc_change.sac_state == SCTP_COMM_UP) {
  596. PLOG_INFO << "SCTP connected";
  597. changeState(State::Connected);
  598. } else {
  599. if (state() == State::Connecting) {
  600. PLOG_ERROR << "SCTP connection failed";
  601. changeState(State::Failed);
  602. } else {
  603. PLOG_INFO << "SCTP disconnected";
  604. changeState(State::Disconnected);
  605. }
  606. mWrittenCondition.notify_all();
  607. }
  608. break;
  609. }
  610. case SCTP_SENDER_DRY_EVENT: {
  611. PLOG_VERBOSE << "SCTP dry event";
  612. // It should not be necessary since the send callback should have been called already,
  613. // but to be sure, let's try to send now.
  614. flush();
  615. break;
  616. }
  617. case SCTP_STREAM_RESET_EVENT: {
  618. const struct sctp_stream_reset_event &reset_event = notify->sn_strreset_event;
  619. const int count = (reset_event.strreset_length - sizeof(reset_event)) / sizeof(uint16_t);
  620. const uint16_t flags = reset_event.strreset_flags;
  621. IF_PLOG(plog::verbose) {
  622. std::ostringstream desc;
  623. desc << "flags=";
  624. if (flags & SCTP_STREAM_RESET_OUTGOING_SSN && flags & SCTP_STREAM_RESET_INCOMING_SSN)
  625. desc << "outgoing|incoming";
  626. else if (flags & SCTP_STREAM_RESET_OUTGOING_SSN)
  627. desc << "outgoing";
  628. else if (flags & SCTP_STREAM_RESET_INCOMING_SSN)
  629. desc << "incoming";
  630. else
  631. desc << "0";
  632. desc << ", streams=[";
  633. for (int i = 0; i < count; ++i) {
  634. uint16_t streamId = reset_event.strreset_stream_list[i];
  635. desc << (i != 0 ? "," : "") << streamId;
  636. }
  637. desc << "]";
  638. PLOG_VERBOSE << "SCTP reset event, " << desc.str();
  639. }
  640. if (flags & SCTP_STREAM_RESET_OUTGOING_SSN) {
  641. for (int i = 0; i < count; ++i) {
  642. uint16_t streamId = reset_event.strreset_stream_list[i];
  643. closeStream(streamId);
  644. }
  645. }
  646. if (flags & SCTP_STREAM_RESET_INCOMING_SSN) {
  647. const byte dataChannelCloseMessage{0x04};
  648. for (int i = 0; i < count; ++i) {
  649. uint16_t streamId = reset_event.strreset_stream_list[i];
  650. recv(make_message(&dataChannelCloseMessage, &dataChannelCloseMessage + 1,
  651. Message::Control, streamId));
  652. }
  653. }
  654. break;
  655. }
  656. default:
  657. // Ignore
  658. break;
  659. }
  660. }
  661. void SctpTransport::clearStats() {
  662. mBytesReceived = 0;
  663. mBytesSent = 0;
  664. }
  665. size_t SctpTransport::bytesSent() { return mBytesSent; }
  666. size_t SctpTransport::bytesReceived() { return mBytesReceived; }
  667. std::optional<milliseconds> SctpTransport::rtt() {
  668. if (!mSock || state() != State::Connected)
  669. return nullopt;
  670. struct sctp_status status = {};
  671. socklen_t len = sizeof(status);
  672. if (usrsctp_getsockopt(mSock, IPPROTO_SCTP, SCTP_STATUS, &status, &len)) {
  673. COUNTER_BAD_SCTP_STATUS++;
  674. return nullopt;
  675. }
  676. return milliseconds(status.sstat_primary.spinfo_srtt);
  677. }
  678. void SctpTransport::UpcallCallback(struct socket *, void *arg, int /* flags */) {
  679. auto *transport = static_cast<SctpTransport *>(arg);
  680. std::shared_lock lock(InstancesMutex);
  681. if (Instances.find(transport) == Instances.end())
  682. return;
  683. transport->handleUpcall();
  684. }
  685. int SctpTransport::WriteCallback(void *ptr, void *data, size_t len, uint8_t tos, uint8_t set_df) {
  686. auto *transport = static_cast<SctpTransport *>(ptr);
  687. // Workaround for sctplab/usrsctp#405: Send callback is invoked on already closed socket
  688. // https://github.com/sctplab/usrsctp/issues/405
  689. std::shared_lock lock(InstancesMutex);
  690. if (Instances.find(transport) == Instances.end())
  691. return -1;
  692. return transport->handleWrite(static_cast<byte *>(data), len, tos, set_df);
  693. }
  694. } // namespace rtc