blob: 8c8a6a192fa25833c3de66c0587b9ed7ed3bccb3 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
jlmiller@webrtc.org5f93d0a2015-01-20 21:36:13 +00002 * libjingle
3 * Copyright 2012 Google Inc. and Robin Seggelmann
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/media/sctp/sctpdataengine.h"
29
henrike@webrtc.org28e20752013-07-10 00:45:36 +000030#include <stdarg.h>
31#include <stdio.h>
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000032#include <sstream>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000033#include <vector>
34
henrike@webrtc.org28e20752013-07-10 00:45:36 +000035#include "talk/media/base/codec.h"
36#include "talk/media/base/constants.h"
37#include "talk/media/base/streamparams.h"
38#include "usrsctplib/usrsctp.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000039#include "webrtc/base/buffer.h"
40#include "webrtc/base/helpers.h"
41#include "webrtc/base/logging.h"
42#include "webrtc/base/safe_conversions.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000044namespace {
45typedef cricket::SctpDataMediaChannel::StreamSet StreamSet;
46// Returns a comma-separated, human-readable list of the stream IDs in 's'
47std::string ListStreams(const StreamSet& s) {
48 std::stringstream result;
49 bool first = true;
wu@webrtc.orge00265e2014-01-07 19:32:40 +000050 for (StreamSet::const_iterator it = s.begin(); it != s.end(); ++it) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000051 if (!first) {
52 result << ", " << *it;
53 } else {
54 result << *it;
55 first = false;
56 }
57 }
58 return result.str();
59}
60
61// Returns a pipe-separated, human-readable list of the SCTP_STREAM_RESET
62// flags in 'flags'
63std::string ListFlags(int flags) {
64 std::stringstream result;
65 bool first = true;
66 // Skip past the first 12 chars (strlen("SCTP_STREAM_"))
67#define MAKEFLAG(X) { X, #X + 12}
68 struct flaginfo_t {
69 int value;
70 const char* name;
71 } flaginfo[] = {
72 MAKEFLAG(SCTP_STREAM_RESET_INCOMING_SSN),
73 MAKEFLAG(SCTP_STREAM_RESET_OUTGOING_SSN),
74 MAKEFLAG(SCTP_STREAM_RESET_DENIED),
75 MAKEFLAG(SCTP_STREAM_RESET_FAILED),
76 MAKEFLAG(SCTP_STREAM_CHANGE_DENIED)
77 };
78#undef MAKEFLAG
79 for (int i = 0; i < ARRAY_SIZE(flaginfo); ++i) {
80 if (flags & flaginfo[i].value) {
81 if (!first) result << " | ";
82 result << flaginfo[i].name;
83 first = false;
84 }
85 }
86 return result.str();
87}
88
89// Returns a comma-separated, human-readable list of the integers in 'array'.
90// All 'num_elems' of them.
91std::string ListArray(const uint16* array, int num_elems) {
92 std::stringstream result;
93 for (int i = 0; i < num_elems; ++i) {
94 if (i) {
95 result << ", " << array[i];
96 } else {
97 result << array[i];
98 }
99 }
100 return result.str();
101}
102} // namespace
103
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104namespace cricket {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000105typedef rtc::ScopedMessageData<SctpInboundPacket> InboundPacketMessage;
106typedef rtc::ScopedMessageData<rtc::Buffer> OutboundPacketMessage;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000108// The biggest SCTP packet. Starting from a 'safe' wire MTU value of 1280,
109// take off 80 bytes for DTLS/TURN/TCP/IP overhead.
110static const size_t kSctpMtu = 1200;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111
112enum {
113 MSG_SCTPINBOUNDPACKET = 1, // MessageData is SctpInboundPacket
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000114 MSG_SCTPOUTBOUNDPACKET = 2, // MessageData is rtc:Buffer
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115};
116
117struct SctpInboundPacket {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000118 rtc::Buffer buffer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119 ReceiveDataParams params;
120 // The |flags| parameter is used by SCTP to distinguish notification packets
121 // from other types of packets.
122 int flags;
123};
124
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000125// Helper for logging SCTP messages.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000126static void debug_sctp_printf(const char *format, ...) {
127 char s[255];
128 va_list ap;
129 va_start(ap, format);
130 vsnprintf(s, sizeof(s), format, ap);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000131 LOG(LS_INFO) << "SCTP: " << s;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132 va_end(ap);
133}
134
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000135// Get the PPID to use for the terminating fragment of this type.
136static SctpDataMediaChannel::PayloadProtocolIdentifier GetPpid(
137 cricket::DataMessageType type) {
138 switch (type) {
139 default:
140 case cricket::DMT_NONE:
141 return SctpDataMediaChannel::PPID_NONE;
142 case cricket::DMT_CONTROL:
143 return SctpDataMediaChannel::PPID_CONTROL;
144 case cricket::DMT_BINARY:
145 return SctpDataMediaChannel::PPID_BINARY_LAST;
146 case cricket::DMT_TEXT:
147 return SctpDataMediaChannel::PPID_TEXT_LAST;
148 };
149}
150
151static bool GetDataMediaType(
152 SctpDataMediaChannel::PayloadProtocolIdentifier ppid,
153 cricket::DataMessageType *dest) {
154 ASSERT(dest != NULL);
155 switch (ppid) {
156 case SctpDataMediaChannel::PPID_BINARY_PARTIAL:
157 case SctpDataMediaChannel::PPID_BINARY_LAST:
158 *dest = cricket::DMT_BINARY;
159 return true;
160
161 case SctpDataMediaChannel::PPID_TEXT_PARTIAL:
162 case SctpDataMediaChannel::PPID_TEXT_LAST:
163 *dest = cricket::DMT_TEXT;
164 return true;
165
166 case SctpDataMediaChannel::PPID_CONTROL:
167 *dest = cricket::DMT_CONTROL;
168 return true;
169
170 case SctpDataMediaChannel::PPID_NONE:
171 *dest = cricket::DMT_NONE;
172 return true;
173
174 default:
175 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177}
178
Lally Singh4c277bb2015-05-08 14:39:04 -0400179// Log the packet in text2pcap format, if log level is at LS_VERBOSE.
tommi73918812015-08-27 04:29:58 -0700180static void VerboseLogPacket(void *addr, size_t length, int direction) {
Lally Singh4c277bb2015-05-08 14:39:04 -0400181 if (LOG_CHECK_LEVEL(LS_VERBOSE) && length > 0) {
182 char *dump_buf;
183 if ((dump_buf = usrsctp_dumppacket(
tommi73918812015-08-27 04:29:58 -0700184 addr, length, direction)) != NULL) {
Lally Singh4c277bb2015-05-08 14:39:04 -0400185 LOG(LS_VERBOSE) << dump_buf;
186 usrsctp_freedumpbuffer(dump_buf);
187 }
188 }
189}
190
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191// This is the callback usrsctp uses when there's data to send on the network
192// that has been wrapped appropriatly for the SCTP protocol.
193static int OnSctpOutboundPacket(void* addr, void* data, size_t length,
194 uint8_t tos, uint8_t set_df) {
195 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
201 VerboseLogPacket(addr, 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(
204 new rtc::Buffer(reinterpret_cast<uint8_t*>(data), length));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000205 channel->worker_thread()->Post(channel, MSG_SCTPOUTBOUNDPACKET, msg);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000206 return 0;
207}
208
209// This is the callback called from usrsctp when data has been received, after
210// a packet has been interpreted and parsed by usrsctp and found to contain
211// payload data. It is called by a usrsctp thread. It is assumed this function
212// will free the memory used by 'data'.
213static int OnSctpInboundPacket(struct socket* sock, union sctp_sockstore addr,
214 void* data, size_t length,
215 struct sctp_rcvinfo rcv, int flags,
216 void* ulp_info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000217 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(ulp_info);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218 // Post data to the channel's receiver thread (copying it).
219 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
220 // memory cleanup. But this does simplify code.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000221 const SctpDataMediaChannel::PayloadProtocolIdentifier ppid =
222 static_cast<SctpDataMediaChannel::PayloadProtocolIdentifier>(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000223 rtc::HostToNetwork32(rcv.rcv_ppid));
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000224 cricket::DataMessageType type = cricket::DMT_NONE;
225 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
226 // It's neither a notification nor a recognized data packet. Drop it.
227 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
228 << " on an SCTP packet. Dropping.";
229 } else {
230 SctpInboundPacket* packet = new SctpInboundPacket;
Karl Wiberg94784372015-04-20 14:03:07 +0200231 packet->buffer.SetData(reinterpret_cast<uint8_t*>(data), length);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000232 packet->params.ssrc = rcv.rcv_sid;
233 packet->params.seq_num = rcv.rcv_ssn;
234 packet->params.timestamp = rcv.rcv_tsn;
235 packet->params.type = type;
236 packet->flags = flags;
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000237 // The ownership of |packet| transfers to |msg|.
238 InboundPacketMessage* msg = new InboundPacketMessage(packet);
239 channel->worker_thread()->Post(channel, MSG_SCTPINBOUNDPACKET, msg);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000240 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000241 free(data);
242 return 1;
243}
244
245// Set the initial value of the static SCTP Data Engines reference count.
246int SctpDataEngine::usrsctp_engines_count = 0;
247
wu@webrtc.org0de29502014-02-13 19:54:28 +0000248SctpDataEngine::SctpDataEngine() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000249 if (usrsctp_engines_count == 0) {
250 // First argument is udp_encapsulation_port, which is not releveant for our
251 // AF_CONN use of sctp.
252 usrsctp_init(0, cricket::OnSctpOutboundPacket, debug_sctp_printf);
253
254 // To turn on/off detailed SCTP debugging. You will also need to have the
255 // SCTP_DEBUG cpp defines flag.
256 // usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
257
258 // TODO(ldixon): Consider turning this on/off.
259 usrsctp_sysctl_set_sctp_ecn_enable(0);
260
261 // TODO(ldixon): Consider turning this on/off.
262 // This is not needed right now (we don't do dynamic address changes):
263 // If SCTP Auto-ASCONF is enabled, the peer is informed automatically
264 // when a new address is added or removed. This feature is enabled by
265 // default.
266 // usrsctp_sysctl_set_sctp_auto_asconf(0);
267
268 // TODO(ldixon): Consider turning this on/off.
269 // Add a blackhole sysctl. Setting it to 1 results in no ABORTs
270 // being sent in response to INITs, setting it to 2 results
271 // in no ABORTs being sent for received OOTB packets.
272 // This is similar to the TCP sysctl.
273 //
274 // See: http://lakerest.net/pipermail/sctp-coders/2012-January/009438.html
275 // See: http://svnweb.freebsd.org/base?view=revision&revision=229805
276 // usrsctp_sysctl_set_sctp_blackhole(2);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000277
278 // Set the number of default outgoing streams. This is the number we'll
279 // send in the SCTP INIT message. The 'appropriate default' in the
280 // second paragraph of
281 // http://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-05#section-6.2
282 // is cricket::kMaxSctpSid.
283 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(
284 cricket::kMaxSctpSid);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000285 }
286 usrsctp_engines_count++;
287
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000288 cricket::DataCodec codec(kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, 0);
289 codec.SetParam(kCodecParamPort, kSctpDefaultPort);
290 codecs_.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000291}
292
293SctpDataEngine::~SctpDataEngine() {
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000294 usrsctp_engines_count--;
295 LOG(LS_VERBOSE) << "usrsctp_engines_count:" << usrsctp_engines_count;
296
297 if (usrsctp_engines_count == 0) {
298 // usrsctp_finish() may fail if it's called too soon after the channels are
299 // closed. Wait and try again until it succeeds for up to 3 seconds.
300 for (size_t i = 0; i < 300; ++i) {
301 if (usrsctp_finish() == 0)
302 return;
303
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000304 rtc::Thread::SleepMs(10);
jiayl@webrtc.orgf8063d32014-06-18 21:30:40 +0000305 }
306 LOG(LS_ERROR) << "Failed to shutdown usrsctp.";
307 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000308}
309
310DataMediaChannel* SctpDataEngine::CreateChannel(
311 DataChannelType data_channel_type) {
312 if (data_channel_type != DCT_SCTP) {
313 return NULL;
314 }
tommi73918812015-08-27 04:29:58 -0700315 return new SctpDataMediaChannel(rtc::Thread::Current());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000316}
317
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000318SctpDataMediaChannel::SctpDataMediaChannel(rtc::Thread* thread)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000319 : worker_thread_(thread),
jiayl@webrtc.org9c16c392014-05-01 18:30:30 +0000320 local_port_(kSctpDefaultPort),
321 remote_port_(kSctpDefaultPort),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000322 sock_(NULL),
323 sending_(false),
324 receiving_(false),
325 debug_name_("SctpDataMediaChannel") {
326}
327
328SctpDataMediaChannel::~SctpDataMediaChannel() {
329 CloseSctpSocket();
330}
331
332sockaddr_conn SctpDataMediaChannel::GetSctpSockAddr(int port) {
333 sockaddr_conn sconn = {0};
334 sconn.sconn_family = AF_CONN;
335#ifdef HAVE_SCONN_LEN
336 sconn.sconn_len = sizeof(sockaddr_conn);
337#endif
338 // Note: conversion from int to uint16_t happens here.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000339 sconn.sconn_port = rtc::HostToNetwork16(port);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000340 sconn.sconn_addr = this;
341 return sconn;
342}
343
344bool SctpDataMediaChannel::OpenSctpSocket() {
345 if (sock_) {
346 LOG(LS_VERBOSE) << debug_name_
347 << "->Ignoring attempt to re-create existing socket.";
348 return false;
349 }
350 sock_ = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP,
tommi73918812015-08-27 04:29:58 -0700351 cricket::OnSctpInboundPacket, NULL, 0, this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000352 if (!sock_) {
353 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to create SCTP socket.";
354 return false;
355 }
356
357 // Make the socket non-blocking. Connect, close, shutdown etc will not block
358 // the thread waiting for the socket operation to complete.
359 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
360 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP to non blocking.";
361 return false;
362 }
363
364 // This ensures that the usrsctp close call deletes the association. This
365 // prevents usrsctp from calling OnSctpOutboundPacket with references to
366 // this class as the address.
367 linger linger_opt;
368 linger_opt.l_onoff = 1;
369 linger_opt.l_linger = 0;
370 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
371 sizeof(linger_opt))) {
372 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SO_LINGER.";
373 return false;
374 }
375
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000376 // Enable stream ID resets.
377 struct sctp_assoc_value stream_rst;
378 stream_rst.assoc_id = SCTP_ALL_ASSOC;
379 stream_rst.assoc_value = 1;
380 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
381 &stream_rst, sizeof(stream_rst))) {
382 LOG_ERRNO(LS_ERROR) << debug_name_
383 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
384 return false;
385 }
386
387 // Nagle.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000388 uint32_t nodelay = 1;
389 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
390 sizeof(nodelay))) {
391 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_NODELAY.";
392 return false;
393 }
394
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000395 // Disable MTU discovery
tommi73918812015-08-27 04:29:58 -0700396 struct sctp_paddrparams params = {{0}};
buildbot@webrtc.org624a5042014-08-05 22:13:05 +0000397 params.spp_assoc_id = 0;
398 params.spp_flags = SPP_PMTUD_DISABLE;
399 params.spp_pathmtu = kSctpMtu;
400 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &params,
401 sizeof(params))) {
402 LOG_ERRNO(LS_ERROR) << debug_name_
403 << "Failed to set SCTP_PEER_ADDR_PARAMS.";
404 return false;
405 }
406
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000407 // Subscribe to SCTP event notifications.
408 int event_types[] = {SCTP_ASSOC_CHANGE,
409 SCTP_PEER_ADDR_CHANGE,
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000410 SCTP_SEND_FAILED_EVENT,
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000411 SCTP_SENDER_DRY_EVENT,
412 SCTP_STREAM_RESET_EVENT};
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000413 struct sctp_event event = {0};
414 event.se_assoc_id = SCTP_ALL_ASSOC;
415 event.se_on = 1;
416 for (size_t i = 0; i < ARRAY_SIZE(event_types); i++) {
417 event.se_type = event_types[i];
418 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
419 sizeof(event)) < 0) {
420 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_EVENT type: "
421 << event.se_type;
422 return false;
423 }
424 }
425
426 // Register this class as an address for usrsctp. This is used by SCTP to
427 // direct the packets received (by the created socket) to this class.
428 usrsctp_register_address(this);
429 sending_ = true;
430 return true;
431}
432
433void SctpDataMediaChannel::CloseSctpSocket() {
434 sending_ = false;
435 if (sock_) {
436 // We assume that SO_LINGER option is set to close the association when
437 // close is called. This means that any pending packets in usrsctp will be
438 // discarded instead of being sent.
439 usrsctp_close(sock_);
440 sock_ = NULL;
441 usrsctp_deregister_address(this);
442 }
443}
444
445bool SctpDataMediaChannel::Connect() {
446 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
447
448 // If we already have a socket connection, just return.
449 if (sock_) {
450 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
451 "is already established.";
452 return true;
453 }
454
455 // If no socket (it was closed) try to start it again. This can happen when
456 // the socket we are connecting to closes, does an sctp shutdown handshake,
457 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
458 if (!sock_ && !OpenSctpSocket()) {
459 return false;
460 }
461
462 // Note: conversion from int to uint16_t happens on assignment.
463 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
464 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
465 sizeof(local_sconn)) < 0) {
466 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
467 << ("Failed usrsctp_bind");
468 CloseSctpSocket();
469 return false;
470 }
471
472 // Note: conversion from int to uint16_t happens on assignment.
473 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
474 int connect_result = usrsctp_connect(
475 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000476 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
477 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
478 << errno << ", but wanted " << SCTP_EINPROGRESS;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000479 CloseSctpSocket();
480 return false;
481 }
482 return true;
483}
484
485void SctpDataMediaChannel::Disconnect() {
486 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
487 // shutdown handshake and remove the association.
488 CloseSctpSocket();
489}
490
491bool SctpDataMediaChannel::SetSend(bool send) {
492 if (!sending_ && send) {
493 return Connect();
494 }
495 if (sending_ && !send) {
496 Disconnect();
497 }
498 return true;
499}
500
501bool SctpDataMediaChannel::SetReceive(bool receive) {
502 receiving_ = receive;
503 return true;
504}
505
506bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000507 return AddStream(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000508}
509
510bool SctpDataMediaChannel::RemoveSendStream(uint32 ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000511 return ResetStream(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000512}
513
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000514bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000515 // SCTP DataChannels are always bi-directional and calling AddSendStream will
516 // enable both sending and receiving on the stream. So AddRecvStream is a
517 // no-op.
518 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000519}
520
521bool SctpDataMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000522 // SCTP DataChannels are always bi-directional and calling RemoveSendStream
523 // will disable both sending and receiving on the stream. So RemoveRecvStream
524 // is a no-op.
525 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000526}
527
528bool SctpDataMediaChannel::SendData(
529 const SendDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000530 const rtc::Buffer& payload,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531 SendDataResult* result) {
532 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000533 // Preset |result| to assume an error. If SendData succeeds, we'll
534 // overwrite |*result| once more at the end.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000535 *result = SDR_ERROR;
536 }
537
538 if (!sending_) {
539 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
540 << "Not sending packet with ssrc=" << params.ssrc
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000541 << " len=" << payload.size() << " before SetSend(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000542 return false;
543 }
544
wu@webrtc.org91053e72013-08-10 07:18:04 +0000545 if (params.type != cricket::DMT_CONTROL &&
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000546 open_streams_.find(params.ssrc) == open_streams_.end()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
548 << "Not sending data because ssrc is unknown: "
549 << params.ssrc;
550 return false;
551 }
552
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000553 //
554 // Send data using SCTP.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000555 ssize_t send_res = 0; // result from usrsctp_sendv.
556 struct sctp_sendv_spa spa = {0};
557 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
558 spa.sendv_sndinfo.snd_sid = params.ssrc;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000559 spa.sendv_sndinfo.snd_ppid = rtc::HostToNetwork32(
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000560 GetPpid(params.type));
561
562 // Ordered implies reliable.
563 if (!params.ordered) {
564 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
565 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
566 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
567 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
568 spa.sendv_prinfo.pr_value = params.max_rtx_count;
569 } else {
570 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
571 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
572 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
573 }
574 }
575
576 // We don't fragment.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000577 send_res = usrsctp_sendv(
578 sock_, payload.data(), static_cast<size_t>(payload.size()), NULL, 0, &spa,
579 rtc::checked_cast<socklen_t>(sizeof(spa)), SCTP_SENDV_SPA, 0);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000580 if (send_res < 0) {
jiayl@webrtc.orgf7026cd2014-05-08 16:02:23 +0000581 if (errno == SCTP_EWOULDBLOCK) {
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000582 *result = SDR_BLOCK;
583 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
584 } else {
585 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
586 << "->SendData(...): "
587 << " usrsctp_sendv: ";
588 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589 return false;
590 }
591 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000592 // Only way out now is success.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 *result = SDR_SUCCESS;
594 }
595 return true;
596}
597
598// Called by network interface when a packet has been received.
wu@webrtc.orga9890802013-12-13 00:21:03 +0000599void SctpDataMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000600 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000601 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): "
602 << " length=" << packet->size() << ", sending: " << sending_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000603 // Only give receiving packets to usrsctp after if connected. This enables two
604 // peers to each make a connect call, but for them not to receive an INIT
605 // packet before they have called connect; least the last receiver of the INIT
606 // packet will have called connect, and a connection will be established.
607 if (sending_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000608 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
609 // will be will be given to the global OnSctpInboundData, and then,
610 // marshalled by a Post and handled with OnMessage.
Lally Singh4c277bb2015-05-08 14:39:04 -0400611
612 VerboseLogPacket(packet->data(), packet->size(), SCTP_DUMP_INBOUND);
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000613 usrsctp_conninput(this, packet->data(), packet->size(), 0);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000614 } else {
615 // TODO(ldixon): Consider caching the packet for very slightly better
616 // reliability.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000617 }
618}
619
620void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
621 SctpInboundPacket* packet) {
622 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
623 << "Received SCTP data:"
624 << " ssrc=" << packet->params.ssrc
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000625 << " notification: " << (packet->flags & MSG_NOTIFICATION)
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000626 << " length=" << packet->buffer.size();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000627 // Sending a packet with data == NULL (no data) is SCTPs "close the
628 // connection" message. This sets sock_ = NULL;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000629 if (!packet->buffer.size() || !packet->buffer.data()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000630 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
631 "No data, closing.";
632 return;
633 }
634 if (packet->flags & MSG_NOTIFICATION) {
635 OnNotificationFromSctp(&packet->buffer);
636 } else {
637 OnDataFromSctpToChannel(packet->params, &packet->buffer);
638 }
639}
640
641void SctpDataMediaChannel::OnDataFromSctpToChannel(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000642 const ReceiveDataParams& params, rtc::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000643 if (receiving_) {
644 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000645 << "Posting with length: " << buffer->size()
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000646 << " on stream " << params.ssrc;
647 // Reports all received messages to upper layers, no matter whether the sid
648 // is known.
Karl Wiberg94784372015-04-20 14:03:07 +0200649 SignalDataReceived(params, buffer->data<char>(), buffer->size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000650 } else {
651 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
652 << "Not receiving packet with sid=" << params.ssrc
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000653 << " len=" << buffer->size() << " before SetReceive(true).";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000654 }
655}
656
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000657bool SctpDataMediaChannel::AddStream(const StreamParams& stream) {
658 if (!stream.has_ssrcs()) {
659 return false;
660 }
661
662 const uint32 ssrc = stream.first_ssrc();
663 if (open_streams_.find(ssrc) != open_streams_.end()) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000664 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000665 << "Not adding data stream '" << stream.id
666 << "' with ssrc=" << ssrc
667 << " because stream is already open.";
668 return false;
669 } else if (queued_reset_streams_.find(ssrc) != queued_reset_streams_.end()
670 || sent_reset_streams_.find(ssrc) != sent_reset_streams_.end()) {
671 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
672 << "Not adding data stream '" << stream.id
673 << "' with ssrc=" << ssrc
674 << " because stream is still closing.";
675 return false;
676 }
677
678 open_streams_.insert(ssrc);
679 return true;
680}
681
682bool SctpDataMediaChannel::ResetStream(uint32 ssrc) {
683 // We typically get this called twice for the same stream, once each for
684 // Send and Recv.
685 StreamSet::iterator found = open_streams_.find(ssrc);
686
687 if (found == open_streams_.end()) {
688 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
689 << "stream not found.";
690 return false;
691 } else {
692 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
693 << "Removing and queuing RE-CONFIG chunk.";
694 open_streams_.erase(found);
695 }
696
697 // SCTP won't let you have more than one stream reset pending at a time, but
698 // you can close multiple streams in a single reset. So, we keep an internal
699 // queue of streams-to-reset, and send them as one reset message in
700 // SendQueuedStreamResets().
701 queued_reset_streams_.insert(ssrc);
702
703 // Signal our stream-reset logic that it should try to send now, if it can.
704 SendQueuedStreamResets();
705
706 // The stream will actually get removed when we get the acknowledgment.
707 return true;
708}
709
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000710void SctpDataMediaChannel::OnNotificationFromSctp(rtc::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000711 const sctp_notification& notification =
712 reinterpret_cast<const sctp_notification&>(*buffer->data());
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +0000713 ASSERT(notification.sn_header.sn_length == buffer->size());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714
715 // TODO(ldixon): handle notifications appropriately.
716 switch (notification.sn_header.sn_type) {
717 case SCTP_ASSOC_CHANGE:
718 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
719 OnNotificationAssocChange(notification.sn_assoc_change);
720 break;
721 case SCTP_REMOTE_ERROR:
722 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
723 break;
724 case SCTP_SHUTDOWN_EVENT:
725 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
726 break;
727 case SCTP_ADAPTATION_INDICATION:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000728 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000729 break;
730 case SCTP_PARTIAL_DELIVERY_EVENT:
731 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
732 break;
733 case SCTP_AUTHENTICATION_EVENT:
734 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
735 break;
736 case SCTP_SENDER_DRY_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000737 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000738 SignalReadyToSend(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000739 break;
740 // TODO(ldixon): Unblock after congestion.
741 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
742 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
743 break;
744 case SCTP_SEND_FAILED_EVENT:
745 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
746 break;
747 case SCTP_STREAM_RESET_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000748 OnStreamResetEvent(&notification.sn_strreset_event);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749 break;
750 case SCTP_ASSOC_RESET_EVENT:
751 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
752 break;
753 case SCTP_STREAM_CHANGE_EVENT:
754 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000755 // An acknowledgment we get after our stream resets have gone through,
756 // if they've failed. We log the message, but don't react -- we don't
757 // keep around the last-transmitted set of SSIDs we wanted to close for
758 // error recovery. It doesn't seem likely to occur, and if so, likely
759 // harmless within the lifetime of a single SCTP association.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000760 break;
761 default:
762 LOG(LS_WARNING) << "Unknown SCTP event: "
763 << notification.sn_header.sn_type;
764 break;
765 }
766}
767
768void SctpDataMediaChannel::OnNotificationAssocChange(
769 const sctp_assoc_change& change) {
770 switch (change.sac_state) {
771 case SCTP_COMM_UP:
772 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
773 break;
774 case SCTP_COMM_LOST:
775 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
776 break;
777 case SCTP_RESTART:
778 LOG(LS_INFO) << "Association change SCTP_RESTART";
779 break;
780 case SCTP_SHUTDOWN_COMP:
781 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
782 break;
783 case SCTP_CANT_STR_ASSOC:
784 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
785 break;
786 default:
787 LOG(LS_INFO) << "Association change UNKNOWN";
788 break;
789 }
790}
791
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000792void SctpDataMediaChannel::OnStreamResetEvent(
793 const struct sctp_stream_reset_event* evt) {
794 // A stream reset always involves two RE-CONFIG chunks for us -- we always
795 // simultaneously reset a sid's sequence number in both directions. The
796 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
797 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
798 // RE-CONFIGs.
799 const int num_ssrcs = (evt->strreset_length - sizeof(*evt)) /
800 sizeof(evt->strreset_stream_list[0]);
801 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
802 << "): Flags = 0x"
803 << std::hex << evt->strreset_flags << " ("
804 << ListFlags(evt->strreset_flags) << ")";
805 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
806 << ListArray(evt->strreset_stream_list, num_ssrcs)
807 << "], Open: ["
808 << ListStreams(open_streams_) << "], Q'd: ["
809 << ListStreams(queued_reset_streams_) << "], Sent: ["
810 << ListStreams(sent_reset_streams_) << "]";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000811
812 // If both sides try to reset some streams at the same time (even if they're
813 // disjoint sets), we can get reset failures.
814 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
815 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
816 // is set seem to be garbage values. Ignore them.
817 queued_reset_streams_.insert(
818 sent_reset_streams_.begin(),
819 sent_reset_streams_.end());
820 sent_reset_streams_.clear();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000821
822 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
823 // Each side gets an event for each direction of a stream. That is,
824 // closing sid k will make each side receive INCOMING and OUTGOING reset
825 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
826 // get an INCOMING event first.
827 for (int i = 0; i < num_ssrcs; i++) {
828 const int stream_id = evt->strreset_stream_list[i];
829
830 // See if this stream ID was closed by our peer or ourselves.
831 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
832
833 // The reset was requested locally.
834 if (it != sent_reset_streams_.end()) {
835 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
836 << "): local sid " << stream_id << " acknowledged.";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000837 sent_reset_streams_.erase(it);
838
839 } else if ((it = open_streams_.find(stream_id))
840 != open_streams_.end()) {
841 // The peer requested the reset.
842 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
843 << "): closing sid " << stream_id;
844 open_streams_.erase(it);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +0000845 SignalStreamClosedRemotely(stream_id);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000846
847 } else if ((it = queued_reset_streams_.find(stream_id))
848 != queued_reset_streams_.end()) {
849 // The peer requested the reset, but there was a local reset
850 // queued.
851 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
852 << "): double-sided close for sid " << stream_id;
853 // Both sides want the stream closed, and the peer got to send the
854 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
855 // finished quickly.
856 queued_reset_streams_.erase(it);
857
858 } else {
859 // This stream is unknown. Sometimes this can be from an
860 // RESET_FAILED-related retransmit.
861 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
862 << "): Unknown sid " << stream_id;
863 }
864 }
865 }
866
jiayl@webrtc.org1a6c6282014-06-12 21:59:29 +0000867 // Always try to send the queued RESET because this call indicates that the
868 // last local RESET or remote RESET has made some progress.
869 SendQueuedStreamResets();
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000870}
871
wu@webrtc.org78187522013-10-07 23:32:02 +0000872// Puts the specified |param| from the codec identified by |id| into |dest|
873// and returns true. Or returns false if it wasn't there, leaving |dest|
874// untouched.
875static bool GetCodecIntParameter(const std::vector<DataCodec>& codecs,
876 int id, const std::string& name,
877 const std::string& param, int* dest) {
878 std::string value;
879 Codec match_pattern;
880 match_pattern.id = id;
881 match_pattern.name = name;
882 for (size_t i = 0; i < codecs.size(); ++i) {
883 if (codecs[i].Matches(match_pattern)) {
884 if (codecs[i].GetParam(param, &value)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000885 *dest = rtc::FromString<int>(value);
wu@webrtc.org78187522013-10-07 23:32:02 +0000886 return true;
887 }
888 }
889 }
890 return false;
891}
892
893bool SctpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
894 return GetCodecIntParameter(
895 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
896 &remote_port_);
897}
898
899bool SctpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
900 return GetCodecIntParameter(
901 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
902 &local_port_);
903}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904
905void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000906 rtc::Buffer* buffer) {
tommi73918812015-08-27 04:29:58 -0700907 if (buffer->size() > kSctpMtu) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000908 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000909 << "SCTP seems to have made a packet that is bigger "
tommi73918812015-08-27 04:29:58 -0700910 "than its official MTU.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000911 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000912 MediaChannel::SendPacket(buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913}
914
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000915bool SctpDataMediaChannel::SendQueuedStreamResets() {
916 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty())
917 return true;
918
919 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
920 << ListStreams(queued_reset_streams_) << "], Open: ["
921 << ListStreams(open_streams_) << "], Sent: ["
922 << ListStreams(sent_reset_streams_) << "]";
923
924 const size_t num_streams = queued_reset_streams_.size();
925 const size_t num_bytes = sizeof(struct sctp_reset_streams)
926 + (num_streams * sizeof(uint16));
927
928 std::vector<uint8> reset_stream_buf(num_bytes, 0);
929 struct sctp_reset_streams* resetp = reinterpret_cast<sctp_reset_streams*>(
930 &reset_stream_buf[0]);
931 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
932 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000933 resetp->srs_number_streams = rtc::checked_cast<uint16_t>(num_streams);
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000934 int result_idx = 0;
935 for (StreamSet::iterator it = queued_reset_streams_.begin();
936 it != queued_reset_streams_.end(); ++it) {
937 resetp->srs_stream_list[result_idx++] = *it;
938 }
939
jiayl@webrtc.orga576faf2014-01-29 17:45:53 +0000940 int ret = usrsctp_setsockopt(
941 sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000942 rtc::checked_cast<socklen_t>(reset_stream_buf.size()));
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000943 if (ret < 0) {
944 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to send a stream reset for "
945 << num_streams << " streams";
946 return false;
947 }
948
949 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
950 // it now.
951 queued_reset_streams_.swap(sent_reset_streams_);
952 return true;
953}
954
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000955void SctpDataMediaChannel::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956 switch (msg->message_id) {
957 case MSG_SCTPINBOUNDPACKET: {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000958 rtc::scoped_ptr<InboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000959 static_cast<InboundPacketMessage*>(msg->pdata));
960 OnInboundPacketFromSctpToChannel(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961 break;
962 }
963 case MSG_SCTPOUTBOUNDPACKET: {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000964 rtc::scoped_ptr<OutboundPacketMessage> pdata(
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000965 static_cast<OutboundPacketMessage*>(msg->pdata));
966 OnPacketFromSctpToNetwork(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967 break;
968 }
969 }
970}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000971} // namespace cricket