blob: 9ba75682ffef1dbd2f0bdbc89bcc21fa3b71241b [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellander1afca732016-02-07 20:46:45 -08002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellander1afca732016-02-07 20:46:45 -08004 * 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.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
kjellandera96e2d72016-02-04 23:52:28 -080011#include "webrtc/media/sctp/sctpdataengine.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
henrike@webrtc.org28e20752013-07-10 00:45:36 +000013#include <stdarg.h>
14#include <stdio.h>
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000015#include <sstream>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000016#include <vector>
17
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018#include "usrsctplib/usrsctp.h"
tfarina5237aaf2015-11-10 23:44:30 -080019#include "webrtc/base/arraysize.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000020#include "webrtc/base/buffer.h"
21#include "webrtc/base/helpers.h"
22#include "webrtc/base/logging.h"
23#include "webrtc/base/safe_conversions.h"
kjellandera96e2d72016-02-04 23:52:28 -080024#include "webrtc/media/base/codec.h"
25#include "webrtc/media/base/constants.h"
26#include "webrtc/media/base/streamparams.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000027
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000028namespace {
29typedef cricket::SctpDataMediaChannel::StreamSet StreamSet;
30// Returns a comma-separated, human-readable list of the stream IDs in 's'
31std::string ListStreams(const StreamSet& s) {
32 std::stringstream result;
33 bool first = true;
wu@webrtc.orge00265e2014-01-07 19:32:40 +000034 for (StreamSet::const_iterator it = s.begin(); it != s.end(); ++it) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000035 if (!first) {
36 result << ", " << *it;
37 } else {
38 result << *it;
39 first = false;
40 }
41 }
42 return result.str();
43}
44
45// Returns a pipe-separated, human-readable list of the SCTP_STREAM_RESET
46// flags in 'flags'
47std::string ListFlags(int flags) {
48 std::stringstream result;
49 bool first = true;
50 // Skip past the first 12 chars (strlen("SCTP_STREAM_"))
51#define MAKEFLAG(X) { X, #X + 12}
52 struct flaginfo_t {
53 int value;
54 const char* name;
55 } flaginfo[] = {
56 MAKEFLAG(SCTP_STREAM_RESET_INCOMING_SSN),
57 MAKEFLAG(SCTP_STREAM_RESET_OUTGOING_SSN),
58 MAKEFLAG(SCTP_STREAM_RESET_DENIED),
59 MAKEFLAG(SCTP_STREAM_RESET_FAILED),
60 MAKEFLAG(SCTP_STREAM_CHANGE_DENIED)
61 };
62#undef MAKEFLAG
kjellandera96e2d72016-02-04 23:52:28 -080063 for (uint32_t i = 0; i < arraysize(flaginfo); ++i) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000064 if (flags & flaginfo[i].value) {
65 if (!first) result << " | ";
66 result << flaginfo[i].name;
67 first = false;
68 }
69 }
70 return result.str();
71}
72
73// Returns a comma-separated, human-readable list of the integers in 'array'.
74// All 'num_elems' of them.
Peter Boström0c4e06b2015-10-07 12:23:21 +020075std::string ListArray(const uint16_t* array, int num_elems) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000076 std::stringstream result;
77 for (int i = 0; i < num_elems; ++i) {
78 if (i) {
79 result << ", " << array[i];
80 } else {
81 result << array[i];
82 }
83 }
84 return result.str();
85}
86} // namespace
87
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088namespace cricket {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000089typedef rtc::ScopedMessageData<SctpInboundPacket> InboundPacketMessage;
90typedef rtc::ScopedMessageData<rtc::Buffer> OutboundPacketMessage;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091
buildbot@webrtc.org624a5042014-08-05 22:13:05 +000092// The biggest SCTP packet. Starting from a 'safe' wire MTU value of 1280,
93// take off 80 bytes for DTLS/TURN/TCP/IP overhead.
94static const size_t kSctpMtu = 1200;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Lally Singhe8386d22015-08-28 14:54:37 -040096// The size of the SCTP association send buffer. 256kB, the usrsctp default.
97static const int kSendBufferSize = 262144;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098enum {
99 MSG_SCTPINBOUNDPACKET = 1, // MessageData is SctpInboundPacket
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000100 MSG_SCTPOUTBOUNDPACKET = 2, // MessageData is rtc:Buffer
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101};
102
103struct SctpInboundPacket {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000104 rtc::Buffer buffer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 ReceiveDataParams params;
106 // The |flags| parameter is used by SCTP to distinguish notification packets
107 // from other types of packets.
108 int flags;
109};
110
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000111// Helper for logging SCTP messages.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112static void debug_sctp_printf(const char *format, ...) {
113 char s[255];
114 va_list ap;
115 va_start(ap, format);
116 vsnprintf(s, sizeof(s), format, ap);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000117 LOG(LS_INFO) << "SCTP: " << s;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 va_end(ap);
119}
120
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000121// Get the PPID to use for the terminating fragment of this type.
122static SctpDataMediaChannel::PayloadProtocolIdentifier GetPpid(
123 cricket::DataMessageType type) {
124 switch (type) {
125 default:
126 case cricket::DMT_NONE:
127 return SctpDataMediaChannel::PPID_NONE;
128 case cricket::DMT_CONTROL:
129 return SctpDataMediaChannel::PPID_CONTROL;
130 case cricket::DMT_BINARY:
131 return SctpDataMediaChannel::PPID_BINARY_LAST;
132 case cricket::DMT_TEXT:
133 return SctpDataMediaChannel::PPID_TEXT_LAST;
134 };
135}
136
137static bool GetDataMediaType(
138 SctpDataMediaChannel::PayloadProtocolIdentifier ppid,
139 cricket::DataMessageType *dest) {
140 ASSERT(dest != NULL);
141 switch (ppid) {
142 case SctpDataMediaChannel::PPID_BINARY_PARTIAL:
143 case SctpDataMediaChannel::PPID_BINARY_LAST:
144 *dest = cricket::DMT_BINARY;
145 return true;
146
147 case SctpDataMediaChannel::PPID_TEXT_PARTIAL:
148 case SctpDataMediaChannel::PPID_TEXT_LAST:
149 *dest = cricket::DMT_TEXT;
150 return true;
151
152 case SctpDataMediaChannel::PPID_CONTROL:
153 *dest = cricket::DMT_CONTROL;
154 return true;
155
156 case SctpDataMediaChannel::PPID_NONE:
157 *dest = cricket::DMT_NONE;
158 return true;
159
160 default:
161 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000162 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000163}
164
Lally Singh4c277bb2015-05-08 14:39:04 -0400165// Log the packet in text2pcap format, if log level is at LS_VERBOSE.
Lally Singhe8386d22015-08-28 14:54:37 -0400166static void VerboseLogPacket(void *data, size_t length, int direction) {
Lally Singh4c277bb2015-05-08 14:39:04 -0400167 if (LOG_CHECK_LEVEL(LS_VERBOSE) && length > 0) {
168 char *dump_buf;
169 if ((dump_buf = usrsctp_dumppacket(
Lally Singhe8386d22015-08-28 14:54:37 -0400170 data, length, direction)) != NULL) {
Lally Singh4c277bb2015-05-08 14:39:04 -0400171 LOG(LS_VERBOSE) << dump_buf;
172 usrsctp_freedumpbuffer(dump_buf);
173 }
174 }
175}
176
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177// This is the callback usrsctp uses when there's data to send on the network
178// that has been wrapped appropriatly for the SCTP protocol.
179static int OnSctpOutboundPacket(void* addr, void* data, size_t length,
180 uint8_t tos, uint8_t set_df) {
181 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(addr);
182 LOG(LS_VERBOSE) << "global OnSctpOutboundPacket():"
183 << "addr: " << addr << "; length: " << length
184 << "; tos: " << std::hex << static_cast<int>(tos)
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000185 << "; set_df: " << std::hex << static_cast<int>(set_df);
Lally Singh4c277bb2015-05-08 14:39:04 -0400186
187 VerboseLogPacket(addr, length, SCTP_DUMP_OUTBOUND);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188 // Note: We have to copy the data; the caller will delete it.
Karl Wiberg94784372015-04-20 14:03:07 +0200189 auto* msg = new OutboundPacketMessage(
190 new rtc::Buffer(reinterpret_cast<uint8_t*>(data), length));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000191 channel->worker_thread()->Post(channel, MSG_SCTPOUTBOUNDPACKET, msg);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000192 return 0;
193}
194
195// This is the callback called from usrsctp when data has been received, after
196// a packet has been interpreted and parsed by usrsctp and found to contain
197// payload data. It is called by a usrsctp thread. It is assumed this function
198// will free the memory used by 'data'.
199static int OnSctpInboundPacket(struct socket* sock, union sctp_sockstore addr,
200 void* data, size_t length,
201 struct sctp_rcvinfo rcv, int flags,
202 void* ulp_info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(ulp_info);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000204 // Post data to the channel's receiver thread (copying it).
205 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
206 // memory cleanup. But this does simplify code.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000207 const SctpDataMediaChannel::PayloadProtocolIdentifier ppid =
208 static_cast<SctpDataMediaChannel::PayloadProtocolIdentifier>(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000209 rtc::HostToNetwork32(rcv.rcv_ppid));
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000210 cricket::DataMessageType type = cricket::DMT_NONE;
211 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
212 // It's neither a notification nor a recognized data packet. Drop it.
213 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
214 << " on an SCTP packet. Dropping.";
215 } else {
216 SctpInboundPacket* packet = new SctpInboundPacket;
Karl Wiberg94784372015-04-20 14:03:07 +0200217 packet->buffer.SetData(reinterpret_cast<uint8_t*>(data), length);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000218 packet->params.ssrc = rcv.rcv_sid;
219 packet->params.seq_num = rcv.rcv_ssn;
220 packet->params.timestamp = rcv.rcv_tsn;
221 packet->params.type = type;
222 packet->flags = flags;
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000223 // The ownership of |packet| transfers to |msg|.
224 InboundPacketMessage* msg = new InboundPacketMessage(packet);
225 channel->worker_thread()->Post(channel, MSG_SCTPINBOUNDPACKET, msg);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000226 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000227 free(data);
228 return 1;
229}
230
231// Set the initial value of the static SCTP Data Engines reference count.
232int SctpDataEngine::usrsctp_engines_count = 0;
233
wu@webrtc.org0de29502014-02-13 19:54:28 +0000234SctpDataEngine::SctpDataEngine() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235 if (usrsctp_engines_count == 0) {
236 // First argument is udp_encapsulation_port, which is not releveant for our
237 // AF_CONN use of sctp.
238 usrsctp_init(0, cricket::OnSctpOutboundPacket, debug_sctp_printf);
239
240 // To turn on/off detailed SCTP debugging. You will also need to have the
241 // SCTP_DEBUG cpp defines flag.
242 // usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
243
244 // TODO(ldixon): Consider turning this on/off.
245 usrsctp_sysctl_set_sctp_ecn_enable(0);
246
Lally Singhe8386d22015-08-28 14:54:37 -0400247 // This is harmless, but we should find out when the library default
248 // changes.
249 int send_size = usrsctp_sysctl_get_sctp_sendspace();
250 if (send_size != kSendBufferSize) {
251 LOG(LS_ERROR) << "Got different send size than expected: " << send_size;
252 }
253
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000254 // TODO(ldixon): Consider turning this on/off.
255 // This is not needed right now (we don't do dynamic address changes):
256 // If SCTP Auto-ASCONF is enabled, the peer is informed automatically
257 // when a new address is added or removed. This feature is enabled by
258 // default.
259 // usrsctp_sysctl_set_sctp_auto_asconf(0);
260
261 // TODO(ldixon): Consider turning this on/off.
262 // Add a blackhole sysctl. Setting it to 1 results in no ABORTs
263 // being sent in response to INITs, setting it to 2 results
264 // in no ABORTs being sent for received OOTB packets.
265 // This is similar to the TCP sysctl.
266 //
267 // See: http://lakerest.net/pipermail/sctp-coders/2012-January/009438.html
268 // See: http://svnweb.freebsd.org/base?view=revision&revision=229805
269 // usrsctp_sysctl_set_sctp_blackhole(2);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000270
271 // Set the number of default outgoing streams. This is the number we'll
272 // send in the SCTP INIT message. The 'appropriate default' in the
273 // second paragraph of
274 // http://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-05#section-6.2
275 // is cricket::kMaxSctpSid.
276 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(
277 cricket::kMaxSctpSid);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000278 }
279 usrsctp_engines_count++;
280
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000281 cricket::DataCodec codec(kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, 0);
282 codec.SetParam(kCodecParamPort, kSctpDefaultPort);
283 codecs_.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000284}
285
286SctpDataEngine::~SctpDataEngine() {
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000287 usrsctp_engines_count--;
288 LOG(LS_VERBOSE) << "usrsctp_engines_count:" << usrsctp_engines_count;
289
290 if (usrsctp_engines_count == 0) {
291 // usrsctp_finish() may fail if it's called too soon after the channels are
292 // closed. Wait and try again until it succeeds for up to 3 seconds.
293 for (size_t i = 0; i < 300; ++i) {
294 if (usrsctp_finish() == 0)
295 return;
296
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000297 rtc::Thread::SleepMs(10);
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000298 }
299 LOG(LS_ERROR) << "Failed to shutdown usrsctp.";
300 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000301}
302
303DataMediaChannel* SctpDataEngine::CreateChannel(
304 DataChannelType data_channel_type) {
305 if (data_channel_type != DCT_SCTP) {
306 return NULL;
307 }
tommi73918812015-08-27 04:29:58 -0700308 return new SctpDataMediaChannel(rtc::Thread::Current());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000309}
310
Lally Singhe8386d22015-08-28 14:54:37 -0400311// static
312SctpDataMediaChannel* SctpDataEngine::GetChannelFromSocket(
313 struct socket* sock) {
314 struct sockaddr* addrs = nullptr;
315 int naddrs = usrsctp_getladdrs(sock, 0, &addrs);
316 if (naddrs <= 0 || addrs[0].sa_family != AF_CONN) {
317 return nullptr;
318 }
319 // usrsctp_getladdrs() returns the addresses bound to this socket, which
320 // contains the SctpDataMediaChannel* as sconn_addr. Read the pointer,
321 // then free the list of addresses once we have the pointer. We only open
322 // AF_CONN sockets, and they should all have the sconn_addr set to the
323 // pointer that created them, so [0] is as good as any other.
324 struct sockaddr_conn* sconn =
325 reinterpret_cast<struct sockaddr_conn*>(&addrs[0]);
326 SctpDataMediaChannel* channel =
327 reinterpret_cast<SctpDataMediaChannel*>(sconn->sconn_addr);
328 usrsctp_freeladdrs(addrs);
329
330 return channel;
331}
332
333// static
334int SctpDataEngine::SendThresholdCallback(struct socket* sock,
335 uint32_t sb_free) {
336 // Fired on our I/O thread. SctpDataMediaChannel::OnPacketReceived() gets
337 // a packet containing acknowledgments, which goes into usrsctp_conninput,
338 // and then back here.
339 SctpDataMediaChannel* channel = GetChannelFromSocket(sock);
340 if (!channel) {
341 LOG(LS_ERROR) << "SendThresholdCallback: Failed to get channel for socket "
342 << sock;
343 return 0;
344 }
345 channel->OnSendThresholdCallback();
346 return 0;
347}
348
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000349SctpDataMediaChannel::SctpDataMediaChannel(rtc::Thread* thread)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000350 : worker_thread_(thread),
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000351 local_port_(kSctpDefaultPort),
352 remote_port_(kSctpDefaultPort),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000353 sock_(NULL),
354 sending_(false),
355 receiving_(false),
356 debug_name_("SctpDataMediaChannel") {
357}
358
359SctpDataMediaChannel::~SctpDataMediaChannel() {
360 CloseSctpSocket();
361}
362
Lally Singhe8386d22015-08-28 14:54:37 -0400363void SctpDataMediaChannel::OnSendThresholdCallback() {
henrikg91d6ede2015-09-17 00:24:34 -0700364 RTC_DCHECK(rtc::Thread::Current() == worker_thread_);
Lally Singhe8386d22015-08-28 14:54:37 -0400365 SignalReadyToSend(true);
366}
367
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000368sockaddr_conn SctpDataMediaChannel::GetSctpSockAddr(int port) {
369 sockaddr_conn sconn = {0};
370 sconn.sconn_family = AF_CONN;
371#ifdef HAVE_SCONN_LEN
372 sconn.sconn_len = sizeof(sockaddr_conn);
373#endif
374 // Note: conversion from int to uint16_t happens here.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000375 sconn.sconn_port = rtc::HostToNetwork16(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000376 sconn.sconn_addr = this;
377 return sconn;
378}
379
380bool SctpDataMediaChannel::OpenSctpSocket() {
381 if (sock_) {
382 LOG(LS_VERBOSE) << debug_name_
383 << "->Ignoring attempt to re-create existing socket.";
384 return false;
385 }
Lally Singhe8386d22015-08-28 14:54:37 -0400386
387 // If kSendBufferSize isn't reflective of reality, we log an error, but we
388 // still have to do something reasonable here. Look up what the buffer's
389 // real size is and set our threshold to something reasonable.
390 const static int kSendThreshold = usrsctp_sysctl_get_sctp_sendspace() / 2;
391
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000392 sock_ = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP,
Lally Singhe8386d22015-08-28 14:54:37 -0400393 cricket::OnSctpInboundPacket,
394 &SctpDataEngine::SendThresholdCallback,
395 kSendThreshold, this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000396 if (!sock_) {
397 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to create SCTP socket.";
398 return false;
399 }
400
401 // Make the socket non-blocking. Connect, close, shutdown etc will not block
402 // the thread waiting for the socket operation to complete.
403 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
404 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP to non blocking.";
405 return false;
406 }
407
408 // This ensures that the usrsctp close call deletes the association. This
409 // prevents usrsctp from calling OnSctpOutboundPacket with references to
410 // this class as the address.
411 linger linger_opt;
412 linger_opt.l_onoff = 1;
413 linger_opt.l_linger = 0;
414 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
415 sizeof(linger_opt))) {
416 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SO_LINGER.";
417 return false;
418 }
419
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000420 // Enable stream ID resets.
421 struct sctp_assoc_value stream_rst;
422 stream_rst.assoc_id = SCTP_ALL_ASSOC;
423 stream_rst.assoc_value = 1;
424 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
425 &stream_rst, sizeof(stream_rst))) {
426 LOG_ERRNO(LS_ERROR) << debug_name_
427 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
428 return false;
429 }
430
431 // Nagle.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000432 uint32_t nodelay = 1;
433 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
434 sizeof(nodelay))) {
435 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_NODELAY.";
436 return false;
437 }
438
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000439 // Disable MTU discovery
Lally Singhe8386d22015-08-28 14:54:37 -0400440 sctp_paddrparams params = {{0}};
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000441 params.spp_assoc_id = 0;
442 params.spp_flags = SPP_PMTUD_DISABLE;
443 params.spp_pathmtu = kSctpMtu;
444 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &params,
445 sizeof(params))) {
446 LOG_ERRNO(LS_ERROR) << debug_name_
447 << "Failed to set SCTP_PEER_ADDR_PARAMS.";
448 return false;
449 }
450
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000451 // Subscribe to SCTP event notifications.
452 int event_types[] = {SCTP_ASSOC_CHANGE,
453 SCTP_PEER_ADDR_CHANGE,
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000454 SCTP_SEND_FAILED_EVENT,
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000455 SCTP_SENDER_DRY_EVENT,
456 SCTP_STREAM_RESET_EVENT};
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000457 struct sctp_event event = {0};
458 event.se_assoc_id = SCTP_ALL_ASSOC;
459 event.se_on = 1;
tfarina5237aaf2015-11-10 23:44:30 -0800460 for (size_t i = 0; i < arraysize(event_types); i++) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000461 event.se_type = event_types[i];
462 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
463 sizeof(event)) < 0) {
464 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_EVENT type: "
465 << event.se_type;
466 return false;
467 }
468 }
469
470 // Register this class as an address for usrsctp. This is used by SCTP to
471 // direct the packets received (by the created socket) to this class.
472 usrsctp_register_address(this);
473 sending_ = true;
474 return true;
475}
476
477void SctpDataMediaChannel::CloseSctpSocket() {
478 sending_ = false;
479 if (sock_) {
480 // We assume that SO_LINGER option is set to close the association when
481 // close is called. This means that any pending packets in usrsctp will be
482 // discarded instead of being sent.
483 usrsctp_close(sock_);
484 sock_ = NULL;
485 usrsctp_deregister_address(this);
486 }
487}
488
489bool SctpDataMediaChannel::Connect() {
490 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
491
492 // If we already have a socket connection, just return.
493 if (sock_) {
494 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
495 "is already established.";
496 return true;
497 }
498
499 // If no socket (it was closed) try to start it again. This can happen when
500 // the socket we are connecting to closes, does an sctp shutdown handshake,
501 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
502 if (!sock_ && !OpenSctpSocket()) {
503 return false;
504 }
505
506 // Note: conversion from int to uint16_t happens on assignment.
507 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
508 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
509 sizeof(local_sconn)) < 0) {
510 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
511 << ("Failed usrsctp_bind");
512 CloseSctpSocket();
513 return false;
514 }
515
516 // Note: conversion from int to uint16_t happens on assignment.
517 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
518 int connect_result = usrsctp_connect(
519 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000520 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
521 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
522 << errno << ", but wanted " << SCTP_EINPROGRESS;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000523 CloseSctpSocket();
524 return false;
525 }
526 return true;
527}
528
529void SctpDataMediaChannel::Disconnect() {
530 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
531 // shutdown handshake and remove the association.
532 CloseSctpSocket();
533}
534
535bool SctpDataMediaChannel::SetSend(bool send) {
536 if (!sending_ && send) {
537 return Connect();
538 }
539 if (sending_ && !send) {
540 Disconnect();
541 }
542 return true;
543}
544
545bool SctpDataMediaChannel::SetReceive(bool receive) {
546 receiving_ = receive;
547 return true;
548}
549
Fredrik Solenbergb071a192015-09-17 16:42:56 +0200550bool SctpDataMediaChannel::SetSendParameters(const DataSendParameters& params) {
551 return SetSendCodecs(params.codecs);
552}
553
554bool SctpDataMediaChannel::SetRecvParameters(const DataRecvParameters& params) {
555 return SetRecvCodecs(params.codecs);
556}
557
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000558bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000559 return AddStream(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000560}
561
Peter Boström0c4e06b2015-10-07 12:23:21 +0200562bool SctpDataMediaChannel::RemoveSendStream(uint32_t ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000563 return ResetStream(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000564}
565
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000566bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000567 // SCTP DataChannels are always bi-directional and calling AddSendStream will
568 // enable both sending and receiving on the stream. So AddRecvStream is a
569 // no-op.
570 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000571}
572
Peter Boström0c4e06b2015-10-07 12:23:21 +0200573bool SctpDataMediaChannel::RemoveRecvStream(uint32_t ssrc) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000574 // SCTP DataChannels are always bi-directional and calling RemoveSendStream
575 // will disable both sending and receiving on the stream. So RemoveRecvStream
576 // is a no-op.
577 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000578}
579
580bool SctpDataMediaChannel::SendData(
581 const SendDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000582 const rtc::Buffer& payload,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000583 SendDataResult* result) {
584 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000585 // Preset |result| to assume an error. If SendData succeeds, we'll
586 // overwrite |*result| once more at the end.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587 *result = SDR_ERROR;
588 }
589
590 if (!sending_) {
591 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
592 << "Not sending packet with ssrc=" << params.ssrc
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000593 << " len=" << payload.size() << " before SetSend(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000594 return false;
595 }
596
wu@webrtc.org91053e72013-08-10 07:18:04 +0000597 if (params.type != cricket::DMT_CONTROL &&
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000598 open_streams_.find(params.ssrc) == open_streams_.end()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
600 << "Not sending data because ssrc is unknown: "
601 << params.ssrc;
602 return false;
603 }
604
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605 //
606 // Send data using SCTP.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000607 ssize_t send_res = 0; // result from usrsctp_sendv.
608 struct sctp_sendv_spa spa = {0};
609 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
610 spa.sendv_sndinfo.snd_sid = params.ssrc;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000611 spa.sendv_sndinfo.snd_ppid = rtc::HostToNetwork32(
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000612 GetPpid(params.type));
613
614 // Ordered implies reliable.
615 if (!params.ordered) {
616 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
617 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
618 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
619 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
620 spa.sendv_prinfo.pr_value = params.max_rtx_count;
621 } else {
622 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
623 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
624 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
625 }
626 }
627
628 // We don't fragment.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000629 send_res = usrsctp_sendv(
630 sock_, payload.data(), static_cast<size_t>(payload.size()), NULL, 0, &spa,
631 rtc::checked_cast<socklen_t>(sizeof(spa)), SCTP_SENDV_SPA, 0);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000632 if (send_res < 0) {
jiayl@webrtc.orgf7026cd2014-05-08 16:02:23 +0000633 if (errno == SCTP_EWOULDBLOCK) {
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000634 *result = SDR_BLOCK;
635 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
636 } else {
637 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
638 << "->SendData(...): "
639 << " usrsctp_sendv: ";
640 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641 return false;
642 }
643 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000644 // Only way out now is success.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000645 *result = SDR_SUCCESS;
646 }
647 return true;
648}
649
650// Called by network interface when a packet has been received.
wu@webrtc.orga9890802013-12-13 00:21:03 +0000651void SctpDataMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000652 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -0700653 RTC_DCHECK(rtc::Thread::Current() == worker_thread_);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000654 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): "
655 << " length=" << packet->size() << ", sending: " << sending_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000656 // Only give receiving packets to usrsctp after if connected. This enables two
657 // peers to each make a connect call, but for them not to receive an INIT
658 // packet before they have called connect; least the last receiver of the INIT
659 // packet will have called connect, and a connection will be established.
660 if (sending_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000661 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
662 // will be will be given to the global OnSctpInboundData, and then,
663 // marshalled by a Post and handled with OnMessage.
Lally Singh4c277bb2015-05-08 14:39:04 -0400664 VerboseLogPacket(packet->data(), packet->size(), SCTP_DUMP_INBOUND);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000665 usrsctp_conninput(this, packet->data(), packet->size(), 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000666 } else {
667 // TODO(ldixon): Consider caching the packet for very slightly better
668 // reliability.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669 }
670}
671
672void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
673 SctpInboundPacket* packet) {
674 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
675 << "Received SCTP data:"
676 << " ssrc=" << packet->params.ssrc
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677 << " notification: " << (packet->flags & MSG_NOTIFICATION)
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000678 << " length=" << packet->buffer.size();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000679 // Sending a packet with data == NULL (no data) is SCTPs "close the
680 // connection" message. This sets sock_ = NULL;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000681 if (!packet->buffer.size() || !packet->buffer.data()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
683 "No data, closing.";
684 return;
685 }
686 if (packet->flags & MSG_NOTIFICATION) {
687 OnNotificationFromSctp(&packet->buffer);
688 } else {
689 OnDataFromSctpToChannel(packet->params, &packet->buffer);
690 }
691}
692
693void SctpDataMediaChannel::OnDataFromSctpToChannel(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000694 const ReceiveDataParams& params, rtc::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 if (receiving_) {
696 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000697 << "Posting with length: " << buffer->size()
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000698 << " on stream " << params.ssrc;
699 // Reports all received messages to upper layers, no matter whether the sid
700 // is known.
Karl Wiberg94784372015-04-20 14:03:07 +0200701 SignalDataReceived(params, buffer->data<char>(), buffer->size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702 } else {
703 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
704 << "Not receiving packet with sid=" << params.ssrc
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000705 << " len=" << buffer->size() << " before SetReceive(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000706 }
707}
708
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000709bool SctpDataMediaChannel::AddStream(const StreamParams& stream) {
710 if (!stream.has_ssrcs()) {
711 return false;
712 }
713
Peter Boström0c4e06b2015-10-07 12:23:21 +0200714 const uint32_t ssrc = stream.first_ssrc();
lally27ed3cc2016-01-11 10:24:33 -0800715 if (ssrc >= cricket::kMaxSctpSid) {
716 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
717 << "Not adding data stream '" << stream.id
718 << "' with ssrc=" << ssrc
719 << " because stream ssrc is too high.";
720 return false;
721 } else if (open_streams_.find(ssrc) != open_streams_.end()) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000722 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000723 << "Not adding data stream '" << stream.id
724 << "' with ssrc=" << ssrc
725 << " because stream is already open.";
726 return false;
727 } else if (queued_reset_streams_.find(ssrc) != queued_reset_streams_.end()
728 || sent_reset_streams_.find(ssrc) != sent_reset_streams_.end()) {
729 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
730 << "Not adding data stream '" << stream.id
731 << "' with ssrc=" << ssrc
732 << " because stream is still closing.";
733 return false;
734 }
735
736 open_streams_.insert(ssrc);
737 return true;
738}
739
Peter Boström0c4e06b2015-10-07 12:23:21 +0200740bool SctpDataMediaChannel::ResetStream(uint32_t ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000741 // We typically get this called twice for the same stream, once each for
742 // Send and Recv.
743 StreamSet::iterator found = open_streams_.find(ssrc);
744
745 if (found == open_streams_.end()) {
746 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
747 << "stream not found.";
748 return false;
749 } else {
750 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
751 << "Removing and queuing RE-CONFIG chunk.";
752 open_streams_.erase(found);
753 }
754
755 // SCTP won't let you have more than one stream reset pending at a time, but
756 // you can close multiple streams in a single reset. So, we keep an internal
757 // queue of streams-to-reset, and send them as one reset message in
758 // SendQueuedStreamResets().
759 queued_reset_streams_.insert(ssrc);
760
761 // Signal our stream-reset logic that it should try to send now, if it can.
762 SendQueuedStreamResets();
763
764 // The stream will actually get removed when we get the acknowledgment.
765 return true;
766}
767
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000768void SctpDataMediaChannel::OnNotificationFromSctp(rtc::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769 const sctp_notification& notification =
770 reinterpret_cast<const sctp_notification&>(*buffer->data());
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000771 ASSERT(notification.sn_header.sn_length == buffer->size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000772
773 // TODO(ldixon): handle notifications appropriately.
774 switch (notification.sn_header.sn_type) {
775 case SCTP_ASSOC_CHANGE:
776 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
777 OnNotificationAssocChange(notification.sn_assoc_change);
778 break;
779 case SCTP_REMOTE_ERROR:
780 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
781 break;
782 case SCTP_SHUTDOWN_EVENT:
783 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
784 break;
785 case SCTP_ADAPTATION_INDICATION:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000786 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000787 break;
788 case SCTP_PARTIAL_DELIVERY_EVENT:
789 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
790 break;
791 case SCTP_AUTHENTICATION_EVENT:
792 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
793 break;
794 case SCTP_SENDER_DRY_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000795 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000796 SignalReadyToSend(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000797 break;
798 // TODO(ldixon): Unblock after congestion.
799 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
800 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
801 break;
802 case SCTP_SEND_FAILED_EVENT:
803 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
804 break;
805 case SCTP_STREAM_RESET_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000806 OnStreamResetEvent(&notification.sn_strreset_event);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 break;
808 case SCTP_ASSOC_RESET_EVENT:
809 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
810 break;
811 case SCTP_STREAM_CHANGE_EVENT:
812 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000813 // An acknowledgment we get after our stream resets have gone through,
814 // if they've failed. We log the message, but don't react -- we don't
815 // keep around the last-transmitted set of SSIDs we wanted to close for
816 // error recovery. It doesn't seem likely to occur, and if so, likely
817 // harmless within the lifetime of a single SCTP association.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 break;
819 default:
820 LOG(LS_WARNING) << "Unknown SCTP event: "
821 << notification.sn_header.sn_type;
822 break;
823 }
824}
825
826void SctpDataMediaChannel::OnNotificationAssocChange(
827 const sctp_assoc_change& change) {
828 switch (change.sac_state) {
829 case SCTP_COMM_UP:
830 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
831 break;
832 case SCTP_COMM_LOST:
833 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
834 break;
835 case SCTP_RESTART:
836 LOG(LS_INFO) << "Association change SCTP_RESTART";
837 break;
838 case SCTP_SHUTDOWN_COMP:
839 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
840 break;
841 case SCTP_CANT_STR_ASSOC:
842 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
843 break;
844 default:
845 LOG(LS_INFO) << "Association change UNKNOWN";
846 break;
847 }
848}
849
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000850void SctpDataMediaChannel::OnStreamResetEvent(
851 const struct sctp_stream_reset_event* evt) {
852 // A stream reset always involves two RE-CONFIG chunks for us -- we always
853 // simultaneously reset a sid's sequence number in both directions. The
854 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
855 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
856 // RE-CONFIGs.
857 const int num_ssrcs = (evt->strreset_length - sizeof(*evt)) /
858 sizeof(evt->strreset_stream_list[0]);
859 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
860 << "): Flags = 0x"
861 << std::hex << evt->strreset_flags << " ("
862 << ListFlags(evt->strreset_flags) << ")";
863 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
864 << ListArray(evt->strreset_stream_list, num_ssrcs)
865 << "], Open: ["
866 << ListStreams(open_streams_) << "], Q'd: ["
867 << ListStreams(queued_reset_streams_) << "], Sent: ["
868 << ListStreams(sent_reset_streams_) << "]";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000869
870 // If both sides try to reset some streams at the same time (even if they're
871 // disjoint sets), we can get reset failures.
872 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
873 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
874 // is set seem to be garbage values. Ignore them.
875 queued_reset_streams_.insert(
876 sent_reset_streams_.begin(),
877 sent_reset_streams_.end());
878 sent_reset_streams_.clear();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000879
880 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
881 // Each side gets an event for each direction of a stream. That is,
882 // closing sid k will make each side receive INCOMING and OUTGOING reset
883 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
884 // get an INCOMING event first.
885 for (int i = 0; i < num_ssrcs; i++) {
886 const int stream_id = evt->strreset_stream_list[i];
887
888 // See if this stream ID was closed by our peer or ourselves.
889 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
890
891 // The reset was requested locally.
892 if (it != sent_reset_streams_.end()) {
893 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
894 << "): local sid " << stream_id << " acknowledged.";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000895 sent_reset_streams_.erase(it);
896
897 } else if ((it = open_streams_.find(stream_id))
898 != open_streams_.end()) {
899 // The peer requested the reset.
900 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
901 << "): closing sid " << stream_id;
902 open_streams_.erase(it);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +0000903 SignalStreamClosedRemotely(stream_id);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000904
905 } else if ((it = queued_reset_streams_.find(stream_id))
906 != queued_reset_streams_.end()) {
907 // The peer requested the reset, but there was a local reset
908 // queued.
909 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
910 << "): double-sided close for sid " << stream_id;
911 // Both sides want the stream closed, and the peer got to send the
912 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
913 // finished quickly.
914 queued_reset_streams_.erase(it);
915
916 } else {
917 // This stream is unknown. Sometimes this can be from an
918 // RESET_FAILED-related retransmit.
919 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
920 << "): Unknown sid " << stream_id;
921 }
922 }
923 }
924
jiayl@webrtc.org1a6c6282014-06-12 21:59:29 +0000925 // Always try to send the queued RESET because this call indicates that the
926 // last local RESET or remote RESET has made some progress.
927 SendQueuedStreamResets();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000928}
929
wu@webrtc.org78187522013-10-07 23:32:02 +0000930// Puts the specified |param| from the codec identified by |id| into |dest|
931// and returns true. Or returns false if it wasn't there, leaving |dest|
932// untouched.
933static bool GetCodecIntParameter(const std::vector<DataCodec>& codecs,
934 int id, const std::string& name,
935 const std::string& param, int* dest) {
936 std::string value;
937 Codec match_pattern;
938 match_pattern.id = id;
939 match_pattern.name = name;
940 for (size_t i = 0; i < codecs.size(); ++i) {
941 if (codecs[i].Matches(match_pattern)) {
942 if (codecs[i].GetParam(param, &value)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000943 *dest = rtc::FromString<int>(value);
wu@webrtc.org78187522013-10-07 23:32:02 +0000944 return true;
945 }
946 }
947 }
948 return false;
949}
950
951bool SctpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
952 return GetCodecIntParameter(
953 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
954 &remote_port_);
955}
956
957bool SctpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
958 return GetCodecIntParameter(
959 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
960 &local_port_);
961}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962
963void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000964 rtc::Buffer* buffer) {
Lally Singhe8386d22015-08-28 14:54:37 -0400965 // usrsctp seems to interpret the MTU we give it strangely -- it seems to
966 // give us back packets bigger than that MTU, if only by a fixed amount.
967 // This is that amount that we've observed.
968 const int kSctpOverhead = 76;
969 if (buffer->size() > (kSctpOverhead + kSctpMtu)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000971 << "SCTP seems to have made a packet that is bigger "
Lally Singhe8386d22015-08-28 14:54:37 -0400972 << "than its official MTU: " << buffer->size()
973 << " vs max of " << kSctpMtu
974 << " even after adding " << kSctpOverhead
975 << " extra SCTP overhead";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976 }
stefanc1aeaf02015-10-15 07:26:07 -0700977 MediaChannel::SendPacket(buffer, rtc::PacketOptions());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978}
979
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000980bool SctpDataMediaChannel::SendQueuedStreamResets() {
981 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty())
982 return true;
983
984 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
985 << ListStreams(queued_reset_streams_) << "], Open: ["
986 << ListStreams(open_streams_) << "], Sent: ["
987 << ListStreams(sent_reset_streams_) << "]";
988
989 const size_t num_streams = queued_reset_streams_.size();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200990 const size_t num_bytes =
991 sizeof(struct sctp_reset_streams) + (num_streams * sizeof(uint16_t));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000992
Peter Boström0c4e06b2015-10-07 12:23:21 +0200993 std::vector<uint8_t> reset_stream_buf(num_bytes, 0);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000994 struct sctp_reset_streams* resetp = reinterpret_cast<sctp_reset_streams*>(
995 &reset_stream_buf[0]);
996 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
997 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000998 resetp->srs_number_streams = rtc::checked_cast<uint16_t>(num_streams);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000999 int result_idx = 0;
1000 for (StreamSet::iterator it = queued_reset_streams_.begin();
1001 it != queued_reset_streams_.end(); ++it) {
1002 resetp->srs_stream_list[result_idx++] = *it;
1003 }
1004
jiayl@webrtc.orga576faf2014-01-29 17:45:53 +00001005 int ret = usrsctp_setsockopt(
1006 sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001007 rtc::checked_cast<socklen_t>(reset_stream_buf.size()));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001008 if (ret < 0) {
1009 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to send a stream reset for "
1010 << num_streams << " streams";
1011 return false;
1012 }
1013
1014 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
1015 // it now.
1016 queued_reset_streams_.swap(sent_reset_streams_);
1017 return true;
1018}
1019
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001020void SctpDataMediaChannel::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021 switch (msg->message_id) {
1022 case MSG_SCTPINBOUNDPACKET: {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001023 rtc::scoped_ptr<InboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001024 static_cast<InboundPacketMessage*>(msg->pdata));
1025 OnInboundPacketFromSctpToChannel(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026 break;
1027 }
1028 case MSG_SCTPOUTBOUNDPACKET: {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001029 rtc::scoped_ptr<OutboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001030 static_cast<OutboundPacketMessage*>(msg->pdata));
1031 OnPacketFromSctpToNetwork(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032 break;
1033 }
1034 }
1035}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036} // namespace cricket