blob: fa70ab16affdeb2401dbcab10e8927f94cc538c0 [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>
kwiberg686a8ef2016-02-26 03:00:35 -080015
16#include <memory>
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000017#include <sstream>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018#include <vector>
19
henrike@webrtc.org28e20752013-07-10 00:45:36 +000020#include "usrsctplib/usrsctp.h"
tfarina5237aaf2015-11-10 23:44:30 -080021#include "webrtc/base/arraysize.h"
jbaucheec21bd2016-03-20 06:15:43 -070022#include "webrtc/base/copyonwritebuffer.h"
Tommi7d013312016-05-19 19:58:38 +020023#include "webrtc/base/criticalsection.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000024#include "webrtc/base/helpers.h"
25#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080026#include "webrtc/base/safe_conversions.h"
kjellandera96e2d72016-02-04 23:52:28 -080027#include "webrtc/media/base/codec.h"
kjellanderf4752772016-03-02 05:42:30 -080028#include "webrtc/media/base/mediaconstants.h"
kjellandera96e2d72016-02-04 23:52:28 -080029#include "webrtc/media/base/streamparams.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000030
Tommi7d013312016-05-19 19:58:38 +020031namespace cricket {
32// The biggest SCTP packet. Starting from a 'safe' wire MTU value of 1280,
33// take off 80 bytes for DTLS/TURN/TCP/IP overhead.
34static const size_t kSctpMtu = 1200;
35
36// The size of the SCTP association send buffer. 256kB, the usrsctp default.
37static const int kSendBufferSize = 262144;
38
39struct SctpInboundPacket {
40 rtc::CopyOnWriteBuffer buffer;
41 ReceiveDataParams params;
42 // The |flags| parameter is used by SCTP to distinguish notification packets
43 // from other types of packets.
44 int flags;
45};
46
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000047namespace {
Tommi7d013312016-05-19 19:58:38 +020048// Set the initial value of the static SCTP Data Engines reference count.
49int g_usrsctp_usage_count = 0;
50rtc::GlobalLockPod g_usrsctp_lock_;
51
52typedef SctpDataMediaChannel::StreamSet StreamSet;
53
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000054// Returns a comma-separated, human-readable list of the stream IDs in 's'
55std::string ListStreams(const StreamSet& s) {
56 std::stringstream result;
57 bool first = true;
wu@webrtc.orge00265e2014-01-07 19:32:40 +000058 for (StreamSet::const_iterator it = s.begin(); it != s.end(); ++it) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000059 if (!first) {
60 result << ", " << *it;
61 } else {
62 result << *it;
63 first = false;
64 }
65 }
66 return result.str();
67}
68
69// Returns a pipe-separated, human-readable list of the SCTP_STREAM_RESET
70// flags in 'flags'
71std::string ListFlags(int flags) {
72 std::stringstream result;
73 bool first = true;
74 // Skip past the first 12 chars (strlen("SCTP_STREAM_"))
75#define MAKEFLAG(X) { X, #X + 12}
76 struct flaginfo_t {
77 int value;
78 const char* name;
79 } flaginfo[] = {
80 MAKEFLAG(SCTP_STREAM_RESET_INCOMING_SSN),
81 MAKEFLAG(SCTP_STREAM_RESET_OUTGOING_SSN),
82 MAKEFLAG(SCTP_STREAM_RESET_DENIED),
83 MAKEFLAG(SCTP_STREAM_RESET_FAILED),
84 MAKEFLAG(SCTP_STREAM_CHANGE_DENIED)
85 };
86#undef MAKEFLAG
kjellandera96e2d72016-02-04 23:52:28 -080087 for (uint32_t i = 0; i < arraysize(flaginfo); ++i) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000088 if (flags & flaginfo[i].value) {
89 if (!first) result << " | ";
90 result << flaginfo[i].name;
91 first = false;
92 }
93 }
94 return result.str();
95}
96
97// Returns a comma-separated, human-readable list of the integers in 'array'.
98// All 'num_elems' of them.
Peter Boström0c4e06b2015-10-07 12:23:21 +020099std::string ListArray(const uint16_t* array, int num_elems) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000100 std::stringstream result;
101 for (int i = 0; i < num_elems; ++i) {
102 if (i) {
103 result << ", " << array[i];
104 } else {
105 result << array[i];
106 }
107 }
108 return result.str();
109}
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111typedef rtc::ScopedMessageData<SctpInboundPacket> InboundPacketMessage;
jbaucheec21bd2016-03-20 06:15:43 -0700112typedef rtc::ScopedMessageData<rtc::CopyOnWriteBuffer> OutboundPacketMessage;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000113
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
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000119// Helper for logging SCTP messages.
Tommi7d013312016-05-19 19:58:38 +0200120void DebugSctpPrintf(const char* format, ...) {
121#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122 char s[255];
123 va_list ap;
124 va_start(ap, format);
125 vsnprintf(s, sizeof(s), format, ap);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000126 LOG(LS_INFO) << "SCTP: " << s;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000127 va_end(ap);
Tommi7d013312016-05-19 19:58:38 +0200128#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000129}
130
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000131// Get the PPID to use for the terminating fragment of this type.
Tommi7d013312016-05-19 19:58:38 +0200132SctpDataMediaChannel::PayloadProtocolIdentifier GetPpid(DataMessageType type) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000133 switch (type) {
134 default:
Tommi7d013312016-05-19 19:58:38 +0200135 case DMT_NONE:
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000136 return SctpDataMediaChannel::PPID_NONE;
Tommi7d013312016-05-19 19:58:38 +0200137 case DMT_CONTROL:
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000138 return SctpDataMediaChannel::PPID_CONTROL;
Tommi7d013312016-05-19 19:58:38 +0200139 case DMT_BINARY:
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000140 return SctpDataMediaChannel::PPID_BINARY_LAST;
Tommi7d013312016-05-19 19:58:38 +0200141 case DMT_TEXT:
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000142 return SctpDataMediaChannel::PPID_TEXT_LAST;
143 };
144}
145
Tommi7d013312016-05-19 19:58:38 +0200146bool GetDataMediaType(SctpDataMediaChannel::PayloadProtocolIdentifier ppid,
147 DataMessageType* dest) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000148 ASSERT(dest != NULL);
149 switch (ppid) {
150 case SctpDataMediaChannel::PPID_BINARY_PARTIAL:
151 case SctpDataMediaChannel::PPID_BINARY_LAST:
Tommi7d013312016-05-19 19:58:38 +0200152 *dest = DMT_BINARY;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000153 return true;
154
155 case SctpDataMediaChannel::PPID_TEXT_PARTIAL:
156 case SctpDataMediaChannel::PPID_TEXT_LAST:
Tommi7d013312016-05-19 19:58:38 +0200157 *dest = DMT_TEXT;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000158 return true;
159
160 case SctpDataMediaChannel::PPID_CONTROL:
Tommi7d013312016-05-19 19:58:38 +0200161 *dest = DMT_CONTROL;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000162 return true;
163
164 case SctpDataMediaChannel::PPID_NONE:
Tommi7d013312016-05-19 19:58:38 +0200165 *dest = DMT_NONE;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000166 return true;
167
168 default:
169 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000170 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171}
172
Lally Singh4c277bb2015-05-08 14:39:04 -0400173// Log the packet in text2pcap format, if log level is at LS_VERBOSE.
Tommi7d013312016-05-19 19:58:38 +0200174void VerboseLogPacket(const void* data, size_t length, int direction) {
Lally Singh4c277bb2015-05-08 14:39:04 -0400175 if (LOG_CHECK_LEVEL(LS_VERBOSE) && length > 0) {
176 char *dump_buf;
jbaucheec21bd2016-03-20 06:15:43 -0700177 // Some downstream project uses an older version of usrsctp that expects
178 // a non-const "void*" as first parameter when dumping the packet, so we
179 // need to cast the const away here to avoid a compiler error.
Lally Singh4c277bb2015-05-08 14:39:04 -0400180 if ((dump_buf = usrsctp_dumppacket(
jbaucheec21bd2016-03-20 06:15:43 -0700181 const_cast<void*>(data), length, direction)) != NULL) {
Lally Singh4c277bb2015-05-08 14:39:04 -0400182 LOG(LS_VERBOSE) << dump_buf;
183 usrsctp_freedumpbuffer(dump_buf);
184 }
185 }
186}
187
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188// This is the callback usrsctp uses when there's data to send on the network
189// that has been wrapped appropriatly for the SCTP protocol.
Tommi7d013312016-05-19 19:58:38 +0200190int OnSctpOutboundPacket(void* addr,
191 void* data,
192 size_t length,
193 uint8_t tos,
194 uint8_t set_df) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000195 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(addr);
196 LOG(LS_VERBOSE) << "global OnSctpOutboundPacket():"
197 << "addr: " << addr << "; length: " << length
198 << "; tos: " << std::hex << static_cast<int>(tos)
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000199 << "; set_df: " << std::hex << static_cast<int>(set_df);
Lally Singh4c277bb2015-05-08 14:39:04 -0400200
deadbeefe9fc75e2016-06-13 17:30:32 -0700201 VerboseLogPacket(data, length, SCTP_DUMP_OUTBOUND);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000202 // Note: We have to copy the data; the caller will delete it.
Karl Wiberg94784372015-04-20 14:03:07 +0200203 auto* msg = new OutboundPacketMessage(
jbaucheec21bd2016-03-20 06:15:43 -0700204 new rtc::CopyOnWriteBuffer(reinterpret_cast<uint8_t*>(data), length));
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700205 channel->worker_thread()->Post(RTC_FROM_HERE, channel, MSG_SCTPOUTBOUNDPACKET,
206 msg);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000207 return 0;
208}
209
210// This is the callback called from usrsctp when data has been received, after
211// a packet has been interpreted and parsed by usrsctp and found to contain
212// payload data. It is called by a usrsctp thread. It is assumed this function
213// will free the memory used by 'data'.
Tommi7d013312016-05-19 19:58:38 +0200214int OnSctpInboundPacket(struct socket* sock,
215 union sctp_sockstore addr,
216 void* data,
217 size_t length,
218 struct sctp_rcvinfo rcv,
219 int flags,
220 void* ulp_info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(ulp_info);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000222 // Post data to the channel's receiver thread (copying it).
223 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
224 // memory cleanup. But this does simplify code.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000225 const SctpDataMediaChannel::PayloadProtocolIdentifier ppid =
226 static_cast<SctpDataMediaChannel::PayloadProtocolIdentifier>(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000227 rtc::HostToNetwork32(rcv.rcv_ppid));
Tommi7d013312016-05-19 19:58:38 +0200228 DataMessageType type = DMT_NONE;
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000229 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
230 // It's neither a notification nor a recognized data packet. Drop it.
231 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
232 << " on an SCTP packet. Dropping.";
233 } else {
234 SctpInboundPacket* packet = new SctpInboundPacket;
Karl Wiberg94784372015-04-20 14:03:07 +0200235 packet->buffer.SetData(reinterpret_cast<uint8_t*>(data), length);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000236 packet->params.ssrc = rcv.rcv_sid;
237 packet->params.seq_num = rcv.rcv_ssn;
238 packet->params.timestamp = rcv.rcv_tsn;
239 packet->params.type = type;
240 packet->flags = flags;
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000241 // The ownership of |packet| transfers to |msg|.
242 InboundPacketMessage* msg = new InboundPacketMessage(packet);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700243 channel->worker_thread()->Post(RTC_FROM_HERE, channel,
244 MSG_SCTPINBOUNDPACKET, msg);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000245 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000246 free(data);
247 return 1;
248}
249
Tommi7d013312016-05-19 19:58:38 +0200250void InitializeUsrSctp() {
251 LOG(LS_INFO) << __FUNCTION__;
252 // First argument is udp_encapsulation_port, which is not releveant for our
253 // AF_CONN use of sctp.
254 usrsctp_init(0, &OnSctpOutboundPacket, &DebugSctpPrintf);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000255
Tommi7d013312016-05-19 19:58:38 +0200256 // 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);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259
Tommi7d013312016-05-19 19:58:38 +0200260 // TODO(ldixon): Consider turning this on/off.
261 usrsctp_sysctl_set_sctp_ecn_enable(0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262
Tommi7d013312016-05-19 19:58:38 +0200263 // 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 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000269
Tommi7d013312016-05-19 19:58:38 +0200270 // 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);
286
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 kMaxSctpSid.
292 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(kMaxSctpSid);
293}
294
295void UninitializeUsrSctp() {
296 LOG(LS_INFO) << __FUNCTION__;
297 // usrsctp_finish() may fail if it's called too soon after the channels are
298 // closed. Wait and try again until it succeeds for up to 3 seconds.
299 for (size_t i = 0; i < 300; ++i) {
300 if (usrsctp_finish() == 0) {
301 return;
Lally Singhe8386d22015-08-28 14:54:37 -0400302 }
303
Tommi7d013312016-05-19 19:58:38 +0200304 rtc::Thread::SleepMs(10);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000305 }
Tommi7d013312016-05-19 19:58:38 +0200306 LOG(LS_ERROR) << "Failed to shutdown usrsctp.";
307}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000308
Tommi7d013312016-05-19 19:58:38 +0200309void IncrementUsrSctpUsageCount() {
310 rtc::GlobalLockScope lock(&g_usrsctp_lock_);
311 if (!g_usrsctp_usage_count) {
312 InitializeUsrSctp();
313 }
314 ++g_usrsctp_usage_count;
315}
316
317void DecrementUsrSctpUsageCount() {
318 rtc::GlobalLockScope lock(&g_usrsctp_lock_);
319 --g_usrsctp_usage_count;
320 if (!g_usrsctp_usage_count) {
321 UninitializeUsrSctp();
322 }
323}
324
325DataCodec GetSctpDataCodec() {
326 DataCodec codec(kGoogleSctpDataCodecId, kGoogleSctpDataCodecName);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000327 codec.SetParam(kCodecParamPort, kSctpDefaultPort);
Tommi7d013312016-05-19 19:58:38 +0200328 return codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000329}
330
Tommi7d013312016-05-19 19:58:38 +0200331} // namespace
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000332
Tommi7d013312016-05-19 19:58:38 +0200333SctpDataEngine::SctpDataEngine() : codecs_(1, GetSctpDataCodec()) {}
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000334
Tommi7d013312016-05-19 19:58:38 +0200335SctpDataEngine::~SctpDataEngine() {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000336
Tommi7d013312016-05-19 19:58:38 +0200337// Called on the worker thread.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000338DataMediaChannel* SctpDataEngine::CreateChannel(
339 DataChannelType data_channel_type) {
340 if (data_channel_type != DCT_SCTP) {
341 return NULL;
342 }
tommi73918812015-08-27 04:29:58 -0700343 return new SctpDataMediaChannel(rtc::Thread::Current());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000344}
345
Lally Singhe8386d22015-08-28 14:54:37 -0400346// static
Tommi7d013312016-05-19 19:58:38 +0200347SctpDataMediaChannel* SctpDataMediaChannel::GetChannelFromSocket(
Lally Singhe8386d22015-08-28 14:54:37 -0400348 struct socket* sock) {
349 struct sockaddr* addrs = nullptr;
350 int naddrs = usrsctp_getladdrs(sock, 0, &addrs);
351 if (naddrs <= 0 || addrs[0].sa_family != AF_CONN) {
352 return nullptr;
353 }
354 // usrsctp_getladdrs() returns the addresses bound to this socket, which
355 // contains the SctpDataMediaChannel* as sconn_addr. Read the pointer,
356 // then free the list of addresses once we have the pointer. We only open
357 // AF_CONN sockets, and they should all have the sconn_addr set to the
358 // pointer that created them, so [0] is as good as any other.
359 struct sockaddr_conn* sconn =
360 reinterpret_cast<struct sockaddr_conn*>(&addrs[0]);
361 SctpDataMediaChannel* channel =
362 reinterpret_cast<SctpDataMediaChannel*>(sconn->sconn_addr);
363 usrsctp_freeladdrs(addrs);
364
365 return channel;
366}
367
368// static
Tommi7d013312016-05-19 19:58:38 +0200369int SctpDataMediaChannel::SendThresholdCallback(struct socket* sock,
370 uint32_t sb_free) {
Lally Singhe8386d22015-08-28 14:54:37 -0400371 // Fired on our I/O thread. SctpDataMediaChannel::OnPacketReceived() gets
372 // a packet containing acknowledgments, which goes into usrsctp_conninput,
373 // and then back here.
374 SctpDataMediaChannel* channel = GetChannelFromSocket(sock);
375 if (!channel) {
376 LOG(LS_ERROR) << "SendThresholdCallback: Failed to get channel for socket "
377 << sock;
378 return 0;
379 }
380 channel->OnSendThresholdCallback();
381 return 0;
382}
383
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000384SctpDataMediaChannel::SctpDataMediaChannel(rtc::Thread* thread)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000385 : worker_thread_(thread),
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000386 local_port_(kSctpDefaultPort),
387 remote_port_(kSctpDefaultPort),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388 sock_(NULL),
389 sending_(false),
390 receiving_(false),
391 debug_name_("SctpDataMediaChannel") {
392}
393
394SctpDataMediaChannel::~SctpDataMediaChannel() {
395 CloseSctpSocket();
396}
397
Lally Singhe8386d22015-08-28 14:54:37 -0400398void SctpDataMediaChannel::OnSendThresholdCallback() {
henrikg91d6ede2015-09-17 00:24:34 -0700399 RTC_DCHECK(rtc::Thread::Current() == worker_thread_);
Lally Singhe8386d22015-08-28 14:54:37 -0400400 SignalReadyToSend(true);
401}
402
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000403sockaddr_conn SctpDataMediaChannel::GetSctpSockAddr(int port) {
404 sockaddr_conn sconn = {0};
405 sconn.sconn_family = AF_CONN;
406#ifdef HAVE_SCONN_LEN
407 sconn.sconn_len = sizeof(sockaddr_conn);
408#endif
409 // Note: conversion from int to uint16_t happens here.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000410 sconn.sconn_port = rtc::HostToNetwork16(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000411 sconn.sconn_addr = this;
412 return sconn;
413}
414
415bool SctpDataMediaChannel::OpenSctpSocket() {
416 if (sock_) {
417 LOG(LS_VERBOSE) << debug_name_
418 << "->Ignoring attempt to re-create existing socket.";
419 return false;
420 }
Lally Singhe8386d22015-08-28 14:54:37 -0400421
Tommi7d013312016-05-19 19:58:38 +0200422 IncrementUsrSctpUsageCount();
423
Lally Singhe8386d22015-08-28 14:54:37 -0400424 // If kSendBufferSize isn't reflective of reality, we log an error, but we
425 // still have to do something reasonable here. Look up what the buffer's
426 // real size is and set our threshold to something reasonable.
427 const static int kSendThreshold = usrsctp_sysctl_get_sctp_sendspace() / 2;
428
Tommi7d013312016-05-19 19:58:38 +0200429 sock_ = usrsctp_socket(
430 AF_CONN, SOCK_STREAM, IPPROTO_SCTP, OnSctpInboundPacket,
431 &SctpDataMediaChannel::SendThresholdCallback, kSendThreshold, this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000432 if (!sock_) {
433 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to create SCTP socket.";
Tommi7d013312016-05-19 19:58:38 +0200434 DecrementUsrSctpUsageCount();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000435 return false;
436 }
437
438 // Make the socket non-blocking. Connect, close, shutdown etc will not block
439 // the thread waiting for the socket operation to complete.
440 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
441 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP to non blocking.";
442 return false;
443 }
444
445 // This ensures that the usrsctp close call deletes the association. This
446 // prevents usrsctp from calling OnSctpOutboundPacket with references to
447 // this class as the address.
448 linger linger_opt;
449 linger_opt.l_onoff = 1;
450 linger_opt.l_linger = 0;
451 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
452 sizeof(linger_opt))) {
453 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SO_LINGER.";
454 return false;
455 }
456
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000457 // Enable stream ID resets.
458 struct sctp_assoc_value stream_rst;
459 stream_rst.assoc_id = SCTP_ALL_ASSOC;
460 stream_rst.assoc_value = 1;
461 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
462 &stream_rst, sizeof(stream_rst))) {
463 LOG_ERRNO(LS_ERROR) << debug_name_
464 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
465 return false;
466 }
467
468 // Nagle.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000469 uint32_t nodelay = 1;
470 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
471 sizeof(nodelay))) {
472 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_NODELAY.";
473 return false;
474 }
475
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000476 // Disable MTU discovery
Lally Singhe8386d22015-08-28 14:54:37 -0400477 sctp_paddrparams params = {{0}};
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000478 params.spp_assoc_id = 0;
479 params.spp_flags = SPP_PMTUD_DISABLE;
480 params.spp_pathmtu = kSctpMtu;
481 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &params,
482 sizeof(params))) {
483 LOG_ERRNO(LS_ERROR) << debug_name_
484 << "Failed to set SCTP_PEER_ADDR_PARAMS.";
485 return false;
486 }
487
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000488 // Subscribe to SCTP event notifications.
489 int event_types[] = {SCTP_ASSOC_CHANGE,
490 SCTP_PEER_ADDR_CHANGE,
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000491 SCTP_SEND_FAILED_EVENT,
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000492 SCTP_SENDER_DRY_EVENT,
493 SCTP_STREAM_RESET_EVENT};
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000494 struct sctp_event event = {0};
495 event.se_assoc_id = SCTP_ALL_ASSOC;
496 event.se_on = 1;
tfarina5237aaf2015-11-10 23:44:30 -0800497 for (size_t i = 0; i < arraysize(event_types); i++) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000498 event.se_type = event_types[i];
499 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
500 sizeof(event)) < 0) {
501 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_EVENT type: "
502 << event.se_type;
503 return false;
504 }
505 }
506
507 // Register this class as an address for usrsctp. This is used by SCTP to
508 // direct the packets received (by the created socket) to this class.
509 usrsctp_register_address(this);
510 sending_ = true;
511 return true;
512}
513
514void SctpDataMediaChannel::CloseSctpSocket() {
515 sending_ = false;
516 if (sock_) {
517 // We assume that SO_LINGER option is set to close the association when
518 // close is called. This means that any pending packets in usrsctp will be
519 // discarded instead of being sent.
520 usrsctp_close(sock_);
521 sock_ = NULL;
522 usrsctp_deregister_address(this);
Tommi7d013312016-05-19 19:58:38 +0200523
524 DecrementUsrSctpUsageCount();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000525 }
526}
527
528bool SctpDataMediaChannel::Connect() {
529 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
530
531 // If we already have a socket connection, just return.
532 if (sock_) {
533 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
534 "is already established.";
535 return true;
536 }
537
538 // If no socket (it was closed) try to start it again. This can happen when
539 // the socket we are connecting to closes, does an sctp shutdown handshake,
540 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
541 if (!sock_ && !OpenSctpSocket()) {
542 return false;
543 }
544
545 // Note: conversion from int to uint16_t happens on assignment.
546 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
547 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
548 sizeof(local_sconn)) < 0) {
549 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
550 << ("Failed usrsctp_bind");
551 CloseSctpSocket();
552 return false;
553 }
554
555 // Note: conversion from int to uint16_t happens on assignment.
556 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
557 int connect_result = usrsctp_connect(
558 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000559 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
560 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
561 << errno << ", but wanted " << SCTP_EINPROGRESS;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000562 CloseSctpSocket();
563 return false;
564 }
565 return true;
566}
567
568void SctpDataMediaChannel::Disconnect() {
569 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
570 // shutdown handshake and remove the association.
571 CloseSctpSocket();
572}
573
574bool SctpDataMediaChannel::SetSend(bool send) {
575 if (!sending_ && send) {
576 return Connect();
577 }
578 if (sending_ && !send) {
579 Disconnect();
580 }
581 return true;
582}
583
584bool SctpDataMediaChannel::SetReceive(bool receive) {
585 receiving_ = receive;
586 return true;
587}
588
Fredrik Solenbergb071a192015-09-17 16:42:56 +0200589bool SctpDataMediaChannel::SetSendParameters(const DataSendParameters& params) {
590 return SetSendCodecs(params.codecs);
591}
592
593bool SctpDataMediaChannel::SetRecvParameters(const DataRecvParameters& params) {
594 return SetRecvCodecs(params.codecs);
595}
596
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000598 return AddStream(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599}
600
Peter Boström0c4e06b2015-10-07 12:23:21 +0200601bool SctpDataMediaChannel::RemoveSendStream(uint32_t ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000602 return ResetStream(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000603}
604
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000606 // SCTP DataChannels are always bi-directional and calling AddSendStream will
607 // enable both sending and receiving on the stream. So AddRecvStream is a
608 // no-op.
609 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610}
611
Peter Boström0c4e06b2015-10-07 12:23:21 +0200612bool SctpDataMediaChannel::RemoveRecvStream(uint32_t ssrc) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000613 // SCTP DataChannels are always bi-directional and calling RemoveSendStream
614 // will disable both sending and receiving on the stream. So RemoveRecvStream
615 // is a no-op.
616 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000617}
618
619bool SctpDataMediaChannel::SendData(
620 const SendDataParams& params,
jbaucheec21bd2016-03-20 06:15:43 -0700621 const rtc::CopyOnWriteBuffer& payload,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000622 SendDataResult* result) {
623 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000624 // Preset |result| to assume an error. If SendData succeeds, we'll
625 // overwrite |*result| once more at the end.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626 *result = SDR_ERROR;
627 }
628
629 if (!sending_) {
630 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
631 << "Not sending packet with ssrc=" << params.ssrc
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000632 << " len=" << payload.size() << " before SetSend(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000633 return false;
634 }
635
Tommi7d013312016-05-19 19:58:38 +0200636 if (params.type != DMT_CONTROL &&
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000637 open_streams_.find(params.ssrc) == open_streams_.end()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000638 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
639 << "Not sending data because ssrc is unknown: "
640 << params.ssrc;
641 return false;
642 }
643
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000644 //
645 // Send data using SCTP.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000646 ssize_t send_res = 0; // result from usrsctp_sendv.
647 struct sctp_sendv_spa spa = {0};
648 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
649 spa.sendv_sndinfo.snd_sid = params.ssrc;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000650 spa.sendv_sndinfo.snd_ppid = rtc::HostToNetwork32(
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000651 GetPpid(params.type));
652
653 // Ordered implies reliable.
654 if (!params.ordered) {
655 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
656 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
657 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
658 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
659 spa.sendv_prinfo.pr_value = params.max_rtx_count;
660 } else {
661 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
662 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
663 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
664 }
665 }
666
667 // We don't fragment.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000668 send_res = usrsctp_sendv(
669 sock_, payload.data(), static_cast<size_t>(payload.size()), NULL, 0, &spa,
670 rtc::checked_cast<socklen_t>(sizeof(spa)), SCTP_SENDV_SPA, 0);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000671 if (send_res < 0) {
jiayl@webrtc.orgf7026cd2014-05-08 16:02:23 +0000672 if (errno == SCTP_EWOULDBLOCK) {
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000673 *result = SDR_BLOCK;
674 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
675 } else {
676 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
677 << "->SendData(...): "
678 << " usrsctp_sendv: ";
679 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 return false;
681 }
682 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000683 // Only way out now is success.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 *result = SDR_SUCCESS;
685 }
686 return true;
687}
688
689// Called by network interface when a packet has been received.
wu@webrtc.orga9890802013-12-13 00:21:03 +0000690void SctpDataMediaChannel::OnPacketReceived(
jbaucheec21bd2016-03-20 06:15:43 -0700691 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -0700692 RTC_DCHECK(rtc::Thread::Current() == worker_thread_);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000693 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): "
694 << " length=" << packet->size() << ", sending: " << sending_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 // Only give receiving packets to usrsctp after if connected. This enables two
696 // peers to each make a connect call, but for them not to receive an INIT
697 // packet before they have called connect; least the last receiver of the INIT
698 // packet will have called connect, and a connection will be established.
699 if (sending_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000700 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
701 // will be will be given to the global OnSctpInboundData, and then,
702 // marshalled by a Post and handled with OnMessage.
jbaucheec21bd2016-03-20 06:15:43 -0700703 VerboseLogPacket(packet->cdata(), packet->size(), SCTP_DUMP_INBOUND);
704 usrsctp_conninput(this, packet->cdata(), packet->size(), 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000705 } else {
706 // TODO(ldixon): Consider caching the packet for very slightly better
707 // reliability.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708 }
709}
710
711void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
712 SctpInboundPacket* packet) {
713 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
714 << "Received SCTP data:"
715 << " ssrc=" << packet->params.ssrc
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716 << " notification: " << (packet->flags & MSG_NOTIFICATION)
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000717 << " length=" << packet->buffer.size();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718 // Sending a packet with data == NULL (no data) is SCTPs "close the
719 // connection" message. This sets sock_ = NULL;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000720 if (!packet->buffer.size() || !packet->buffer.data()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
722 "No data, closing.";
723 return;
724 }
725 if (packet->flags & MSG_NOTIFICATION) {
jbaucheec21bd2016-03-20 06:15:43 -0700726 OnNotificationFromSctp(packet->buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 } else {
jbaucheec21bd2016-03-20 06:15:43 -0700728 OnDataFromSctpToChannel(packet->params, packet->buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729 }
730}
731
732void SctpDataMediaChannel::OnDataFromSctpToChannel(
jbaucheec21bd2016-03-20 06:15:43 -0700733 const ReceiveDataParams& params, const rtc::CopyOnWriteBuffer& buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734 if (receiving_) {
735 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
jbaucheec21bd2016-03-20 06:15:43 -0700736 << "Posting with length: " << buffer.size()
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000737 << " on stream " << params.ssrc;
738 // Reports all received messages to upper layers, no matter whether the sid
739 // is known.
jbaucheec21bd2016-03-20 06:15:43 -0700740 SignalDataReceived(params, buffer.data<char>(), buffer.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741 } else {
742 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
743 << "Not receiving packet with sid=" << params.ssrc
jbaucheec21bd2016-03-20 06:15:43 -0700744 << " len=" << buffer.size() << " before SetReceive(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745 }
746}
747
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000748bool SctpDataMediaChannel::AddStream(const StreamParams& stream) {
749 if (!stream.has_ssrcs()) {
750 return false;
751 }
752
Peter Boström0c4e06b2015-10-07 12:23:21 +0200753 const uint32_t ssrc = stream.first_ssrc();
Tommi7d013312016-05-19 19:58:38 +0200754 if (ssrc >= kMaxSctpSid) {
lally27ed3cc2016-01-11 10:24:33 -0800755 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
756 << "Not adding data stream '" << stream.id
757 << "' with ssrc=" << ssrc
758 << " because stream ssrc is too high.";
759 return false;
760 } else if (open_streams_.find(ssrc) != open_streams_.end()) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000761 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000762 << "Not adding data stream '" << stream.id
763 << "' with ssrc=" << ssrc
764 << " because stream is already open.";
765 return false;
766 } else if (queued_reset_streams_.find(ssrc) != queued_reset_streams_.end()
767 || sent_reset_streams_.find(ssrc) != sent_reset_streams_.end()) {
768 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
769 << "Not adding data stream '" << stream.id
770 << "' with ssrc=" << ssrc
771 << " because stream is still closing.";
772 return false;
773 }
774
775 open_streams_.insert(ssrc);
776 return true;
777}
778
Peter Boström0c4e06b2015-10-07 12:23:21 +0200779bool SctpDataMediaChannel::ResetStream(uint32_t ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000780 // We typically get this called twice for the same stream, once each for
781 // Send and Recv.
782 StreamSet::iterator found = open_streams_.find(ssrc);
783
784 if (found == open_streams_.end()) {
785 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
786 << "stream not found.";
787 return false;
788 } else {
789 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
790 << "Removing and queuing RE-CONFIG chunk.";
791 open_streams_.erase(found);
792 }
793
794 // SCTP won't let you have more than one stream reset pending at a time, but
795 // you can close multiple streams in a single reset. So, we keep an internal
796 // queue of streams-to-reset, and send them as one reset message in
797 // SendQueuedStreamResets().
798 queued_reset_streams_.insert(ssrc);
799
800 // Signal our stream-reset logic that it should try to send now, if it can.
801 SendQueuedStreamResets();
802
803 // The stream will actually get removed when we get the acknowledgment.
804 return true;
805}
806
jbaucheec21bd2016-03-20 06:15:43 -0700807void SctpDataMediaChannel::OnNotificationFromSctp(
808 const rtc::CopyOnWriteBuffer& buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809 const sctp_notification& notification =
jbaucheec21bd2016-03-20 06:15:43 -0700810 reinterpret_cast<const sctp_notification&>(*buffer.data());
811 ASSERT(notification.sn_header.sn_length == buffer.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812
813 // TODO(ldixon): handle notifications appropriately.
814 switch (notification.sn_header.sn_type) {
815 case SCTP_ASSOC_CHANGE:
816 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
817 OnNotificationAssocChange(notification.sn_assoc_change);
818 break;
819 case SCTP_REMOTE_ERROR:
820 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
821 break;
822 case SCTP_SHUTDOWN_EVENT:
823 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
824 break;
825 case SCTP_ADAPTATION_INDICATION:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000826 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 break;
828 case SCTP_PARTIAL_DELIVERY_EVENT:
829 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
830 break;
831 case SCTP_AUTHENTICATION_EVENT:
832 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
833 break;
834 case SCTP_SENDER_DRY_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000835 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000836 SignalReadyToSend(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000837 break;
838 // TODO(ldixon): Unblock after congestion.
839 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
840 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
841 break;
842 case SCTP_SEND_FAILED_EVENT:
843 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
844 break;
845 case SCTP_STREAM_RESET_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000846 OnStreamResetEvent(&notification.sn_strreset_event);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000847 break;
848 case SCTP_ASSOC_RESET_EVENT:
849 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
850 break;
851 case SCTP_STREAM_CHANGE_EVENT:
852 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000853 // An acknowledgment we get after our stream resets have gone through,
854 // if they've failed. We log the message, but don't react -- we don't
855 // keep around the last-transmitted set of SSIDs we wanted to close for
856 // error recovery. It doesn't seem likely to occur, and if so, likely
857 // harmless within the lifetime of a single SCTP association.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000858 break;
859 default:
860 LOG(LS_WARNING) << "Unknown SCTP event: "
861 << notification.sn_header.sn_type;
862 break;
863 }
864}
865
866void SctpDataMediaChannel::OnNotificationAssocChange(
867 const sctp_assoc_change& change) {
868 switch (change.sac_state) {
869 case SCTP_COMM_UP:
870 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
871 break;
872 case SCTP_COMM_LOST:
873 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
874 break;
875 case SCTP_RESTART:
876 LOG(LS_INFO) << "Association change SCTP_RESTART";
877 break;
878 case SCTP_SHUTDOWN_COMP:
879 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
880 break;
881 case SCTP_CANT_STR_ASSOC:
882 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
883 break;
884 default:
885 LOG(LS_INFO) << "Association change UNKNOWN";
886 break;
887 }
888}
889
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000890void SctpDataMediaChannel::OnStreamResetEvent(
891 const struct sctp_stream_reset_event* evt) {
892 // A stream reset always involves two RE-CONFIG chunks for us -- we always
893 // simultaneously reset a sid's sequence number in both directions. The
894 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
895 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
896 // RE-CONFIGs.
897 const int num_ssrcs = (evt->strreset_length - sizeof(*evt)) /
898 sizeof(evt->strreset_stream_list[0]);
899 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
900 << "): Flags = 0x"
901 << std::hex << evt->strreset_flags << " ("
902 << ListFlags(evt->strreset_flags) << ")";
903 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
904 << ListArray(evt->strreset_stream_list, num_ssrcs)
905 << "], Open: ["
906 << ListStreams(open_streams_) << "], Q'd: ["
907 << ListStreams(queued_reset_streams_) << "], Sent: ["
908 << ListStreams(sent_reset_streams_) << "]";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000909
910 // If both sides try to reset some streams at the same time (even if they're
911 // disjoint sets), we can get reset failures.
912 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
913 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
914 // is set seem to be garbage values. Ignore them.
915 queued_reset_streams_.insert(
916 sent_reset_streams_.begin(),
917 sent_reset_streams_.end());
918 sent_reset_streams_.clear();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000919
920 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
921 // Each side gets an event for each direction of a stream. That is,
922 // closing sid k will make each side receive INCOMING and OUTGOING reset
923 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
924 // get an INCOMING event first.
925 for (int i = 0; i < num_ssrcs; i++) {
926 const int stream_id = evt->strreset_stream_list[i];
927
928 // See if this stream ID was closed by our peer or ourselves.
929 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
930
931 // The reset was requested locally.
932 if (it != sent_reset_streams_.end()) {
933 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
934 << "): local sid " << stream_id << " acknowledged.";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000935 sent_reset_streams_.erase(it);
936
937 } else if ((it = open_streams_.find(stream_id))
938 != open_streams_.end()) {
939 // The peer requested the reset.
940 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
941 << "): closing sid " << stream_id;
942 open_streams_.erase(it);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +0000943 SignalStreamClosedRemotely(stream_id);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000944
945 } else if ((it = queued_reset_streams_.find(stream_id))
946 != queued_reset_streams_.end()) {
947 // The peer requested the reset, but there was a local reset
948 // queued.
949 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
950 << "): double-sided close for sid " << stream_id;
951 // Both sides want the stream closed, and the peer got to send the
952 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
953 // finished quickly.
954 queued_reset_streams_.erase(it);
955
956 } else {
957 // This stream is unknown. Sometimes this can be from an
958 // RESET_FAILED-related retransmit.
959 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
960 << "): Unknown sid " << stream_id;
961 }
962 }
963 }
964
jiayl@webrtc.org1a6c6282014-06-12 21:59:29 +0000965 // Always try to send the queued RESET because this call indicates that the
966 // last local RESET or remote RESET has made some progress.
967 SendQueuedStreamResets();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000968}
969
wu@webrtc.org78187522013-10-07 23:32:02 +0000970// Puts the specified |param| from the codec identified by |id| into |dest|
971// and returns true. Or returns false if it wasn't there, leaving |dest|
972// untouched.
973static bool GetCodecIntParameter(const std::vector<DataCodec>& codecs,
974 int id, const std::string& name,
975 const std::string& param, int* dest) {
976 std::string value;
977 Codec match_pattern;
978 match_pattern.id = id;
979 match_pattern.name = name;
980 for (size_t i = 0; i < codecs.size(); ++i) {
981 if (codecs[i].Matches(match_pattern)) {
982 if (codecs[i].GetParam(param, &value)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000983 *dest = rtc::FromString<int>(value);
wu@webrtc.org78187522013-10-07 23:32:02 +0000984 return true;
985 }
986 }
987 }
988 return false;
989}
990
991bool SctpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
992 return GetCodecIntParameter(
993 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
994 &remote_port_);
995}
996
997bool SctpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
998 return GetCodecIntParameter(
999 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
1000 &local_port_);
1001}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002
1003void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
jbaucheec21bd2016-03-20 06:15:43 -07001004 rtc::CopyOnWriteBuffer* buffer) {
Lally Singhe8386d22015-08-28 14:54:37 -04001005 // usrsctp seems to interpret the MTU we give it strangely -- it seems to
1006 // give us back packets bigger than that MTU, if only by a fixed amount.
1007 // This is that amount that we've observed.
1008 const int kSctpOverhead = 76;
1009 if (buffer->size() > (kSctpOverhead + kSctpMtu)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001010 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001011 << "SCTP seems to have made a packet that is bigger "
Lally Singhe8386d22015-08-28 14:54:37 -04001012 << "than its official MTU: " << buffer->size()
1013 << " vs max of " << kSctpMtu
1014 << " even after adding " << kSctpOverhead
1015 << " extra SCTP overhead";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016 }
stefanc1aeaf02015-10-15 07:26:07 -07001017 MediaChannel::SendPacket(buffer, rtc::PacketOptions());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018}
1019
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001020bool SctpDataMediaChannel::SendQueuedStreamResets() {
Tommi7d013312016-05-19 19:58:38 +02001021 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty()) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001022 return true;
Tommi7d013312016-05-19 19:58:38 +02001023 }
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001024
1025 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
1026 << ListStreams(queued_reset_streams_) << "], Open: ["
1027 << ListStreams(open_streams_) << "], Sent: ["
1028 << ListStreams(sent_reset_streams_) << "]";
1029
1030 const size_t num_streams = queued_reset_streams_.size();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001031 const size_t num_bytes =
1032 sizeof(struct sctp_reset_streams) + (num_streams * sizeof(uint16_t));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001033
Peter Boström0c4e06b2015-10-07 12:23:21 +02001034 std::vector<uint8_t> reset_stream_buf(num_bytes, 0);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001035 struct sctp_reset_streams* resetp = reinterpret_cast<sctp_reset_streams*>(
1036 &reset_stream_buf[0]);
1037 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
1038 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001039 resetp->srs_number_streams = rtc::checked_cast<uint16_t>(num_streams);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001040 int result_idx = 0;
1041 for (StreamSet::iterator it = queued_reset_streams_.begin();
1042 it != queued_reset_streams_.end(); ++it) {
1043 resetp->srs_stream_list[result_idx++] = *it;
1044 }
1045
jiayl@webrtc.orga576faf2014-01-29 17:45:53 +00001046 int ret = usrsctp_setsockopt(
1047 sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001048 rtc::checked_cast<socklen_t>(reset_stream_buf.size()));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001049 if (ret < 0) {
1050 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to send a stream reset for "
1051 << num_streams << " streams";
1052 return false;
1053 }
1054
1055 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
1056 // it now.
1057 queued_reset_streams_.swap(sent_reset_streams_);
1058 return true;
1059}
1060
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001061void SctpDataMediaChannel::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001062 switch (msg->message_id) {
1063 case MSG_SCTPINBOUNDPACKET: {
kwiberg686a8ef2016-02-26 03:00:35 -08001064 std::unique_ptr<InboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001065 static_cast<InboundPacketMessage*>(msg->pdata));
1066 OnInboundPacketFromSctpToChannel(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 break;
1068 }
1069 case MSG_SCTPOUTBOUNDPACKET: {
kwiberg686a8ef2016-02-26 03:00:35 -08001070 std::unique_ptr<OutboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001071 static_cast<OutboundPacketMessage*>(msg->pdata));
1072 OnPacketFromSctpToNetwork(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073 break;
1074 }
1075 }
1076}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001077} // namespace cricket