blob: 2e8e90c19318d9d1ffdb09f77ae3c679eba31b04 [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>
32#include <vector>
33
34#include "talk/base/buffer.h"
35#include "talk/base/helpers.h"
36#include "talk/base/logging.h"
37#include "talk/media/base/codec.h"
38#include "talk/media/base/constants.h"
39#include "talk/media/base/streamparams.h"
40#include "usrsctplib/usrsctp.h"
41
henrike@webrtc.org28e20752013-07-10 00:45:36 +000042namespace cricket {
43
44// This is the SCTP port to use. It is passed along the wire and the listener
45// and connector must be using the same port. It is not related to the ports at
46// the IP level. (Corresponds to: sockaddr_conn.sconn_port in usrsctp.h)
47//
48// TODO(ldixon): Allow port to be set from higher level code.
49static const int kSctpDefaultPort = 5001;
50// TODO(ldixon): Find where this is defined, and also check is Sctp really
51// respects this.
52static const size_t kSctpMtu = 1280;
53
54enum {
55 MSG_SCTPINBOUNDPACKET = 1, // MessageData is SctpInboundPacket
56 MSG_SCTPOUTBOUNDPACKET = 2, // MessageData is talk_base:Buffer
57};
58
59struct SctpInboundPacket {
60 talk_base::Buffer buffer;
61 ReceiveDataParams params;
62 // The |flags| parameter is used by SCTP to distinguish notification packets
63 // from other types of packets.
64 int flags;
65};
66
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000067// Helper for logging SCTP messages.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068static void debug_sctp_printf(const char *format, ...) {
69 char s[255];
70 va_list ap;
71 va_start(ap, format);
72 vsnprintf(s, sizeof(s), format, ap);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000073 LOG(LS_INFO) << "SCTP: " << s;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074 va_end(ap);
75}
76
mallinath@webrtc.org1112c302013-09-23 20:34:45 +000077// Get the PPID to use for the terminating fragment of this type.
78static SctpDataMediaChannel::PayloadProtocolIdentifier GetPpid(
79 cricket::DataMessageType type) {
80 switch (type) {
81 default:
82 case cricket::DMT_NONE:
83 return SctpDataMediaChannel::PPID_NONE;
84 case cricket::DMT_CONTROL:
85 return SctpDataMediaChannel::PPID_CONTROL;
86 case cricket::DMT_BINARY:
87 return SctpDataMediaChannel::PPID_BINARY_LAST;
88 case cricket::DMT_TEXT:
89 return SctpDataMediaChannel::PPID_TEXT_LAST;
90 };
91}
92
93static bool GetDataMediaType(
94 SctpDataMediaChannel::PayloadProtocolIdentifier ppid,
95 cricket::DataMessageType *dest) {
96 ASSERT(dest != NULL);
97 switch (ppid) {
98 case SctpDataMediaChannel::PPID_BINARY_PARTIAL:
99 case SctpDataMediaChannel::PPID_BINARY_LAST:
100 *dest = cricket::DMT_BINARY;
101 return true;
102
103 case SctpDataMediaChannel::PPID_TEXT_PARTIAL:
104 case SctpDataMediaChannel::PPID_TEXT_LAST:
105 *dest = cricket::DMT_TEXT;
106 return true;
107
108 case SctpDataMediaChannel::PPID_CONTROL:
109 *dest = cricket::DMT_CONTROL;
110 return true;
111
112 case SctpDataMediaChannel::PPID_NONE:
113 *dest = cricket::DMT_NONE;
114 return true;
115
116 default:
117 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119}
120
121// This is the callback usrsctp uses when there's data to send on the network
122// that has been wrapped appropriatly for the SCTP protocol.
123static int OnSctpOutboundPacket(void* addr, void* data, size_t length,
124 uint8_t tos, uint8_t set_df) {
125 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(addr);
126 LOG(LS_VERBOSE) << "global OnSctpOutboundPacket():"
127 << "addr: " << addr << "; length: " << length
128 << "; tos: " << std::hex << static_cast<int>(tos)
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000129 << "; set_df: " << std::hex << static_cast<int>(set_df);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000130 // Note: We have to copy the data; the caller will delete it.
131 talk_base::Buffer* buffer = new talk_base::Buffer(data, length);
132 channel->worker_thread()->Post(channel, MSG_SCTPOUTBOUNDPACKET,
133 talk_base::WrapMessageData(buffer));
134 return 0;
135}
136
137// This is the callback called from usrsctp when data has been received, after
138// a packet has been interpreted and parsed by usrsctp and found to contain
139// payload data. It is called by a usrsctp thread. It is assumed this function
140// will free the memory used by 'data'.
141static int OnSctpInboundPacket(struct socket* sock, union sctp_sockstore addr,
142 void* data, size_t length,
143 struct sctp_rcvinfo rcv, int flags,
144 void* ulp_info) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000145 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(ulp_info);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000146 // Post data to the channel's receiver thread (copying it).
147 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
148 // memory cleanup. But this does simplify code.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000149 const SctpDataMediaChannel::PayloadProtocolIdentifier ppid =
150 static_cast<SctpDataMediaChannel::PayloadProtocolIdentifier>(
151 talk_base::HostToNetwork32(rcv.rcv_ppid));
152 cricket::DataMessageType type = cricket::DMT_NONE;
153 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
154 // It's neither a notification nor a recognized data packet. Drop it.
155 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
156 << " on an SCTP packet. Dropping.";
157 } else {
158 SctpInboundPacket* packet = new SctpInboundPacket;
159 packet->buffer.SetData(data, length);
160 packet->params.ssrc = rcv.rcv_sid;
161 packet->params.seq_num = rcv.rcv_ssn;
162 packet->params.timestamp = rcv.rcv_tsn;
163 packet->params.type = type;
164 packet->flags = flags;
165 channel->worker_thread()->Post(channel, MSG_SCTPINBOUNDPACKET,
166 talk_base::WrapMessageData(packet));
167 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000168 free(data);
169 return 1;
170}
171
172// Set the initial value of the static SCTP Data Engines reference count.
173int SctpDataEngine::usrsctp_engines_count = 0;
174
175SctpDataEngine::SctpDataEngine() {
176 if (usrsctp_engines_count == 0) {
177 // First argument is udp_encapsulation_port, which is not releveant for our
178 // AF_CONN use of sctp.
179 usrsctp_init(0, cricket::OnSctpOutboundPacket, debug_sctp_printf);
180
181 // To turn on/off detailed SCTP debugging. You will also need to have the
182 // SCTP_DEBUG cpp defines flag.
183 // usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
184
185 // TODO(ldixon): Consider turning this on/off.
186 usrsctp_sysctl_set_sctp_ecn_enable(0);
187
188 // TODO(ldixon): Consider turning this on/off.
189 // This is not needed right now (we don't do dynamic address changes):
190 // If SCTP Auto-ASCONF is enabled, the peer is informed automatically
191 // when a new address is added or removed. This feature is enabled by
192 // default.
193 // usrsctp_sysctl_set_sctp_auto_asconf(0);
194
195 // TODO(ldixon): Consider turning this on/off.
196 // Add a blackhole sysctl. Setting it to 1 results in no ABORTs
197 // being sent in response to INITs, setting it to 2 results
198 // in no ABORTs being sent for received OOTB packets.
199 // This is similar to the TCP sysctl.
200 //
201 // See: http://lakerest.net/pipermail/sctp-coders/2012-January/009438.html
202 // See: http://svnweb.freebsd.org/base?view=revision&revision=229805
203 // usrsctp_sysctl_set_sctp_blackhole(2);
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000204
205 // Set the number of default outgoing streams. This is the number we'll
206 // send in the SCTP INIT message. The 'appropriate default' in the
207 // second paragraph of
208 // http://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-05#section-6.2
209 // is cricket::kMaxSctpSid.
210 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(
211 cricket::kMaxSctpSid);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000212 }
213 usrsctp_engines_count++;
214
215 // We don't put in a codec because we don't want one offered when we
216 // use the hybrid data engine.
217 // codecs_.push_back(cricket::DataCodec( kGoogleSctpDataCodecId,
218 // kGoogleSctpDataCodecName, 0));
219}
220
221SctpDataEngine::~SctpDataEngine() {
222 // TODO(ldixon): There is currently a bug in teardown of usrsctp that blocks
223 // indefintely if a finish call made too soon after close calls. So teardown
224 // has been skipped. Once the bug is fixed, retest and enable teardown.
225 //
226 // usrsctp_engines_count--;
227 // LOG(LS_VERBOSE) << "usrsctp_engines_count:" << usrsctp_engines_count;
228 // if (usrsctp_engines_count == 0) {
229 // if (usrsctp_finish() != 0) {
230 // LOG(LS_WARNING) << "usrsctp_finish.";
231 // }
232 // }
233}
234
235DataMediaChannel* SctpDataEngine::CreateChannel(
236 DataChannelType data_channel_type) {
237 if (data_channel_type != DCT_SCTP) {
238 return NULL;
239 }
240 return new SctpDataMediaChannel(talk_base::Thread::Current());
241}
242
243SctpDataMediaChannel::SctpDataMediaChannel(talk_base::Thread* thread)
244 : worker_thread_(thread),
wu@webrtc.org78187522013-10-07 23:32:02 +0000245 local_port_(-1),
246 remote_port_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000247 sock_(NULL),
248 sending_(false),
249 receiving_(false),
250 debug_name_("SctpDataMediaChannel") {
251}
252
253SctpDataMediaChannel::~SctpDataMediaChannel() {
254 CloseSctpSocket();
255}
256
257sockaddr_conn SctpDataMediaChannel::GetSctpSockAddr(int port) {
258 sockaddr_conn sconn = {0};
259 sconn.sconn_family = AF_CONN;
260#ifdef HAVE_SCONN_LEN
261 sconn.sconn_len = sizeof(sockaddr_conn);
262#endif
263 // Note: conversion from int to uint16_t happens here.
264 sconn.sconn_port = talk_base::HostToNetwork16(port);
265 sconn.sconn_addr = this;
266 return sconn;
267}
268
269bool SctpDataMediaChannel::OpenSctpSocket() {
270 if (sock_) {
271 LOG(LS_VERBOSE) << debug_name_
272 << "->Ignoring attempt to re-create existing socket.";
273 return false;
274 }
275 sock_ = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP,
276 cricket::OnSctpInboundPacket, NULL, 0, this);
277 if (!sock_) {
278 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to create SCTP socket.";
279 return false;
280 }
281
282 // Make the socket non-blocking. Connect, close, shutdown etc will not block
283 // the thread waiting for the socket operation to complete.
284 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
285 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP to non blocking.";
286 return false;
287 }
288
289 // This ensures that the usrsctp close call deletes the association. This
290 // prevents usrsctp from calling OnSctpOutboundPacket with references to
291 // this class as the address.
292 linger linger_opt;
293 linger_opt.l_onoff = 1;
294 linger_opt.l_linger = 0;
295 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
296 sizeof(linger_opt))) {
297 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SO_LINGER.";
298 return false;
299 }
300
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000301 uint32_t nodelay = 1;
302 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
303 sizeof(nodelay))) {
304 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_NODELAY.";
305 return false;
306 }
307
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000308 // Subscribe to SCTP event notifications.
309 int event_types[] = {SCTP_ASSOC_CHANGE,
310 SCTP_PEER_ADDR_CHANGE,
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000311 SCTP_SEND_FAILED_EVENT,
312 SCTP_SENDER_DRY_EVENT};
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000313 struct sctp_event event = {0};
314 event.se_assoc_id = SCTP_ALL_ASSOC;
315 event.se_on = 1;
316 for (size_t i = 0; i < ARRAY_SIZE(event_types); i++) {
317 event.se_type = event_types[i];
318 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
319 sizeof(event)) < 0) {
320 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_EVENT type: "
321 << event.se_type;
322 return false;
323 }
324 }
325
326 // Register this class as an address for usrsctp. This is used by SCTP to
327 // direct the packets received (by the created socket) to this class.
328 usrsctp_register_address(this);
329 sending_ = true;
330 return true;
331}
332
333void SctpDataMediaChannel::CloseSctpSocket() {
334 sending_ = false;
335 if (sock_) {
336 // We assume that SO_LINGER option is set to close the association when
337 // close is called. This means that any pending packets in usrsctp will be
338 // discarded instead of being sent.
339 usrsctp_close(sock_);
340 sock_ = NULL;
341 usrsctp_deregister_address(this);
342 }
343}
344
345bool SctpDataMediaChannel::Connect() {
346 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
wu@webrtc.org78187522013-10-07 23:32:02 +0000347 if (remote_port_ < 0) {
348 remote_port_ = kSctpDefaultPort;
349 }
350 if (local_port_ < 0) {
351 local_port_ = kSctpDefaultPort;
352 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000353
354 // If we already have a socket connection, just return.
355 if (sock_) {
356 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
357 "is already established.";
358 return true;
359 }
360
361 // If no socket (it was closed) try to start it again. This can happen when
362 // the socket we are connecting to closes, does an sctp shutdown handshake,
363 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
364 if (!sock_ && !OpenSctpSocket()) {
365 return false;
366 }
367
368 // Note: conversion from int to uint16_t happens on assignment.
369 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
370 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
371 sizeof(local_sconn)) < 0) {
372 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
373 << ("Failed usrsctp_bind");
374 CloseSctpSocket();
375 return false;
376 }
377
378 // Note: conversion from int to uint16_t happens on assignment.
379 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
380 int connect_result = usrsctp_connect(
381 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000382 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
383 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
384 << errno << ", but wanted " << SCTP_EINPROGRESS;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000385 CloseSctpSocket();
386 return false;
387 }
388 return true;
389}
390
391void SctpDataMediaChannel::Disconnect() {
392 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
393 // shutdown handshake and remove the association.
394 CloseSctpSocket();
395}
396
397bool SctpDataMediaChannel::SetSend(bool send) {
398 if (!sending_ && send) {
399 return Connect();
400 }
401 if (sending_ && !send) {
402 Disconnect();
403 }
404 return true;
405}
406
407bool SctpDataMediaChannel::SetReceive(bool receive) {
408 receiving_ = receive;
409 return true;
410}
411
412bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
413 if (!stream.has_ssrcs()) {
414 return false;
415 }
416
417 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000418 // TODO(lally): Consider keeping this sorted.
419 if (GetStreamBySsrc(streams_, stream.first_ssrc(), &found_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000420 LOG(LS_WARNING) << debug_name_ << "->AddSendStream(...): "
421 << "Not adding data send stream '" << stream.id
422 << "' with ssrc=" << stream.first_ssrc()
423 << " because stream already exists.";
424 return false;
425 }
426
wu@webrtc.org91053e72013-08-10 07:18:04 +0000427 streams_.push_back(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000428 return true;
429}
430
431bool SctpDataMediaChannel::RemoveSendStream(uint32 ssrc) {
432 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000433 if (!GetStreamBySsrc(streams_, ssrc, &found_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000434 return false;
435 }
436
wu@webrtc.org91053e72013-08-10 07:18:04 +0000437 RemoveStreamBySsrc(&streams_, ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000438 return true;
439}
440
441// Note: expects exactly one ssrc. If none are given, it will fail. If more
442// than one are given, it will use the first.
443bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
444 if (!stream.has_ssrcs()) {
445 return false;
446 }
447
448 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000449 if (GetStreamBySsrc(streams_, stream.first_ssrc(), &found_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000450 LOG(LS_WARNING) << debug_name_ << "->AddRecvStream(...): "
451 << "Not adding data recv stream '" << stream.id
452 << "' with ssrc=" << stream.first_ssrc()
453 << " because stream already exists.";
454 return false;
455 }
456
wu@webrtc.org91053e72013-08-10 07:18:04 +0000457 streams_.push_back(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000458 LOG(LS_VERBOSE) << debug_name_ << "->AddRecvStream(...): "
459 << "Added data recv stream '" << stream.id
460 << "' with ssrc=" << stream.first_ssrc();
461 return true;
462}
463
464bool SctpDataMediaChannel::RemoveRecvStream(uint32 ssrc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000465 RemoveStreamBySsrc(&streams_, ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000466 return true;
467}
468
469bool SctpDataMediaChannel::SendData(
470 const SendDataParams& params,
471 const talk_base::Buffer& payload,
472 SendDataResult* result) {
473 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000474 // Preset |result| to assume an error. If SendData succeeds, we'll
475 // overwrite |*result| once more at the end.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000476 *result = SDR_ERROR;
477 }
478
479 if (!sending_) {
480 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
481 << "Not sending packet with ssrc=" << params.ssrc
482 << " len=" << payload.length() << " before SetSend(true).";
483 return false;
484 }
485
486 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000487 if (params.type != cricket::DMT_CONTROL &&
488 !GetStreamBySsrc(streams_, params.ssrc, &found_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000489 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
490 << "Not sending data because ssrc is unknown: "
491 << params.ssrc;
492 return false;
493 }
494
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000495 //
496 // Send data using SCTP.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000497 ssize_t send_res = 0; // result from usrsctp_sendv.
498 struct sctp_sendv_spa spa = {0};
499 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
500 spa.sendv_sndinfo.snd_sid = params.ssrc;
501 spa.sendv_sndinfo.snd_ppid = talk_base::HostToNetwork32(
502 GetPpid(params.type));
503
504 // Ordered implies reliable.
505 if (!params.ordered) {
506 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
507 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
508 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
509 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
510 spa.sendv_prinfo.pr_value = params.max_rtx_count;
511 } else {
512 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
513 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
514 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
515 }
516 }
517
518 // We don't fragment.
519 send_res = usrsctp_sendv(sock_, payload.data(),
520 static_cast<size_t>(payload.length()),
521 NULL, 0, &spa,
522 static_cast<socklen_t>(sizeof(spa)),
523 SCTP_SENDV_SPA, 0);
524 if (send_res < 0) {
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000525 if (errno == EWOULDBLOCK) {
526 *result = SDR_BLOCK;
527 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
528 } else {
529 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
530 << "->SendData(...): "
531 << " usrsctp_sendv: ";
532 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533 return false;
534 }
535 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000536 // Only way out now is success.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000537 *result = SDR_SUCCESS;
538 }
539 return true;
540}
541
542// Called by network interface when a packet has been received.
543void SctpDataMediaChannel::OnPacketReceived(talk_base::Buffer* packet) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000544 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): " << " length="
545 << packet->length() << ", sending: " << sending_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000546 // Only give receiving packets to usrsctp after if connected. This enables two
547 // peers to each make a connect call, but for them not to receive an INIT
548 // packet before they have called connect; least the last receiver of the INIT
549 // packet will have called connect, and a connection will be established.
550 if (sending_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000551 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
552 // will be will be given to the global OnSctpInboundData, and then,
553 // marshalled by a Post and handled with OnMessage.
554 usrsctp_conninput(this, packet->data(), packet->length(), 0);
555 } else {
556 // TODO(ldixon): Consider caching the packet for very slightly better
557 // reliability.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000558 }
559}
560
561void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
562 SctpInboundPacket* packet) {
563 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
564 << "Received SCTP data:"
565 << " ssrc=" << packet->params.ssrc
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000566 << " notification: " << (packet->flags & MSG_NOTIFICATION)
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000567 << " length=" << packet->buffer.length();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000568 // Sending a packet with data == NULL (no data) is SCTPs "close the
569 // connection" message. This sets sock_ = NULL;
570 if (!packet->buffer.length() || !packet->buffer.data()) {
571 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
572 "No data, closing.";
573 return;
574 }
575 if (packet->flags & MSG_NOTIFICATION) {
576 OnNotificationFromSctp(&packet->buffer);
577 } else {
578 OnDataFromSctpToChannel(packet->params, &packet->buffer);
579 }
580}
581
582void SctpDataMediaChannel::OnDataFromSctpToChannel(
583 const ReceiveDataParams& params, talk_base::Buffer* buffer) {
584 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000585 if (!GetStreamBySsrc(streams_, params.ssrc, &found_stream)) {
586 if (params.type == DMT_CONTROL) {
587 SignalDataReceived(params, buffer->data(), buffer->length());
588 } else {
589 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
590 << "Received packet for unknown ssrc: " << params.ssrc;
591 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000592 return;
593 }
594
595 if (receiving_) {
596 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
597 << "Posting with length: " << buffer->length();
598 SignalDataReceived(params, buffer->data(), buffer->length());
599 } else {
600 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
601 << "Not receiving packet with sid=" << params.ssrc
602 << " len=" << buffer->length()
603 << " before SetReceive(true).";
604 }
605}
606
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000607void SctpDataMediaChannel::OnNotificationFromSctp(talk_base::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000608 const sctp_notification& notification =
609 reinterpret_cast<const sctp_notification&>(*buffer->data());
610 ASSERT(notification.sn_header.sn_length == buffer->length());
611
612 // TODO(ldixon): handle notifications appropriately.
613 switch (notification.sn_header.sn_type) {
614 case SCTP_ASSOC_CHANGE:
615 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
616 OnNotificationAssocChange(notification.sn_assoc_change);
617 break;
618 case SCTP_REMOTE_ERROR:
619 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
620 break;
621 case SCTP_SHUTDOWN_EVENT:
622 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
623 break;
624 case SCTP_ADAPTATION_INDICATION:
625 LOG(LS_INFO) << "SCTP_ADAPTATION_INIDICATION";
626 break;
627 case SCTP_PARTIAL_DELIVERY_EVENT:
628 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
629 break;
630 case SCTP_AUTHENTICATION_EVENT:
631 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
632 break;
633 case SCTP_SENDER_DRY_EVENT:
634 LOG(LS_INFO) << "SCTP_SENDER_DRY_EVENT";
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000635 SignalReadyToSend(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000636 break;
637 // TODO(ldixon): Unblock after congestion.
638 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
639 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
640 break;
641 case SCTP_SEND_FAILED_EVENT:
642 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
643 break;
644 case SCTP_STREAM_RESET_EVENT:
645 LOG(LS_INFO) << "SCTP_STREAM_RESET_EVENT";
646 // TODO(ldixon): Notify up to channel that stream resent has happened,
647 // and write unit test for this case.
648 break;
649 case SCTP_ASSOC_RESET_EVENT:
650 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
651 break;
652 case SCTP_STREAM_CHANGE_EVENT:
653 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
654 break;
655 default:
656 LOG(LS_WARNING) << "Unknown SCTP event: "
657 << notification.sn_header.sn_type;
658 break;
659 }
660}
661
662void SctpDataMediaChannel::OnNotificationAssocChange(
663 const sctp_assoc_change& change) {
664 switch (change.sac_state) {
665 case SCTP_COMM_UP:
666 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
667 break;
668 case SCTP_COMM_LOST:
669 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
670 break;
671 case SCTP_RESTART:
672 LOG(LS_INFO) << "Association change SCTP_RESTART";
673 break;
674 case SCTP_SHUTDOWN_COMP:
675 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
676 break;
677 case SCTP_CANT_STR_ASSOC:
678 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
679 break;
680 default:
681 LOG(LS_INFO) << "Association change UNKNOWN";
682 break;
683 }
684}
685
wu@webrtc.org78187522013-10-07 23:32:02 +0000686// Puts the specified |param| from the codec identified by |id| into |dest|
687// and returns true. Or returns false if it wasn't there, leaving |dest|
688// untouched.
689static bool GetCodecIntParameter(const std::vector<DataCodec>& codecs,
690 int id, const std::string& name,
691 const std::string& param, int* dest) {
692 std::string value;
693 Codec match_pattern;
694 match_pattern.id = id;
695 match_pattern.name = name;
696 for (size_t i = 0; i < codecs.size(); ++i) {
697 if (codecs[i].Matches(match_pattern)) {
698 if (codecs[i].GetParam(param, &value)) {
699 *dest = talk_base::FromString<int>(value);
700 return true;
701 }
702 }
703 }
704 return false;
705}
706
707bool SctpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
708 return GetCodecIntParameter(
709 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
710 &remote_port_);
711}
712
713bool SctpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
714 return GetCodecIntParameter(
715 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
716 &local_port_);
717}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718
719void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
720 talk_base::Buffer* buffer) {
721 if (buffer->length() > kSctpMtu) {
722 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
723 << "SCTP seems to have made a poacket that is bigger "
724 "than its official MTU.";
725 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000726 MediaChannel::SendPacket(buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727}
728
729void SctpDataMediaChannel::OnMessage(talk_base::Message* msg) {
730 switch (msg->message_id) {
731 case MSG_SCTPINBOUNDPACKET: {
732 SctpInboundPacket* packet =
733 static_cast<talk_base::TypedMessageData<SctpInboundPacket*>*>(
734 msg->pdata)->data();
735 OnInboundPacketFromSctpToChannel(packet);
736 delete packet;
737 break;
738 }
739 case MSG_SCTPOUTBOUNDPACKET: {
740 talk_base::Buffer* buffer =
741 static_cast<talk_base::TypedMessageData<talk_base::Buffer*>*>(
742 msg->pdata)->data();
743 OnPacketFromSctpToNetwork(buffer);
744 delete buffer;
745 break;
746 }
747 }
748}
749
750} // namespace cricket