blob: 0804fed76916017da61fcb2a427658073f109b54 [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 {
deadbeeffe8f4892016-08-24 16:26:55 -070032// The biggest SCTP packet. Starting from a 'safe' wire MTU value of 1280,
Tommi7d013312016-05-19 19:58:38 +020033// take off 80 bytes for DTLS/TURN/TCP/IP overhead.
deadbeeffe8f4892016-08-24 16:26:55 -070034static constexpr size_t kSctpMtu = 1200;
Tommi7d013312016-05-19 19:58:38 +020035
36// The size of the SCTP association send buffer. 256kB, the usrsctp default.
deadbeeffe8f4892016-08-24 16:26:55 -070037static constexpr int kSendBufferSize = 262144;
Tommi7d013312016-05-19 19:58:38 +020038
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, ...) {
kwibergab0b9292016-10-03 05:04:21 -0700121#if RTC_DCHECK_IS_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
Taylor Brandstetter1d7a6372016-08-24 13:15:27 -0700287 // Set the number of default outgoing streams. This is the number we'll
288 // send in the SCTP INIT message.
289 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(kMaxSctpStreams);
Tommi7d013312016-05-19 19:58:38 +0200290}
291
292void UninitializeUsrSctp() {
293 LOG(LS_INFO) << __FUNCTION__;
294 // usrsctp_finish() may fail if it's called too soon after the channels are
295 // closed. Wait and try again until it succeeds for up to 3 seconds.
296 for (size_t i = 0; i < 300; ++i) {
297 if (usrsctp_finish() == 0) {
298 return;
Lally Singhe8386d22015-08-28 14:54:37 -0400299 }
300
Tommi7d013312016-05-19 19:58:38 +0200301 rtc::Thread::SleepMs(10);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000302 }
Tommi7d013312016-05-19 19:58:38 +0200303 LOG(LS_ERROR) << "Failed to shutdown usrsctp.";
304}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000305
Tommi7d013312016-05-19 19:58:38 +0200306void IncrementUsrSctpUsageCount() {
307 rtc::GlobalLockScope lock(&g_usrsctp_lock_);
308 if (!g_usrsctp_usage_count) {
309 InitializeUsrSctp();
310 }
311 ++g_usrsctp_usage_count;
312}
313
314void DecrementUsrSctpUsageCount() {
315 rtc::GlobalLockScope lock(&g_usrsctp_lock_);
316 --g_usrsctp_usage_count;
317 if (!g_usrsctp_usage_count) {
318 UninitializeUsrSctp();
319 }
320}
321
322DataCodec GetSctpDataCodec() {
323 DataCodec codec(kGoogleSctpDataCodecId, kGoogleSctpDataCodecName);
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000324 codec.SetParam(kCodecParamPort, kSctpDefaultPort);
Tommi7d013312016-05-19 19:58:38 +0200325 return codec;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000326}
327
Tommi7d013312016-05-19 19:58:38 +0200328} // namespace
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000329
Tommi7d013312016-05-19 19:58:38 +0200330SctpDataEngine::SctpDataEngine() : codecs_(1, GetSctpDataCodec()) {}
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000331
Tommi7d013312016-05-19 19:58:38 +0200332SctpDataEngine::~SctpDataEngine() {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000333
Tommi7d013312016-05-19 19:58:38 +0200334// Called on the worker thread.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000335DataMediaChannel* SctpDataEngine::CreateChannel(
336 DataChannelType data_channel_type) {
337 if (data_channel_type != DCT_SCTP) {
338 return NULL;
339 }
tommi73918812015-08-27 04:29:58 -0700340 return new SctpDataMediaChannel(rtc::Thread::Current());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000341}
342
Lally Singhe8386d22015-08-28 14:54:37 -0400343// static
Tommi7d013312016-05-19 19:58:38 +0200344SctpDataMediaChannel* SctpDataMediaChannel::GetChannelFromSocket(
Lally Singhe8386d22015-08-28 14:54:37 -0400345 struct socket* sock) {
346 struct sockaddr* addrs = nullptr;
347 int naddrs = usrsctp_getladdrs(sock, 0, &addrs);
348 if (naddrs <= 0 || addrs[0].sa_family != AF_CONN) {
349 return nullptr;
350 }
351 // usrsctp_getladdrs() returns the addresses bound to this socket, which
352 // contains the SctpDataMediaChannel* as sconn_addr. Read the pointer,
353 // then free the list of addresses once we have the pointer. We only open
354 // AF_CONN sockets, and they should all have the sconn_addr set to the
355 // pointer that created them, so [0] is as good as any other.
356 struct sockaddr_conn* sconn =
357 reinterpret_cast<struct sockaddr_conn*>(&addrs[0]);
358 SctpDataMediaChannel* channel =
359 reinterpret_cast<SctpDataMediaChannel*>(sconn->sconn_addr);
360 usrsctp_freeladdrs(addrs);
361
362 return channel;
363}
364
365// static
Tommi7d013312016-05-19 19:58:38 +0200366int SctpDataMediaChannel::SendThresholdCallback(struct socket* sock,
367 uint32_t sb_free) {
Lally Singhe8386d22015-08-28 14:54:37 -0400368 // Fired on our I/O thread. SctpDataMediaChannel::OnPacketReceived() gets
369 // a packet containing acknowledgments, which goes into usrsctp_conninput,
370 // and then back here.
371 SctpDataMediaChannel* channel = GetChannelFromSocket(sock);
372 if (!channel) {
373 LOG(LS_ERROR) << "SendThresholdCallback: Failed to get channel for socket "
374 << sock;
375 return 0;
376 }
377 channel->OnSendThresholdCallback();
378 return 0;
379}
380
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000381SctpDataMediaChannel::SctpDataMediaChannel(rtc::Thread* thread)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000382 : worker_thread_(thread),
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000383 local_port_(kSctpDefaultPort),
384 remote_port_(kSctpDefaultPort),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000385 sock_(NULL),
386 sending_(false),
387 receiving_(false),
388 debug_name_("SctpDataMediaChannel") {
389}
390
391SctpDataMediaChannel::~SctpDataMediaChannel() {
392 CloseSctpSocket();
393}
394
Lally Singhe8386d22015-08-28 14:54:37 -0400395void SctpDataMediaChannel::OnSendThresholdCallback() {
henrikg91d6ede2015-09-17 00:24:34 -0700396 RTC_DCHECK(rtc::Thread::Current() == worker_thread_);
Lally Singhe8386d22015-08-28 14:54:37 -0400397 SignalReadyToSend(true);
398}
399
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000400sockaddr_conn SctpDataMediaChannel::GetSctpSockAddr(int port) {
401 sockaddr_conn sconn = {0};
402 sconn.sconn_family = AF_CONN;
403#ifdef HAVE_SCONN_LEN
404 sconn.sconn_len = sizeof(sockaddr_conn);
405#endif
406 // Note: conversion from int to uint16_t happens here.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000407 sconn.sconn_port = rtc::HostToNetwork16(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000408 sconn.sconn_addr = this;
409 return sconn;
410}
411
412bool SctpDataMediaChannel::OpenSctpSocket() {
413 if (sock_) {
414 LOG(LS_VERBOSE) << debug_name_
415 << "->Ignoring attempt to re-create existing socket.";
416 return false;
417 }
Lally Singhe8386d22015-08-28 14:54:37 -0400418
Tommi7d013312016-05-19 19:58:38 +0200419 IncrementUsrSctpUsageCount();
420
Lally Singhe8386d22015-08-28 14:54:37 -0400421 // If kSendBufferSize isn't reflective of reality, we log an error, but we
422 // still have to do something reasonable here. Look up what the buffer's
423 // real size is and set our threshold to something reasonable.
424 const static int kSendThreshold = usrsctp_sysctl_get_sctp_sendspace() / 2;
425
Tommi7d013312016-05-19 19:58:38 +0200426 sock_ = usrsctp_socket(
427 AF_CONN, SOCK_STREAM, IPPROTO_SCTP, OnSctpInboundPacket,
428 &SctpDataMediaChannel::SendThresholdCallback, kSendThreshold, this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000429 if (!sock_) {
430 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to create SCTP socket.";
Tommi7d013312016-05-19 19:58:38 +0200431 DecrementUsrSctpUsageCount();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000432 return false;
433 }
434
435 // Make the socket non-blocking. Connect, close, shutdown etc will not block
436 // the thread waiting for the socket operation to complete.
437 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
438 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP to non blocking.";
439 return false;
440 }
441
442 // This ensures that the usrsctp close call deletes the association. This
443 // prevents usrsctp from calling OnSctpOutboundPacket with references to
444 // this class as the address.
445 linger linger_opt;
446 linger_opt.l_onoff = 1;
447 linger_opt.l_linger = 0;
448 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
449 sizeof(linger_opt))) {
450 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SO_LINGER.";
451 return false;
452 }
453
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000454 // Enable stream ID resets.
455 struct sctp_assoc_value stream_rst;
456 stream_rst.assoc_id = SCTP_ALL_ASSOC;
457 stream_rst.assoc_value = 1;
458 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
459 &stream_rst, sizeof(stream_rst))) {
460 LOG_ERRNO(LS_ERROR) << debug_name_
461 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
462 return false;
463 }
464
465 // Nagle.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000466 uint32_t nodelay = 1;
467 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
468 sizeof(nodelay))) {
469 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_NODELAY.";
470 return false;
471 }
472
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000473 // Subscribe to SCTP event notifications.
474 int event_types[] = {SCTP_ASSOC_CHANGE,
475 SCTP_PEER_ADDR_CHANGE,
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000476 SCTP_SEND_FAILED_EVENT,
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000477 SCTP_SENDER_DRY_EVENT,
478 SCTP_STREAM_RESET_EVENT};
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000479 struct sctp_event event = {0};
480 event.se_assoc_id = SCTP_ALL_ASSOC;
481 event.se_on = 1;
tfarina5237aaf2015-11-10 23:44:30 -0800482 for (size_t i = 0; i < arraysize(event_types); i++) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000483 event.se_type = event_types[i];
484 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
485 sizeof(event)) < 0) {
486 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_EVENT type: "
487 << event.se_type;
488 return false;
489 }
490 }
491
492 // Register this class as an address for usrsctp. This is used by SCTP to
493 // direct the packets received (by the created socket) to this class.
494 usrsctp_register_address(this);
495 sending_ = true;
496 return true;
497}
498
499void SctpDataMediaChannel::CloseSctpSocket() {
500 sending_ = false;
501 if (sock_) {
502 // We assume that SO_LINGER option is set to close the association when
503 // close is called. This means that any pending packets in usrsctp will be
504 // discarded instead of being sent.
505 usrsctp_close(sock_);
506 sock_ = NULL;
507 usrsctp_deregister_address(this);
Tommi7d013312016-05-19 19:58:38 +0200508
509 DecrementUsrSctpUsageCount();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000510 }
511}
512
513bool SctpDataMediaChannel::Connect() {
514 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
515
516 // If we already have a socket connection, just return.
517 if (sock_) {
518 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
519 "is already established.";
520 return true;
521 }
522
523 // If no socket (it was closed) try to start it again. This can happen when
524 // the socket we are connecting to closes, does an sctp shutdown handshake,
525 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
526 if (!sock_ && !OpenSctpSocket()) {
527 return false;
528 }
529
530 // Note: conversion from int to uint16_t happens on assignment.
531 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
532 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
533 sizeof(local_sconn)) < 0) {
534 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
535 << ("Failed usrsctp_bind");
536 CloseSctpSocket();
537 return false;
538 }
539
540 // Note: conversion from int to uint16_t happens on assignment.
541 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
542 int connect_result = usrsctp_connect(
543 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000544 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
545 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
546 << errno << ", but wanted " << SCTP_EINPROGRESS;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547 CloseSctpSocket();
548 return false;
549 }
deadbeeffe8f4892016-08-24 16:26:55 -0700550 // Set the MTU and disable MTU discovery.
551 // We can only do this after usrsctp_connect or it has no effect.
552 sctp_paddrparams params = {{0}};
Taylor Brandstettera4d40cb2016-09-07 10:05:21 -0700553 memcpy(&params.spp_address, &remote_sconn, sizeof(remote_sconn));
deadbeeffe8f4892016-08-24 16:26:55 -0700554 params.spp_flags = SPP_PMTUD_DISABLE;
555 params.spp_pathmtu = kSctpMtu;
556 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &params,
557 sizeof(params))) {
558 LOG_ERRNO(LS_ERROR) << debug_name_
559 << "Failed to set SCTP_PEER_ADDR_PARAMS.";
560 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000561 return true;
562}
563
564void SctpDataMediaChannel::Disconnect() {
565 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
566 // shutdown handshake and remove the association.
567 CloseSctpSocket();
568}
569
570bool SctpDataMediaChannel::SetSend(bool send) {
571 if (!sending_ && send) {
572 return Connect();
573 }
574 if (sending_ && !send) {
575 Disconnect();
576 }
577 return true;
578}
579
580bool SctpDataMediaChannel::SetReceive(bool receive) {
581 receiving_ = receive;
582 return true;
583}
584
Fredrik Solenbergb071a192015-09-17 16:42:56 +0200585bool SctpDataMediaChannel::SetSendParameters(const DataSendParameters& params) {
586 return SetSendCodecs(params.codecs);
587}
588
589bool SctpDataMediaChannel::SetRecvParameters(const DataRecvParameters& params) {
590 return SetRecvCodecs(params.codecs);
591}
592
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000594 return AddStream(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595}
596
Peter Boström0c4e06b2015-10-07 12:23:21 +0200597bool SctpDataMediaChannel::RemoveSendStream(uint32_t ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000598 return ResetStream(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000599}
600
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000601bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000602 // SCTP DataChannels are always bi-directional and calling AddSendStream will
603 // enable both sending and receiving on the stream. So AddRecvStream is a
604 // no-op.
605 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000606}
607
Peter Boström0c4e06b2015-10-07 12:23:21 +0200608bool SctpDataMediaChannel::RemoveRecvStream(uint32_t ssrc) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000609 // SCTP DataChannels are always bi-directional and calling RemoveSendStream
610 // will disable both sending and receiving on the stream. So RemoveRecvStream
611 // is a no-op.
612 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000613}
614
615bool SctpDataMediaChannel::SendData(
616 const SendDataParams& params,
jbaucheec21bd2016-03-20 06:15:43 -0700617 const rtc::CopyOnWriteBuffer& payload,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000618 SendDataResult* result) {
619 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000620 // Preset |result| to assume an error. If SendData succeeds, we'll
621 // overwrite |*result| once more at the end.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000622 *result = SDR_ERROR;
623 }
624
625 if (!sending_) {
626 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
627 << "Not sending packet with ssrc=" << params.ssrc
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000628 << " len=" << payload.size() << " before SetSend(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000629 return false;
630 }
631
Tommi7d013312016-05-19 19:58:38 +0200632 if (params.type != DMT_CONTROL &&
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000633 open_streams_.find(params.ssrc) == open_streams_.end()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000634 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
635 << "Not sending data because ssrc is unknown: "
636 << params.ssrc;
637 return false;
638 }
639
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 //
641 // Send data using SCTP.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000642 ssize_t send_res = 0; // result from usrsctp_sendv.
643 struct sctp_sendv_spa spa = {0};
644 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
645 spa.sendv_sndinfo.snd_sid = params.ssrc;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000646 spa.sendv_sndinfo.snd_ppid = rtc::HostToNetwork32(
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000647 GetPpid(params.type));
648
649 // Ordered implies reliable.
650 if (!params.ordered) {
651 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
652 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
653 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
654 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
655 spa.sendv_prinfo.pr_value = params.max_rtx_count;
656 } else {
657 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
658 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
659 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
660 }
661 }
662
663 // We don't fragment.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000664 send_res = usrsctp_sendv(
665 sock_, payload.data(), static_cast<size_t>(payload.size()), NULL, 0, &spa,
666 rtc::checked_cast<socklen_t>(sizeof(spa)), SCTP_SENDV_SPA, 0);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000667 if (send_res < 0) {
jiayl@webrtc.orgf7026cd2014-05-08 16:02:23 +0000668 if (errno == SCTP_EWOULDBLOCK) {
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000669 *result = SDR_BLOCK;
670 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
671 } else {
672 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
673 << "->SendData(...): "
674 << " usrsctp_sendv: ";
675 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 return false;
677 }
678 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000679 // Only way out now is success.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 *result = SDR_SUCCESS;
681 }
682 return true;
683}
684
685// Called by network interface when a packet has been received.
wu@webrtc.orga9890802013-12-13 00:21:03 +0000686void SctpDataMediaChannel::OnPacketReceived(
jbaucheec21bd2016-03-20 06:15:43 -0700687 rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -0700688 RTC_DCHECK(rtc::Thread::Current() == worker_thread_);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000689 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): "
690 << " length=" << packet->size() << ", sending: " << sending_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691 // Only give receiving packets to usrsctp after if connected. This enables two
692 // peers to each make a connect call, but for them not to receive an INIT
693 // packet before they have called connect; least the last receiver of the INIT
694 // packet will have called connect, and a connection will be established.
695 if (sending_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000696 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
697 // will be will be given to the global OnSctpInboundData, and then,
698 // marshalled by a Post and handled with OnMessage.
jbaucheec21bd2016-03-20 06:15:43 -0700699 VerboseLogPacket(packet->cdata(), packet->size(), SCTP_DUMP_INBOUND);
700 usrsctp_conninput(this, packet->cdata(), packet->size(), 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000701 } else {
702 // TODO(ldixon): Consider caching the packet for very slightly better
703 // reliability.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 }
705}
706
707void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
708 SctpInboundPacket* packet) {
709 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
710 << "Received SCTP data:"
711 << " ssrc=" << packet->params.ssrc
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712 << " notification: " << (packet->flags & MSG_NOTIFICATION)
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000713 << " length=" << packet->buffer.size();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714 // Sending a packet with data == NULL (no data) is SCTPs "close the
715 // connection" message. This sets sock_ = NULL;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000716 if (!packet->buffer.size() || !packet->buffer.data()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
718 "No data, closing.";
719 return;
720 }
721 if (packet->flags & MSG_NOTIFICATION) {
jbaucheec21bd2016-03-20 06:15:43 -0700722 OnNotificationFromSctp(packet->buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 } else {
jbaucheec21bd2016-03-20 06:15:43 -0700724 OnDataFromSctpToChannel(packet->params, packet->buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 }
726}
727
728void SctpDataMediaChannel::OnDataFromSctpToChannel(
jbaucheec21bd2016-03-20 06:15:43 -0700729 const ReceiveDataParams& params, const rtc::CopyOnWriteBuffer& buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730 if (receiving_) {
731 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
jbaucheec21bd2016-03-20 06:15:43 -0700732 << "Posting with length: " << buffer.size()
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000733 << " on stream " << params.ssrc;
734 // Reports all received messages to upper layers, no matter whether the sid
735 // is known.
jbaucheec21bd2016-03-20 06:15:43 -0700736 SignalDataReceived(params, buffer.data<char>(), buffer.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737 } else {
738 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
739 << "Not receiving packet with sid=" << params.ssrc
jbaucheec21bd2016-03-20 06:15:43 -0700740 << " len=" << buffer.size() << " before SetReceive(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741 }
742}
743
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000744bool SctpDataMediaChannel::AddStream(const StreamParams& stream) {
745 if (!stream.has_ssrcs()) {
746 return false;
747 }
748
Peter Boström0c4e06b2015-10-07 12:23:21 +0200749 const uint32_t ssrc = stream.first_ssrc();
Taylor Brandstetter1d7a6372016-08-24 13:15:27 -0700750 if (ssrc > kMaxSctpSid) {
lally27ed3cc2016-01-11 10:24:33 -0800751 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
752 << "Not adding data stream '" << stream.id
Taylor Brandstetter1d7a6372016-08-24 13:15:27 -0700753 << "' with sid=" << ssrc << " because sid is too high.";
lally27ed3cc2016-01-11 10:24:33 -0800754 return false;
755 } else if (open_streams_.find(ssrc) != open_streams_.end()) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000756 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000757 << "Not adding data stream '" << stream.id
Taylor Brandstetter1d7a6372016-08-24 13:15:27 -0700758 << "' with sid=" << ssrc
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000759 << " because stream is already open.";
760 return false;
761 } else if (queued_reset_streams_.find(ssrc) != queued_reset_streams_.end()
762 || sent_reset_streams_.find(ssrc) != sent_reset_streams_.end()) {
763 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
764 << "Not adding data stream '" << stream.id
Taylor Brandstetter1d7a6372016-08-24 13:15:27 -0700765 << "' with sid=" << ssrc
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000766 << " because stream is still closing.";
767 return false;
768 }
769
770 open_streams_.insert(ssrc);
771 return true;
772}
773
Peter Boström0c4e06b2015-10-07 12:23:21 +0200774bool SctpDataMediaChannel::ResetStream(uint32_t ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000775 // We typically get this called twice for the same stream, once each for
776 // Send and Recv.
777 StreamSet::iterator found = open_streams_.find(ssrc);
778
779 if (found == open_streams_.end()) {
780 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
781 << "stream not found.";
782 return false;
783 } else {
784 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
785 << "Removing and queuing RE-CONFIG chunk.";
786 open_streams_.erase(found);
787 }
788
789 // SCTP won't let you have more than one stream reset pending at a time, but
790 // you can close multiple streams in a single reset. So, we keep an internal
791 // queue of streams-to-reset, and send them as one reset message in
792 // SendQueuedStreamResets().
793 queued_reset_streams_.insert(ssrc);
794
795 // Signal our stream-reset logic that it should try to send now, if it can.
796 SendQueuedStreamResets();
797
798 // The stream will actually get removed when we get the acknowledgment.
799 return true;
800}
801
jbaucheec21bd2016-03-20 06:15:43 -0700802void SctpDataMediaChannel::OnNotificationFromSctp(
803 const rtc::CopyOnWriteBuffer& buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 const sctp_notification& notification =
jbaucheec21bd2016-03-20 06:15:43 -0700805 reinterpret_cast<const sctp_notification&>(*buffer.data());
806 ASSERT(notification.sn_header.sn_length == buffer.size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807
808 // TODO(ldixon): handle notifications appropriately.
809 switch (notification.sn_header.sn_type) {
810 case SCTP_ASSOC_CHANGE:
811 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
812 OnNotificationAssocChange(notification.sn_assoc_change);
813 break;
814 case SCTP_REMOTE_ERROR:
815 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
816 break;
817 case SCTP_SHUTDOWN_EVENT:
818 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
819 break;
820 case SCTP_ADAPTATION_INDICATION:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000821 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 break;
823 case SCTP_PARTIAL_DELIVERY_EVENT:
824 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
825 break;
826 case SCTP_AUTHENTICATION_EVENT:
827 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
828 break;
829 case SCTP_SENDER_DRY_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000830 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000831 SignalReadyToSend(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 break;
833 // TODO(ldixon): Unblock after congestion.
834 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
835 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
836 break;
837 case SCTP_SEND_FAILED_EVENT:
838 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
839 break;
840 case SCTP_STREAM_RESET_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000841 OnStreamResetEvent(&notification.sn_strreset_event);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 break;
843 case SCTP_ASSOC_RESET_EVENT:
844 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
845 break;
846 case SCTP_STREAM_CHANGE_EVENT:
847 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000848 // An acknowledgment we get after our stream resets have gone through,
849 // if they've failed. We log the message, but don't react -- we don't
850 // keep around the last-transmitted set of SSIDs we wanted to close for
851 // error recovery. It doesn't seem likely to occur, and if so, likely
852 // harmless within the lifetime of a single SCTP association.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000853 break;
854 default:
855 LOG(LS_WARNING) << "Unknown SCTP event: "
856 << notification.sn_header.sn_type;
857 break;
858 }
859}
860
861void SctpDataMediaChannel::OnNotificationAssocChange(
862 const sctp_assoc_change& change) {
863 switch (change.sac_state) {
864 case SCTP_COMM_UP:
865 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
866 break;
867 case SCTP_COMM_LOST:
868 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
869 break;
870 case SCTP_RESTART:
871 LOG(LS_INFO) << "Association change SCTP_RESTART";
872 break;
873 case SCTP_SHUTDOWN_COMP:
874 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
875 break;
876 case SCTP_CANT_STR_ASSOC:
877 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
878 break;
879 default:
880 LOG(LS_INFO) << "Association change UNKNOWN";
881 break;
882 }
883}
884
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000885void SctpDataMediaChannel::OnStreamResetEvent(
886 const struct sctp_stream_reset_event* evt) {
887 // A stream reset always involves two RE-CONFIG chunks for us -- we always
888 // simultaneously reset a sid's sequence number in both directions. The
889 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
890 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
891 // RE-CONFIGs.
892 const int num_ssrcs = (evt->strreset_length - sizeof(*evt)) /
893 sizeof(evt->strreset_stream_list[0]);
894 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
895 << "): Flags = 0x"
896 << std::hex << evt->strreset_flags << " ("
897 << ListFlags(evt->strreset_flags) << ")";
898 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
899 << ListArray(evt->strreset_stream_list, num_ssrcs)
900 << "], Open: ["
901 << ListStreams(open_streams_) << "], Q'd: ["
902 << ListStreams(queued_reset_streams_) << "], Sent: ["
903 << ListStreams(sent_reset_streams_) << "]";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000904
905 // If both sides try to reset some streams at the same time (even if they're
906 // disjoint sets), we can get reset failures.
907 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
908 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
909 // is set seem to be garbage values. Ignore them.
910 queued_reset_streams_.insert(
911 sent_reset_streams_.begin(),
912 sent_reset_streams_.end());
913 sent_reset_streams_.clear();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000914
915 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
916 // Each side gets an event for each direction of a stream. That is,
917 // closing sid k will make each side receive INCOMING and OUTGOING reset
918 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
919 // get an INCOMING event first.
920 for (int i = 0; i < num_ssrcs; i++) {
921 const int stream_id = evt->strreset_stream_list[i];
922
923 // See if this stream ID was closed by our peer or ourselves.
924 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
925
926 // The reset was requested locally.
927 if (it != sent_reset_streams_.end()) {
928 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
929 << "): local sid " << stream_id << " acknowledged.";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000930 sent_reset_streams_.erase(it);
931
932 } else if ((it = open_streams_.find(stream_id))
933 != open_streams_.end()) {
934 // The peer requested the reset.
935 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
936 << "): closing sid " << stream_id;
937 open_streams_.erase(it);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +0000938 SignalStreamClosedRemotely(stream_id);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000939
940 } else if ((it = queued_reset_streams_.find(stream_id))
941 != queued_reset_streams_.end()) {
942 // The peer requested the reset, but there was a local reset
943 // queued.
944 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
945 << "): double-sided close for sid " << stream_id;
946 // Both sides want the stream closed, and the peer got to send the
947 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
948 // finished quickly.
949 queued_reset_streams_.erase(it);
950
951 } else {
952 // This stream is unknown. Sometimes this can be from an
953 // RESET_FAILED-related retransmit.
954 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
955 << "): Unknown sid " << stream_id;
956 }
957 }
958 }
959
jiayl@webrtc.org1a6c6282014-06-12 21:59:29 +0000960 // Always try to send the queued RESET because this call indicates that the
961 // last local RESET or remote RESET has made some progress.
962 SendQueuedStreamResets();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000963}
964
wu@webrtc.org78187522013-10-07 23:32:02 +0000965// Puts the specified |param| from the codec identified by |id| into |dest|
966// and returns true. Or returns false if it wasn't there, leaving |dest|
967// untouched.
968static bool GetCodecIntParameter(const std::vector<DataCodec>& codecs,
969 int id, const std::string& name,
970 const std::string& param, int* dest) {
971 std::string value;
972 Codec match_pattern;
973 match_pattern.id = id;
974 match_pattern.name = name;
975 for (size_t i = 0; i < codecs.size(); ++i) {
976 if (codecs[i].Matches(match_pattern)) {
977 if (codecs[i].GetParam(param, &value)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000978 *dest = rtc::FromString<int>(value);
wu@webrtc.org78187522013-10-07 23:32:02 +0000979 return true;
980 }
981 }
982 }
983 return false;
984}
985
986bool SctpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
987 return GetCodecIntParameter(
988 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
989 &remote_port_);
990}
991
992bool SctpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
993 return GetCodecIntParameter(
994 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
995 &local_port_);
996}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997
998void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
jbaucheec21bd2016-03-20 06:15:43 -0700999 rtc::CopyOnWriteBuffer* buffer) {
deadbeeffe8f4892016-08-24 16:26:55 -07001000 if (buffer->size() > (kSctpMtu)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001002 << "SCTP seems to have made a packet that is bigger "
Lally Singhe8386d22015-08-28 14:54:37 -04001003 << "than its official MTU: " << buffer->size()
deadbeeffe8f4892016-08-24 16:26:55 -07001004 << " vs max of " << kSctpMtu;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005 }
stefanc1aeaf02015-10-15 07:26:07 -07001006 MediaChannel::SendPacket(buffer, rtc::PacketOptions());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007}
1008
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001009bool SctpDataMediaChannel::SendQueuedStreamResets() {
Tommi7d013312016-05-19 19:58:38 +02001010 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty()) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001011 return true;
Tommi7d013312016-05-19 19:58:38 +02001012 }
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001013
1014 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
1015 << ListStreams(queued_reset_streams_) << "], Open: ["
1016 << ListStreams(open_streams_) << "], Sent: ["
1017 << ListStreams(sent_reset_streams_) << "]";
1018
1019 const size_t num_streams = queued_reset_streams_.size();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001020 const size_t num_bytes =
1021 sizeof(struct sctp_reset_streams) + (num_streams * sizeof(uint16_t));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001022
Peter Boström0c4e06b2015-10-07 12:23:21 +02001023 std::vector<uint8_t> reset_stream_buf(num_bytes, 0);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001024 struct sctp_reset_streams* resetp = reinterpret_cast<sctp_reset_streams*>(
1025 &reset_stream_buf[0]);
1026 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
1027 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001028 resetp->srs_number_streams = rtc::checked_cast<uint16_t>(num_streams);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001029 int result_idx = 0;
1030 for (StreamSet::iterator it = queued_reset_streams_.begin();
1031 it != queued_reset_streams_.end(); ++it) {
1032 resetp->srs_stream_list[result_idx++] = *it;
1033 }
1034
jiayl@webrtc.orga576faf2014-01-29 17:45:53 +00001035 int ret = usrsctp_setsockopt(
1036 sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001037 rtc::checked_cast<socklen_t>(reset_stream_buf.size()));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001038 if (ret < 0) {
1039 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to send a stream reset for "
1040 << num_streams << " streams";
1041 return false;
1042 }
1043
1044 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
1045 // it now.
1046 queued_reset_streams_.swap(sent_reset_streams_);
1047 return true;
1048}
1049
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001050void SctpDataMediaChannel::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051 switch (msg->message_id) {
1052 case MSG_SCTPINBOUNDPACKET: {
kwiberg686a8ef2016-02-26 03:00:35 -08001053 std::unique_ptr<InboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001054 static_cast<InboundPacketMessage*>(msg->pdata));
1055 OnInboundPacketFromSctpToChannel(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056 break;
1057 }
1058 case MSG_SCTPOUTBOUNDPACKET: {
kwiberg686a8ef2016-02-26 03:00:35 -08001059 std::unique_ptr<OutboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +00001060 static_cast<OutboundPacketMessage*>(msg->pdata));
1061 OnPacketFromSctpToNetwork(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001062 break;
1063 }
1064 }
1065}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066} // namespace cricket