blob: 1ead8e0f2ee9896d672f3e583cb30e86c42b8bbb [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00002 * libjingle
3 * Copyright 2012 Google Inc. and Robin Seggelmann
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/media/sctp/sctpdataengine.h"
29
henrike@webrtc.org28e20752013-07-10 00:45:36 +000030#include <stdarg.h>
31#include <stdio.h>
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000032#include <sstream>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000033#include <vector>
34
henrike@webrtc.org28e20752013-07-10 00:45:36 +000035#include "talk/media/base/codec.h"
36#include "talk/media/base/constants.h"
37#include "talk/media/base/streamparams.h"
38#include "usrsctplib/usrsctp.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000039#include "webrtc/base/buffer.h"
40#include "webrtc/base/helpers.h"
41#include "webrtc/base/logging.h"
42#include "webrtc/base/safe_conversions.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000044namespace {
45typedef cricket::SctpDataMediaChannel::StreamSet StreamSet;
46// Returns a comma-separated, human-readable list of the stream IDs in 's'
47std::string ListStreams(const StreamSet& s) {
48 std::stringstream result;
49 bool first = true;
wu@webrtc.orge00265e2014-01-07 19:32:40 +000050 for (StreamSet::const_iterator it = s.begin(); it != s.end(); ++it) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000051 if (!first) {
52 result << ", " << *it;
53 } else {
54 result << *it;
55 first = false;
56 }
57 }
58 return result.str();
59}
60
61// Returns a pipe-separated, human-readable list of the SCTP_STREAM_RESET
62// flags in 'flags'
63std::string ListFlags(int flags) {
64 std::stringstream result;
65 bool first = true;
66 // Skip past the first 12 chars (strlen("SCTP_STREAM_"))
67#define MAKEFLAG(X) { X, #X + 12}
68 struct flaginfo_t {
69 int value;
70 const char* name;
71 } flaginfo[] = {
72 MAKEFLAG(SCTP_STREAM_RESET_INCOMING_SSN),
73 MAKEFLAG(SCTP_STREAM_RESET_OUTGOING_SSN),
74 MAKEFLAG(SCTP_STREAM_RESET_DENIED),
75 MAKEFLAG(SCTP_STREAM_RESET_FAILED),
76 MAKEFLAG(SCTP_STREAM_CHANGE_DENIED)
77 };
78#undef MAKEFLAG
79 for (int i = 0; i < ARRAY_SIZE(flaginfo); ++i) {
80 if (flags & flaginfo[i].value) {
81 if (!first) result << " | ";
82 result << flaginfo[i].name;
83 first = false;
84 }
85 }
86 return result.str();
87}
88
89// Returns a comma-separated, human-readable list of the integers in 'array'.
90// All 'num_elems' of them.
91std::string ListArray(const uint16* array, int num_elems) {
92 std::stringstream result;
93 for (int i = 0; i < num_elems; ++i) {
94 if (i) {
95 result << ", " << array[i];
96 } else {
97 result << array[i];
98 }
99 }
100 return result.str();
101}
102} // namespace
103
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104namespace cricket {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000105typedef rtc::ScopedMessageData<SctpInboundPacket> InboundPacketMessage;
106typedef rtc::ScopedMessageData<rtc::Buffer> OutboundPacketMessage;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000108// The biggest SCTP packet. Starting from a 'safe' wire MTU value of 1280,
109// take off 80 bytes for DTLS/TURN/TCP/IP overhead.
110static const size_t kSctpMtu = 1200;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111
Lally Singhe8386d22015-08-28 14:54:37 -0400112// The size of the SCTP association send buffer. 256kB, the usrsctp default.
113static const int kSendBufferSize = 262144;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114enum {
115 MSG_SCTPINBOUNDPACKET = 1, // MessageData is SctpInboundPacket
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116 MSG_SCTPOUTBOUNDPACKET = 2, // MessageData is rtc:Buffer
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000117};
118
119struct SctpInboundPacket {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000120 rtc::Buffer buffer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000121 ReceiveDataParams params;
122 // The |flags| parameter is used by SCTP to distinguish notification packets
123 // from other types of packets.
124 int flags;
125};
126
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000127// Helper for logging SCTP messages.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000128static void debug_sctp_printf(const char *format, ...) {
129 char s[255];
130 va_list ap;
131 va_start(ap, format);
132 vsnprintf(s, sizeof(s), format, ap);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000133 LOG(LS_INFO) << "SCTP: " << s;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 va_end(ap);
135}
136
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000137// Get the PPID to use for the terminating fragment of this type.
138static SctpDataMediaChannel::PayloadProtocolIdentifier GetPpid(
139 cricket::DataMessageType type) {
140 switch (type) {
141 default:
142 case cricket::DMT_NONE:
143 return SctpDataMediaChannel::PPID_NONE;
144 case cricket::DMT_CONTROL:
145 return SctpDataMediaChannel::PPID_CONTROL;
146 case cricket::DMT_BINARY:
147 return SctpDataMediaChannel::PPID_BINARY_LAST;
148 case cricket::DMT_TEXT:
149 return SctpDataMediaChannel::PPID_TEXT_LAST;
150 };
151}
152
153static bool GetDataMediaType(
154 SctpDataMediaChannel::PayloadProtocolIdentifier ppid,
155 cricket::DataMessageType *dest) {
156 ASSERT(dest != NULL);
157 switch (ppid) {
158 case SctpDataMediaChannel::PPID_BINARY_PARTIAL:
159 case SctpDataMediaChannel::PPID_BINARY_LAST:
160 *dest = cricket::DMT_BINARY;
161 return true;
162
163 case SctpDataMediaChannel::PPID_TEXT_PARTIAL:
164 case SctpDataMediaChannel::PPID_TEXT_LAST:
165 *dest = cricket::DMT_TEXT;
166 return true;
167
168 case SctpDataMediaChannel::PPID_CONTROL:
169 *dest = cricket::DMT_CONTROL;
170 return true;
171
172 case SctpDataMediaChannel::PPID_NONE:
173 *dest = cricket::DMT_NONE;
174 return true;
175
176 default:
177 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000178 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000179}
180
Lally Singh4c277bb2015-05-08 14:39:04 -0400181// Log the packet in text2pcap format, if log level is at LS_VERBOSE.
Lally Singhe8386d22015-08-28 14:54:37 -0400182static void VerboseLogPacket(void *data, size_t length, int direction) {
Lally Singh4c277bb2015-05-08 14:39:04 -0400183 if (LOG_CHECK_LEVEL(LS_VERBOSE) && length > 0) {
184 char *dump_buf;
185 if ((dump_buf = usrsctp_dumppacket(
Lally Singhe8386d22015-08-28 14:54:37 -0400186 data, length, direction)) != NULL) {
Lally Singh4c277bb2015-05-08 14:39:04 -0400187 LOG(LS_VERBOSE) << dump_buf;
188 usrsctp_freedumpbuffer(dump_buf);
189 }
190 }
191}
192
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193// This is the callback usrsctp uses when there's data to send on the network
194// that has been wrapped appropriatly for the SCTP protocol.
195static int OnSctpOutboundPacket(void* addr, void* data, size_t length,
196 uint8_t tos, uint8_t set_df) {
197 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(addr);
198 LOG(LS_VERBOSE) << "global OnSctpOutboundPacket():"
199 << "addr: " << addr << "; length: " << length
200 << "; tos: " << std::hex << static_cast<int>(tos)
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000201 << "; set_df: " << std::hex << static_cast<int>(set_df);
Lally Singh4c277bb2015-05-08 14:39:04 -0400202
203 VerboseLogPacket(addr, length, SCTP_DUMP_OUTBOUND);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000204 // Note: We have to copy the data; the caller will delete it.
Karl Wiberg94784372015-04-20 14:03:07 +0200205 auto* msg = new OutboundPacketMessage(
206 new rtc::Buffer(reinterpret_cast<uint8_t*>(data), length));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000207 channel->worker_thread()->Post(channel, MSG_SCTPOUTBOUNDPACKET, msg);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000208 return 0;
209}
210
211// This is the callback called from usrsctp when data has been received, after
212// a packet has been interpreted and parsed by usrsctp and found to contain
213// payload data. It is called by a usrsctp thread. It is assumed this function
214// will free the memory used by 'data'.
215static int OnSctpInboundPacket(struct socket* sock, union sctp_sockstore addr,
216 void* data, size_t length,
217 struct sctp_rcvinfo rcv, int flags,
218 void* ulp_info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(ulp_info);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000220 // Post data to the channel's receiver thread (copying it).
221 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
222 // memory cleanup. But this does simplify code.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000223 const SctpDataMediaChannel::PayloadProtocolIdentifier ppid =
224 static_cast<SctpDataMediaChannel::PayloadProtocolIdentifier>(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000225 rtc::HostToNetwork32(rcv.rcv_ppid));
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000226 cricket::DataMessageType type = cricket::DMT_NONE;
227 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
228 // It's neither a notification nor a recognized data packet. Drop it.
229 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
230 << " on an SCTP packet. Dropping.";
231 } else {
232 SctpInboundPacket* packet = new SctpInboundPacket;
Karl Wiberg94784372015-04-20 14:03:07 +0200233 packet->buffer.SetData(reinterpret_cast<uint8_t*>(data), length);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000234 packet->params.ssrc = rcv.rcv_sid;
235 packet->params.seq_num = rcv.rcv_ssn;
236 packet->params.timestamp = rcv.rcv_tsn;
237 packet->params.type = type;
238 packet->flags = flags;
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000239 // The ownership of |packet| transfers to |msg|.
240 InboundPacketMessage* msg = new InboundPacketMessage(packet);
241 channel->worker_thread()->Post(channel, MSG_SCTPINBOUNDPACKET, msg);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000242 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243 free(data);
244 return 1;
245}
246
247// Set the initial value of the static SCTP Data Engines reference count.
248int SctpDataEngine::usrsctp_engines_count = 0;
249
wu@webrtc.org0de29502014-02-13 19:54:28 +0000250SctpDataEngine::SctpDataEngine() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251 if (usrsctp_engines_count == 0) {
252 // First argument is udp_encapsulation_port, which is not releveant for our
253 // AF_CONN use of sctp.
254 usrsctp_init(0, cricket::OnSctpOutboundPacket, debug_sctp_printf);
255
256 // To turn on/off detailed SCTP debugging. You will also need to have the
257 // SCTP_DEBUG cpp defines flag.
258 // usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
259
260 // TODO(ldixon): Consider turning this on/off.
261 usrsctp_sysctl_set_sctp_ecn_enable(0);
262
Lally Singhe8386d22015-08-28 14:54:37 -0400263 // This is harmless, but we should find out when the library default
264 // changes.
265 int send_size = usrsctp_sysctl_get_sctp_sendspace();
266 if (send_size != kSendBufferSize) {
267 LOG(LS_ERROR) << "Got different send size than expected: " << send_size;
268 }
269
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270 // TODO(ldixon): Consider turning this on/off.
271 // This is not needed right now (we don't do dynamic address changes):
272 // If SCTP Auto-ASCONF is enabled, the peer is informed automatically
273 // when a new address is added or removed. This feature is enabled by
274 // default.
275 // usrsctp_sysctl_set_sctp_auto_asconf(0);
276
277 // TODO(ldixon): Consider turning this on/off.
278 // Add a blackhole sysctl. Setting it to 1 results in no ABORTs
279 // being sent in response to INITs, setting it to 2 results
280 // in no ABORTs being sent for received OOTB packets.
281 // This is similar to the TCP sysctl.
282 //
283 // See: http://lakerest.net/pipermail/sctp-coders/2012-January/009438.html
284 // See: http://svnweb.freebsd.org/base?view=revision&revision=229805
285 // usrsctp_sysctl_set_sctp_blackhole(2);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000286
287 // Set the number of default outgoing streams. This is the number we'll
288 // send in the SCTP INIT message. The 'appropriate default' in the
289 // second paragraph of
290 // http://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-05#section-6.2
291 // is cricket::kMaxSctpSid.
292 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(
293 cricket::kMaxSctpSid);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000294 }
295 usrsctp_engines_count++;
296
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000297 cricket::DataCodec codec(kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, 0);
298 codec.SetParam(kCodecParamPort, kSctpDefaultPort);
299 codecs_.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000300}
301
302SctpDataEngine::~SctpDataEngine() {
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000303 usrsctp_engines_count--;
304 LOG(LS_VERBOSE) << "usrsctp_engines_count:" << usrsctp_engines_count;
305
306 if (usrsctp_engines_count == 0) {
307 // usrsctp_finish() may fail if it's called too soon after the channels are
308 // closed. Wait and try again until it succeeds for up to 3 seconds.
309 for (size_t i = 0; i < 300; ++i) {
310 if (usrsctp_finish() == 0)
311 return;
312
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000313 rtc::Thread::SleepMs(10);
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000314 }
315 LOG(LS_ERROR) << "Failed to shutdown usrsctp.";
316 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000317}
318
319DataMediaChannel* SctpDataEngine::CreateChannel(
320 DataChannelType data_channel_type) {
321 if (data_channel_type != DCT_SCTP) {
322 return NULL;
323 }
tommi73918812015-08-27 04:29:58 -0700324 return new SctpDataMediaChannel(rtc::Thread::Current());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000325}
326
Lally Singhe8386d22015-08-28 14:54:37 -0400327// static
328SctpDataMediaChannel* SctpDataEngine::GetChannelFromSocket(
329 struct socket* sock) {
330 struct sockaddr* addrs = nullptr;
331 int naddrs = usrsctp_getladdrs(sock, 0, &addrs);
332 if (naddrs <= 0 || addrs[0].sa_family != AF_CONN) {
333 return nullptr;
334 }
335 // usrsctp_getladdrs() returns the addresses bound to this socket, which
336 // contains the SctpDataMediaChannel* as sconn_addr. Read the pointer,
337 // then free the list of addresses once we have the pointer. We only open
338 // AF_CONN sockets, and they should all have the sconn_addr set to the
339 // pointer that created them, so [0] is as good as any other.
340 struct sockaddr_conn* sconn =
341 reinterpret_cast<struct sockaddr_conn*>(&addrs[0]);
342 SctpDataMediaChannel* channel =
343 reinterpret_cast<SctpDataMediaChannel*>(sconn->sconn_addr);
344 usrsctp_freeladdrs(addrs);
345
346 return channel;
347}
348
349// static
350int SctpDataEngine::SendThresholdCallback(struct socket* sock,
351 uint32_t sb_free) {
352 // Fired on our I/O thread. SctpDataMediaChannel::OnPacketReceived() gets
353 // a packet containing acknowledgments, which goes into usrsctp_conninput,
354 // and then back here.
355 SctpDataMediaChannel* channel = GetChannelFromSocket(sock);
356 if (!channel) {
357 LOG(LS_ERROR) << "SendThresholdCallback: Failed to get channel for socket "
358 << sock;
359 return 0;
360 }
361 channel->OnSendThresholdCallback();
362 return 0;
363}
364
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000365SctpDataMediaChannel::SctpDataMediaChannel(rtc::Thread* thread)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366 : worker_thread_(thread),
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000367 local_port_(kSctpDefaultPort),
368 remote_port_(kSctpDefaultPort),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000369 sock_(NULL),
370 sending_(false),
371 receiving_(false),
372 debug_name_("SctpDataMediaChannel") {
373}
374
375SctpDataMediaChannel::~SctpDataMediaChannel() {
376 CloseSctpSocket();
377}
378
Lally Singhe8386d22015-08-28 14:54:37 -0400379void SctpDataMediaChannel::OnSendThresholdCallback() {
henrikg91d6ede2015-09-17 00:24:34 -0700380 RTC_DCHECK(rtc::Thread::Current() == worker_thread_);
Lally Singhe8386d22015-08-28 14:54:37 -0400381 SignalReadyToSend(true);
382}
383
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000384sockaddr_conn SctpDataMediaChannel::GetSctpSockAddr(int port) {
385 sockaddr_conn sconn = {0};
386 sconn.sconn_family = AF_CONN;
387#ifdef HAVE_SCONN_LEN
388 sconn.sconn_len = sizeof(sockaddr_conn);
389#endif
390 // Note: conversion from int to uint16_t happens here.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000391 sconn.sconn_port = rtc::HostToNetwork16(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000392 sconn.sconn_addr = this;
393 return sconn;
394}
395
396bool SctpDataMediaChannel::OpenSctpSocket() {
397 if (sock_) {
398 LOG(LS_VERBOSE) << debug_name_
399 << "->Ignoring attempt to re-create existing socket.";
400 return false;
401 }
Lally Singhe8386d22015-08-28 14:54:37 -0400402
403 // If kSendBufferSize isn't reflective of reality, we log an error, but we
404 // still have to do something reasonable here. Look up what the buffer's
405 // real size is and set our threshold to something reasonable.
406 const static int kSendThreshold = usrsctp_sysctl_get_sctp_sendspace() / 2;
407
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000408 sock_ = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP,
Lally Singhe8386d22015-08-28 14:54:37 -0400409 cricket::OnSctpInboundPacket,
410 &SctpDataEngine::SendThresholdCallback,
411 kSendThreshold, this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000412 if (!sock_) {
413 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to create SCTP socket.";
414 return false;
415 }
416
417 // Make the socket non-blocking. Connect, close, shutdown etc will not block
418 // the thread waiting for the socket operation to complete.
419 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
420 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP to non blocking.";
421 return false;
422 }
423
424 // This ensures that the usrsctp close call deletes the association. This
425 // prevents usrsctp from calling OnSctpOutboundPacket with references to
426 // this class as the address.
427 linger linger_opt;
428 linger_opt.l_onoff = 1;
429 linger_opt.l_linger = 0;
430 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
431 sizeof(linger_opt))) {
432 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SO_LINGER.";
433 return false;
434 }
435
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000436 // Enable stream ID resets.
437 struct sctp_assoc_value stream_rst;
438 stream_rst.assoc_id = SCTP_ALL_ASSOC;
439 stream_rst.assoc_value = 1;
440 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
441 &stream_rst, sizeof(stream_rst))) {
442 LOG_ERRNO(LS_ERROR) << debug_name_
443 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
444 return false;
445 }
446
447 // Nagle.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000448 uint32_t nodelay = 1;
449 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
450 sizeof(nodelay))) {
451 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_NODELAY.";
452 return false;
453 }
454
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000455 // Disable MTU discovery
Lally Singhe8386d22015-08-28 14:54:37 -0400456 sctp_paddrparams params = {{0}};
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000457 params.spp_assoc_id = 0;
458 params.spp_flags = SPP_PMTUD_DISABLE;
459 params.spp_pathmtu = kSctpMtu;
460 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &params,
461 sizeof(params))) {
462 LOG_ERRNO(LS_ERROR) << debug_name_
463 << "Failed to set SCTP_PEER_ADDR_PARAMS.";
464 return false;
465 }
466
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000467 // Subscribe to SCTP event notifications.
468 int event_types[] = {SCTP_ASSOC_CHANGE,
469 SCTP_PEER_ADDR_CHANGE,
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000470 SCTP_SEND_FAILED_EVENT,
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000471 SCTP_SENDER_DRY_EVENT,
472 SCTP_STREAM_RESET_EVENT};
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000473 struct sctp_event event = {0};
474 event.se_assoc_id = SCTP_ALL_ASSOC;
475 event.se_on = 1;
476 for (size_t i = 0; i < ARRAY_SIZE(event_types); i++) {
477 event.se_type = event_types[i];
478 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
479 sizeof(event)) < 0) {
480 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_EVENT type: "
481 << event.se_type;
482 return false;
483 }
484 }
485
486 // Register this class as an address for usrsctp. This is used by SCTP to
487 // direct the packets received (by the created socket) to this class.
488 usrsctp_register_address(this);
489 sending_ = true;
490 return true;
491}
492
493void SctpDataMediaChannel::CloseSctpSocket() {
494 sending_ = false;
495 if (sock_) {
496 // We assume that SO_LINGER option is set to close the association when
497 // close is called. This means that any pending packets in usrsctp will be
498 // discarded instead of being sent.
499 usrsctp_close(sock_);
500 sock_ = NULL;
501 usrsctp_deregister_address(this);
502 }
503}
504
505bool SctpDataMediaChannel::Connect() {
506 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
507
508 // If we already have a socket connection, just return.
509 if (sock_) {
510 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
511 "is already established.";
512 return true;
513 }
514
515 // If no socket (it was closed) try to start it again. This can happen when
516 // the socket we are connecting to closes, does an sctp shutdown handshake,
517 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
518 if (!sock_ && !OpenSctpSocket()) {
519 return false;
520 }
521
522 // Note: conversion from int to uint16_t happens on assignment.
523 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
524 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
525 sizeof(local_sconn)) < 0) {
526 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
527 << ("Failed usrsctp_bind");
528 CloseSctpSocket();
529 return false;
530 }
531
532 // Note: conversion from int to uint16_t happens on assignment.
533 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
534 int connect_result = usrsctp_connect(
535 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000536 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
537 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
538 << errno << ", but wanted " << SCTP_EINPROGRESS;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000539 CloseSctpSocket();
540 return false;
541 }
542 return true;
543}
544
545void SctpDataMediaChannel::Disconnect() {
546 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
547 // shutdown handshake and remove the association.
548 CloseSctpSocket();
549}
550
551bool SctpDataMediaChannel::SetSend(bool send) {
552 if (!sending_ && send) {
553 return Connect();
554 }
555 if (sending_ && !send) {
556 Disconnect();
557 }
558 return true;
559}
560
561bool SctpDataMediaChannel::SetReceive(bool receive) {
562 receiving_ = receive;
563 return true;
564}
565
Fredrik Solenbergb071a192015-09-17 16:42:56 +0200566bool SctpDataMediaChannel::SetSendParameters(const DataSendParameters& params) {
567 return SetSendCodecs(params.codecs);
568}
569
570bool SctpDataMediaChannel::SetRecvParameters(const DataRecvParameters& params) {
571 return SetRecvCodecs(params.codecs);
572}
573
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000574bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000575 return AddStream(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000576}
577
578bool SctpDataMediaChannel::RemoveSendStream(uint32 ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000579 return ResetStream(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000580}
581
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000582bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000583 // SCTP DataChannels are always bi-directional and calling AddSendStream will
584 // enable both sending and receiving on the stream. So AddRecvStream is a
585 // no-op.
586 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000587}
588
589bool SctpDataMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000590 // SCTP DataChannels are always bi-directional and calling RemoveSendStream
591 // will disable both sending and receiving on the stream. So RemoveRecvStream
592 // is a no-op.
593 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000594}
595
596bool SctpDataMediaChannel::SendData(
597 const SendDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000598 const rtc::Buffer& payload,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599 SendDataResult* result) {
600 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000601 // Preset |result| to assume an error. If SendData succeeds, we'll
602 // overwrite |*result| once more at the end.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000603 *result = SDR_ERROR;
604 }
605
606 if (!sending_) {
607 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
608 << "Not sending packet with ssrc=" << params.ssrc
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000609 << " len=" << payload.size() << " before SetSend(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610 return false;
611 }
612
wu@webrtc.org91053e72013-08-10 07:18:04 +0000613 if (params.type != cricket::DMT_CONTROL &&
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000614 open_streams_.find(params.ssrc) == open_streams_.end()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000615 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
616 << "Not sending data because ssrc is unknown: "
617 << params.ssrc;
618 return false;
619 }
620
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000621 //
622 // Send data using SCTP.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000623 ssize_t send_res = 0; // result from usrsctp_sendv.
624 struct sctp_sendv_spa spa = {0};
625 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
626 spa.sendv_sndinfo.snd_sid = params.ssrc;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000627 spa.sendv_sndinfo.snd_ppid = rtc::HostToNetwork32(
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000628 GetPpid(params.type));
629
630 // Ordered implies reliable.
631 if (!params.ordered) {
632 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
633 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
634 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
635 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
636 spa.sendv_prinfo.pr_value = params.max_rtx_count;
637 } else {
638 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
639 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
640 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
641 }
642 }
643
644 // We don't fragment.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000645 send_res = usrsctp_sendv(
646 sock_, payload.data(), static_cast<size_t>(payload.size()), NULL, 0, &spa,
647 rtc::checked_cast<socklen_t>(sizeof(spa)), SCTP_SENDV_SPA, 0);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000648 if (send_res < 0) {
jiayl@webrtc.orgf7026cd2014-05-08 16:02:23 +0000649 if (errno == SCTP_EWOULDBLOCK) {
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000650 *result = SDR_BLOCK;
651 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
652 } else {
653 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
654 << "->SendData(...): "
655 << " usrsctp_sendv: ";
656 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000657 return false;
658 }
659 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000660 // Only way out now is success.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000661 *result = SDR_SUCCESS;
662 }
663 return true;
664}
665
666// Called by network interface when a packet has been received.
wu@webrtc.orga9890802013-12-13 00:21:03 +0000667void SctpDataMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000668 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -0700669 RTC_DCHECK(rtc::Thread::Current() == worker_thread_);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000670 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): "
671 << " length=" << packet->size() << ", sending: " << sending_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672 // Only give receiving packets to usrsctp after if connected. This enables two
673 // peers to each make a connect call, but for them not to receive an INIT
674 // packet before they have called connect; least the last receiver of the INIT
675 // packet will have called connect, and a connection will be established.
676 if (sending_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
678 // will be will be given to the global OnSctpInboundData, and then,
679 // marshalled by a Post and handled with OnMessage.
Lally Singh4c277bb2015-05-08 14:39:04 -0400680 VerboseLogPacket(packet->data(), packet->size(), SCTP_DUMP_INBOUND);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000681 usrsctp_conninput(this, packet->data(), packet->size(), 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 } else {
683 // TODO(ldixon): Consider caching the packet for very slightly better
684 // reliability.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 }
686}
687
688void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
689 SctpInboundPacket* packet) {
690 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
691 << "Received SCTP data:"
692 << " ssrc=" << packet->params.ssrc
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693 << " notification: " << (packet->flags & MSG_NOTIFICATION)
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000694 << " length=" << packet->buffer.size();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 // Sending a packet with data == NULL (no data) is SCTPs "close the
696 // connection" message. This sets sock_ = NULL;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000697 if (!packet->buffer.size() || !packet->buffer.data()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000698 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
699 "No data, closing.";
700 return;
701 }
702 if (packet->flags & MSG_NOTIFICATION) {
703 OnNotificationFromSctp(&packet->buffer);
704 } else {
705 OnDataFromSctpToChannel(packet->params, &packet->buffer);
706 }
707}
708
709void SctpDataMediaChannel::OnDataFromSctpToChannel(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000710 const ReceiveDataParams& params, rtc::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000711 if (receiving_) {
712 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000713 << "Posting with length: " << buffer->size()
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000714 << " on stream " << params.ssrc;
715 // Reports all received messages to upper layers, no matter whether the sid
716 // is known.
Karl Wiberg94784372015-04-20 14:03:07 +0200717 SignalDataReceived(params, buffer->data<char>(), buffer->size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718 } else {
719 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
720 << "Not receiving packet with sid=" << params.ssrc
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000721 << " len=" << buffer->size() << " before SetReceive(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 }
723}
724
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000725bool SctpDataMediaChannel::AddStream(const StreamParams& stream) {
726 if (!stream.has_ssrcs()) {
727 return false;
728 }
729
730 const uint32 ssrc = stream.first_ssrc();
731 if (open_streams_.find(ssrc) != open_streams_.end()) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000732 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000733 << "Not adding data stream '" << stream.id
734 << "' with ssrc=" << ssrc
735 << " because stream is already open.";
736 return false;
737 } else if (queued_reset_streams_.find(ssrc) != queued_reset_streams_.end()
738 || sent_reset_streams_.find(ssrc) != sent_reset_streams_.end()) {
739 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
740 << "Not adding data stream '" << stream.id
741 << "' with ssrc=" << ssrc
742 << " because stream is still closing.";
743 return false;
744 }
745
746 open_streams_.insert(ssrc);
747 return true;
748}
749
750bool SctpDataMediaChannel::ResetStream(uint32 ssrc) {
751 // We typically get this called twice for the same stream, once each for
752 // Send and Recv.
753 StreamSet::iterator found = open_streams_.find(ssrc);
754
755 if (found == open_streams_.end()) {
756 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
757 << "stream not found.";
758 return false;
759 } else {
760 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
761 << "Removing and queuing RE-CONFIG chunk.";
762 open_streams_.erase(found);
763 }
764
765 // SCTP won't let you have more than one stream reset pending at a time, but
766 // you can close multiple streams in a single reset. So, we keep an internal
767 // queue of streams-to-reset, and send them as one reset message in
768 // SendQueuedStreamResets().
769 queued_reset_streams_.insert(ssrc);
770
771 // Signal our stream-reset logic that it should try to send now, if it can.
772 SendQueuedStreamResets();
773
774 // The stream will actually get removed when we get the acknowledgment.
775 return true;
776}
777
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000778void SctpDataMediaChannel::OnNotificationFromSctp(rtc::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779 const sctp_notification& notification =
780 reinterpret_cast<const sctp_notification&>(*buffer->data());
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000781 ASSERT(notification.sn_header.sn_length == buffer->size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000782
783 // TODO(ldixon): handle notifications appropriately.
784 switch (notification.sn_header.sn_type) {
785 case SCTP_ASSOC_CHANGE:
786 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
787 OnNotificationAssocChange(notification.sn_assoc_change);
788 break;
789 case SCTP_REMOTE_ERROR:
790 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
791 break;
792 case SCTP_SHUTDOWN_EVENT:
793 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
794 break;
795 case SCTP_ADAPTATION_INDICATION:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000796 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000797 break;
798 case SCTP_PARTIAL_DELIVERY_EVENT:
799 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
800 break;
801 case SCTP_AUTHENTICATION_EVENT:
802 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
803 break;
804 case SCTP_SENDER_DRY_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000805 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000806 SignalReadyToSend(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 break;
808 // TODO(ldixon): Unblock after congestion.
809 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
810 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
811 break;
812 case SCTP_SEND_FAILED_EVENT:
813 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
814 break;
815 case SCTP_STREAM_RESET_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000816 OnStreamResetEvent(&notification.sn_strreset_event);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817 break;
818 case SCTP_ASSOC_RESET_EVENT:
819 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
820 break;
821 case SCTP_STREAM_CHANGE_EVENT:
822 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000823 // An acknowledgment we get after our stream resets have gone through,
824 // if they've failed. We log the message, but don't react -- we don't
825 // keep around the last-transmitted set of SSIDs we wanted to close for
826 // error recovery. It doesn't seem likely to occur, and if so, likely
827 // harmless within the lifetime of a single SCTP association.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828 break;
829 default:
830 LOG(LS_WARNING) << "Unknown SCTP event: "
831 << notification.sn_header.sn_type;
832 break;
833 }
834}
835
836void SctpDataMediaChannel::OnNotificationAssocChange(
837 const sctp_assoc_change& change) {
838 switch (change.sac_state) {
839 case SCTP_COMM_UP:
840 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
841 break;
842 case SCTP_COMM_LOST:
843 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
844 break;
845 case SCTP_RESTART:
846 LOG(LS_INFO) << "Association change SCTP_RESTART";
847 break;
848 case SCTP_SHUTDOWN_COMP:
849 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
850 break;
851 case SCTP_CANT_STR_ASSOC:
852 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
853 break;
854 default:
855 LOG(LS_INFO) << "Association change UNKNOWN";
856 break;
857 }
858}
859
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000860void SctpDataMediaChannel::OnStreamResetEvent(
861 const struct sctp_stream_reset_event* evt) {
862 // A stream reset always involves two RE-CONFIG chunks for us -- we always
863 // simultaneously reset a sid's sequence number in both directions. The
864 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
865 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
866 // RE-CONFIGs.
867 const int num_ssrcs = (evt->strreset_length - sizeof(*evt)) /
868 sizeof(evt->strreset_stream_list[0]);
869 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
870 << "): Flags = 0x"
871 << std::hex << evt->strreset_flags << " ("
872 << ListFlags(evt->strreset_flags) << ")";
873 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
874 << ListArray(evt->strreset_stream_list, num_ssrcs)
875 << "], Open: ["
876 << ListStreams(open_streams_) << "], Q'd: ["
877 << ListStreams(queued_reset_streams_) << "], Sent: ["
878 << ListStreams(sent_reset_streams_) << "]";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000879
880 // If both sides try to reset some streams at the same time (even if they're
881 // disjoint sets), we can get reset failures.
882 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
883 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
884 // is set seem to be garbage values. Ignore them.
885 queued_reset_streams_.insert(
886 sent_reset_streams_.begin(),
887 sent_reset_streams_.end());
888 sent_reset_streams_.clear();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000889
890 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
891 // Each side gets an event for each direction of a stream. That is,
892 // closing sid k will make each side receive INCOMING and OUTGOING reset
893 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
894 // get an INCOMING event first.
895 for (int i = 0; i < num_ssrcs; i++) {
896 const int stream_id = evt->strreset_stream_list[i];
897
898 // See if this stream ID was closed by our peer or ourselves.
899 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
900
901 // The reset was requested locally.
902 if (it != sent_reset_streams_.end()) {
903 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
904 << "): local sid " << stream_id << " acknowledged.";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000905 sent_reset_streams_.erase(it);
906
907 } else if ((it = open_streams_.find(stream_id))
908 != open_streams_.end()) {
909 // The peer requested the reset.
910 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
911 << "): closing sid " << stream_id;
912 open_streams_.erase(it);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +0000913 SignalStreamClosedRemotely(stream_id);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000914
915 } else if ((it = queued_reset_streams_.find(stream_id))
916 != queued_reset_streams_.end()) {
917 // The peer requested the reset, but there was a local reset
918 // queued.
919 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
920 << "): double-sided close for sid " << stream_id;
921 // Both sides want the stream closed, and the peer got to send the
922 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
923 // finished quickly.
924 queued_reset_streams_.erase(it);
925
926 } else {
927 // This stream is unknown. Sometimes this can be from an
928 // RESET_FAILED-related retransmit.
929 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
930 << "): Unknown sid " << stream_id;
931 }
932 }
933 }
934
jiayl@webrtc.org1a6c6282014-06-12 21:59:29 +0000935 // Always try to send the queued RESET because this call indicates that the
936 // last local RESET or remote RESET has made some progress.
937 SendQueuedStreamResets();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000938}
939
wu@webrtc.org78187522013-10-07 23:32:02 +0000940// Puts the specified |param| from the codec identified by |id| into |dest|
941// and returns true. Or returns false if it wasn't there, leaving |dest|
942// untouched.
943static bool GetCodecIntParameter(const std::vector<DataCodec>& codecs,
944 int id, const std::string& name,
945 const std::string& param, int* dest) {
946 std::string value;
947 Codec match_pattern;
948 match_pattern.id = id;
949 match_pattern.name = name;
950 for (size_t i = 0; i < codecs.size(); ++i) {
951 if (codecs[i].Matches(match_pattern)) {
952 if (codecs[i].GetParam(param, &value)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000953 *dest = rtc::FromString<int>(value);
wu@webrtc.org78187522013-10-07 23:32:02 +0000954 return true;
955 }
956 }
957 }
958 return false;
959}
960
961bool SctpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
962 return GetCodecIntParameter(
963 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
964 &remote_port_);
965}
966
967bool SctpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
968 return GetCodecIntParameter(
969 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
970 &local_port_);
971}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972
973void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000974 rtc::Buffer* buffer) {
Lally Singhe8386d22015-08-28 14:54:37 -0400975 // usrsctp seems to interpret the MTU we give it strangely -- it seems to
976 // give us back packets bigger than that MTU, if only by a fixed amount.
977 // This is that amount that we've observed.
978 const int kSctpOverhead = 76;
979 if (buffer->size() > (kSctpOverhead + kSctpMtu)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000981 << "SCTP seems to have made a packet that is bigger "
Lally Singhe8386d22015-08-28 14:54:37 -0400982 << "than its official MTU: " << buffer->size()
983 << " vs max of " << kSctpMtu
984 << " even after adding " << kSctpOverhead
985 << " extra SCTP overhead";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000986 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000987 MediaChannel::SendPacket(buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988}
989
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000990bool SctpDataMediaChannel::SendQueuedStreamResets() {
991 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty())
992 return true;
993
994 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
995 << ListStreams(queued_reset_streams_) << "], Open: ["
996 << ListStreams(open_streams_) << "], Sent: ["
997 << ListStreams(sent_reset_streams_) << "]";
998
999 const size_t num_streams = queued_reset_streams_.size();
1000 const size_t num_bytes = sizeof(struct sctp_reset_streams)
1001 + (num_streams * sizeof(uint16));
1002
1003 std::vector<uint8> reset_stream_buf(num_bytes, 0);
1004 struct sctp_reset_streams* resetp = reinterpret_cast<sctp_reset_streams*>(
1005 &reset_stream_buf[0]);
1006 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
1007 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001008 resetp->srs_number_streams = rtc::checked_cast<uint16_t>(num_streams);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001009 int result_idx = 0;
1010 for (StreamSet::iterator it = queued_reset_streams_.begin();
1011 it != queued_reset_streams_.end(); ++it) {
1012 resetp->srs_stream_list[result_idx++] = *it;
1013 }
1014
jiayl@webrtc.orga576faf2014-01-29 17:45:53 +00001015 int ret = usrsctp_setsockopt(
1016 sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001017 rtc::checked_cast<socklen_t>(reset_stream_buf.size()));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001018 if (ret < 0) {
1019 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to send a stream reset for "
1020 << num_streams << " streams";
1021 return false;
1022 }
1023
1024 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
1025 // it now.
1026 queued_reset_streams_.swap(sent_reset_streams_);
1027 return true;
1028}
1029
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001030void SctpDataMediaChannel::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031 switch (msg->message_id) {
1032 case MSG_SCTPINBOUNDPACKET: {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001033 rtc::scoped_ptr<InboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001034 static_cast<InboundPacketMessage*>(msg->pdata));
1035 OnInboundPacketFromSctpToChannel(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036 break;
1037 }
1038 case MSG_SCTPOUTBOUNDPACKET: {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001039 rtc::scoped_ptr<OutboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001040 static_cast<OutboundPacketMessage*>(msg->pdata));
1041 OnPacketFromSctpToNetwork(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042 break;
1043 }
1044 }
1045}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001046} // namespace cricket