blob: 3d450c6863b99700d814d08d23ae58272ee7d5d0 [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),
245 local_port_(kSctpDefaultPort),
246 remote_port_(kSctpDefaultPort),
247 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().";
347
348 // If we already have a socket connection, just return.
349 if (sock_) {
350 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
351 "is already established.";
352 return true;
353 }
354
355 // If no socket (it was closed) try to start it again. This can happen when
356 // the socket we are connecting to closes, does an sctp shutdown handshake,
357 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
358 if (!sock_ && !OpenSctpSocket()) {
359 return false;
360 }
361
362 // Note: conversion from int to uint16_t happens on assignment.
363 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
364 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
365 sizeof(local_sconn)) < 0) {
366 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
367 << ("Failed usrsctp_bind");
368 CloseSctpSocket();
369 return false;
370 }
371
372 // Note: conversion from int to uint16_t happens on assignment.
373 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
374 int connect_result = usrsctp_connect(
375 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000376 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
377 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
378 << errno << ", but wanted " << SCTP_EINPROGRESS;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000379 CloseSctpSocket();
380 return false;
381 }
382 return true;
383}
384
385void SctpDataMediaChannel::Disconnect() {
386 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
387 // shutdown handshake and remove the association.
388 CloseSctpSocket();
389}
390
391bool SctpDataMediaChannel::SetSend(bool send) {
392 if (!sending_ && send) {
393 return Connect();
394 }
395 if (sending_ && !send) {
396 Disconnect();
397 }
398 return true;
399}
400
401bool SctpDataMediaChannel::SetReceive(bool receive) {
402 receiving_ = receive;
403 return true;
404}
405
406bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
407 if (!stream.has_ssrcs()) {
408 return false;
409 }
410
411 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000412 // TODO(lally): Consider keeping this sorted.
413 if (GetStreamBySsrc(streams_, stream.first_ssrc(), &found_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000414 LOG(LS_WARNING) << debug_name_ << "->AddSendStream(...): "
415 << "Not adding data send stream '" << stream.id
416 << "' with ssrc=" << stream.first_ssrc()
417 << " because stream already exists.";
418 return false;
419 }
420
wu@webrtc.org91053e72013-08-10 07:18:04 +0000421 streams_.push_back(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000422 return true;
423}
424
425bool SctpDataMediaChannel::RemoveSendStream(uint32 ssrc) {
426 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000427 if (!GetStreamBySsrc(streams_, ssrc, &found_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000428 return false;
429 }
430
wu@webrtc.org91053e72013-08-10 07:18:04 +0000431 RemoveStreamBySsrc(&streams_, ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000432 return true;
433}
434
435// Note: expects exactly one ssrc. If none are given, it will fail. If more
436// than one are given, it will use the first.
437bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
438 if (!stream.has_ssrcs()) {
439 return false;
440 }
441
442 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000443 if (GetStreamBySsrc(streams_, stream.first_ssrc(), &found_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000444 LOG(LS_WARNING) << debug_name_ << "->AddRecvStream(...): "
445 << "Not adding data recv stream '" << stream.id
446 << "' with ssrc=" << stream.first_ssrc()
447 << " because stream already exists.";
448 return false;
449 }
450
wu@webrtc.org91053e72013-08-10 07:18:04 +0000451 streams_.push_back(stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000452 LOG(LS_VERBOSE) << debug_name_ << "->AddRecvStream(...): "
453 << "Added data recv stream '" << stream.id
454 << "' with ssrc=" << stream.first_ssrc();
455 return true;
456}
457
458bool SctpDataMediaChannel::RemoveRecvStream(uint32 ssrc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000459 RemoveStreamBySsrc(&streams_, ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000460 return true;
461}
462
463bool SctpDataMediaChannel::SendData(
464 const SendDataParams& params,
465 const talk_base::Buffer& payload,
466 SendDataResult* result) {
467 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000468 // Preset |result| to assume an error. If SendData succeeds, we'll
469 // overwrite |*result| once more at the end.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000470 *result = SDR_ERROR;
471 }
472
473 if (!sending_) {
474 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
475 << "Not sending packet with ssrc=" << params.ssrc
476 << " len=" << payload.length() << " before SetSend(true).";
477 return false;
478 }
479
480 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000481 if (params.type != cricket::DMT_CONTROL &&
482 !GetStreamBySsrc(streams_, params.ssrc, &found_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000483 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
484 << "Not sending data because ssrc is unknown: "
485 << params.ssrc;
486 return false;
487 }
488
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000489 //
490 // Send data using SCTP.
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000491 ssize_t send_res = 0; // result from usrsctp_sendv.
492 struct sctp_sendv_spa spa = {0};
493 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
494 spa.sendv_sndinfo.snd_sid = params.ssrc;
495 spa.sendv_sndinfo.snd_ppid = talk_base::HostToNetwork32(
496 GetPpid(params.type));
497
498 // Ordered implies reliable.
499 if (!params.ordered) {
500 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
501 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
502 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
503 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
504 spa.sendv_prinfo.pr_value = params.max_rtx_count;
505 } else {
506 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
507 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
508 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
509 }
510 }
511
512 // We don't fragment.
513 send_res = usrsctp_sendv(sock_, payload.data(),
514 static_cast<size_t>(payload.length()),
515 NULL, 0, &spa,
516 static_cast<socklen_t>(sizeof(spa)),
517 SCTP_SENDV_SPA, 0);
518 if (send_res < 0) {
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000519 if (errno == EWOULDBLOCK) {
520 *result = SDR_BLOCK;
521 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
522 } else {
523 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
524 << "->SendData(...): "
525 << " usrsctp_sendv: ";
526 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000527 return false;
528 }
529 if (result) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000530 // Only way out now is success.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531 *result = SDR_SUCCESS;
532 }
533 return true;
534}
535
536// Called by network interface when a packet has been received.
537void SctpDataMediaChannel::OnPacketReceived(talk_base::Buffer* packet) {
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000538 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): " << " length="
539 << packet->length() << ", sending: " << sending_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000540 // Only give receiving packets to usrsctp after if connected. This enables two
541 // peers to each make a connect call, but for them not to receive an INIT
542 // packet before they have called connect; least the last receiver of the INIT
543 // packet will have called connect, and a connection will be established.
544 if (sending_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000545 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
546 // will be will be given to the global OnSctpInboundData, and then,
547 // marshalled by a Post and handled with OnMessage.
548 usrsctp_conninput(this, packet->data(), packet->length(), 0);
549 } else {
550 // TODO(ldixon): Consider caching the packet for very slightly better
551 // reliability.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000552 }
553}
554
555void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
556 SctpInboundPacket* packet) {
557 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
558 << "Received SCTP data:"
559 << " ssrc=" << packet->params.ssrc
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000560 << " notification: " << (packet->flags & MSG_NOTIFICATION)
mallinath@webrtc.org1112c302013-09-23 20:34:45 +0000561 << " length=" << packet->buffer.length();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000562 // Sending a packet with data == NULL (no data) is SCTPs "close the
563 // connection" message. This sets sock_ = NULL;
564 if (!packet->buffer.length() || !packet->buffer.data()) {
565 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
566 "No data, closing.";
567 return;
568 }
569 if (packet->flags & MSG_NOTIFICATION) {
570 OnNotificationFromSctp(&packet->buffer);
571 } else {
572 OnDataFromSctpToChannel(packet->params, &packet->buffer);
573 }
574}
575
576void SctpDataMediaChannel::OnDataFromSctpToChannel(
577 const ReceiveDataParams& params, talk_base::Buffer* buffer) {
578 StreamParams found_stream;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000579 if (!GetStreamBySsrc(streams_, params.ssrc, &found_stream)) {
580 if (params.type == DMT_CONTROL) {
581 SignalDataReceived(params, buffer->data(), buffer->length());
582 } else {
583 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
584 << "Received packet for unknown ssrc: " << params.ssrc;
585 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000586 return;
587 }
588
589 if (receiving_) {
590 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
591 << "Posting with length: " << buffer->length();
592 SignalDataReceived(params, buffer->data(), buffer->length());
593 } else {
594 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
595 << "Not receiving packet with sid=" << params.ssrc
596 << " len=" << buffer->length()
597 << " before SetReceive(true).";
598 }
599}
600
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000601void SctpDataMediaChannel::OnNotificationFromSctp(talk_base::Buffer* buffer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000602 const sctp_notification& notification =
603 reinterpret_cast<const sctp_notification&>(*buffer->data());
604 ASSERT(notification.sn_header.sn_length == buffer->length());
605
606 // TODO(ldixon): handle notifications appropriately.
607 switch (notification.sn_header.sn_type) {
608 case SCTP_ASSOC_CHANGE:
609 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
610 OnNotificationAssocChange(notification.sn_assoc_change);
611 break;
612 case SCTP_REMOTE_ERROR:
613 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
614 break;
615 case SCTP_SHUTDOWN_EVENT:
616 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
617 break;
618 case SCTP_ADAPTATION_INDICATION:
619 LOG(LS_INFO) << "SCTP_ADAPTATION_INIDICATION";
620 break;
621 case SCTP_PARTIAL_DELIVERY_EVENT:
622 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
623 break;
624 case SCTP_AUTHENTICATION_EVENT:
625 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
626 break;
627 case SCTP_SENDER_DRY_EVENT:
628 LOG(LS_INFO) << "SCTP_SENDER_DRY_EVENT";
wu@webrtc.orgd64719d2013-08-01 00:00:07 +0000629 SignalReadyToSend(true);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000630 break;
631 // TODO(ldixon): Unblock after congestion.
632 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
633 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
634 break;
635 case SCTP_SEND_FAILED_EVENT:
636 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
637 break;
638 case SCTP_STREAM_RESET_EVENT:
639 LOG(LS_INFO) << "SCTP_STREAM_RESET_EVENT";
640 // TODO(ldixon): Notify up to channel that stream resent has happened,
641 // and write unit test for this case.
642 break;
643 case SCTP_ASSOC_RESET_EVENT:
644 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
645 break;
646 case SCTP_STREAM_CHANGE_EVENT:
647 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
648 break;
649 default:
650 LOG(LS_WARNING) << "Unknown SCTP event: "
651 << notification.sn_header.sn_type;
652 break;
653 }
654}
655
656void SctpDataMediaChannel::OnNotificationAssocChange(
657 const sctp_assoc_change& change) {
658 switch (change.sac_state) {
659 case SCTP_COMM_UP:
660 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
661 break;
662 case SCTP_COMM_LOST:
663 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
664 break;
665 case SCTP_RESTART:
666 LOG(LS_INFO) << "Association change SCTP_RESTART";
667 break;
668 case SCTP_SHUTDOWN_COMP:
669 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
670 break;
671 case SCTP_CANT_STR_ASSOC:
672 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
673 break;
674 default:
675 LOG(LS_INFO) << "Association change UNKNOWN";
676 break;
677 }
678}
679
680
681void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
682 talk_base::Buffer* buffer) {
683 if (buffer->length() > kSctpMtu) {
684 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
685 << "SCTP seems to have made a poacket that is bigger "
686 "than its official MTU.";
687 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000688 MediaChannel::SendPacket(buffer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689}
690
691void SctpDataMediaChannel::OnMessage(talk_base::Message* msg) {
692 switch (msg->message_id) {
693 case MSG_SCTPINBOUNDPACKET: {
694 SctpInboundPacket* packet =
695 static_cast<talk_base::TypedMessageData<SctpInboundPacket*>*>(
696 msg->pdata)->data();
697 OnInboundPacketFromSctpToChannel(packet);
698 delete packet;
699 break;
700 }
701 case MSG_SCTPOUTBOUNDPACKET: {
702 talk_base::Buffer* buffer =
703 static_cast<talk_base::TypedMessageData<talk_base::Buffer*>*>(
704 msg->pdata)->data();
705 OnPacketFromSctpToNetwork(buffer);
706 delete buffer;
707 break;
708 }
709 }
710}
711
712} // namespace cricket