blob: 03bbdcaa1fe1e758d49f928b70afc39811629831 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle SCTP
3 * Copyright 2012 Google Inc, and Robin Seggelmann
4 *
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
35#include "talk/base/buffer.h"
36#include "talk/base/helpers.h"
37#include "talk/base/logging.h"
38#include "talk/media/base/codec.h"
39#include "talk/media/base/constants.h"
40#include "talk/media/base/streamparams.h"
41#include "usrsctplib/usrsctp.h"
42
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000043namespace {
44typedef cricket::SctpDataMediaChannel::StreamSet StreamSet;
45// Returns a comma-separated, human-readable list of the stream IDs in 's'
46std::string ListStreams(const StreamSet& s) {
47 std::stringstream result;
48 bool first = true;
wu@webrtc.orge00265e2014-01-07 19:32:40 +000049 for (StreamSet::const_iterator it = s.begin(); it != s.end(); ++it) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +000050 if (!first) {
51 result << ", " << *it;
52 } else {
53 result << *it;
54 first = false;
55 }
56 }
57 return result.str();
58}
59
60// Returns a pipe-separated, human-readable list of the SCTP_STREAM_RESET
61// flags in 'flags'
62std::string ListFlags(int flags) {
63 std::stringstream result;
64 bool first = true;
65 // Skip past the first 12 chars (strlen("SCTP_STREAM_"))
66#define MAKEFLAG(X) { X, #X + 12}
67 struct flaginfo_t {
68 int value;
69 const char* name;
70 } flaginfo[] = {
71 MAKEFLAG(SCTP_STREAM_RESET_INCOMING_SSN),
72 MAKEFLAG(SCTP_STREAM_RESET_OUTGOING_SSN),
73 MAKEFLAG(SCTP_STREAM_RESET_DENIED),
74 MAKEFLAG(SCTP_STREAM_RESET_FAILED),
75 MAKEFLAG(SCTP_STREAM_CHANGE_DENIED)
76 };
77#undef MAKEFLAG
78 for (int i = 0; i < ARRAY_SIZE(flaginfo); ++i) {
79 if (flags & flaginfo[i].value) {
80 if (!first) result << " | ";
81 result << flaginfo[i].name;
82 first = false;
83 }
84 }
85 return result.str();
86}
87
88// Returns a comma-separated, human-readable list of the integers in 'array'.
89// All 'num_elems' of them.
90std::string ListArray(const uint16* array, int num_elems) {
91 std::stringstream result;
92 for (int i = 0; i < num_elems; ++i) {
93 if (i) {
94 result << ", " << array[i];
95 } else {
96 result << array[i];
97 }
98 }
99 return result.str();
100}
101} // namespace
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103namespace cricket {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000104typedef talk_base::ScopedMessageData<SctpInboundPacket> InboundPacketMessage;
105typedef talk_base::ScopedMessageData<talk_base::Buffer> OutboundPacketMessage;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106
107// This is the SCTP port to use. It is passed along the wire and the listener
108// and connector must be using the same port. It is not related to the ports at
109// the IP level. (Corresponds to: sockaddr_conn.sconn_port in usrsctp.h)
110//
111// TODO(ldixon): Allow port to be set from higher level code.
112static const int kSctpDefaultPort = 5001;
113// TODO(ldixon): Find where this is defined, and also check is Sctp really
114// respects this.
115static const size_t kSctpMtu = 1280;
116
117enum {
118 MSG_SCTPINBOUNDPACKET = 1, // MessageData is SctpInboundPacket
119 MSG_SCTPOUTBOUNDPACKET = 2, // MessageData is talk_base:Buffer
120};
121
122struct SctpInboundPacket {
123 talk_base::Buffer buffer;
124 ReceiveDataParams params;
125 // The |flags| parameter is used by SCTP to distinguish notification packets
126 // from other types of packets.
127 int flags;
128};
129
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000130// Helper for logging SCTP messages.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131static void debug_sctp_printf(const char *format, ...) {
132 char s[255];
133 va_list ap;
134 va_start(ap, format);
135 vsnprintf(s, sizeof(s), format, ap);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000136 LOG(LS_INFO) << "SCTP: " << s;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137 va_end(ap);
138}
139
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000140// Get the PPID to use for the terminating fragment of this type.
141static SctpDataMediaChannel::PayloadProtocolIdentifier GetPpid(
142 cricket::DataMessageType type) {
143 switch (type) {
144 default:
145 case cricket::DMT_NONE:
146 return SctpDataMediaChannel::PPID_NONE;
147 case cricket::DMT_CONTROL:
148 return SctpDataMediaChannel::PPID_CONTROL;
149 case cricket::DMT_BINARY:
150 return SctpDataMediaChannel::PPID_BINARY_LAST;
151 case cricket::DMT_TEXT:
152 return SctpDataMediaChannel::PPID_TEXT_LAST;
153 };
154}
155
156static bool GetDataMediaType(
157 SctpDataMediaChannel::PayloadProtocolIdentifier ppid,
158 cricket::DataMessageType *dest) {
159 ASSERT(dest != NULL);
160 switch (ppid) {
161 case SctpDataMediaChannel::PPID_BINARY_PARTIAL:
162 case SctpDataMediaChannel::PPID_BINARY_LAST:
163 *dest = cricket::DMT_BINARY;
164 return true;
165
166 case SctpDataMediaChannel::PPID_TEXT_PARTIAL:
167 case SctpDataMediaChannel::PPID_TEXT_LAST:
168 *dest = cricket::DMT_TEXT;
169 return true;
170
171 case SctpDataMediaChannel::PPID_CONTROL:
172 *dest = cricket::DMT_CONTROL;
173 return true;
174
175 case SctpDataMediaChannel::PPID_NONE:
176 *dest = cricket::DMT_NONE;
177 return true;
178
179 default:
180 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000181 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182}
183
184// This is the callback usrsctp uses when there's data to send on the network
185// that has been wrapped appropriatly for the SCTP protocol.
186static int OnSctpOutboundPacket(void* addr, void* data, size_t length,
187 uint8_t tos, uint8_t set_df) {
188 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(addr);
189 LOG(LS_VERBOSE) << "global OnSctpOutboundPacket():"
190 << "addr: " << addr << "; length: " << length
191 << "; tos: " << std::hex << static_cast<int>(tos)
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000192 << "; set_df: " << std::hex << static_cast<int>(set_df);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193 // Note: We have to copy the data; the caller will delete it.
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000194 OutboundPacketMessage* msg =
195 new OutboundPacketMessage(new talk_base::Buffer(data, length));
196 channel->worker_thread()->Post(channel, MSG_SCTPOUTBOUNDPACKET, msg);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000197 return 0;
198}
199
200// This is the callback called from usrsctp when data has been received, after
201// a packet has been interpreted and parsed by usrsctp and found to contain
202// payload data. It is called by a usrsctp thread. It is assumed this function
203// will free the memory used by 'data'.
204static int OnSctpInboundPacket(struct socket* sock, union sctp_sockstore addr,
205 void* data, size_t length,
206 struct sctp_rcvinfo rcv, int flags,
207 void* ulp_info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000208 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(ulp_info);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000209 // Post data to the channel's receiver thread (copying it).
210 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
211 // memory cleanup. But this does simplify code.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000212 const SctpDataMediaChannel::PayloadProtocolIdentifier ppid =
213 static_cast<SctpDataMediaChannel::PayloadProtocolIdentifier>(
214 talk_base::HostToNetwork32(rcv.rcv_ppid));
215 cricket::DataMessageType type = cricket::DMT_NONE;
216 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
217 // It's neither a notification nor a recognized data packet. Drop it.
218 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
219 << " on an SCTP packet. Dropping.";
220 } else {
221 SctpInboundPacket* packet = new SctpInboundPacket;
222 packet->buffer.SetData(data, length);
223 packet->params.ssrc = rcv.rcv_sid;
224 packet->params.seq_num = rcv.rcv_ssn;
225 packet->params.timestamp = rcv.rcv_tsn;
226 packet->params.type = type;
227 packet->flags = flags;
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000228 // The ownership of |packet| transfers to |msg|.
229 InboundPacketMessage* msg = new InboundPacketMessage(packet);
230 channel->worker_thread()->Post(channel, MSG_SCTPINBOUNDPACKET, msg);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000231 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000232 free(data);
233 return 1;
234}
235
236// Set the initial value of the static SCTP Data Engines reference count.
237int SctpDataEngine::usrsctp_engines_count = 0;
238
239SctpDataEngine::SctpDataEngine() {
240 if (usrsctp_engines_count == 0) {
241 // First argument is udp_encapsulation_port, which is not releveant for our
242 // AF_CONN use of sctp.
243 usrsctp_init(0, cricket::OnSctpOutboundPacket, debug_sctp_printf);
244
245 // To turn on/off detailed SCTP debugging. You will also need to have the
246 // SCTP_DEBUG cpp defines flag.
247 // usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
248
249 // TODO(ldixon): Consider turning this on/off.
250 usrsctp_sysctl_set_sctp_ecn_enable(0);
251
252 // TODO(ldixon): Consider turning this on/off.
253 // This is not needed right now (we don't do dynamic address changes):
254 // If SCTP Auto-ASCONF is enabled, the peer is informed automatically
255 // when a new address is added or removed. This feature is enabled by
256 // default.
257 // usrsctp_sysctl_set_sctp_auto_asconf(0);
258
259 // TODO(ldixon): Consider turning this on/off.
260 // Add a blackhole sysctl. Setting it to 1 results in no ABORTs
261 // being sent in response to INITs, setting it to 2 results
262 // in no ABORTs being sent for received OOTB packets.
263 // This is similar to the TCP sysctl.
264 //
265 // See: http://lakerest.net/pipermail/sctp-coders/2012-January/009438.html
266 // See: http://svnweb.freebsd.org/base?view=revision&revision=229805
267 // usrsctp_sysctl_set_sctp_blackhole(2);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000268
269 // Set the number of default outgoing streams. This is the number we'll
270 // send in the SCTP INIT message. The 'appropriate default' in the
271 // second paragraph of
272 // http://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-05#section-6.2
273 // is cricket::kMaxSctpSid.
274 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(
275 cricket::kMaxSctpSid);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000276 }
277 usrsctp_engines_count++;
278
279 // We don't put in a codec because we don't want one offered when we
280 // use the hybrid data engine.
281 // codecs_.push_back(cricket::DataCodec( kGoogleSctpDataCodecId,
282 // kGoogleSctpDataCodecName, 0));
283}
284
285SctpDataEngine::~SctpDataEngine() {
286 // TODO(ldixon): There is currently a bug in teardown of usrsctp that blocks
287 // indefintely if a finish call made too soon after close calls. So teardown
288 // has been skipped. Once the bug is fixed, retest and enable teardown.
289 //
290 // usrsctp_engines_count--;
291 // LOG(LS_VERBOSE) << "usrsctp_engines_count:" << usrsctp_engines_count;
292 // if (usrsctp_engines_count == 0) {
293 // if (usrsctp_finish() != 0) {
294 // LOG(LS_WARNING) << "usrsctp_finish.";
295 // }
296 // }
297}
298
299DataMediaChannel* SctpDataEngine::CreateChannel(
300 DataChannelType data_channel_type) {
301 if (data_channel_type != DCT_SCTP) {
302 return NULL;
303 }
304 return new SctpDataMediaChannel(talk_base::Thread::Current());
305}
306
307SctpDataMediaChannel::SctpDataMediaChannel(talk_base::Thread* thread)
308 : worker_thread_(thread),
wu@webrtc.org78187522013-10-07 23:32:02 +0000309 local_port_(-1),
310 remote_port_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000311 sock_(NULL),
312 sending_(false),
313 receiving_(false),
314 debug_name_("SctpDataMediaChannel") {
315}
316
317SctpDataMediaChannel::~SctpDataMediaChannel() {
318 CloseSctpSocket();
319}
320
321sockaddr_conn SctpDataMediaChannel::GetSctpSockAddr(int port) {
322 sockaddr_conn sconn = {0};
323 sconn.sconn_family = AF_CONN;
324#ifdef HAVE_SCONN_LEN
325 sconn.sconn_len = sizeof(sockaddr_conn);
326#endif
327 // Note: conversion from int to uint16_t happens here.
328 sconn.sconn_port = talk_base::HostToNetwork16(port);
329 sconn.sconn_addr = this;
330 return sconn;
331}
332
333bool SctpDataMediaChannel::OpenSctpSocket() {
334 if (sock_) {
335 LOG(LS_VERBOSE) << debug_name_
336 << "->Ignoring attempt to re-create existing socket.";
337 return false;
338 }
339 sock_ = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP,
340 cricket::OnSctpInboundPacket, NULL, 0, this);
341 if (!sock_) {
342 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to create SCTP socket.";
343 return false;
344 }
345
346 // Make the socket non-blocking. Connect, close, shutdown etc will not block
347 // the thread waiting for the socket operation to complete.
348 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
349 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP to non blocking.";
350 return false;
351 }
352
353 // This ensures that the usrsctp close call deletes the association. This
354 // prevents usrsctp from calling OnSctpOutboundPacket with references to
355 // this class as the address.
356 linger linger_opt;
357 linger_opt.l_onoff = 1;
358 linger_opt.l_linger = 0;
359 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
360 sizeof(linger_opt))) {
361 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SO_LINGER.";
362 return false;
363 }
364
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000365 // Enable stream ID resets.
366 struct sctp_assoc_value stream_rst;
367 stream_rst.assoc_id = SCTP_ALL_ASSOC;
368 stream_rst.assoc_value = 1;
369 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
370 &stream_rst, sizeof(stream_rst))) {
371 LOG_ERRNO(LS_ERROR) << debug_name_
372 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
373 return false;
374 }
375
376 // Nagle.
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000377 uint32_t nodelay = 1;
378 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
379 sizeof(nodelay))) {
380 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_NODELAY.";
381 return false;
382 }
383
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000384 // Subscribe to SCTP event notifications.
385 int event_types[] = {SCTP_ASSOC_CHANGE,
386 SCTP_PEER_ADDR_CHANGE,
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000387 SCTP_SEND_FAILED_EVENT,
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000388 SCTP_SENDER_DRY_EVENT,
389 SCTP_STREAM_RESET_EVENT};
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000390 struct sctp_event event = {0};
391 event.se_assoc_id = SCTP_ALL_ASSOC;
392 event.se_on = 1;
393 for (size_t i = 0; i < ARRAY_SIZE(event_types); i++) {
394 event.se_type = event_types[i];
395 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
396 sizeof(event)) < 0) {
397 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_EVENT type: "
398 << event.se_type;
399 return false;
400 }
401 }
402
403 // Register this class as an address for usrsctp. This is used by SCTP to
404 // direct the packets received (by the created socket) to this class.
405 usrsctp_register_address(this);
406 sending_ = true;
407 return true;
408}
409
410void SctpDataMediaChannel::CloseSctpSocket() {
411 sending_ = false;
412 if (sock_) {
413 // We assume that SO_LINGER option is set to close the association when
414 // close is called. This means that any pending packets in usrsctp will be
415 // discarded instead of being sent.
416 usrsctp_close(sock_);
417 sock_ = NULL;
418 usrsctp_deregister_address(this);
419 }
420}
421
422bool SctpDataMediaChannel::Connect() {
423 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
wu@webrtc.org78187522013-10-07 23:32:02 +0000424 if (remote_port_ < 0) {
425 remote_port_ = kSctpDefaultPort;
426 }
427 if (local_port_ < 0) {
428 local_port_ = kSctpDefaultPort;
429 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000430
431 // If we already have a socket connection, just return.
432 if (sock_) {
433 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
434 "is already established.";
435 return true;
436 }
437
438 // If no socket (it was closed) try to start it again. This can happen when
439 // the socket we are connecting to closes, does an sctp shutdown handshake,
440 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
441 if (!sock_ && !OpenSctpSocket()) {
442 return false;
443 }
444
445 // Note: conversion from int to uint16_t happens on assignment.
446 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
447 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
448 sizeof(local_sconn)) < 0) {
449 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
450 << ("Failed usrsctp_bind");
451 CloseSctpSocket();
452 return false;
453 }
454
455 // Note: conversion from int to uint16_t happens on assignment.
456 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
457 int connect_result = usrsctp_connect(
458 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000459 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
460 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
461 << errno << ", but wanted " << SCTP_EINPROGRESS;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000462 CloseSctpSocket();
463 return false;
464 }
465 return true;
466}
467
468void SctpDataMediaChannel::Disconnect() {
469 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
470 // shutdown handshake and remove the association.
471 CloseSctpSocket();
472}
473
474bool SctpDataMediaChannel::SetSend(bool send) {
475 if (!sending_ && send) {
476 return Connect();
477 }
478 if (sending_ && !send) {
479 Disconnect();
480 }
481 return true;
482}
483
484bool SctpDataMediaChannel::SetReceive(bool receive) {
485 receiving_ = receive;
486 return true;
487}
488
489bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000490 return AddStream(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000491}
492
493bool SctpDataMediaChannel::RemoveSendStream(uint32 ssrc) {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000494 return ResetStream(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000495}
496
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000497bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
mallinath@webrtc.org0f3356e2014-01-11 01:26:23 +0000498 // SCTP DataChannels are always bi-directional and calling AddSendStream will
499 // enable both sending and receiving on the stream. So AddRecvStream is a
500 // no-op.
501 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000502}
503
504bool SctpDataMediaChannel::RemoveRecvStream(uint32 ssrc) {
mallinath@webrtc.org0f3356e2014-01-11 01:26:23 +0000505 // SCTP DataChannels are always bi-directional and calling RemoveSendStream
506 // will disable both sending and receiving on the stream. So RemoveRecvStream
507 // is a no-op.
508 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000509}
510
511bool SctpDataMediaChannel::SendData(
512 const SendDataParams& params,
513 const talk_base::Buffer& payload,
514 SendDataResult* result) {
515 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000516 // Preset |result| to assume an error. If SendData succeeds, we'll
517 // overwrite |*result| once more at the end.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000518 *result = SDR_ERROR;
519 }
520
521 if (!sending_) {
522 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
523 << "Not sending packet with ssrc=" << params.ssrc
524 << " len=" << payload.length() << " before SetSend(true).";
525 return false;
526 }
527
wu@webrtc.org91053e72013-08-10 07:18:04 +0000528 if (params.type != cricket::DMT_CONTROL &&
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000529 open_streams_.find(params.ssrc) == open_streams_.end()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000530 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
531 << "Not sending data because ssrc is unknown: "
532 << params.ssrc;
533 return false;
534 }
535
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000536 //
537 // Send data using SCTP.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000538 ssize_t send_res = 0; // result from usrsctp_sendv.
539 struct sctp_sendv_spa spa = {0};
540 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
541 spa.sendv_sndinfo.snd_sid = params.ssrc;
542 spa.sendv_sndinfo.snd_ppid = talk_base::HostToNetwork32(
543 GetPpid(params.type));
544
545 // Ordered implies reliable.
546 if (!params.ordered) {
547 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
548 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
549 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
550 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
551 spa.sendv_prinfo.pr_value = params.max_rtx_count;
552 } else {
553 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
554 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
555 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
556 }
557 }
558
559 // We don't fragment.
560 send_res = usrsctp_sendv(sock_, payload.data(),
561 static_cast<size_t>(payload.length()),
562 NULL, 0, &spa,
563 static_cast<socklen_t>(sizeof(spa)),
564 SCTP_SENDV_SPA, 0);
565 if (send_res < 0) {
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000566 if (errno == EWOULDBLOCK) {
567 *result = SDR_BLOCK;
568 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
569 } else {
570 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
571 << "->SendData(...): "
572 << " usrsctp_sendv: ";
573 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000574 return false;
575 }
576 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000577 // Only way out now is success.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000578 *result = SDR_SUCCESS;
579 }
580 return true;
581}
582
583// Called by network interface when a packet has been received.
wu@webrtc.orga9890802013-12-13 00:21:03 +0000584void SctpDataMediaChannel::OnPacketReceived(
585 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000586 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): " << " length="
587 << packet->length() << ", sending: " << sending_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000588 // Only give receiving packets to usrsctp after if connected. This enables two
589 // peers to each make a connect call, but for them not to receive an INIT
590 // packet before they have called connect; least the last receiver of the INIT
591 // packet will have called connect, and a connection will be established.
592 if (sending_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
594 // will be will be given to the global OnSctpInboundData, and then,
595 // marshalled by a Post and handled with OnMessage.
596 usrsctp_conninput(this, packet->data(), packet->length(), 0);
597 } else {
598 // TODO(ldixon): Consider caching the packet for very slightly better
599 // reliability.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000600 }
601}
602
603void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
604 SctpInboundPacket* packet) {
605 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
606 << "Received SCTP data:"
607 << " ssrc=" << packet->params.ssrc
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000608 << " notification: " << (packet->flags & MSG_NOTIFICATION)
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000609 << " length=" << packet->buffer.length();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000610 // Sending a packet with data == NULL (no data) is SCTPs "close the
611 // connection" message. This sets sock_ = NULL;
612 if (!packet->buffer.length() || !packet->buffer.data()) {
613 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
614 "No data, closing.";
615 return;
616 }
617 if (packet->flags & MSG_NOTIFICATION) {
618 OnNotificationFromSctp(&packet->buffer);
619 } else {
620 OnDataFromSctpToChannel(packet->params, &packet->buffer);
621 }
622}
623
624void SctpDataMediaChannel::OnDataFromSctpToChannel(
625 const ReceiveDataParams& params, talk_base::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000626 if (receiving_) {
627 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
mallinath@webrtc.org0f3356e2014-01-11 01:26:23 +0000628 << "Posting with length: " << buffer->length()
629 << " on stream " << params.ssrc;
630 // Reports all received messages to upper layers, no matter whether the sid
631 // is known.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000632 SignalDataReceived(params, buffer->data(), buffer->length());
633 } else {
634 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
635 << "Not receiving packet with sid=" << params.ssrc
636 << " len=" << buffer->length()
637 << " before SetReceive(true).";
638 }
639}
640
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000641bool SctpDataMediaChannel::AddStream(const StreamParams& stream) {
642 if (!stream.has_ssrcs()) {
643 return false;
644 }
645
646 const uint32 ssrc = stream.first_ssrc();
647 if (open_streams_.find(ssrc) != open_streams_.end()) {
mallinath@webrtc.org0f3356e2014-01-11 01:26:23 +0000648 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000649 << "Not adding data stream '" << stream.id
650 << "' with ssrc=" << ssrc
651 << " because stream is already open.";
652 return false;
653 } else if (queued_reset_streams_.find(ssrc) != queued_reset_streams_.end()
654 || sent_reset_streams_.find(ssrc) != sent_reset_streams_.end()) {
655 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
656 << "Not adding data stream '" << stream.id
657 << "' with ssrc=" << ssrc
658 << " because stream is still closing.";
659 return false;
660 }
661
662 open_streams_.insert(ssrc);
663 return true;
664}
665
666bool SctpDataMediaChannel::ResetStream(uint32 ssrc) {
667 // We typically get this called twice for the same stream, once each for
668 // Send and Recv.
669 StreamSet::iterator found = open_streams_.find(ssrc);
670
671 if (found == open_streams_.end()) {
672 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
673 << "stream not found.";
674 return false;
675 } else {
676 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
677 << "Removing and queuing RE-CONFIG chunk.";
678 open_streams_.erase(found);
679 }
680
681 // SCTP won't let you have more than one stream reset pending at a time, but
682 // you can close multiple streams in a single reset. So, we keep an internal
683 // queue of streams-to-reset, and send them as one reset message in
684 // SendQueuedStreamResets().
685 queued_reset_streams_.insert(ssrc);
686
687 // Signal our stream-reset logic that it should try to send now, if it can.
688 SendQueuedStreamResets();
689
690 // The stream will actually get removed when we get the acknowledgment.
691 return true;
692}
693
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000694void SctpDataMediaChannel::OnNotificationFromSctp(talk_base::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000695 const sctp_notification& notification =
696 reinterpret_cast<const sctp_notification&>(*buffer->data());
697 ASSERT(notification.sn_header.sn_length == buffer->length());
698
699 // TODO(ldixon): handle notifications appropriately.
700 switch (notification.sn_header.sn_type) {
701 case SCTP_ASSOC_CHANGE:
702 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
703 OnNotificationAssocChange(notification.sn_assoc_change);
704 break;
705 case SCTP_REMOTE_ERROR:
706 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
707 break;
708 case SCTP_SHUTDOWN_EVENT:
709 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
710 break;
711 case SCTP_ADAPTATION_INDICATION:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000712 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000713 break;
714 case SCTP_PARTIAL_DELIVERY_EVENT:
715 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
716 break;
717 case SCTP_AUTHENTICATION_EVENT:
718 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
719 break;
720 case SCTP_SENDER_DRY_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000721 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000722 SignalReadyToSend(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723 break;
724 // TODO(ldixon): Unblock after congestion.
725 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
726 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
727 break;
728 case SCTP_SEND_FAILED_EVENT:
729 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
730 break;
731 case SCTP_STREAM_RESET_EVENT:
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000732 OnStreamResetEvent(&notification.sn_strreset_event);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 break;
734 case SCTP_ASSOC_RESET_EVENT:
735 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
736 break;
737 case SCTP_STREAM_CHANGE_EVENT:
738 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000739 // An acknowledgment we get after our stream resets have gone through,
740 // if they've failed. We log the message, but don't react -- we don't
741 // keep around the last-transmitted set of SSIDs we wanted to close for
742 // error recovery. It doesn't seem likely to occur, and if so, likely
743 // harmless within the lifetime of a single SCTP association.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744 break;
745 default:
746 LOG(LS_WARNING) << "Unknown SCTP event: "
747 << notification.sn_header.sn_type;
748 break;
749 }
750}
751
752void SctpDataMediaChannel::OnNotificationAssocChange(
753 const sctp_assoc_change& change) {
754 switch (change.sac_state) {
755 case SCTP_COMM_UP:
756 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
757 break;
758 case SCTP_COMM_LOST:
759 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
760 break;
761 case SCTP_RESTART:
762 LOG(LS_INFO) << "Association change SCTP_RESTART";
763 break;
764 case SCTP_SHUTDOWN_COMP:
765 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
766 break;
767 case SCTP_CANT_STR_ASSOC:
768 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
769 break;
770 default:
771 LOG(LS_INFO) << "Association change UNKNOWN";
772 break;
773 }
774}
775
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000776void SctpDataMediaChannel::OnStreamResetEvent(
777 const struct sctp_stream_reset_event* evt) {
778 // A stream reset always involves two RE-CONFIG chunks for us -- we always
779 // simultaneously reset a sid's sequence number in both directions. The
780 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
781 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
782 // RE-CONFIGs.
783 const int num_ssrcs = (evt->strreset_length - sizeof(*evt)) /
784 sizeof(evt->strreset_stream_list[0]);
785 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
786 << "): Flags = 0x"
787 << std::hex << evt->strreset_flags << " ("
788 << ListFlags(evt->strreset_flags) << ")";
789 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
790 << ListArray(evt->strreset_stream_list, num_ssrcs)
791 << "], Open: ["
792 << ListStreams(open_streams_) << "], Q'd: ["
793 << ListStreams(queued_reset_streams_) << "], Sent: ["
794 << ListStreams(sent_reset_streams_) << "]";
795 bool local_stream_reset_acknowledged = false;
796
797 // If both sides try to reset some streams at the same time (even if they're
798 // disjoint sets), we can get reset failures.
799 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
800 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
801 // is set seem to be garbage values. Ignore them.
802 queued_reset_streams_.insert(
803 sent_reset_streams_.begin(),
804 sent_reset_streams_.end());
805 sent_reset_streams_.clear();
806 local_stream_reset_acknowledged = true;
807
808 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
809 // Each side gets an event for each direction of a stream. That is,
810 // closing sid k will make each side receive INCOMING and OUTGOING reset
811 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
812 // get an INCOMING event first.
813 for (int i = 0; i < num_ssrcs; i++) {
814 const int stream_id = evt->strreset_stream_list[i];
815
816 // See if this stream ID was closed by our peer or ourselves.
817 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
818
819 // The reset was requested locally.
820 if (it != sent_reset_streams_.end()) {
821 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
822 << "): local sid " << stream_id << " acknowledged.";
823 local_stream_reset_acknowledged = true;
824 sent_reset_streams_.erase(it);
825
826 } else if ((it = open_streams_.find(stream_id))
827 != open_streams_.end()) {
828 // The peer requested the reset.
829 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
830 << "): closing sid " << stream_id;
831 open_streams_.erase(it);
832 SignalStreamClosed(stream_id);
833
834 } else if ((it = queued_reset_streams_.find(stream_id))
835 != queued_reset_streams_.end()) {
836 // The peer requested the reset, but there was a local reset
837 // queued.
838 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
839 << "): double-sided close for sid " << stream_id;
840 // Both sides want the stream closed, and the peer got to send the
841 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
842 // finished quickly.
843 queued_reset_streams_.erase(it);
844
845 } else {
846 // This stream is unknown. Sometimes this can be from an
847 // RESET_FAILED-related retransmit.
848 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
849 << "): Unknown sid " << stream_id;
850 }
851 }
852 }
853
854 if (local_stream_reset_acknowledged) {
855 // This message acknowledges the last stream-reset request we sent out
856 // (only one can be outstanding at a time). Send out the next one.
857 SendQueuedStreamResets();
858 }
859}
860
wu@webrtc.org78187522013-10-07 23:32:02 +0000861// Puts the specified |param| from the codec identified by |id| into |dest|
862// and returns true. Or returns false if it wasn't there, leaving |dest|
863// untouched.
864static bool GetCodecIntParameter(const std::vector<DataCodec>& codecs,
865 int id, const std::string& name,
866 const std::string& param, int* dest) {
867 std::string value;
868 Codec match_pattern;
869 match_pattern.id = id;
870 match_pattern.name = name;
871 for (size_t i = 0; i < codecs.size(); ++i) {
872 if (codecs[i].Matches(match_pattern)) {
873 if (codecs[i].GetParam(param, &value)) {
874 *dest = talk_base::FromString<int>(value);
875 return true;
876 }
877 }
878 }
879 return false;
880}
881
882bool SctpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
883 return GetCodecIntParameter(
884 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
885 &remote_port_);
886}
887
888bool SctpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
889 return GetCodecIntParameter(
890 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
891 &local_port_);
892}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000893
894void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
895 talk_base::Buffer* buffer) {
896 if (buffer->length() > kSctpMtu) {
897 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000898 << "SCTP seems to have made a packet that is bigger "
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899 "than its official MTU.";
900 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000901 MediaChannel::SendPacket(buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000902}
903
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000904bool SctpDataMediaChannel::SendQueuedStreamResets() {
905 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty())
906 return true;
907
908 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
909 << ListStreams(queued_reset_streams_) << "], Open: ["
910 << ListStreams(open_streams_) << "], Sent: ["
911 << ListStreams(sent_reset_streams_) << "]";
912
913 const size_t num_streams = queued_reset_streams_.size();
914 const size_t num_bytes = sizeof(struct sctp_reset_streams)
915 + (num_streams * sizeof(uint16));
916
917 std::vector<uint8> reset_stream_buf(num_bytes, 0);
918 struct sctp_reset_streams* resetp = reinterpret_cast<sctp_reset_streams*>(
919 &reset_stream_buf[0]);
920 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
921 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
922 resetp->srs_number_streams = num_streams;
923 int result_idx = 0;
924 for (StreamSet::iterator it = queued_reset_streams_.begin();
925 it != queued_reset_streams_.end(); ++it) {
926 resetp->srs_stream_list[result_idx++] = *it;
927 }
928
929 int ret = usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
930 reset_stream_buf.size());
931 if (ret < 0) {
932 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to send a stream reset for "
933 << num_streams << " streams";
934 return false;
935 }
936
937 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
938 // it now.
939 queued_reset_streams_.swap(sent_reset_streams_);
940 return true;
941}
942
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943void SctpDataMediaChannel::OnMessage(talk_base::Message* msg) {
944 switch (msg->message_id) {
945 case MSG_SCTPINBOUNDPACKET: {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000946 talk_base::scoped_ptr<InboundPacketMessage> pdata(
947 static_cast<InboundPacketMessage*>(msg->pdata));
948 OnInboundPacketFromSctpToChannel(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 break;
950 }
951 case MSG_SCTPOUTBOUNDPACKET: {
wu@webrtc.orgf6d6ed02014-01-03 22:08:47 +0000952 talk_base::scoped_ptr<OutboundPacketMessage> pdata(
953 static_cast<OutboundPacketMessage*>(msg->pdata));
954 OnPacketFromSctpToNetwork(pdata->data().get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 break;
956 }
957 }
958}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959} // namespace cricket