blob: 2dcc33903283754b651740496a778667fa5ff526 [file] [log] [blame]
deadbeef953c2ce2017-01-09 14:53:41 -08001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include <errno.h>
12namespace {
13// Some ERRNO values get re-#defined to WSA* equivalents in some talk/
14// headers. We save the original ones in an enum.
15enum PreservedErrno {
16 SCTP_EINPROGRESS = EINPROGRESS,
17 SCTP_EWOULDBLOCK = EWOULDBLOCK
18};
19}
20
21#include "webrtc/media/sctp/sctptransport.h"
22
23#include <stdarg.h>
24#include <stdio.h>
25
26#include <memory>
27#include <sstream>
28
29#include "usrsctplib/usrsctp.h"
deadbeef953c2ce2017-01-09 14:53:41 -080030#include "webrtc/media/base/codec.h"
31#include "webrtc/media/base/mediaconstants.h"
deadbeef953c2ce2017-01-09 14:53:41 -080032#include "webrtc/media/base/streamparams.h"
zhihuangb2cdd932017-01-19 16:54:25 -080033#include "webrtc/p2p/base/dtlstransportinternal.h" // For PF_NORMAL
Edward Lemurc20978e2017-07-06 19:44:34 +020034#include "webrtc/rtc_base/arraysize.h"
35#include "webrtc/rtc_base/copyonwritebuffer.h"
36#include "webrtc/rtc_base/criticalsection.h"
37#include "webrtc/rtc_base/helpers.h"
38#include "webrtc/rtc_base/logging.h"
39#include "webrtc/rtc_base/safe_conversions.h"
40#include "webrtc/rtc_base/thread_checker.h"
41#include "webrtc/rtc_base/trace_event.h"
deadbeef953c2ce2017-01-09 14:53:41 -080042
43namespace {
44
45// The biggest SCTP packet. Starting from a 'safe' wire MTU value of 1280,
46// take off 80 bytes for DTLS/TURN/TCP/IP overhead.
47static constexpr size_t kSctpMtu = 1200;
48
49// The size of the SCTP association send buffer. 256kB, the usrsctp default.
50static constexpr int kSendBufferSize = 262144;
51
52// Set the initial value of the static SCTP Data Engines reference count.
53int g_usrsctp_usage_count = 0;
54rtc::GlobalLockPod g_usrsctp_lock_;
55
56// DataMessageType is used for the SCTP "Payload Protocol Identifier", as
57// defined in http://tools.ietf.org/html/rfc4960#section-14.4
58//
59// For the list of IANA approved values see:
60// http://www.iana.org/assignments/sctp-parameters/sctp-parameters.xml
61// The value is not used by SCTP itself. It indicates the protocol running
62// on top of SCTP.
63enum PayloadProtocolIdentifier {
64 PPID_NONE = 0, // No protocol is specified.
65 // Matches the PPIDs in mozilla source and
66 // https://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-protocol Sec. 9
67 // They're not yet assigned by IANA.
68 PPID_CONTROL = 50,
69 PPID_BINARY_PARTIAL = 52,
70 PPID_BINARY_LAST = 53,
71 PPID_TEXT_PARTIAL = 54,
72 PPID_TEXT_LAST = 51
73};
74
75typedef std::set<uint32_t> StreamSet;
76
77// Returns a comma-separated, human-readable list of the stream IDs in 's'
78std::string ListStreams(const StreamSet& s) {
79 std::stringstream result;
80 bool first = true;
81 for (StreamSet::const_iterator it = s.begin(); it != s.end(); ++it) {
82 if (!first) {
83 result << ", " << *it;
84 } else {
85 result << *it;
86 first = false;
87 }
88 }
89 return result.str();
90}
91
92// Returns a pipe-separated, human-readable list of the SCTP_STREAM_RESET
93// flags in 'flags'
94std::string ListFlags(int flags) {
95 std::stringstream result;
96 bool first = true;
97// Skip past the first 12 chars (strlen("SCTP_STREAM_"))
98#define MAKEFLAG(X) \
99 { X, #X + 12 }
100 struct flaginfo_t {
101 int value;
102 const char* name;
103 } flaginfo[] = {MAKEFLAG(SCTP_STREAM_RESET_INCOMING_SSN),
104 MAKEFLAG(SCTP_STREAM_RESET_OUTGOING_SSN),
105 MAKEFLAG(SCTP_STREAM_RESET_DENIED),
106 MAKEFLAG(SCTP_STREAM_RESET_FAILED),
107 MAKEFLAG(SCTP_STREAM_CHANGE_DENIED)};
108#undef MAKEFLAG
109 for (uint32_t i = 0; i < arraysize(flaginfo); ++i) {
110 if (flags & flaginfo[i].value) {
111 if (!first)
112 result << " | ";
113 result << flaginfo[i].name;
114 first = false;
115 }
116 }
117 return result.str();
118}
119
120// Returns a comma-separated, human-readable list of the integers in 'array'.
121// All 'num_elems' of them.
122std::string ListArray(const uint16_t* array, int num_elems) {
123 std::stringstream result;
124 for (int i = 0; i < num_elems; ++i) {
125 if (i) {
126 result << ", " << array[i];
127 } else {
128 result << array[i];
129 }
130 }
131 return result.str();
132}
133
134// Helper for logging SCTP messages.
135void DebugSctpPrintf(const char* format, ...) {
136#if RTC_DCHECK_IS_ON
137 char s[255];
138 va_list ap;
139 va_start(ap, format);
140 vsnprintf(s, sizeof(s), format, ap);
141 LOG(LS_INFO) << "SCTP: " << s;
142 va_end(ap);
143#endif
144}
145
146// Get the PPID to use for the terminating fragment of this type.
147PayloadProtocolIdentifier GetPpid(cricket::DataMessageType type) {
148 switch (type) {
149 default:
150 case cricket::DMT_NONE:
151 return PPID_NONE;
152 case cricket::DMT_CONTROL:
153 return PPID_CONTROL;
154 case cricket::DMT_BINARY:
155 return PPID_BINARY_LAST;
156 case cricket::DMT_TEXT:
157 return PPID_TEXT_LAST;
158 }
159}
160
161bool GetDataMediaType(PayloadProtocolIdentifier ppid,
162 cricket::DataMessageType* dest) {
163 RTC_DCHECK(dest != NULL);
164 switch (ppid) {
165 case PPID_BINARY_PARTIAL:
166 case PPID_BINARY_LAST:
167 *dest = cricket::DMT_BINARY;
168 return true;
169
170 case PPID_TEXT_PARTIAL:
171 case PPID_TEXT_LAST:
172 *dest = cricket::DMT_TEXT;
173 return true;
174
175 case PPID_CONTROL:
176 *dest = cricket::DMT_CONTROL;
177 return true;
178
179 case PPID_NONE:
180 *dest = cricket::DMT_NONE;
181 return true;
182
183 default:
184 return false;
185 }
186}
187
188// Log the packet in text2pcap format, if log level is at LS_VERBOSE.
189void VerboseLogPacket(const void* data, size_t length, int direction) {
190 if (LOG_CHECK_LEVEL(LS_VERBOSE) && length > 0) {
191 char* dump_buf;
192 // Some downstream project uses an older version of usrsctp that expects
193 // a non-const "void*" as first parameter when dumping the packet, so we
194 // need to cast the const away here to avoid a compiler error.
195 if ((dump_buf = usrsctp_dumppacket(const_cast<void*>(data), length,
196 direction)) != NULL) {
197 LOG(LS_VERBOSE) << dump_buf;
198 usrsctp_freedumpbuffer(dump_buf);
199 }
200 }
201}
202
203} // namespace
204
205namespace cricket {
206
207// Handles global init/deinit, and mapping from usrsctp callbacks to
208// SctpTransport calls.
209class SctpTransport::UsrSctpWrapper {
210 public:
211 static void InitializeUsrSctp() {
212 LOG(LS_INFO) << __FUNCTION__;
213 // First argument is udp_encapsulation_port, which is not releveant for our
214 // AF_CONN use of sctp.
215 usrsctp_init(0, &UsrSctpWrapper::OnSctpOutboundPacket, &DebugSctpPrintf);
216
217 // To turn on/off detailed SCTP debugging. You will also need to have the
218 // SCTP_DEBUG cpp defines flag.
219 // usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
220
221 // TODO(ldixon): Consider turning this on/off.
222 usrsctp_sysctl_set_sctp_ecn_enable(0);
223
224 // This is harmless, but we should find out when the library default
225 // changes.
226 int send_size = usrsctp_sysctl_get_sctp_sendspace();
227 if (send_size != kSendBufferSize) {
228 LOG(LS_ERROR) << "Got different send size than expected: " << send_size;
229 }
230
231 // TODO(ldixon): Consider turning this on/off.
232 // This is not needed right now (we don't do dynamic address changes):
233 // If SCTP Auto-ASCONF is enabled, the peer is informed automatically
234 // when a new address is added or removed. This feature is enabled by
235 // default.
236 // usrsctp_sysctl_set_sctp_auto_asconf(0);
237
238 // TODO(ldixon): Consider turning this on/off.
239 // Add a blackhole sysctl. Setting it to 1 results in no ABORTs
240 // being sent in response to INITs, setting it to 2 results
241 // in no ABORTs being sent for received OOTB packets.
242 // This is similar to the TCP sysctl.
243 //
244 // See: http://lakerest.net/pipermail/sctp-coders/2012-January/009438.html
245 // See: http://svnweb.freebsd.org/base?view=revision&revision=229805
246 // usrsctp_sysctl_set_sctp_blackhole(2);
247
248 // Set the number of default outgoing streams. This is the number we'll
249 // send in the SCTP INIT message.
250 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(kMaxSctpStreams);
251 }
252
253 static void UninitializeUsrSctp() {
254 LOG(LS_INFO) << __FUNCTION__;
255 // usrsctp_finish() may fail if it's called too soon after the transports
256 // are
257 // closed. Wait and try again until it succeeds for up to 3 seconds.
258 for (size_t i = 0; i < 300; ++i) {
259 if (usrsctp_finish() == 0) {
260 return;
261 }
262
263 rtc::Thread::SleepMs(10);
264 }
265 LOG(LS_ERROR) << "Failed to shutdown usrsctp.";
266 }
267
268 static void IncrementUsrSctpUsageCount() {
269 rtc::GlobalLockScope lock(&g_usrsctp_lock_);
270 if (!g_usrsctp_usage_count) {
271 InitializeUsrSctp();
272 }
273 ++g_usrsctp_usage_count;
274 }
275
276 static void DecrementUsrSctpUsageCount() {
277 rtc::GlobalLockScope lock(&g_usrsctp_lock_);
278 --g_usrsctp_usage_count;
279 if (!g_usrsctp_usage_count) {
280 UninitializeUsrSctp();
281 }
282 }
283
284 // This is the callback usrsctp uses when there's data to send on the network
285 // that has been wrapped appropriatly for the SCTP protocol.
286 static int OnSctpOutboundPacket(void* addr,
287 void* data,
288 size_t length,
289 uint8_t tos,
290 uint8_t set_df) {
291 SctpTransport* transport = static_cast<SctpTransport*>(addr);
292 LOG(LS_VERBOSE) << "global OnSctpOutboundPacket():"
293 << "addr: " << addr << "; length: " << length
294 << "; tos: " << std::hex << static_cast<int>(tos)
295 << "; set_df: " << std::hex << static_cast<int>(set_df);
296
297 VerboseLogPacket(data, length, SCTP_DUMP_OUTBOUND);
298 // Note: We have to copy the data; the caller will delete it.
299 rtc::CopyOnWriteBuffer buf(reinterpret_cast<uint8_t*>(data), length);
300 // TODO(deadbeef): Why do we need an AsyncInvoke here? We're already on the
301 // right thread and don't need to unwind the stack.
302 transport->invoker_.AsyncInvoke<void>(
303 RTC_FROM_HERE, transport->network_thread_,
304 rtc::Bind(&SctpTransport::OnPacketFromSctpToNetwork, transport, buf));
305 return 0;
306 }
307
308 // This is the callback called from usrsctp when data has been received, after
309 // a packet has been interpreted and parsed by usrsctp and found to contain
310 // payload data. It is called by a usrsctp thread. It is assumed this function
311 // will free the memory used by 'data'.
312 static int OnSctpInboundPacket(struct socket* sock,
313 union sctp_sockstore addr,
314 void* data,
315 size_t length,
316 struct sctp_rcvinfo rcv,
317 int flags,
318 void* ulp_info) {
319 SctpTransport* transport = static_cast<SctpTransport*>(ulp_info);
320 // Post data to the transport's receiver thread (copying it).
321 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
322 // memory cleanup. But this does simplify code.
323 const PayloadProtocolIdentifier ppid =
324 static_cast<PayloadProtocolIdentifier>(
325 rtc::HostToNetwork32(rcv.rcv_ppid));
326 DataMessageType type = DMT_NONE;
327 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
328 // It's neither a notification nor a recognized data packet. Drop it.
329 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
330 << " on an SCTP packet. Dropping.";
331 } else {
332 rtc::CopyOnWriteBuffer buffer;
333 ReceiveDataParams params;
334 buffer.SetData(reinterpret_cast<uint8_t*>(data), length);
335 params.sid = rcv.rcv_sid;
336 params.seq_num = rcv.rcv_ssn;
337 params.timestamp = rcv.rcv_tsn;
338 params.type = type;
339 // The ownership of the packet transfers to |invoker_|. Using
340 // CopyOnWriteBuffer is the most convenient way to do this.
341 transport->invoker_.AsyncInvoke<void>(
342 RTC_FROM_HERE, transport->network_thread_,
343 rtc::Bind(&SctpTransport::OnInboundPacketFromSctpToChannel, transport,
344 buffer, params, flags));
345 }
346 free(data);
347 return 1;
348 }
349
350 static SctpTransport* GetTransportFromSocket(struct socket* sock) {
351 struct sockaddr* addrs = nullptr;
352 int naddrs = usrsctp_getladdrs(sock, 0, &addrs);
353 if (naddrs <= 0 || addrs[0].sa_family != AF_CONN) {
354 return nullptr;
355 }
356 // usrsctp_getladdrs() returns the addresses bound to this socket, which
357 // contains the SctpTransport* as sconn_addr. Read the pointer,
358 // then free the list of addresses once we have the pointer. We only open
359 // AF_CONN sockets, and they should all have the sconn_addr set to the
360 // pointer that created them, so [0] is as good as any other.
361 struct sockaddr_conn* sconn =
362 reinterpret_cast<struct sockaddr_conn*>(&addrs[0]);
363 SctpTransport* transport =
364 reinterpret_cast<SctpTransport*>(sconn->sconn_addr);
365 usrsctp_freeladdrs(addrs);
366
367 return transport;
368 }
369
370 static int SendThresholdCallback(struct socket* sock, uint32_t sb_free) {
371 // Fired on our I/O thread. SctpTransport::OnPacketReceived() gets
372 // a packet containing acknowledgments, which goes into usrsctp_conninput,
373 // and then back here.
374 SctpTransport* transport = GetTransportFromSocket(sock);
375 if (!transport) {
376 LOG(LS_ERROR)
377 << "SendThresholdCallback: Failed to get transport for socket "
378 << sock;
379 return 0;
380 }
381 transport->OnSendThresholdCallback();
382 return 0;
383 }
384};
385
386SctpTransport::SctpTransport(rtc::Thread* network_thread,
deadbeef5bd5ca32017-02-10 11:31:50 -0800387 rtc::PacketTransportInternal* channel)
deadbeef953c2ce2017-01-09 14:53:41 -0800388 : network_thread_(network_thread),
389 transport_channel_(channel),
390 was_ever_writable_(channel->writable()) {
391 RTC_DCHECK(network_thread_);
392 RTC_DCHECK(transport_channel_);
393 RTC_DCHECK_RUN_ON(network_thread_);
394 ConnectTransportChannelSignals();
395}
396
397SctpTransport::~SctpTransport() {
398 // Close abruptly; no reset procedure.
399 CloseSctpSocket();
400}
401
deadbeef5bd5ca32017-02-10 11:31:50 -0800402void SctpTransport::SetTransportChannel(rtc::PacketTransportInternal* channel) {
deadbeef953c2ce2017-01-09 14:53:41 -0800403 RTC_DCHECK_RUN_ON(network_thread_);
404 RTC_DCHECK(channel);
405 DisconnectTransportChannelSignals();
406 transport_channel_ = channel;
407 ConnectTransportChannelSignals();
408 if (!was_ever_writable_ && channel->writable()) {
409 was_ever_writable_ = true;
410 // New channel is writable, now we can start the SCTP connection if Start
411 // was called already.
412 if (started_) {
413 RTC_DCHECK(!sock_);
414 Connect();
415 }
416 }
417}
418
419bool SctpTransport::Start(int local_sctp_port, int remote_sctp_port) {
420 RTC_DCHECK_RUN_ON(network_thread_);
421 if (local_sctp_port == -1) {
422 local_sctp_port = kSctpDefaultPort;
423 }
424 if (remote_sctp_port == -1) {
425 remote_sctp_port = kSctpDefaultPort;
426 }
427 if (started_) {
428 if (local_sctp_port != local_port_ || remote_sctp_port != remote_port_) {
429 LOG(LS_ERROR) << "Can't change SCTP port after SCTP association formed.";
430 return false;
431 }
432 return true;
433 }
434 local_port_ = local_sctp_port;
435 remote_port_ = remote_sctp_port;
436 started_ = true;
437 RTC_DCHECK(!sock_);
438 // Only try to connect if the DTLS channel has been writable before
439 // (indicating that the DTLS handshake is complete).
440 if (was_ever_writable_) {
441 return Connect();
442 }
443 return true;
444}
445
446bool SctpTransport::OpenStream(int sid) {
447 RTC_DCHECK_RUN_ON(network_thread_);
448 if (sid > kMaxSctpSid) {
449 LOG(LS_WARNING) << debug_name_ << "->OpenStream(...): "
450 << "Not adding data stream "
451 << "with sid=" << sid << " because sid is too high.";
452 return false;
453 } else if (open_streams_.find(sid) != open_streams_.end()) {
454 LOG(LS_WARNING) << debug_name_ << "->OpenStream(...): "
455 << "Not adding data stream "
456 << "with sid=" << sid << " because stream is already open.";
457 return false;
458 } else if (queued_reset_streams_.find(sid) != queued_reset_streams_.end() ||
459 sent_reset_streams_.find(sid) != sent_reset_streams_.end()) {
460 LOG(LS_WARNING) << debug_name_ << "->OpenStream(...): "
461 << "Not adding data stream "
462 << " with sid=" << sid
463 << " because stream is still closing.";
464 return false;
465 }
466
467 open_streams_.insert(sid);
468 return true;
469}
470
471bool SctpTransport::ResetStream(int sid) {
472 RTC_DCHECK_RUN_ON(network_thread_);
473 StreamSet::iterator found = open_streams_.find(sid);
474 if (found == open_streams_.end()) {
475 LOG(LS_WARNING) << debug_name_ << "->ResetStream(" << sid << "): "
476 << "stream not found.";
477 return false;
478 } else {
479 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << sid << "): "
480 << "Removing and queuing RE-CONFIG chunk.";
481 open_streams_.erase(found);
482 }
483
484 // SCTP won't let you have more than one stream reset pending at a time, but
485 // you can close multiple streams in a single reset. So, we keep an internal
486 // queue of streams-to-reset, and send them as one reset message in
487 // SendQueuedStreamResets().
488 queued_reset_streams_.insert(sid);
489
490 // Signal our stream-reset logic that it should try to send now, if it can.
491 SendQueuedStreamResets();
492
493 // The stream will actually get removed when we get the acknowledgment.
494 return true;
495}
496
497bool SctpTransport::SendData(const SendDataParams& params,
498 const rtc::CopyOnWriteBuffer& payload,
499 SendDataResult* result) {
500 RTC_DCHECK_RUN_ON(network_thread_);
501 if (result) {
502 // Preset |result| to assume an error. If SendData succeeds, we'll
503 // overwrite |*result| once more at the end.
504 *result = SDR_ERROR;
505 }
506
507 if (!sock_) {
508 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
509 << "Not sending packet with sid=" << params.sid
510 << " len=" << payload.size() << " before Start().";
511 return false;
512 }
513
514 if (params.type != DMT_CONTROL &&
515 open_streams_.find(params.sid) == open_streams_.end()) {
516 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
517 << "Not sending data because sid is unknown: "
518 << params.sid;
519 return false;
520 }
521
522 // Send data using SCTP.
523 ssize_t send_res = 0; // result from usrsctp_sendv.
524 struct sctp_sendv_spa spa = {0};
525 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
526 spa.sendv_sndinfo.snd_sid = params.sid;
527 spa.sendv_sndinfo.snd_ppid = rtc::HostToNetwork32(GetPpid(params.type));
528
529 // Ordered implies reliable.
530 if (!params.ordered) {
531 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
532 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
533 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
534 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
535 spa.sendv_prinfo.pr_value = params.max_rtx_count;
536 } else {
537 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
538 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
539 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
540 }
541 }
542
543 // We don't fragment.
544 send_res = usrsctp_sendv(
545 sock_, payload.data(), static_cast<size_t>(payload.size()), NULL, 0, &spa,
546 rtc::checked_cast<socklen_t>(sizeof(spa)), SCTP_SENDV_SPA, 0);
547 if (send_res < 0) {
548 if (errno == SCTP_EWOULDBLOCK) {
549 *result = SDR_BLOCK;
550 ready_to_send_data_ = false;
551 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
552 } else {
553 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_ << "->SendData(...): "
554 << " usrsctp_sendv: ";
555 }
556 return false;
557 }
558 if (result) {
559 // Only way out now is success.
560 *result = SDR_SUCCESS;
561 }
562 return true;
563}
564
565bool SctpTransport::ReadyToSendData() {
566 RTC_DCHECK_RUN_ON(network_thread_);
567 return ready_to_send_data_;
568}
569
570void SctpTransport::ConnectTransportChannelSignals() {
571 RTC_DCHECK_RUN_ON(network_thread_);
572 transport_channel_->SignalWritableState.connect(
573 this, &SctpTransport::OnWritableState);
574 transport_channel_->SignalReadPacket.connect(this,
575 &SctpTransport::OnPacketRead);
576}
577
578void SctpTransport::DisconnectTransportChannelSignals() {
579 RTC_DCHECK_RUN_ON(network_thread_);
580 transport_channel_->SignalWritableState.disconnect(this);
581 transport_channel_->SignalReadPacket.disconnect(this);
582}
583
584bool SctpTransport::Connect() {
585 RTC_DCHECK_RUN_ON(network_thread_);
586 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
587
588 // If we already have a socket connection (which shouldn't ever happen), just
589 // return.
590 RTC_DCHECK(!sock_);
591 if (sock_) {
592 LOG(LS_ERROR) << debug_name_ << "->Connect(): Ignored as socket "
593 "is already established.";
594 return true;
595 }
596
597 // If no socket (it was closed) try to start it again. This can happen when
598 // the socket we are connecting to closes, does an sctp shutdown handshake,
599 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
600 if (!OpenSctpSocket()) {
601 return false;
602 }
603
604 // Note: conversion from int to uint16_t happens on assignment.
605 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
606 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr*>(&local_sconn),
607 sizeof(local_sconn)) < 0) {
608 LOG_ERRNO(LS_ERROR) << debug_name_
609 << "->Connect(): " << ("Failed usrsctp_bind");
610 CloseSctpSocket();
611 return false;
612 }
613
614 // Note: conversion from int to uint16_t happens on assignment.
615 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
616 int connect_result = usrsctp_connect(
617 sock_, reinterpret_cast<sockaddr*>(&remote_sconn), sizeof(remote_sconn));
618 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
619 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
620 << "Failed usrsctp_connect. got errno=" << errno
621 << ", but wanted " << SCTP_EINPROGRESS;
622 CloseSctpSocket();
623 return false;
624 }
625 // Set the MTU and disable MTU discovery.
626 // We can only do this after usrsctp_connect or it has no effect.
627 sctp_paddrparams params = {{0}};
628 memcpy(&params.spp_address, &remote_sconn, sizeof(remote_sconn));
629 params.spp_flags = SPP_PMTUD_DISABLE;
630 params.spp_pathmtu = kSctpMtu;
631 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &params,
632 sizeof(params))) {
633 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
634 << "Failed to set SCTP_PEER_ADDR_PARAMS.";
635 }
636 // Since this is a fresh SCTP association, we'll always start out with empty
637 // queues, so "ReadyToSendData" should be true.
638 SetReadyToSendData();
639 return true;
640}
641
642bool SctpTransport::OpenSctpSocket() {
643 RTC_DCHECK_RUN_ON(network_thread_);
644 if (sock_) {
645 LOG(LS_WARNING) << debug_name_ << "->OpenSctpSocket(): "
646 << "Ignoring attempt to re-create existing socket.";
647 return false;
648 }
649
650 UsrSctpWrapper::IncrementUsrSctpUsageCount();
651
652 // If kSendBufferSize isn't reflective of reality, we log an error, but we
653 // still have to do something reasonable here. Look up what the buffer's
654 // real size is and set our threshold to something reasonable.
655 static const int kSendThreshold = usrsctp_sysctl_get_sctp_sendspace() / 2;
656
657 sock_ = usrsctp_socket(
658 AF_CONN, SOCK_STREAM, IPPROTO_SCTP, &UsrSctpWrapper::OnSctpInboundPacket,
659 &UsrSctpWrapper::SendThresholdCallback, kSendThreshold, this);
660 if (!sock_) {
661 LOG_ERRNO(LS_ERROR) << debug_name_ << "->OpenSctpSocket(): "
662 << "Failed to create SCTP socket.";
663 UsrSctpWrapper::DecrementUsrSctpUsageCount();
664 return false;
665 }
666
667 if (!ConfigureSctpSocket()) {
668 usrsctp_close(sock_);
669 sock_ = nullptr;
670 UsrSctpWrapper::DecrementUsrSctpUsageCount();
671 return false;
672 }
673 // Register this class as an address for usrsctp. This is used by SCTP to
674 // direct the packets received (by the created socket) to this class.
675 usrsctp_register_address(this);
676 return true;
677}
678
679bool SctpTransport::ConfigureSctpSocket() {
680 RTC_DCHECK_RUN_ON(network_thread_);
681 RTC_DCHECK(sock_);
682 // Make the socket non-blocking. Connect, close, shutdown etc will not block
683 // the thread waiting for the socket operation to complete.
684 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
685 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
686 << "Failed to set SCTP to non blocking.";
687 return false;
688 }
689
690 // This ensures that the usrsctp close call deletes the association. This
691 // prevents usrsctp from calling OnSctpOutboundPacket with references to
692 // this class as the address.
693 linger linger_opt;
694 linger_opt.l_onoff = 1;
695 linger_opt.l_linger = 0;
696 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
697 sizeof(linger_opt))) {
698 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
699 << "Failed to set SO_LINGER.";
700 return false;
701 }
702
703 // Enable stream ID resets.
704 struct sctp_assoc_value stream_rst;
705 stream_rst.assoc_id = SCTP_ALL_ASSOC;
706 stream_rst.assoc_value = 1;
707 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
708 &stream_rst, sizeof(stream_rst))) {
709 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
710
711 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
712 return false;
713 }
714
715 // Nagle.
716 uint32_t nodelay = 1;
717 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
718 sizeof(nodelay))) {
719 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
720 << "Failed to set SCTP_NODELAY.";
721 return false;
722 }
723
724 // Subscribe to SCTP event notifications.
725 int event_types[] = {SCTP_ASSOC_CHANGE, SCTP_PEER_ADDR_CHANGE,
726 SCTP_SEND_FAILED_EVENT, SCTP_SENDER_DRY_EVENT,
727 SCTP_STREAM_RESET_EVENT};
728 struct sctp_event event = {0};
729 event.se_assoc_id = SCTP_ALL_ASSOC;
730 event.se_on = 1;
731 for (size_t i = 0; i < arraysize(event_types); i++) {
732 event.se_type = event_types[i];
733 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
734 sizeof(event)) < 0) {
735 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
736
737 << "Failed to set SCTP_EVENT type: " << event.se_type;
738 return false;
739 }
740 }
741 return true;
742}
743
744void SctpTransport::CloseSctpSocket() {
745 RTC_DCHECK_RUN_ON(network_thread_);
746 if (sock_) {
747 // We assume that SO_LINGER option is set to close the association when
748 // close is called. This means that any pending packets in usrsctp will be
749 // discarded instead of being sent.
750 usrsctp_close(sock_);
751 sock_ = nullptr;
752 usrsctp_deregister_address(this);
753 UsrSctpWrapper::DecrementUsrSctpUsageCount();
754 ready_to_send_data_ = false;
755 }
756}
757
758bool SctpTransport::SendQueuedStreamResets() {
759 RTC_DCHECK_RUN_ON(network_thread_);
760 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty()) {
761 return true;
762 }
763
764 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
765 << ListStreams(queued_reset_streams_) << "], Open: ["
766 << ListStreams(open_streams_) << "], Sent: ["
767 << ListStreams(sent_reset_streams_) << "]";
768
769 const size_t num_streams = queued_reset_streams_.size();
770 const size_t num_bytes =
771 sizeof(struct sctp_reset_streams) + (num_streams * sizeof(uint16_t));
772
773 std::vector<uint8_t> reset_stream_buf(num_bytes, 0);
774 struct sctp_reset_streams* resetp =
775 reinterpret_cast<sctp_reset_streams*>(&reset_stream_buf[0]);
776 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
777 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
778 resetp->srs_number_streams = rtc::checked_cast<uint16_t>(num_streams);
779 int result_idx = 0;
780 for (StreamSet::iterator it = queued_reset_streams_.begin();
781 it != queued_reset_streams_.end(); ++it) {
782 resetp->srs_stream_list[result_idx++] = *it;
783 }
784
785 int ret =
786 usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
787 rtc::checked_cast<socklen_t>(reset_stream_buf.size()));
788 if (ret < 0) {
789 LOG_ERRNO(LS_ERROR) << debug_name_ << "->SendQueuedStreamResets(): "
790 "Failed to send a stream reset for "
791 << num_streams << " streams";
792 return false;
793 }
794
795 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
796 // it now.
797 queued_reset_streams_.swap(sent_reset_streams_);
798 return true;
799}
800
801void SctpTransport::SetReadyToSendData() {
802 RTC_DCHECK_RUN_ON(network_thread_);
803 if (!ready_to_send_data_) {
804 ready_to_send_data_ = true;
805 SignalReadyToSendData();
806 }
807}
808
deadbeef5bd5ca32017-02-10 11:31:50 -0800809void SctpTransport::OnWritableState(rtc::PacketTransportInternal* transport) {
deadbeef953c2ce2017-01-09 14:53:41 -0800810 RTC_DCHECK_RUN_ON(network_thread_);
811 RTC_DCHECK_EQ(transport_channel_, transport);
812 if (!was_ever_writable_ && transport->writable()) {
813 was_ever_writable_ = true;
814 if (started_) {
815 Connect();
816 }
817 }
818}
819
820// Called by network interface when a packet has been received.
deadbeef5bd5ca32017-02-10 11:31:50 -0800821void SctpTransport::OnPacketRead(rtc::PacketTransportInternal* transport,
deadbeef953c2ce2017-01-09 14:53:41 -0800822 const char* data,
823 size_t len,
824 const rtc::PacketTime& packet_time,
825 int flags) {
826 RTC_DCHECK_RUN_ON(network_thread_);
827 RTC_DCHECK_EQ(transport_channel_, transport);
828 TRACE_EVENT0("webrtc", "SctpTransport::OnPacketRead");
829
jbauch46d24572017-03-10 16:20:04 -0800830 if (flags & PF_SRTP_BYPASS) {
831 // We are only interested in SCTP packets.
deadbeef953c2ce2017-01-09 14:53:41 -0800832 return;
833 }
834
835 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketRead(...): "
836 << " length=" << len << ", started: " << started_;
837 // Only give receiving packets to usrsctp after if connected. This enables two
838 // peers to each make a connect call, but for them not to receive an INIT
839 // packet before they have called connect; least the last receiver of the INIT
840 // packet will have called connect, and a connection will be established.
841 if (sock_) {
842 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
843 // will be will be given to the global OnSctpInboundData, and then,
844 // marshalled by the AsyncInvoker.
845 VerboseLogPacket(data, len, SCTP_DUMP_INBOUND);
846 usrsctp_conninput(this, data, len, 0);
847 } else {
848 // TODO(ldixon): Consider caching the packet for very slightly better
849 // reliability.
850 }
851}
852
853void SctpTransport::OnSendThresholdCallback() {
854 RTC_DCHECK_RUN_ON(network_thread_);
855 SetReadyToSendData();
856}
857
858sockaddr_conn SctpTransport::GetSctpSockAddr(int port) {
859 sockaddr_conn sconn = {0};
860 sconn.sconn_family = AF_CONN;
861#ifdef HAVE_SCONN_LEN
862 sconn.sconn_len = sizeof(sockaddr_conn);
863#endif
864 // Note: conversion from int to uint16_t happens here.
865 sconn.sconn_port = rtc::HostToNetwork16(port);
866 sconn.sconn_addr = this;
867 return sconn;
868}
869
870void SctpTransport::OnPacketFromSctpToNetwork(
871 const rtc::CopyOnWriteBuffer& buffer) {
872 RTC_DCHECK_RUN_ON(network_thread_);
873 if (buffer.size() > (kSctpMtu)) {
874 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
875 << "SCTP seems to have made a packet that is bigger "
876 << "than its official MTU: " << buffer.size() << " vs max of "
877 << kSctpMtu;
878 }
879 TRACE_EVENT0("webrtc", "SctpTransport::OnPacketFromSctpToNetwork");
880
881 // Don't create noise by trying to send a packet when the DTLS channel isn't
882 // even writable.
883 if (!transport_channel_->writable()) {
884 return;
885 }
886
887 // Bon voyage.
888 transport_channel_->SendPacket(buffer.data<char>(), buffer.size(),
889 rtc::PacketOptions(), PF_NORMAL);
890}
891
892void SctpTransport::OnInboundPacketFromSctpToChannel(
893 const rtc::CopyOnWriteBuffer& buffer,
894 ReceiveDataParams params,
895 int flags) {
896 RTC_DCHECK_RUN_ON(network_thread_);
897 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
898 << "Received SCTP data:"
899 << " sid=" << params.sid
900 << " notification: " << (flags & MSG_NOTIFICATION)
901 << " length=" << buffer.size();
902 // Sending a packet with data == NULL (no data) is SCTPs "close the
903 // connection" message. This sets sock_ = NULL;
904 if (!buffer.size() || !buffer.data()) {
905 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
906 "No data, closing.";
907 return;
908 }
909 if (flags & MSG_NOTIFICATION) {
910 OnNotificationFromSctp(buffer);
911 } else {
912 OnDataFromSctpToChannel(params, buffer);
913 }
914}
915
916void SctpTransport::OnDataFromSctpToChannel(
917 const ReceiveDataParams& params,
918 const rtc::CopyOnWriteBuffer& buffer) {
919 RTC_DCHECK_RUN_ON(network_thread_);
920 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
921 << "Posting with length: " << buffer.size() << " on stream "
922 << params.sid;
923 // Reports all received messages to upper layers, no matter whether the sid
924 // is known.
925 SignalDataReceived(params, buffer);
926}
927
928void SctpTransport::OnNotificationFromSctp(
929 const rtc::CopyOnWriteBuffer& buffer) {
930 RTC_DCHECK_RUN_ON(network_thread_);
931 const sctp_notification& notification =
932 reinterpret_cast<const sctp_notification&>(*buffer.data());
933 RTC_DCHECK(notification.sn_header.sn_length == buffer.size());
934
935 // TODO(ldixon): handle notifications appropriately.
936 switch (notification.sn_header.sn_type) {
937 case SCTP_ASSOC_CHANGE:
938 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
939 OnNotificationAssocChange(notification.sn_assoc_change);
940 break;
941 case SCTP_REMOTE_ERROR:
942 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
943 break;
944 case SCTP_SHUTDOWN_EVENT:
945 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
946 break;
947 case SCTP_ADAPTATION_INDICATION:
948 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
949 break;
950 case SCTP_PARTIAL_DELIVERY_EVENT:
951 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
952 break;
953 case SCTP_AUTHENTICATION_EVENT:
954 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
955 break;
956 case SCTP_SENDER_DRY_EVENT:
957 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
958 SetReadyToSendData();
959 break;
960 // TODO(ldixon): Unblock after congestion.
961 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
962 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
963 break;
964 case SCTP_SEND_FAILED_EVENT:
965 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
966 break;
967 case SCTP_STREAM_RESET_EVENT:
968 OnStreamResetEvent(&notification.sn_strreset_event);
969 break;
970 case SCTP_ASSOC_RESET_EVENT:
971 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
972 break;
973 case SCTP_STREAM_CHANGE_EVENT:
974 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
975 // An acknowledgment we get after our stream resets have gone through,
976 // if they've failed. We log the message, but don't react -- we don't
977 // keep around the last-transmitted set of SSIDs we wanted to close for
978 // error recovery. It doesn't seem likely to occur, and if so, likely
979 // harmless within the lifetime of a single SCTP association.
980 break;
981 default:
982 LOG(LS_WARNING) << "Unknown SCTP event: "
983 << notification.sn_header.sn_type;
984 break;
985 }
986}
987
988void SctpTransport::OnNotificationAssocChange(const sctp_assoc_change& change) {
989 RTC_DCHECK_RUN_ON(network_thread_);
990 switch (change.sac_state) {
991 case SCTP_COMM_UP:
992 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
993 break;
994 case SCTP_COMM_LOST:
995 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
996 break;
997 case SCTP_RESTART:
998 LOG(LS_INFO) << "Association change SCTP_RESTART";
999 break;
1000 case SCTP_SHUTDOWN_COMP:
1001 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
1002 break;
1003 case SCTP_CANT_STR_ASSOC:
1004 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
1005 break;
1006 default:
1007 LOG(LS_INFO) << "Association change UNKNOWN";
1008 break;
1009 }
1010}
1011
1012void SctpTransport::OnStreamResetEvent(
1013 const struct sctp_stream_reset_event* evt) {
1014 RTC_DCHECK_RUN_ON(network_thread_);
1015 // A stream reset always involves two RE-CONFIG chunks for us -- we always
1016 // simultaneously reset a sid's sequence number in both directions. The
1017 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
1018 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
1019 // RE-CONFIGs.
1020 const int num_sids = (evt->strreset_length - sizeof(*evt)) /
1021 sizeof(evt->strreset_stream_list[0]);
1022 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1023 << "): Flags = 0x" << std::hex << evt->strreset_flags << " ("
1024 << ListFlags(evt->strreset_flags) << ")";
1025 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
1026 << ListArray(evt->strreset_stream_list, num_sids)
1027 << "], Open: [" << ListStreams(open_streams_) << "], Q'd: ["
1028 << ListStreams(queued_reset_streams_) << "], Sent: ["
1029 << ListStreams(sent_reset_streams_) << "]";
1030
1031 // If both sides try to reset some streams at the same time (even if they're
1032 // disjoint sets), we can get reset failures.
1033 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
1034 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
1035 // is set seem to be garbage values. Ignore them.
1036 queued_reset_streams_.insert(sent_reset_streams_.begin(),
1037 sent_reset_streams_.end());
1038 sent_reset_streams_.clear();
1039
1040 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
1041 // Each side gets an event for each direction of a stream. That is,
1042 // closing sid k will make each side receive INCOMING and OUTGOING reset
1043 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
1044 // get an INCOMING event first.
1045 for (int i = 0; i < num_sids; i++) {
1046 const int stream_id = evt->strreset_stream_list[i];
1047
1048 // See if this stream ID was closed by our peer or ourselves.
1049 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
1050
1051 // The reset was requested locally.
1052 if (it != sent_reset_streams_.end()) {
1053 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1054 << "): local sid " << stream_id << " acknowledged.";
1055 sent_reset_streams_.erase(it);
1056
1057 } else if ((it = open_streams_.find(stream_id)) != open_streams_.end()) {
1058 // The peer requested the reset.
1059 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1060 << "): closing sid " << stream_id;
1061 open_streams_.erase(it);
1062 SignalStreamClosedRemotely(stream_id);
1063
1064 } else if ((it = queued_reset_streams_.find(stream_id)) !=
1065 queued_reset_streams_.end()) {
1066 // The peer requested the reset, but there was a local reset
1067 // queued.
1068 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1069 << "): double-sided close for sid " << stream_id;
1070 // Both sides want the stream closed, and the peer got to send the
1071 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
1072 // finished quickly.
1073 queued_reset_streams_.erase(it);
1074
1075 } else {
1076 // This stream is unknown. Sometimes this can be from an
1077 // RESET_FAILED-related retransmit.
1078 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1079 << "): Unknown sid " << stream_id;
1080 }
1081 }
1082 }
1083
1084 // Always try to send the queued RESET because this call indicates that the
1085 // last local RESET or remote RESET has made some progress.
1086 SendQueuedStreamResets();
1087}
1088
1089} // namespace cricket