Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(633)

Side by Side Diff: webrtc/media/sctp/sctptransport.cc

Issue 2564333002: Reland of: Separating SCTP code from BaseChannel/MediaChannel. (Closed)
Patch Set: Another attempt. Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include <errno.h>
12 namespace {
13 // Some ERRNO values get re-#defined to WSA* equivalents in some talk/
14 // headers. We save the original ones in an enum.
15 enum PreservedErrno {
16 SCTP_EINPROGRESS = EINPROGRESS,
17 SCTP_EWOULDBLOCK = EWOULDBLOCK
18 };
19 }
20
21 #include "webrtc/media/sctp/sctptransport.h"
22
23 #include <stdarg.h>
24 #include <stdio.h>
25
26 #include <memory>
27 #include <sstream>
28
29 #include "usrsctplib/usrsctp.h"
30 #include "webrtc/base/arraysize.h"
31 #include "webrtc/base/copyonwritebuffer.h"
32 #include "webrtc/base/criticalsection.h"
33 #include "webrtc/base/helpers.h"
34 #include "webrtc/base/logging.h"
35 #include "webrtc/base/safe_conversions.h"
36 #include "webrtc/base/trace_event.h"
37 #include "webrtc/media/base/codec.h"
38 #include "webrtc/media/base/mediaconstants.h"
39 #include "webrtc/media/base/rtputils.h" // For IsRtpPacket
40 #include "webrtc/media/base/streamparams.h"
41
42 namespace {
43
44 // The biggest SCTP packet. Starting from a 'safe' wire MTU value of 1280,
45 // take off 80 bytes for DTLS/TURN/TCP/IP overhead.
46 static constexpr size_t kSctpMtu = 1200;
47
48 // The size of the SCTP association send buffer. 256kB, the usrsctp default.
49 static constexpr int kSendBufferSize = 262144;
50
51 // Set the initial value of the static SCTP Data Engines reference count.
52 int g_usrsctp_usage_count = 0;
53 rtc::GlobalLockPod g_usrsctp_lock_;
54
55 // DataMessageType is used for the SCTP "Payload Protocol Identifier", as
56 // defined in http://tools.ietf.org/html/rfc4960#section-14.4
57 //
58 // For the list of IANA approved values see:
59 // http://www.iana.org/assignments/sctp-parameters/sctp-parameters.xml
60 // The value is not used by SCTP itself. It indicates the protocol running
61 // on top of SCTP.
62 enum PayloadProtocolIdentifier {
63 PPID_NONE = 0, // No protocol is specified.
64 // Matches the PPIDs in mozilla source and
65 // https://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-protocol Sec. 9
66 // They're not yet assigned by IANA.
67 PPID_CONTROL = 50,
68 PPID_BINARY_PARTIAL = 52,
69 PPID_BINARY_LAST = 53,
70 PPID_TEXT_PARTIAL = 54,
71 PPID_TEXT_LAST = 51
72 };
73
74 typedef std::set<uint32_t> StreamSet;
75
76 // Returns a comma-separated, human-readable list of the stream IDs in 's'
77 std::string ListStreams(const StreamSet& s) {
78 std::stringstream result;
79 bool first = true;
80 for (StreamSet::const_iterator it = s.begin(); it != s.end(); ++it) {
81 if (!first) {
82 result << ", " << *it;
83 } else {
84 result << *it;
85 first = false;
86 }
87 }
88 return result.str();
89 }
90
91 // Returns a pipe-separated, human-readable list of the SCTP_STREAM_RESET
92 // flags in 'flags'
93 std::string ListFlags(int flags) {
94 std::stringstream result;
95 bool first = true;
96 // Skip past the first 12 chars (strlen("SCTP_STREAM_"))
97 #define MAKEFLAG(X) \
98 { X, #X + 12 }
99 struct flaginfo_t {
100 int value;
101 const char* name;
102 } flaginfo[] = {MAKEFLAG(SCTP_STREAM_RESET_INCOMING_SSN),
103 MAKEFLAG(SCTP_STREAM_RESET_OUTGOING_SSN),
104 MAKEFLAG(SCTP_STREAM_RESET_DENIED),
105 MAKEFLAG(SCTP_STREAM_RESET_FAILED),
106 MAKEFLAG(SCTP_STREAM_CHANGE_DENIED)};
107 #undef MAKEFLAG
108 for (uint32_t i = 0; i < arraysize(flaginfo); ++i) {
109 if (flags & flaginfo[i].value) {
110 if (!first)
111 result << " | ";
112 result << flaginfo[i].name;
113 first = false;
114 }
115 }
116 return result.str();
117 }
118
119 // Returns a comma-separated, human-readable list of the integers in 'array'.
120 // All 'num_elems' of them.
121 std::string ListArray(const uint16_t* array, int num_elems) {
122 std::stringstream result;
123 for (int i = 0; i < num_elems; ++i) {
124 if (i) {
125 result << ", " << array[i];
126 } else {
127 result << array[i];
128 }
129 }
130 return result.str();
131 }
132
133 // Helper for logging SCTP messages.
134 void DebugSctpPrintf(const char* format, ...) {
135 #if RTC_DCHECK_IS_ON
136 char s[255];
137 va_list ap;
138 va_start(ap, format);
139 vsnprintf(s, sizeof(s), format, ap);
140 LOG(LS_INFO) << "SCTP: " << s;
141 va_end(ap);
142 #endif
143 }
144
145 // Get the PPID to use for the terminating fragment of this type.
146 PayloadProtocolIdentifier GetPpid(cricket::DataMessageType type) {
147 switch (type) {
148 default:
149 case cricket::DMT_NONE:
150 return PPID_NONE;
151 case cricket::DMT_CONTROL:
152 return PPID_CONTROL;
153 case cricket::DMT_BINARY:
154 return PPID_BINARY_LAST;
155 case cricket::DMT_TEXT:
156 return PPID_TEXT_LAST;
157 }
158 }
159
160 bool GetDataMediaType(PayloadProtocolIdentifier ppid,
161 cricket::DataMessageType* dest) {
162 RTC_DCHECK(dest != NULL);
163 switch (ppid) {
164 case PPID_BINARY_PARTIAL:
165 case PPID_BINARY_LAST:
166 *dest = cricket::DMT_BINARY;
167 return true;
168
169 case PPID_TEXT_PARTIAL:
170 case PPID_TEXT_LAST:
171 *dest = cricket::DMT_TEXT;
172 return true;
173
174 case PPID_CONTROL:
175 *dest = cricket::DMT_CONTROL;
176 return true;
177
178 case PPID_NONE:
179 *dest = cricket::DMT_NONE;
180 return true;
181
182 default:
183 return false;
184 }
185 }
186
187 // Log the packet in text2pcap format, if log level is at LS_VERBOSE.
188 void VerboseLogPacket(const void* data, size_t length, int direction) {
189 if (LOG_CHECK_LEVEL(LS_VERBOSE) && length > 0) {
190 char* dump_buf;
191 // Some downstream project uses an older version of usrsctp that expects
192 // a non-const "void*" as first parameter when dumping the packet, so we
193 // need to cast the const away here to avoid a compiler error.
194 if ((dump_buf = usrsctp_dumppacket(const_cast<void*>(data), length,
195 direction)) != NULL) {
196 LOG(LS_VERBOSE) << dump_buf;
197 usrsctp_freedumpbuffer(dump_buf);
198 }
199 }
200 }
201
202 } // namespace
203
204 namespace cricket {
205
206 // Handles global init/deinit, and mapping from usrsctp callbacks to
207 // SctpTransport calls.
208 class SctpTransport::UsrSctpWrapper {
209 public:
210 static void InitializeUsrSctp() {
211 LOG(LS_INFO) << __FUNCTION__;
212 // First argument is udp_encapsulation_port, which is not releveant for our
213 // AF_CONN use of sctp.
214 usrsctp_init(0, &UsrSctpWrapper::OnSctpOutboundPacket, &DebugSctpPrintf);
215
216 // To turn on/off detailed SCTP debugging. You will also need to have the
217 // SCTP_DEBUG cpp defines flag.
218 // usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
219
220 // TODO(ldixon): Consider turning this on/off.
221 usrsctp_sysctl_set_sctp_ecn_enable(0);
222
223 // This is harmless, but we should find out when the library default
224 // changes.
225 int send_size = usrsctp_sysctl_get_sctp_sendspace();
226 if (send_size != kSendBufferSize) {
227 LOG(LS_ERROR) << "Got different send size than expected: " << send_size;
228 }
229
230 // TODO(ldixon): Consider turning this on/off.
231 // This is not needed right now (we don't do dynamic address changes):
232 // If SCTP Auto-ASCONF is enabled, the peer is informed automatically
233 // when a new address is added or removed. This feature is enabled by
234 // default.
235 // usrsctp_sysctl_set_sctp_auto_asconf(0);
236
237 // TODO(ldixon): Consider turning this on/off.
238 // Add a blackhole sysctl. Setting it to 1 results in no ABORTs
239 // being sent in response to INITs, setting it to 2 results
240 // in no ABORTs being sent for received OOTB packets.
241 // This is similar to the TCP sysctl.
242 //
243 // See: http://lakerest.net/pipermail/sctp-coders/2012-January/009438.html
244 // See: http://svnweb.freebsd.org/base?view=revision&revision=229805
245 // usrsctp_sysctl_set_sctp_blackhole(2);
246
247 // Set the number of default outgoing streams. This is the number we'll
248 // send in the SCTP INIT message.
249 usrsctp_sysctl_set_sctp_nr_outgoing_streams_default(kMaxSctpStreams);
250 }
251
252 static void UninitializeUsrSctp() {
253 LOG(LS_INFO) << __FUNCTION__;
254 // usrsctp_finish() may fail if it's called too soon after the transports
255 // are
256 // closed. Wait and try again until it succeeds for up to 3 seconds.
257 for (size_t i = 0; i < 300; ++i) {
258 if (usrsctp_finish() == 0) {
259 return;
260 }
261
262 rtc::Thread::SleepMs(10);
263 }
264 LOG(LS_ERROR) << "Failed to shutdown usrsctp.";
265 }
266
267 static void IncrementUsrSctpUsageCount() {
268 rtc::GlobalLockScope lock(&g_usrsctp_lock_);
269 if (!g_usrsctp_usage_count) {
270 InitializeUsrSctp();
271 }
272 ++g_usrsctp_usage_count;
273 }
274
275 static void DecrementUsrSctpUsageCount() {
276 rtc::GlobalLockScope lock(&g_usrsctp_lock_);
277 --g_usrsctp_usage_count;
278 if (!g_usrsctp_usage_count) {
279 UninitializeUsrSctp();
280 }
281 }
282
283 // This is the callback usrsctp uses when there's data to send on the network
284 // that has been wrapped appropriatly for the SCTP protocol.
285 static int OnSctpOutboundPacket(void* addr,
286 void* data,
287 size_t length,
288 uint8_t tos,
289 uint8_t set_df) {
290 SctpTransport* transport = static_cast<SctpTransport*>(addr);
291 LOG(LS_VERBOSE) << "global OnSctpOutboundPacket():"
292 << "addr: " << addr << "; length: " << length
293 << "; tos: " << std::hex << static_cast<int>(tos)
294 << "; set_df: " << std::hex << static_cast<int>(set_df);
295
296 VerboseLogPacket(data, length, SCTP_DUMP_OUTBOUND);
297 // Note: We have to copy the data; the caller will delete it.
298 rtc::CopyOnWriteBuffer buf(reinterpret_cast<uint8_t*>(data), length);
299 // TODO(deadbeef): Why do we need an AsyncInvoke here? We're already on the
300 // right thread and don't need to unwind the stack.
301 transport->invoker_.AsyncInvoke<void>(
302 RTC_FROM_HERE, transport->network_thread_,
303 rtc::Bind(&SctpTransport::OnPacketFromSctpToNetwork, transport, buf));
304 return 0;
305 }
306
307 // This is the callback called from usrsctp when data has been received, after
308 // a packet has been interpreted and parsed by usrsctp and found to contain
309 // payload data. It is called by a usrsctp thread. It is assumed this function
310 // will free the memory used by 'data'.
311 static int OnSctpInboundPacket(struct socket* sock,
312 union sctp_sockstore addr,
313 void* data,
314 size_t length,
315 struct sctp_rcvinfo rcv,
316 int flags,
317 void* ulp_info) {
318 SctpTransport* transport = static_cast<SctpTransport*>(ulp_info);
319 // Post data to the transport's receiver thread (copying it).
320 // TODO(ldixon): Unclear if copy is needed as this method is responsible for
321 // memory cleanup. But this does simplify code.
322 const PayloadProtocolIdentifier ppid =
323 static_cast<PayloadProtocolIdentifier>(
324 rtc::HostToNetwork32(rcv.rcv_ppid));
325 DataMessageType type = DMT_NONE;
326 if (!GetDataMediaType(ppid, &type) && !(flags & MSG_NOTIFICATION)) {
327 // It's neither a notification nor a recognized data packet. Drop it.
328 LOG(LS_ERROR) << "Received an unknown PPID " << ppid
329 << " on an SCTP packet. Dropping.";
330 } else {
331 rtc::CopyOnWriteBuffer buffer;
332 ReceiveDataParams params;
333 buffer.SetData(reinterpret_cast<uint8_t*>(data), length);
334 params.ssrc = rcv.rcv_sid;
335 params.seq_num = rcv.rcv_ssn;
336 params.timestamp = rcv.rcv_tsn;
337 params.type = type;
338 // The ownership of the packet transfers to |invoker_|. Using
339 // CopyOnWriteBuffer is the most convenient way to do this.
340 transport->invoker_.AsyncInvoke<void>(
341 RTC_FROM_HERE, transport->network_thread_,
342 rtc::Bind(&SctpTransport::OnInboundPacketFromSctpToChannel, transport,
343 buffer, params, flags));
344 }
345 free(data);
346 return 1;
347 }
348
349 static SctpTransport* GetTransportFromSocket(struct socket* sock) {
350 struct sockaddr* addrs = nullptr;
351 int naddrs = usrsctp_getladdrs(sock, 0, &addrs);
352 if (naddrs <= 0 || addrs[0].sa_family != AF_CONN) {
353 return nullptr;
354 }
355 // usrsctp_getladdrs() returns the addresses bound to this socket, which
356 // contains the SctpTransport* as sconn_addr. Read the pointer,
357 // then free the list of addresses once we have the pointer. We only open
358 // AF_CONN sockets, and they should all have the sconn_addr set to the
359 // pointer that created them, so [0] is as good as any other.
360 struct sockaddr_conn* sconn =
361 reinterpret_cast<struct sockaddr_conn*>(&addrs[0]);
362 SctpTransport* transport =
363 reinterpret_cast<SctpTransport*>(sconn->sconn_addr);
364 usrsctp_freeladdrs(addrs);
365
366 return transport;
367 }
368
369 static int SendThresholdCallback(struct socket* sock, uint32_t sb_free) {
370 // Fired on our I/O thread. SctpTransport::OnPacketReceived() gets
371 // a packet containing acknowledgments, which goes into usrsctp_conninput,
372 // and then back here.
373 SctpTransport* transport = GetTransportFromSocket(sock);
374 if (!transport) {
375 LOG(LS_ERROR)
376 << "SendThresholdCallback: Failed to get transport for socket "
377 << sock;
378 return 0;
379 }
380 transport->OnSendThresholdCallback();
381 return 0;
382 }
383 };
384
385 SctpTransport::SctpTransport(rtc::Thread* network_thread,
386 TransportChannel* channel)
387 : network_thread_(network_thread),
388 transport_channel_(channel),
389 was_ever_writable_(channel->writable()) {
390 RTC_DCHECK(network_thread_);
391 RTC_DCHECK(transport_channel_);
392 ConnectTransportChannelSignals();
393 }
394
395 SctpTransport::~SctpTransport() {
396 // Close abruptly; no reset procedure.
397 CloseSctpSocket();
398 }
399
400 void SctpTransport::SetTransportChannel(cricket::TransportChannel* channel) {
401 RTC_DCHECK(channel);
402 DisconnectTransportChannelSignals();
403 transport_channel_ = channel;
404 ConnectTransportChannelSignals();
405 if (!was_ever_writable_ && channel->writable()) {
406 was_ever_writable_ = true;
407 // New channel is writable, now we can start the SCTP connection if Start
408 // was called already.
409 if (started_) {
410 RTC_DCHECK(!sock_);
411 Connect();
412 }
413 }
414 }
415
416 bool SctpTransport::Start(int local_sctp_port, int remote_sctp_port) {
417 if (local_sctp_port == -1) {
418 local_sctp_port = kSctpDefaultPort;
419 }
420 if (remote_sctp_port == -1) {
421 remote_sctp_port = kSctpDefaultPort;
422 }
423 if (started_) {
424 if (local_sctp_port != local_port_ || remote_sctp_port != remote_port_) {
425 LOG(LS_ERROR) << "Can't change SCTP port after SCTP association formed.";
426 return false;
427 }
428 return true;
429 }
430 local_port_ = local_sctp_port;
431 remote_port_ = remote_sctp_port;
432 started_ = true;
433 RTC_DCHECK(!sock_);
434 // Only try to connect if the DTLS channel has been writable before
435 // (indicating that the DTLS handshake is complete).
436 if (was_ever_writable_) {
437 return Connect();
438 }
439 return true;
440 }
441
442 bool SctpTransport::OpenStream(int sid) {
443 if (sid > kMaxSctpSid) {
444 LOG(LS_WARNING) << debug_name_ << "->OpenStream(...): "
445 << "Not adding data stream "
446 << "with sid=" << sid << " because sid is too high.";
447 return false;
448 } else if (open_streams_.find(sid) != open_streams_.end()) {
449 LOG(LS_WARNING) << debug_name_ << "->OpenStream(...): "
450 << "Not adding data stream "
451 << "with sid=" << sid << " because stream is already open.";
452 return false;
453 } else if (queued_reset_streams_.find(sid) != queued_reset_streams_.end() ||
454 sent_reset_streams_.find(sid) != sent_reset_streams_.end()) {
455 LOG(LS_WARNING) << debug_name_ << "->OpenStream(...): "
456 << "Not adding data stream "
457 << " with sid=" << sid
458 << " because stream is still closing.";
459 return false;
460 }
461
462 open_streams_.insert(sid);
463 return true;
464 }
465
466 bool SctpTransport::ResetStream(int sid) {
467 StreamSet::iterator found = open_streams_.find(sid);
468 if (found == open_streams_.end()) {
469 LOG(LS_WARNING) << debug_name_ << "->ResetStream(" << sid << "): "
470 << "stream not found.";
471 return false;
472 } else {
473 LOG(LS_VERBOSE) << debug_name_ << "->ResetStream(" << sid << "): "
474 << "Removing and queuing RE-CONFIG chunk.";
475 open_streams_.erase(found);
476 }
477
478 // SCTP won't let you have more than one stream reset pending at a time, but
479 // you can close multiple streams in a single reset. So, we keep an internal
480 // queue of streams-to-reset, and send them as one reset message in
481 // SendQueuedStreamResets().
482 queued_reset_streams_.insert(sid);
483
484 // Signal our stream-reset logic that it should try to send now, if it can.
485 SendQueuedStreamResets();
486
487 // The stream will actually get removed when we get the acknowledgment.
488 return true;
pthatcher1 2016/12/23 01:39:31 Which parts of this file are significantly differe
Taylor Brandstetter 2016/12/23 06:29:05 The public methods (SetTransportChannel, Start, Op
489 }
490
491 bool SctpTransport::SendData(const SendDataParams& params,
492 const rtc::CopyOnWriteBuffer& payload,
493 SendDataResult* result) {
494 if (result) {
495 // Preset |result| to assume an error. If SendData succeeds, we'll
496 // overwrite |*result| once more at the end.
497 *result = SDR_ERROR;
498 }
499
500 if (!sock_) {
501 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
502 << "Not sending packet with sid=" << params.ssrc
503 << " len=" << payload.size() << " before Start().";
504 return false;
505 }
506
507 if (params.type != DMT_CONTROL &&
508 open_streams_.find(params.ssrc) == open_streams_.end()) {
509 LOG(LS_WARNING) << debug_name_ << "->SendData(...): "
510 << "Not sending data because sid is unknown: "
511 << params.ssrc;
512 return false;
513 }
514
515 // Send data using SCTP.
516 ssize_t send_res = 0; // result from usrsctp_sendv.
517 struct sctp_sendv_spa spa = {0};
518 spa.sendv_flags |= SCTP_SEND_SNDINFO_VALID;
519 spa.sendv_sndinfo.snd_sid = params.ssrc;
520 spa.sendv_sndinfo.snd_ppid = rtc::HostToNetwork32(GetPpid(params.type));
521
522 // Ordered implies reliable.
523 if (!params.ordered) {
524 spa.sendv_sndinfo.snd_flags |= SCTP_UNORDERED;
525 if (params.max_rtx_count >= 0 || params.max_rtx_ms == 0) {
526 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
527 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_RTX;
528 spa.sendv_prinfo.pr_value = params.max_rtx_count;
529 } else {
530 spa.sendv_flags |= SCTP_SEND_PRINFO_VALID;
531 spa.sendv_prinfo.pr_policy = SCTP_PR_SCTP_TTL;
532 spa.sendv_prinfo.pr_value = params.max_rtx_ms;
533 }
534 }
535
536 // We don't fragment.
537 send_res = usrsctp_sendv(
538 sock_, payload.data(), static_cast<size_t>(payload.size()), NULL, 0, &spa,
539 rtc::checked_cast<socklen_t>(sizeof(spa)), SCTP_SENDV_SPA, 0);
540 if (send_res < 0) {
541 if (errno == SCTP_EWOULDBLOCK) {
542 *result = SDR_BLOCK;
543 ready_to_send_data_ = false;
544 LOG(LS_INFO) << debug_name_ << "->SendData(...): EWOULDBLOCK returned";
545 } else {
546 LOG_ERRNO(LS_ERROR) << "ERROR:" << debug_name_ << "->SendData(...): "
547 << " usrsctp_sendv: ";
548 }
549 return false;
550 }
551 if (result) {
552 // Only way out now is success.
553 *result = SDR_SUCCESS;
554 }
555 return true;
556 }
557
558 bool SctpTransport::ReadyToSendData() {
559 return ready_to_send_data_;
560 }
561
562 void SctpTransport::ConnectTransportChannelSignals() {
563 transport_channel_->SignalWritableState.connect(
564 this, &SctpTransport::OnWritableState);
565 transport_channel_->SignalReadPacket.connect(this,
566 &SctpTransport::OnPacketRead);
567 }
568
569 void SctpTransport::DisconnectTransportChannelSignals() {
570 transport_channel_->SignalWritableState.disconnect(this);
571 transport_channel_->SignalReadPacket.disconnect(this);
572 }
573
574 bool SctpTransport::Connect() {
575 LOG(LS_VERBOSE) << debug_name_ << "->Connect().";
576
577 // If we already have a socket connection (which shouldn't ever happen), just
578 // return.
579 RTC_DCHECK(!sock_);
580 if (sock_) {
581 LOG(LS_ERROR) << debug_name_ << "->Connect(): Ignored as socket "
582 "is already established.";
583 return true;
584 }
585
586 // If no socket (it was closed) try to start it again. This can happen when
587 // the socket we are connecting to closes, does an sctp shutdown handshake,
588 // or behaves unexpectedly causing us to perform a CloseSctpSocket.
589 if (!OpenSctpSocket()) {
590 return false;
591 }
592
593 // Note: conversion from int to uint16_t happens on assignment.
594 sockaddr_conn local_sconn = GetSctpSockAddr(local_port_);
595 if (usrsctp_bind(sock_, reinterpret_cast<sockaddr*>(&local_sconn),
596 sizeof(local_sconn)) < 0) {
597 LOG_ERRNO(LS_ERROR) << debug_name_
598 << "->Connect(): " << ("Failed usrsctp_bind");
599 CloseSctpSocket();
600 return false;
601 }
602
603 // Note: conversion from int to uint16_t happens on assignment.
604 sockaddr_conn remote_sconn = GetSctpSockAddr(remote_port_);
605 int connect_result = usrsctp_connect(
606 sock_, reinterpret_cast<sockaddr*>(&remote_sconn), sizeof(remote_sconn));
607 if (connect_result < 0 && errno != SCTP_EINPROGRESS) {
608 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
609 << "Failed usrsctp_connect. got errno=" << errno
610 << ", but wanted " << SCTP_EINPROGRESS;
611 CloseSctpSocket();
612 return false;
613 }
614 // Set the MTU and disable MTU discovery.
615 // We can only do this after usrsctp_connect or it has no effect.
616 sctp_paddrparams params = {{0}};
617 memcpy(&params.spp_address, &remote_sconn, sizeof(remote_sconn));
618 params.spp_flags = SPP_PMTUD_DISABLE;
619 params.spp_pathmtu = kSctpMtu;
620 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &params,
621 sizeof(params))) {
622 LOG_ERRNO(LS_ERROR) << debug_name_ << "->Connect(): "
623 << "Failed to set SCTP_PEER_ADDR_PARAMS.";
624 }
625 // Since this is a fresh SCTP association, we'll always start out with empty
626 // queues, so "ReadyToSendData" should be true.
627 SetReadyToSendData();
628 return true;
629 }
630
631 bool SctpTransport::OpenSctpSocket() {
632 if (sock_) {
633 LOG(LS_WARNING) << debug_name_ << "->OpenSctpSocket(): "
634 << "Ignoring attempt to re-create existing socket.";
635 return false;
636 }
637
638 UsrSctpWrapper::IncrementUsrSctpUsageCount();
639
640 // If kSendBufferSize isn't reflective of reality, we log an error, but we
641 // still have to do something reasonable here. Look up what the buffer's
642 // real size is and set our threshold to something reasonable.
643 static const int kSendThreshold = usrsctp_sysctl_get_sctp_sendspace() / 2;
644
645 sock_ = usrsctp_socket(
646 AF_CONN, SOCK_STREAM, IPPROTO_SCTP, &UsrSctpWrapper::OnSctpInboundPacket,
647 &UsrSctpWrapper::SendThresholdCallback, kSendThreshold, this);
648 if (!sock_) {
649 LOG_ERRNO(LS_ERROR) << debug_name_ << "->OpenSctpSocket(): "
650 << "Failed to create SCTP socket.";
651 UsrSctpWrapper::DecrementUsrSctpUsageCount();
652 return false;
653 }
654
655 if (!ConfigureSctpSocket()) {
656 usrsctp_close(sock_);
657 sock_ = nullptr;
658 UsrSctpWrapper::DecrementUsrSctpUsageCount();
659 return false;
660 }
661 // Register this class as an address for usrsctp. This is used by SCTP to
662 // direct the packets received (by the created socket) to this class.
663 usrsctp_register_address(this);
664 return true;
665 }
666
667 bool SctpTransport::ConfigureSctpSocket() {
668 RTC_DCHECK(sock_);
669 // Make the socket non-blocking. Connect, close, shutdown etc will not block
670 // the thread waiting for the socket operation to complete.
671 if (usrsctp_set_non_blocking(sock_, 1) < 0) {
672 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
673 << "Failed to set SCTP to non blocking.";
674 return false;
675 }
676
677 // This ensures that the usrsctp close call deletes the association. This
678 // prevents usrsctp from calling OnSctpOutboundPacket with references to
679 // this class as the address.
680 linger linger_opt;
681 linger_opt.l_onoff = 1;
682 linger_opt.l_linger = 0;
683 if (usrsctp_setsockopt(sock_, SOL_SOCKET, SO_LINGER, &linger_opt,
684 sizeof(linger_opt))) {
685 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
686 << "Failed to set SO_LINGER.";
687 return false;
688 }
689
690 // Enable stream ID resets.
691 struct sctp_assoc_value stream_rst;
692 stream_rst.assoc_id = SCTP_ALL_ASSOC;
693 stream_rst.assoc_value = 1;
694 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_ENABLE_STREAM_RESET,
695 &stream_rst, sizeof(stream_rst))) {
696 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
697
698 << "Failed to set SCTP_ENABLE_STREAM_RESET.";
699 return false;
700 }
701
702 // Nagle.
703 uint32_t nodelay = 1;
704 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_NODELAY, &nodelay,
705 sizeof(nodelay))) {
706 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
707 << "Failed to set SCTP_NODELAY.";
708 return false;
709 }
710
711 // Subscribe to SCTP event notifications.
712 int event_types[] = {SCTP_ASSOC_CHANGE, SCTP_PEER_ADDR_CHANGE,
713 SCTP_SEND_FAILED_EVENT, SCTP_SENDER_DRY_EVENT,
714 SCTP_STREAM_RESET_EVENT};
715 struct sctp_event event = {0};
716 event.se_assoc_id = SCTP_ALL_ASSOC;
717 event.se_on = 1;
718 for (size_t i = 0; i < arraysize(event_types); i++) {
719 event.se_type = event_types[i];
720 if (usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_EVENT, &event,
721 sizeof(event)) < 0) {
722 LOG_ERRNO(LS_ERROR) << debug_name_ << "->ConfigureSctpSocket(): "
723
724 << "Failed to set SCTP_EVENT type: " << event.se_type;
725 return false;
726 }
727 }
728 return true;
729 }
730
731 void SctpTransport::CloseSctpSocket() {
732 if (sock_) {
733 // We assume that SO_LINGER option is set to close the association when
734 // close is called. This means that any pending packets in usrsctp will be
735 // discarded instead of being sent.
736 usrsctp_close(sock_);
737 sock_ = nullptr;
738 usrsctp_deregister_address(this);
739 UsrSctpWrapper::DecrementUsrSctpUsageCount();
740 ready_to_send_data_ = false;
741 }
742 }
743
744 bool SctpTransport::SendQueuedStreamResets() {
745 if (!sent_reset_streams_.empty() || queued_reset_streams_.empty()) {
746 return true;
747 }
748
749 LOG(LS_VERBOSE) << "SendQueuedStreamResets[" << debug_name_ << "]: Sending ["
750 << ListStreams(queued_reset_streams_) << "], Open: ["
751 << ListStreams(open_streams_) << "], Sent: ["
752 << ListStreams(sent_reset_streams_) << "]";
753
754 const size_t num_streams = queued_reset_streams_.size();
755 const size_t num_bytes =
756 sizeof(struct sctp_reset_streams) + (num_streams * sizeof(uint16_t));
757
758 std::vector<uint8_t> reset_stream_buf(num_bytes, 0);
759 struct sctp_reset_streams* resetp =
760 reinterpret_cast<sctp_reset_streams*>(&reset_stream_buf[0]);
761 resetp->srs_assoc_id = SCTP_ALL_ASSOC;
762 resetp->srs_flags = SCTP_STREAM_RESET_INCOMING | SCTP_STREAM_RESET_OUTGOING;
763 resetp->srs_number_streams = rtc::checked_cast<uint16_t>(num_streams);
764 int result_idx = 0;
765 for (StreamSet::iterator it = queued_reset_streams_.begin();
766 it != queued_reset_streams_.end(); ++it) {
767 resetp->srs_stream_list[result_idx++] = *it;
768 }
769
770 int ret =
771 usrsctp_setsockopt(sock_, IPPROTO_SCTP, SCTP_RESET_STREAMS, resetp,
772 rtc::checked_cast<socklen_t>(reset_stream_buf.size()));
773 if (ret < 0) {
774 LOG_ERRNO(LS_ERROR) << debug_name_ << "->SendQueuedStreamResets(): "
775 "Failed to send a stream reset for "
776 << num_streams << " streams";
777 return false;
778 }
779
780 // sent_reset_streams_ is empty, and all the queued_reset_streams_ go into
781 // it now.
782 queued_reset_streams_.swap(sent_reset_streams_);
783 return true;
784 }
785
786 void SctpTransport::SetReadyToSendData() {
787 if (!ready_to_send_data_) {
788 ready_to_send_data_ = true;
789 SignalReadyToSendData();
790 }
791 }
792
793 void SctpTransport::OnWritableState(rtc::PacketTransportInterface* transport) {
794 RTC_DCHECK(network_thread_->IsCurrent());
795 RTC_DCHECK_EQ(transport_channel_, transport);
796 if (!was_ever_writable_ && transport->writable()) {
797 was_ever_writable_ = true;
798 if (started_) {
799 Connect();
800 }
801 }
802 }
803
804 // Called by network interface when a packet has been received.
805 void SctpTransport::OnPacketRead(rtc::PacketTransportInterface* transport,
806 const char* data,
807 size_t len,
808 const rtc::PacketTime& packet_time,
809 int flags) {
810 RTC_DCHECK(network_thread_->IsCurrent());
811 RTC_DCHECK_EQ(transport_channel_, transport);
812 TRACE_EVENT0("webrtc", "SctpTransport::OnPacketRead");
813
814 // TODO(pthatcher): Do this in a more robust way by checking for
815 // SCTP or DTLS.
816 if (IsRtpPacket(data, len)) {
817 return;
818 }
819
820 LOG(LS_VERBOSE) << debug_name_ << "->OnPacketRead(...): "
821 << " length=" << len << ", started: " << started_;
822 // Only give receiving packets to usrsctp after if connected. This enables two
823 // peers to each make a connect call, but for them not to receive an INIT
824 // packet before they have called connect; least the last receiver of the INIT
825 // packet will have called connect, and a connection will be established.
826 if (sock_) {
827 // Pass received packet to SCTP stack. Once processed by usrsctp, the data
828 // will be will be given to the global OnSctpInboundData, and then,
829 // marshalled by the AsyncInvoker.
830 VerboseLogPacket(data, len, SCTP_DUMP_INBOUND);
831 usrsctp_conninput(this, data, len, 0);
832 } else {
833 // TODO(ldixon): Consider caching the packet for very slightly better
834 // reliability.
835 }
836 }
837
838 void SctpTransport::OnSendThresholdCallback() {
839 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
840 SetReadyToSendData();
841 }
842
843 sockaddr_conn SctpTransport::GetSctpSockAddr(int port) {
844 sockaddr_conn sconn = {0};
845 sconn.sconn_family = AF_CONN;
846 #ifdef HAVE_SCONN_LEN
847 sconn.sconn_len = sizeof(sockaddr_conn);
848 #endif
849 // Note: conversion from int to uint16_t happens here.
850 sconn.sconn_port = rtc::HostToNetwork16(port);
851 sconn.sconn_addr = this;
852 return sconn;
853 }
854
855 void SctpTransport::OnPacketFromSctpToNetwork(
856 const rtc::CopyOnWriteBuffer& buffer) {
857 if (buffer.size() > (kSctpMtu)) {
858 LOG(LS_ERROR) << debug_name_ << "->OnPacketFromSctpToNetwork(...): "
859 << "SCTP seems to have made a packet that is bigger "
860 << "than its official MTU: " << buffer.size() << " vs max of "
861 << kSctpMtu;
862 }
863 TRACE_EVENT0("webrtc", "SctpTransport::OnPacketFromSctpToNetwork");
864
865 // Don't create noise by trying to send a packet when the DTLS channel isn't
866 // even writable.
867 if (!transport_channel_->writable()) {
868 return;
869 }
870
871 // Bon voyage.
872 transport_channel_->SendPacket(buffer.data<char>(), buffer.size(),
873 rtc::PacketOptions(), PF_NORMAL);
874 }
875
876 void SctpTransport::OnInboundPacketFromSctpToChannel(
877 const rtc::CopyOnWriteBuffer& buffer,
878 ReceiveDataParams params,
879 int flags) {
880 LOG(LS_VERBOSE) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
881 << "Received SCTP data:"
882 << " ssrc=" << params.ssrc
883 << " notification: " << (flags & MSG_NOTIFICATION)
884 << " length=" << buffer.size();
885 // Sending a packet with data == NULL (no data) is SCTPs "close the
886 // connection" message. This sets sock_ = NULL;
887 if (!buffer.size() || !buffer.data()) {
888 LOG(LS_INFO) << debug_name_ << "->OnInboundPacketFromSctpToChannel(...): "
889 "No data, closing.";
890 return;
891 }
892 if (flags & MSG_NOTIFICATION) {
893 OnNotificationFromSctp(buffer);
894 } else {
895 OnDataFromSctpToChannel(params, buffer);
896 }
897 }
898
899 void SctpTransport::OnDataFromSctpToChannel(
900 const ReceiveDataParams& params,
901 const rtc::CopyOnWriteBuffer& buffer) {
902 LOG(LS_VERBOSE) << debug_name_ << "->OnDataFromSctpToChannel(...): "
903 << "Posting with length: " << buffer.size() << " on stream "
904 << params.ssrc;
905 // Reports all received messages to upper layers, no matter whether the sid
906 // is known.
907 SignalDataReceived(params, buffer);
908 }
909
910 void SctpTransport::OnNotificationFromSctp(
911 const rtc::CopyOnWriteBuffer& buffer) {
912 const sctp_notification& notification =
913 reinterpret_cast<const sctp_notification&>(*buffer.data());
914 RTC_DCHECK(notification.sn_header.sn_length == buffer.size());
915
916 // TODO(ldixon): handle notifications appropriately.
917 switch (notification.sn_header.sn_type) {
918 case SCTP_ASSOC_CHANGE:
919 LOG(LS_VERBOSE) << "SCTP_ASSOC_CHANGE";
920 OnNotificationAssocChange(notification.sn_assoc_change);
921 break;
922 case SCTP_REMOTE_ERROR:
923 LOG(LS_INFO) << "SCTP_REMOTE_ERROR";
924 break;
925 case SCTP_SHUTDOWN_EVENT:
926 LOG(LS_INFO) << "SCTP_SHUTDOWN_EVENT";
927 break;
928 case SCTP_ADAPTATION_INDICATION:
929 LOG(LS_INFO) << "SCTP_ADAPTATION_INDICATION";
930 break;
931 case SCTP_PARTIAL_DELIVERY_EVENT:
932 LOG(LS_INFO) << "SCTP_PARTIAL_DELIVERY_EVENT";
933 break;
934 case SCTP_AUTHENTICATION_EVENT:
935 LOG(LS_INFO) << "SCTP_AUTHENTICATION_EVENT";
936 break;
937 case SCTP_SENDER_DRY_EVENT:
938 LOG(LS_VERBOSE) << "SCTP_SENDER_DRY_EVENT";
939 SetReadyToSendData();
940 break;
941 // TODO(ldixon): Unblock after congestion.
942 case SCTP_NOTIFICATIONS_STOPPED_EVENT:
943 LOG(LS_INFO) << "SCTP_NOTIFICATIONS_STOPPED_EVENT";
944 break;
945 case SCTP_SEND_FAILED_EVENT:
946 LOG(LS_INFO) << "SCTP_SEND_FAILED_EVENT";
947 break;
948 case SCTP_STREAM_RESET_EVENT:
949 OnStreamResetEvent(&notification.sn_strreset_event);
950 break;
951 case SCTP_ASSOC_RESET_EVENT:
952 LOG(LS_INFO) << "SCTP_ASSOC_RESET_EVENT";
953 break;
954 case SCTP_STREAM_CHANGE_EVENT:
955 LOG(LS_INFO) << "SCTP_STREAM_CHANGE_EVENT";
956 // An acknowledgment we get after our stream resets have gone through,
957 // if they've failed. We log the message, but don't react -- we don't
958 // keep around the last-transmitted set of SSIDs we wanted to close for
959 // error recovery. It doesn't seem likely to occur, and if so, likely
960 // harmless within the lifetime of a single SCTP association.
961 break;
962 default:
963 LOG(LS_WARNING) << "Unknown SCTP event: "
964 << notification.sn_header.sn_type;
965 break;
966 }
967 }
968
969 void SctpTransport::OnNotificationAssocChange(const sctp_assoc_change& change) {
970 switch (change.sac_state) {
971 case SCTP_COMM_UP:
972 LOG(LS_VERBOSE) << "Association change SCTP_COMM_UP";
973 break;
974 case SCTP_COMM_LOST:
975 LOG(LS_INFO) << "Association change SCTP_COMM_LOST";
976 break;
977 case SCTP_RESTART:
978 LOG(LS_INFO) << "Association change SCTP_RESTART";
979 break;
980 case SCTP_SHUTDOWN_COMP:
981 LOG(LS_INFO) << "Association change SCTP_SHUTDOWN_COMP";
982 break;
983 case SCTP_CANT_STR_ASSOC:
984 LOG(LS_INFO) << "Association change SCTP_CANT_STR_ASSOC";
985 break;
986 default:
987 LOG(LS_INFO) << "Association change UNKNOWN";
988 break;
989 }
990 }
991
992 void SctpTransport::OnStreamResetEvent(
993 const struct sctp_stream_reset_event* evt) {
994 // A stream reset always involves two RE-CONFIG chunks for us -- we always
995 // simultaneously reset a sid's sequence number in both directions. The
996 // requesting side transmits a RE-CONFIG chunk and waits for the peer to send
997 // one back. Both sides get this SCTP_STREAM_RESET_EVENT when they receive
998 // RE-CONFIGs.
999 const int num_ssrcs = (evt->strreset_length - sizeof(*evt)) /
1000 sizeof(evt->strreset_stream_list[0]);
1001 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1002 << "): Flags = 0x" << std::hex << evt->strreset_flags << " ("
1003 << ListFlags(evt->strreset_flags) << ")";
1004 LOG(LS_VERBOSE) << "Assoc = " << evt->strreset_assoc_id << ", Streams = ["
1005 << ListArray(evt->strreset_stream_list, num_ssrcs)
1006 << "], Open: [" << ListStreams(open_streams_) << "], Q'd: ["
1007 << ListStreams(queued_reset_streams_) << "], Sent: ["
1008 << ListStreams(sent_reset_streams_) << "]";
1009
1010 // If both sides try to reset some streams at the same time (even if they're
1011 // disjoint sets), we can get reset failures.
1012 if (evt->strreset_flags & SCTP_STREAM_RESET_FAILED) {
1013 // OK, just try again. The stream IDs sent over when the RESET_FAILED flag
1014 // is set seem to be garbage values. Ignore them.
1015 queued_reset_streams_.insert(sent_reset_streams_.begin(),
1016 sent_reset_streams_.end());
1017 sent_reset_streams_.clear();
1018
1019 } else if (evt->strreset_flags & SCTP_STREAM_RESET_INCOMING_SSN) {
1020 // Each side gets an event for each direction of a stream. That is,
1021 // closing sid k will make each side receive INCOMING and OUTGOING reset
1022 // events for k. As per RFC6525, Section 5, paragraph 2, each side will
1023 // get an INCOMING event first.
1024 for (int i = 0; i < num_ssrcs; i++) {
1025 const int stream_id = evt->strreset_stream_list[i];
1026
1027 // See if this stream ID was closed by our peer or ourselves.
1028 StreamSet::iterator it = sent_reset_streams_.find(stream_id);
1029
1030 // The reset was requested locally.
1031 if (it != sent_reset_streams_.end()) {
1032 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1033 << "): local sid " << stream_id << " acknowledged.";
1034 sent_reset_streams_.erase(it);
1035
1036 } else if ((it = open_streams_.find(stream_id)) != open_streams_.end()) {
1037 // The peer requested the reset.
1038 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1039 << "): closing sid " << stream_id;
1040 open_streams_.erase(it);
1041 SignalStreamClosedRemotely(stream_id);
1042
1043 } else if ((it = queued_reset_streams_.find(stream_id)) !=
1044 queued_reset_streams_.end()) {
1045 // The peer requested the reset, but there was a local reset
1046 // queued.
1047 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1048 << "): double-sided close for sid " << stream_id;
1049 // Both sides want the stream closed, and the peer got to send the
1050 // RE-CONFIG first. Treat it like the local Remove(Send|Recv)Stream
1051 // finished quickly.
1052 queued_reset_streams_.erase(it);
1053
1054 } else {
1055 // This stream is unknown. Sometimes this can be from an
1056 // RESET_FAILED-related retransmit.
1057 LOG(LS_VERBOSE) << "SCTP_STREAM_RESET_EVENT(" << debug_name_
1058 << "): Unknown sid " << stream_id;
1059 }
1060 }
1061 }
1062
1063 // Always try to send the queued RESET because this call indicates that the
1064 // last local RESET or remote RESET has made some progress.
1065 SendQueuedStreamResets();
1066 }
1067
1068 } // namespace cricket
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698