3 * Copyright 2012 Google Inc, and Robin Seggelmann
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
28 #include "talk/media/sctp/sctpdataengine.h"
35 #include "talk/base/buffer.h"
36 #include "talk/base/helpers.h"
37 #include "talk/base/logging.h"
38 #include "talk/base/safe_conversions.h"
39 #include "talk/media/base/codec.h"
40 #include "talk/media/base/constants.h"
41 #include "talk/media/base/streamparams.h"
42 #include "usrsctplib/usrsctp.h"
45 typedef cricket::SctpDataMediaChannel::StreamSet StreamSet;
46 // Returns a comma-separated, human-readable list of the stream IDs in 's'
47 std::string ListStreams(const StreamSet& s) {
48 std::stringstream result;
50 for (StreamSet::const_iterator it = s.begin(); it != s.end(); ++it) {
52 result << ", " << *it;
61 // Returns a pipe-separated, human-readable list of the SCTP_STREAM_RESET
63 std::string ListFlags(int flags) {
64 std::stringstream result;
66 // Skip past the first 12 chars (strlen("SCTP_STREAM_"))
67 #define MAKEFLAG(X) { X, #X + 12}
72 MAKEFLAG(SCTP_STREAM_RESET_INCOMING_SSN),
73 MAKEFLAG(SCTP_STREAM_RESET_OUTGOING_SSN),
74 MAKEFLAG(SCTP_STREAM_RESET_DENIED),
75 MAKEFLAG(SCTP_STREAM_RESET_FAILED),
76 MAKEFLAG(SCTP_STREAM_CHANGE_DENIED)
79 for (int i = 0; i < ARRAY_SIZE(flaginfo); ++i) {
80 if (flags & flaginfo[i].value) {
81 if (!first) result << " | ";
82 result << flaginfo[i].name;
89 // Returns a comma-separated, human-readable list of the integers in 'array'.
90 // All 'num_elems' of them.
91 std::string ListArray(const uint16* array, int num_elems) {
92 std::stringstream result;
93 for (int i = 0; i < num_elems; ++i) {
95 result << ", " << array[i];
105 typedef talk_base::ScopedMessageData<SctpInboundPacket> InboundPacketMessage;
106 typedef talk_base::ScopedMessageData<talk_base::Buffer> OutboundPacketMessage;
108 // This is the SCTP port to use. It is passed along the wire and the listener
109 // and connector must be using the same port. It is not related to the ports at
110 // the IP level. (Corresponds to: sockaddr_conn.sconn_port in usrsctp.h)
112 // TODO(ldixon): Allow port to be set from higher level code.
113 static const int kSctpDefaultPort = 5001;
114 // TODO(ldixon): Find where this is defined, and also check is Sctp really
116 static const size_t kSctpMtu = 1280;
119 MSG_SCTPINBOUNDPACKET = 1, // MessageData is SctpInboundPacket
120 MSG_SCTPOUTBOUNDPACKET = 2, // MessageData is talk_base:Buffer
123 struct SctpInboundPacket {
124 talk_base::Buffer buffer;
125 ReceiveDataParams params;
126 // The |flags| parameter is used by SCTP to distinguish notification packets
127 // from other types of packets.
131 // Helper for logging SCTP messages.
132 static void debug_sctp_printf(const char *format, ...) {
135 va_start(ap, format);
136 vsnprintf(s, sizeof(s), format, ap);
137 LOG(LS_INFO) << "SCTP: " << s;
141 // Get the PPID to use for the terminating fragment of this type.
142 static SctpDataMediaChannel::PayloadProtocolIdentifier GetPpid(
143 cricket::DataMessageType type) {
146 case cricket::DMT_NONE:
147 return SctpDataMediaChannel::PPID_NONE;
148 case cricket::DMT_CONTROL:
149 return SctpDataMediaChannel::PPID_CONTROL;
150 case cricket::DMT_BINARY:
151 return SctpDataMediaChannel::PPID_BINARY_LAST;
152 case cricket::DMT_TEXT:
153 return SctpDataMediaChannel::PPID_TEXT_LAST;
157 static bool GetDataMediaType(
158 SctpDataMediaChannel::PayloadProtocolIdentifier ppid,
159 cricket::DataMessageType *dest) {
160 ASSERT(dest != NULL);
162 case SctpDataMediaChannel::PPID_BINARY_PARTIAL:
163 case SctpDataMediaChannel::PPID_BINARY_LAST:
164 *dest = cricket::DMT_BINARY;
167 case SctpDataMediaChannel::PPID_TEXT_PARTIAL:
168 case SctpDataMediaChannel::PPID_TEXT_LAST:
169 *dest = cricket::DMT_TEXT;
172 case SctpDataMediaChannel::PPID_CONTROL:
173 *dest = cricket::DMT_CONTROL;
176 case SctpDataMediaChannel::PPID_NONE:
177 *dest = cricket::DMT_NONE;
185 // This is the callback usrsctp uses when there's data to send on the network
186 // that has been wrapped appropriatly for the SCTP protocol.
187 static int OnSctpOutboundPacket(void* addr, void* data, size_t length,
188 uint8_t tos, uint8_t set_df) {
189 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(addr);
190 LOG(LS_VERBOSE) << "global OnSctpOutboundPacket():"
191 << "addr: " << addr << "; length: " << length
192 << "; tos: " << std::hex << static_cast<int>(tos)
193 << "; set_df: " << std::hex << static_cast<int>(set_df);
194 // Note: We have to copy the data; the caller will delete it.
195 OutboundPacketMessage* msg =
196 new OutboundPacketMessage(new talk_base::Buffer(data, length));
197 channel->worker_thread()->Post(channel, MSG_SCTPOUTBOUNDPACKET, msg);
201 // This is the callback called from usrsctp when data has been received, after
202 // a packet has been interpreted and parsed by usrsctp and found to contain
203 // payload data. It is called by a usrsctp thread. It is assumed this function
204 // will free the memory used by 'data'.
205 static int OnSctpInboundPacket(struct socket* sock, union sctp_sockstore addr,
206 void* data, size_t length,
207 struct sctp_rcvinfo rcv, int flags,
209 SctpDataMediaChannel* channel = static_cast<SctpDataMediaChannel*>(ulp_info);
210 // Post data to the channel's receiver thread (copying it).
211 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
212 // memory cleanup. But this does simplify code.
213 const SctpDataMediaChannel::PayloadProtocolIdentifier ppid =
214 static_cast<SctpDataMediaChannel::PayloadProtocolIdentifier>(
215 talk_base::HostToNetwork32(rcv.rcv_ppid));
216 cricket::DataMessageType type = cricket::DMT_NONE;
217 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
218 // It's neither a notification nor a recognized data packet. Drop it.
219 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
220 << " on an SCTP packet. Dropping.";
222 SctpInboundPacket* packet = new SctpInboundPacket;
223 packet->buffer.SetData(data, length);
224 packet->params.ssrc = rcv.rcv_sid;
225 packet->params.seq_num = rcv.rcv_ssn;
226 packet->params.timestamp = rcv.rcv_tsn;
227 packet->params.type = type;
228 packet->flags = flags;
229 // The ownership of |packet| transfers to |msg|.
230 InboundPacketMessage* msg = new InboundPacketMessage(packet);
231 channel->worker_thread()->Post(channel, MSG_SCTPINBOUNDPACKET, msg);
237 // Set the initial value of the static SCTP Data Engines reference count.
238 int SctpDataEngine::usrsctp_engines_count = 0;
240 SctpDataEngine::SctpDataEngine() {
241 if (usrsctp_engines_count == 0) {
242 // First argument is udp_encapsulation_port, which is not releveant for our
243 // AF_CONN use of sctp.
244 usrsctp_init(0, cricket::OnSctpOutboundPacket, debug_sctp_printf);
246 // To turn on/off detailed SCTP debugging. You will also need to have the
247 // SCTP_DEBUG cpp defines flag.
248 // usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
250 // TODO(ldixon): Consider turning this on/off.
251 usrsctp_sysctl_set_sctp_ecn_enable(0);
253 // TODO(ldixon): Consider turning this on/off.
254 // This is not needed right now (we don't do dynamic address changes):
255 // If SCTP Auto-ASCONF is enabled, the peer is informed automatically
256 // when a new address is added or removed. This feature is enabled by
258 // usrsctp_sysctl_set_sctp_auto_asconf(0);
260 // TODO(ldixon): Consider turning this on/off.
261 // Add a blackhole sysctl. Setting it to 1 results in no ABORTs
262 // being sent in response to INITs, setting it to 2 results
263 // in no ABORTs being sent for received OOTB packets.
264 // This is similar to the TCP sysctl.
266 // See: http://lakerest.net/pipermail/sctp-coders/2012-January/009438.html
267 // See: http://svnweb.freebsd.org/base?view=revision&revision=229805
268 // usrsctp_sysctl_set_sctp_blackhole(2);
270 // Set the number of default outgoing streams. This is the number we'll
271 // send in the SCTP INIT message. The 'appropriate default' in the
272 // second paragraph of
273 // http://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-05#section-6.2
274 // is cricket::kMaxSctpSid.
275 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(
276 cricket::kMaxSctpSid);
278 usrsctp_engines_count++;
280 // We don't put in a codec because we don't want one offered when we
281 // use the hybrid data engine.
282 // codecs_.push_back(cricket::DataCodec( kGoogleSctpDataCodecId,
283 // kGoogleSctpDataCodecName, 0));
286 SctpDataEngine::~SctpDataEngine() {
287 // TODO(ldixon): There is currently a bug in teardown of usrsctp that blocks
288 // indefintely if a finish call made too soon after close calls. So teardown
289 // has been skipped. Once the bug is fixed, retest and enable teardown.
290 // Tracked in webrtc issue 2749.
292 // usrsctp_engines_count--;
293 // LOG(LS_VERBOSE) << "usrsctp_engines_count:" << usrsctp_engines_count;
294 // if (usrsctp_engines_count == 0) {
295 // if (usrsctp_finish() != 0) {
296 // LOG(LS_WARNING) << "usrsctp_finish.";
301 DataMediaChannel* SctpDataEngine::CreateChannel(
302 DataChannelType data_channel_type) {
303 if (data_channel_type != DCT_SCTP) {
306 return new SctpDataMediaChannel(talk_base::Thread::Current());
309 SctpDataMediaChannel::SctpDataMediaChannel(talk_base::Thread* thread)
310 : worker_thread_(thread),
316 debug_name_("SctpDataMediaChannel") {
319 SctpDataMediaChannel::~SctpDataMediaChannel() {
323 sockaddr_conn SctpDataMediaChannel::GetSctpSockAddr(int port) {
324 sockaddr_conn sconn = {0};
325 sconn.sconn_family = AF_CONN;
326 #ifdef HAVE_SCONN_LEN
327 sconn.sconn_len = sizeof(sockaddr_conn);
329 // Note: conversion from int to uint16_t happens here.
330 sconn.sconn_port = talk_base::HostToNetwork16(port);
331 sconn.sconn_addr = this;
335 bool SctpDataMediaChannel::OpenSctpSocket() {
337 LOG(LS_VERBOSE) << debug_name_
338 << "->Ignoring attempt to re-create existing socket.";
341 sock_ = usrsctp_socket(AF_CONN, SOCK_STREAM, IPPROTO_SCTP,
342 cricket::OnSctpInboundPacket, NULL, 0, this);
344 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to create SCTP socket.";
348 // Make the socket non-blocking. Connect, close, shutdown etc will not block
349 // the thread waiting for the socket operation to complete.
350 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
351 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP to non blocking.";
355 // This ensures that the usrsctp close call deletes the association. This
356 // prevents usrsctp from calling OnSctpOutboundPacket with references to
357 // this class as the address.
359 linger_opt.l_onoff = 1;
360 linger_opt.l_linger = 0;
361 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
362 sizeof(linger_opt))) {
363 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SO_LINGER.";
367 // Enable stream ID resets.
368 struct sctp_assoc_value stream_rst;
369 stream_rst.assoc_id = SCTP_ALL_ASSOC;
370 stream_rst.assoc_value = 1;
371 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
372 &stream_rst, sizeof(stream_rst))) {
373 LOG_ERRNO(LS_ERROR) << debug_name_
374 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
379 uint32_t nodelay = 1;
380 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
382 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_NODELAY.";
386 // Subscribe to SCTP event notifications.
387 int event_types[] = {SCTP_ASSOC_CHANGE,
388 SCTP_PEER_ADDR_CHANGE,
389 SCTP_SEND_FAILED_EVENT,
390 SCTP_SENDER_DRY_EVENT,
391 SCTP_STREAM_RESET_EVENT};
392 struct sctp_event event = {0};
393 event.se_assoc_id = SCTP_ALL_ASSOC;
395 for (size_t i = 0; i < ARRAY_SIZE(event_types); i++) {
396 event.se_type = event_types[i];
397 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
398 sizeof(event)) < 0) {
399 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to set SCTP_EVENT type: "
405 // Register this class as an address for usrsctp. This is used by SCTP to
406 // direct the packets received (by the created socket) to this class.
407 usrsctp_register_address(this);
412 void SctpDataMediaChannel::CloseSctpSocket() {
415 // We assume that SO_LINGER option is set to close the association when
416 // close is called. This means that any pending packets in usrsctp will be
417 // discarded instead of being sent.
418 usrsctp_close(sock_);
420 usrsctp_deregister_address(this);
424 bool SctpDataMediaChannel::Connect() {
425 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
426 if (remote_port_ < 0) {
427 remote_port_ = kSctpDefaultPort;
429 if (local_port_ < 0) {
430 local_port_ = kSctpDefaultPort;
433 // If we already have a socket connection, just return.
435 LOG(LS_WARNING) << debug_name_ << "->Connect(): Ignored as socket "
436 "is already established.";
440 // If no socket (it was closed) try to start it again. This can happen when
441 // the socket we are connecting to closes, does an sctp shutdown handshake,
442 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
443 if (!sock_ && !OpenSctpSocket()) {
447 // Note: conversion from int to uint16_t happens on assignment.
448 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
449 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr *>(&local_sconn),
450 sizeof(local_sconn)) < 0) {
451 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
452 << ("Failed usrsctp_bind");
457 // Note: conversion from int to uint16_t happens on assignment.
458 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
459 int connect_result = usrsctp_connect(
460 sock_, reinterpret_cast<sockaddr *>(&remote_sconn), sizeof(remote_sconn));
461 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
462 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed usrsctp_connect. got errno="
463 << errno << ", but wanted " << SCTP_EINPROGRESS;
470 void SctpDataMediaChannel::Disconnect() {
471 // TODO(ldixon): Consider calling |usrsctp_shutdown(sock_, ...)| to do a
472 // shutdown handshake and remove the association.
476 bool SctpDataMediaChannel::SetSend(bool send) {
477 if (!sending_ && send) {
480 if (sending_ && !send) {
486 bool SctpDataMediaChannel::SetReceive(bool receive) {
487 receiving_ = receive;
491 bool SctpDataMediaChannel::AddSendStream(const StreamParams& stream) {
492 return AddStream(stream);
495 bool SctpDataMediaChannel::RemoveSendStream(uint32 ssrc) {
496 return ResetStream(ssrc);
499 bool SctpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
500 // SCTP DataChannels are always bi-directional and calling AddSendStream will
501 // enable both sending and receiving on the stream. So AddRecvStream is a
506 bool SctpDataMediaChannel::RemoveRecvStream(uint32 ssrc) {
507 // SCTP DataChannels are always bi-directional and calling RemoveSendStream
508 // will disable both sending and receiving on the stream. So RemoveRecvStream
513 bool SctpDataMediaChannel::SendData(
514 const SendDataParams& params,
515 const talk_base::Buffer& payload,
516 SendDataResult* result) {
518 // Preset |result| to assume an error. If SendData succeeds, we'll
519 // overwrite |*result| once more at the end.
524 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
525 << "Not sending packet with ssrc=" << params.ssrc
526 << " len=" << payload.length() << " before SetSend(true).";
530 if (params.type != cricket::DMT_CONTROL &&
531 open_streams_.find(params.ssrc) == open_streams_.end()) {
532 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
533 << "Not sending data because ssrc is unknown: "
539 // Send data using SCTP.
540 ssize_t send_res = 0; // result from usrsctp_sendv.
541 struct sctp_sendv_spa spa = {0};
542 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
543 spa.sendv_sndinfo.snd_sid = params.ssrc;
544 spa.sendv_sndinfo.snd_ppid = talk_base::HostToNetwork32(
545 GetPpid(params.type));
547 // Ordered implies reliable.
548 if (!params.ordered) {
549 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
550 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
551 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
552 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
553 spa.sendv_prinfo.pr_value = params.max_rtx_count;
555 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
556 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
557 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
561 // We don't fragment.
562 send_res = usrsctp_sendv(sock_, payload.data(),
563 static_cast<size_t>(payload.length()),
565 talk_base::checked_cast<socklen_t>(sizeof(spa)),
568 if (errno == EWOULDBLOCK) {
570 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
572 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_
573 << "->SendData(...): "
574 << " usrsctp_sendv: ";
579 // Only way out now is success.
580 *result = SDR_SUCCESS;
585 // Called by network interface when a packet has been received.
586 void SctpDataMediaChannel::OnPacketReceived(
587 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
588 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketReceived(...): " << " length="
589 << packet->length() << ", sending: " << sending_;
590 // Only give receiving packets to usrsctp after if connected. This enables two
591 // peers to each make a connect call, but for them not to receive an INIT
592 // packet before they have called connect; least the last receiver of the INIT
593 // packet will have called connect, and a connection will be established.
595 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
596 // will be will be given to the global OnSctpInboundData, and then,
597 // marshalled by a Post and handled with OnMessage.
598 usrsctp_conninput(this, packet->data(), packet->length(), 0);
600 // TODO(ldixon): Consider caching the packet for very slightly better
605 void SctpDataMediaChannel::OnInboundPacketFromSctpToChannel(
606 SctpInboundPacket* packet) {
607 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
608 << "Received SCTP data:"
609 << " ssrc=" << packet->params.ssrc
610 << " notification: " << (packet->flags & MSG_NOTIFICATION)
611 << " length=" << packet->buffer.length();
612 // Sending a packet with data == NULL (no data) is SCTPs "close the
613 // connection" message. This sets sock_ = NULL;
614 if (!packet->buffer.length() || !packet->buffer.data()) {
615 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
619 if (packet->flags & MSG_NOTIFICATION) {
620 OnNotificationFromSctp(&packet->buffer);
622 OnDataFromSctpToChannel(packet->params, &packet->buffer);
626 void SctpDataMediaChannel::OnDataFromSctpToChannel(
627 const ReceiveDataParams& params, talk_base::Buffer* buffer) {
629 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
630 << "Posting with length: " << buffer->length()
631 << " on stream " << params.ssrc;
632 // Reports all received messages to upper layers, no matter whether the sid
634 SignalDataReceived(params, buffer->data(), buffer->length());
636 LOG(LS_WARNING) << debug_name_ << "->OnDataFromSctpToChannel(...): "
637 << "Not receiving packet with sid=" << params.ssrc
638 << " len=" << buffer->length()
639 << " before SetReceive(true).";
643 bool SctpDataMediaChannel::AddStream(const StreamParams& stream) {
644 if (!stream.has_ssrcs()) {
648 const uint32 ssrc = stream.first_ssrc();
649 if (open_streams_.find(ssrc) != open_streams_.end()) {
650 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
651 << "Not adding data stream '" << stream.id
652 << "' with ssrc=" << ssrc
653 << " because stream is already open.";
655 } else if (queued_reset_streams_.find(ssrc) != queued_reset_streams_.end()
656 || sent_reset_streams_.find(ssrc) != sent_reset_streams_.end()) {
657 LOG(LS_WARNING) << debug_name_ << "->Add(Send|Recv)Stream(...): "
658 << "Not adding data stream '" << stream.id
659 << "' with ssrc=" << ssrc
660 << " because stream is still closing.";
664 open_streams_.insert(ssrc);
668 bool SctpDataMediaChannel::ResetStream(uint32 ssrc) {
669 // We typically get this called twice for the same stream, once each for
671 StreamSet::iterator found = open_streams_.find(ssrc);
673 if (found == open_streams_.end()) {
674 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
675 << "stream not found.";
678 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << ssrc << "): "
679 << "Removing and queuing RE-CONFIG chunk.";
680 open_streams_.erase(found);
683 // SCTP won't let you have more than one stream reset pending at a time, but
684 // you can close multiple streams in a single reset. So, we keep an internal
685 // queue of streams-to-reset, and send them as one reset message in
686 // SendQueuedStreamResets().
687 queued_reset_streams_.insert(ssrc);
689 // Signal our stream-reset logic that it should try to send now, if it can.
690 SendQueuedStreamResets();
692 // The stream will actually get removed when we get the acknowledgment.
696 void SctpDataMediaChannel::OnNotificationFromSctp(talk_base::Buffer* buffer) {
697 const sctp_notification& notification =
698 reinterpret_cast<const sctp_notification&>(*buffer->data());
699 ASSERT(notification.sn_header.sn_length == buffer->length());
701 // TODO(ldixon): handle notifications appropriately.
702 switch (notification.sn_header.sn_type) {
703 case SCTP_ASSOC_CHANGE:
704 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
705 OnNotificationAssocChange(notification.sn_assoc_change);
707 case SCTP_REMOTE_ERROR:
708 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
710 case SCTP_SHUTDOWN_EVENT:
711 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
713 case SCTP_ADAPTATION_INDICATION:
714 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
716 case SCTP_PARTIAL_DELIVERY_EVENT:
717 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
719 case SCTP_AUTHENTICATION_EVENT:
720 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
722 case SCTP_SENDER_DRY_EVENT:
723 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
724 SignalReadyToSend(true);
726 // TODO(ldixon): Unblock after congestion.
727 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
728 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
730 case SCTP_SEND_FAILED_EVENT:
731 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
733 case SCTP_STREAM_RESET_EVENT:
734 OnStreamResetEvent(¬ification.sn_strreset_event);
736 case SCTP_ASSOC_RESET_EVENT:
737 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
739 case SCTP_STREAM_CHANGE_EVENT:
740 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
741 // An acknowledgment we get after our stream resets have gone through,
742 // if they've failed. We log the message, but don't react -- we don't
743 // keep around the last-transmitted set of SSIDs we wanted to close for
744 // error recovery. It doesn't seem likely to occur, and if so, likely
745 // harmless within the lifetime of a single SCTP association.
748 LOG(LS_WARNING) << "Unknown SCTP event: "
749 << notification.sn_header.sn_type;
754 void SctpDataMediaChannel::OnNotificationAssocChange(
755 const sctp_assoc_change& change) {
756 switch (change.sac_state) {
758 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
761 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
764 LOG(LS_INFO) << "Association change SCTP_RESTART";
766 case SCTP_SHUTDOWN_COMP:
767 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
769 case SCTP_CANT_STR_ASSOC:
770 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
773 LOG(LS_INFO) << "Association change UNKNOWN";
778 void SctpDataMediaChannel::OnStreamResetEvent(
779 const struct sctp_stream_reset_event* evt) {
780 // A stream reset always involves two RE-CONFIG chunks for us -- we always
781 // simultaneously reset a sid's sequence number in both directions. The
782 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
783 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
785 const int num_ssrcs = (evt->strreset_length - sizeof(*evt)) /
786 sizeof(evt->strreset_stream_list[0]);
787 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
789 << std::hex << evt->strreset_flags << " ("
790 << ListFlags(evt->strreset_flags) << ")";
791 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
792 << ListArray(evt->strreset_stream_list, num_ssrcs)
794 << ListStreams(open_streams_) << "], Q'd: ["
795 << ListStreams(queued_reset_streams_) << "], Sent: ["
796 << ListStreams(sent_reset_streams_) << "]";
797 bool local_stream_reset_acknowledged = false;
799 // If both sides try to reset some streams at the same time (even if they're
800 // disjoint sets), we can get reset failures.
801 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
802 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
803 // is set seem to be garbage values. Ignore them.
804 queued_reset_streams_.insert(
805 sent_reset_streams_.begin(),
806 sent_reset_streams_.end());
807 sent_reset_streams_.clear();
808 local_stream_reset_acknowledged = true;
810 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
811 // Each side gets an event for each direction of a stream. That is,
812 // closing sid k will make each side receive INCOMING and OUTGOING reset
813 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
814 // get an INCOMING event first.
815 for (int i = 0; i < num_ssrcs; i++) {
816 const int stream_id = evt->strreset_stream_list[i];
818 // See if this stream ID was closed by our peer or ourselves.
819 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
821 // The reset was requested locally.
822 if (it != sent_reset_streams_.end()) {
823 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
824 << "): local sid " << stream_id << " acknowledged.";
825 local_stream_reset_acknowledged = true;
826 sent_reset_streams_.erase(it);
828 } else if ((it = open_streams_.find(stream_id))
829 != open_streams_.end()) {
830 // The peer requested the reset.
831 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
832 << "): closing sid " << stream_id;
833 open_streams_.erase(it);
834 SignalStreamClosed(stream_id);
836 } else if ((it = queued_reset_streams_.find(stream_id))
837 != queued_reset_streams_.end()) {
838 // The peer requested the reset, but there was a local reset
840 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
841 << "): double-sided close for sid " << stream_id;
842 // Both sides want the stream closed, and the peer got to send the
843 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
845 queued_reset_streams_.erase(it);
848 // This stream is unknown. Sometimes this can be from an
849 // RESET_FAILED-related retransmit.
850 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
851 << "): Unknown sid " << stream_id;
856 if (local_stream_reset_acknowledged) {
857 // This message acknowledges the last stream-reset request we sent out
858 // (only one can be outstanding at a time). Send out the next one.
859 SendQueuedStreamResets();
863 // Puts the specified |param| from the codec identified by |id| into |dest|
864 // and returns true. Or returns false if it wasn't there, leaving |dest|
866 static bool GetCodecIntParameter(const std::vector<DataCodec>& codecs,
867 int id, const std::string& name,
868 const std::string& param, int* dest) {
871 match_pattern.id = id;
872 match_pattern.name = name;
873 for (size_t i = 0; i < codecs.size(); ++i) {
874 if (codecs[i].Matches(match_pattern)) {
875 if (codecs[i].GetParam(param, &value)) {
876 *dest = talk_base::FromString<int>(value);
884 bool SctpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
885 return GetCodecIntParameter(
886 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
890 bool SctpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
891 return GetCodecIntParameter(
892 codecs, kGoogleSctpDataCodecId, kGoogleSctpDataCodecName, kCodecParamPort,
896 void SctpDataMediaChannel::OnPacketFromSctpToNetwork(
897 talk_base::Buffer* buffer) {
898 if (buffer->length() > kSctpMtu) {
899 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
900 << "SCTP seems to have made a packet that is bigger "
901 "than its official MTU.";
903 MediaChannel::SendPacket(buffer);
906 bool SctpDataMediaChannel::SendQueuedStreamResets() {
907 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty())
910 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
911 << ListStreams(queued_reset_streams_) << "], Open: ["
912 << ListStreams(open_streams_) << "], Sent: ["
913 << ListStreams(sent_reset_streams_) << "]";
915 const size_t num_streams = queued_reset_streams_.size();
916 const size_t num_bytes = sizeof(struct sctp_reset_streams)
917 + (num_streams * sizeof(uint16));
919 std::vector<uint8> reset_stream_buf(num_bytes, 0);
920 struct sctp_reset_streams* resetp = reinterpret_cast<sctp_reset_streams*>(
921 &reset_stream_buf[0]);
922 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
923 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
924 resetp->srs_number_streams = talk_base::checked_cast<uint16_t>(num_streams);
926 for (StreamSet::iterator it = queued_reset_streams_.begin();
927 it != queued_reset_streams_.end(); ++it) {
928 resetp->srs_stream_list[result_idx++] = *it;
931 int ret = usrsctp_setsockopt(
932 sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
933 talk_base::checked_cast<socklen_t>(reset_stream_buf.size()));
935 LOG_ERRNO(LS_ERROR) << debug_name_ << "Failed to send a stream reset for "
936 << num_streams << " streams";
940 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
942 queued_reset_streams_.swap(sent_reset_streams_);
946 void SctpDataMediaChannel::OnMessage(talk_base::Message* msg) {
947 switch (msg->message_id) {
948 case MSG_SCTPINBOUNDPACKET: {
949 talk_base::scoped_ptr<InboundPacketMessage> pdata(
950 static_cast<InboundPacketMessage*>(msg->pdata));
951 OnInboundPacketFromSctpToChannel(pdata->data().get());
954 case MSG_SCTPOUTBOUNDPACKET: {
955 talk_base::scoped_ptr<OutboundPacketMessage> pdata(
956 static_cast<OutboundPacketMessage*>(msg->pdata));
957 OnPacketFromSctpToNetwork(pdata->data().get());
962 } // namespace cricket