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

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

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

Powered by Google App Engine
This is Rietveld 408576698