blob: 0c181996a2227ff67194dc9cb8aa819fd65066d0 [file] [log] [blame]
Victor Boivieb6580cc2021-04-08 09:56:59 +02001/*
2 * Copyright (c) 2021 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#include "net/dcsctp/socket/dcsctp_socket.h"
11
12#include <algorithm>
13#include <cstdint>
14#include <limits>
15#include <memory>
16#include <string>
17#include <utility>
18#include <vector>
19
20#include "absl/memory/memory.h"
21#include "absl/strings/string_view.h"
22#include "absl/types/optional.h"
23#include "api/array_view.h"
24#include "net/dcsctp/packet/chunk/abort_chunk.h"
25#include "net/dcsctp/packet/chunk/chunk.h"
26#include "net/dcsctp/packet/chunk/cookie_ack_chunk.h"
27#include "net/dcsctp/packet/chunk/cookie_echo_chunk.h"
28#include "net/dcsctp/packet/chunk/data_chunk.h"
29#include "net/dcsctp/packet/chunk/data_common.h"
30#include "net/dcsctp/packet/chunk/error_chunk.h"
31#include "net/dcsctp/packet/chunk/forward_tsn_chunk.h"
32#include "net/dcsctp/packet/chunk/forward_tsn_common.h"
33#include "net/dcsctp/packet/chunk/heartbeat_ack_chunk.h"
34#include "net/dcsctp/packet/chunk/heartbeat_request_chunk.h"
35#include "net/dcsctp/packet/chunk/idata_chunk.h"
36#include "net/dcsctp/packet/chunk/iforward_tsn_chunk.h"
37#include "net/dcsctp/packet/chunk/init_ack_chunk.h"
38#include "net/dcsctp/packet/chunk/init_chunk.h"
39#include "net/dcsctp/packet/chunk/reconfig_chunk.h"
40#include "net/dcsctp/packet/chunk/sack_chunk.h"
41#include "net/dcsctp/packet/chunk/shutdown_ack_chunk.h"
42#include "net/dcsctp/packet/chunk/shutdown_chunk.h"
43#include "net/dcsctp/packet/chunk/shutdown_complete_chunk.h"
44#include "net/dcsctp/packet/chunk_validators.h"
45#include "net/dcsctp/packet/data.h"
46#include "net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.h"
47#include "net/dcsctp/packet/error_cause/error_cause.h"
48#include "net/dcsctp/packet/error_cause/no_user_data_cause.h"
49#include "net/dcsctp/packet/error_cause/out_of_resource_error_cause.h"
50#include "net/dcsctp/packet/error_cause/protocol_violation_cause.h"
51#include "net/dcsctp/packet/error_cause/unrecognized_chunk_type_cause.h"
52#include "net/dcsctp/packet/error_cause/user_initiated_abort_cause.h"
53#include "net/dcsctp/packet/parameter/forward_tsn_supported_parameter.h"
54#include "net/dcsctp/packet/parameter/parameter.h"
55#include "net/dcsctp/packet/parameter/state_cookie_parameter.h"
56#include "net/dcsctp/packet/parameter/supported_extensions_parameter.h"
57#include "net/dcsctp/packet/sctp_packet.h"
58#include "net/dcsctp/packet/tlv_trait.h"
59#include "net/dcsctp/public/dcsctp_message.h"
60#include "net/dcsctp/public/dcsctp_options.h"
61#include "net/dcsctp/public/dcsctp_socket.h"
62#include "net/dcsctp/public/packet_observer.h"
63#include "net/dcsctp/rx/data_tracker.h"
64#include "net/dcsctp/rx/reassembly_queue.h"
65#include "net/dcsctp/socket/callback_deferrer.h"
66#include "net/dcsctp/socket/capabilities.h"
67#include "net/dcsctp/socket/heartbeat_handler.h"
68#include "net/dcsctp/socket/state_cookie.h"
69#include "net/dcsctp/socket/stream_reset_handler.h"
70#include "net/dcsctp/socket/transmission_control_block.h"
71#include "net/dcsctp/timer/timer.h"
72#include "net/dcsctp/tx/retransmission_queue.h"
73#include "net/dcsctp/tx/send_queue.h"
74#include "rtc_base/checks.h"
75#include "rtc_base/logging.h"
76#include "rtc_base/strings/string_builder.h"
77#include "rtc_base/strings/string_format.h"
78
79namespace dcsctp {
80namespace {
81
82// https://tools.ietf.org/html/rfc4960#section-5.1
83constexpr uint32_t kMinVerificationTag = 1;
84constexpr uint32_t kMaxVerificationTag = std::numeric_limits<uint32_t>::max();
85
86// https://tools.ietf.org/html/rfc4960#section-3.3.2
87constexpr uint32_t kMinInitialTsn = 0;
88constexpr uint32_t kMaxInitialTsn = std::numeric_limits<uint32_t>::max();
89
90Capabilities GetCapabilities(const DcSctpOptions& options,
91 const Parameters& parameters) {
92 Capabilities capabilities;
93 absl::optional<SupportedExtensionsParameter> supported_extensions =
94 parameters.get<SupportedExtensionsParameter>();
95
96 if (options.enable_partial_reliability) {
97 capabilities.partial_reliability =
98 parameters.get<ForwardTsnSupportedParameter>().has_value();
99 if (supported_extensions.has_value()) {
100 capabilities.partial_reliability |=
101 supported_extensions->supports(ForwardTsnChunk::kType);
102 }
103 }
104
105 if (options.enable_message_interleaving && supported_extensions.has_value()) {
106 capabilities.message_interleaving =
107 supported_extensions->supports(IDataChunk::kType) &&
108 supported_extensions->supports(IForwardTsnChunk::kType);
109 }
110 if (supported_extensions.has_value() &&
111 supported_extensions->supports(ReConfigChunk::kType)) {
112 capabilities.reconfig = true;
113 }
114 return capabilities;
115}
116
117void AddCapabilityParameters(const DcSctpOptions& options,
118 Parameters::Builder& builder) {
119 std::vector<uint8_t> chunk_types = {ReConfigChunk::kType};
120
121 if (options.enable_partial_reliability) {
122 builder.Add(ForwardTsnSupportedParameter());
123 chunk_types.push_back(ForwardTsnChunk::kType);
124 }
125 if (options.enable_message_interleaving) {
126 chunk_types.push_back(IDataChunk::kType);
127 chunk_types.push_back(IForwardTsnChunk::kType);
128 }
129 builder.Add(SupportedExtensionsParameter(std::move(chunk_types)));
130}
131
132TieTag MakeTieTag(DcSctpSocketCallbacks& cb) {
133 uint32_t tie_tag_upper =
134 cb.GetRandomInt(0, std::numeric_limits<uint32_t>::max());
135 uint32_t tie_tag_lower =
136 cb.GetRandomInt(1, std::numeric_limits<uint32_t>::max());
137 return TieTag(static_cast<uint64_t>(tie_tag_upper) << 32 |
138 static_cast<uint64_t>(tie_tag_lower));
139}
140
141} // namespace
142
143DcSctpSocket::DcSctpSocket(absl::string_view log_prefix,
144 DcSctpSocketCallbacks& callbacks,
145 std::unique_ptr<PacketObserver> packet_observer,
146 const DcSctpOptions& options)
147 : log_prefix_(std::string(log_prefix) + ": "),
148 packet_observer_(std::move(packet_observer)),
149 options_(options),
150 callbacks_(callbacks),
151 timer_manager_([this]() { return callbacks_.CreateTimeout(); }),
152 t1_init_(timer_manager_.CreateTimer(
153 "t1-init",
154 [this]() { return OnInitTimerExpiry(); },
155 TimerOptions(options.t1_init_timeout,
156 TimerBackoffAlgorithm::kExponential,
157 options.max_init_retransmits))),
158 t1_cookie_(timer_manager_.CreateTimer(
159 "t1-cookie",
160 [this]() { return OnCookieTimerExpiry(); },
161 TimerOptions(options.t1_cookie_timeout,
162 TimerBackoffAlgorithm::kExponential,
163 options.max_init_retransmits))),
164 t2_shutdown_(timer_manager_.CreateTimer(
165 "t2-shutdown",
166 [this]() { return OnShutdownTimerExpiry(); },
167 TimerOptions(options.t2_shutdown_timeout,
168 TimerBackoffAlgorithm::kExponential,
169 options.max_retransmissions))),
Victor Boiviebd9031b2021-05-26 19:48:55 +0200170 send_queue_(
171 log_prefix_,
172 options_.max_send_buffer_size,
Victor Boivie236ac502021-05-20 19:34:18 +0200173 [this](StreamID stream_id) {
174 callbacks_.OnBufferedAmountLow(stream_id);
175 },
176 options_.total_buffered_amount_low_threshold,
177 [this]() { callbacks_.OnTotalBufferedAmountLow(); }) {}
Victor Boivieb6580cc2021-04-08 09:56:59 +0200178
179std::string DcSctpSocket::log_prefix() const {
180 return log_prefix_ + "[" + std::string(ToString(state_)) + "] ";
181}
182
183bool DcSctpSocket::IsConsistent() const {
184 switch (state_) {
185 case State::kClosed:
186 return (tcb_ == nullptr && !t1_init_->is_running() &&
187 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
188 case State::kCookieWait:
189 return (tcb_ == nullptr && t1_init_->is_running() &&
190 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
191 case State::kCookieEchoed:
192 return (tcb_ != nullptr && !t1_init_->is_running() &&
193 t1_cookie_->is_running() && !t2_shutdown_->is_running() &&
194 cookie_echo_chunk_.has_value());
195 case State::kEstablished:
196 return (tcb_ != nullptr && !t1_init_->is_running() &&
197 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
198 case State::kShutdownPending:
199 return (tcb_ != nullptr && !t1_init_->is_running() &&
200 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
201 case State::kShutdownSent:
202 return (tcb_ != nullptr && !t1_init_->is_running() &&
203 !t1_cookie_->is_running() && t2_shutdown_->is_running());
204 case State::kShutdownReceived:
205 return (tcb_ != nullptr && !t1_init_->is_running() &&
206 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
207 case State::kShutdownAckSent:
208 return (tcb_ != nullptr && !t1_init_->is_running() &&
209 !t1_cookie_->is_running() && t2_shutdown_->is_running());
210 }
211}
212
213constexpr absl::string_view DcSctpSocket::ToString(DcSctpSocket::State state) {
214 switch (state) {
215 case DcSctpSocket::State::kClosed:
216 return "CLOSED";
217 case DcSctpSocket::State::kCookieWait:
218 return "COOKIE_WAIT";
219 case DcSctpSocket::State::kCookieEchoed:
220 return "COOKIE_ECHOED";
221 case DcSctpSocket::State::kEstablished:
222 return "ESTABLISHED";
223 case DcSctpSocket::State::kShutdownPending:
224 return "SHUTDOWN_PENDING";
225 case DcSctpSocket::State::kShutdownSent:
226 return "SHUTDOWN_SENT";
227 case DcSctpSocket::State::kShutdownReceived:
228 return "SHUTDOWN_RECEIVED";
229 case DcSctpSocket::State::kShutdownAckSent:
230 return "SHUTDOWN_ACK_SENT";
231 }
232}
233
234void DcSctpSocket::SetState(State state, absl::string_view reason) {
235 if (state_ != state) {
236 RTC_DLOG(LS_VERBOSE) << log_prefix_ << "Socket state changed from "
237 << ToString(state_) << " to " << ToString(state)
238 << " due to " << reason;
239 state_ = state;
240 }
241}
242
243void DcSctpSocket::SendInit() {
244 Parameters::Builder params_builder;
245 AddCapabilityParameters(options_, params_builder);
246 InitChunk init(/*initiate_tag=*/connect_params_.verification_tag,
247 /*a_rwnd=*/options_.max_receiver_window_buffer_size,
248 options_.announced_maximum_outgoing_streams,
249 options_.announced_maximum_incoming_streams,
250 connect_params_.initial_tsn, params_builder.Build());
251 SctpPacket::Builder b(VerificationTag(0), options_);
252 b.Add(init);
253 SendPacket(b);
254}
255
256void DcSctpSocket::MakeConnectionParameters() {
257 VerificationTag new_verification_tag(
258 callbacks_.GetRandomInt(kMinVerificationTag, kMaxVerificationTag));
259 TSN initial_tsn(callbacks_.GetRandomInt(kMinInitialTsn, kMaxInitialTsn));
260 connect_params_.initial_tsn = initial_tsn;
261 connect_params_.verification_tag = new_verification_tag;
262}
263
264void DcSctpSocket::Connect() {
265 if (state_ == State::kClosed) {
266 MakeConnectionParameters();
267 RTC_DLOG(LS_INFO)
268 << log_prefix()
269 << rtc::StringFormat(
270 "Connecting. my_verification_tag=%08x, my_initial_tsn=%u",
271 *connect_params_.verification_tag, *connect_params_.initial_tsn);
272 SendInit();
273 t1_init_->Start();
274 SetState(State::kCookieWait, "Connect called");
275 } else {
276 RTC_DLOG(LS_WARNING) << log_prefix()
277 << "Called Connect on a socket that is not closed";
278 }
279 RTC_DCHECK(IsConsistent());
280 callbacks_.TriggerDeferred();
281}
282
283void DcSctpSocket::Shutdown() {
284 if (tcb_ != nullptr) {
285 // https://tools.ietf.org/html/rfc4960#section-9.2
286 // "Upon receipt of the SHUTDOWN primitive from its upper layer, the
287 // endpoint enters the SHUTDOWN-PENDING state and remains there until all
288 // outstanding data has been acknowledged by its peer."
Victor Boivie50a0b122021-05-06 21:07:49 +0200289
290 // TODO(webrtc:12739): Remove this check, as it just hides the problem that
291 // the socket can transition from ShutdownSent to ShutdownPending, or
292 // ShutdownAckSent to ShutdownPending which is illegal.
293 if (state_ != State::kShutdownSent && state_ != State::kShutdownAckSent) {
294 SetState(State::kShutdownPending, "Shutdown called");
295 t1_init_->Stop();
296 t1_cookie_->Stop();
297 MaybeSendShutdownOrAck();
298 }
Victor Boivieb6580cc2021-04-08 09:56:59 +0200299 } else {
300 // Connection closed before even starting to connect, or during the initial
301 // connection phase. There is no outstanding data, so the socket can just
302 // be closed (stopping any connection timers, if any), as this is the
303 // client's intention, by calling Shutdown.
304 InternalClose(ErrorKind::kNoError, "");
305 }
306 RTC_DCHECK(IsConsistent());
307 callbacks_.TriggerDeferred();
308}
309
310void DcSctpSocket::Close() {
311 if (state_ != State::kClosed) {
312 if (tcb_ != nullptr) {
313 SctpPacket::Builder b = tcb_->PacketBuilder();
314 b.Add(AbortChunk(/*filled_in_verification_tag=*/true,
315 Parameters::Builder()
316 .Add(UserInitiatedAbortCause("Close called"))
317 .Build()));
318 SendPacket(b);
319 }
320 InternalClose(ErrorKind::kNoError, "");
321 } else {
322 RTC_DLOG(LS_INFO) << log_prefix() << "Called Close on a closed socket";
323 }
324 RTC_DCHECK(IsConsistent());
325 callbacks_.TriggerDeferred();
326}
327
328void DcSctpSocket::CloseConnectionBecauseOfTooManyTransmissionErrors() {
329 SendPacket(tcb_->PacketBuilder().Add(AbortChunk(
330 true, Parameters::Builder()
331 .Add(UserInitiatedAbortCause("Too many retransmissions"))
332 .Build())));
333 InternalClose(ErrorKind::kTooManyRetries, "Too many retransmissions");
334}
335
336void DcSctpSocket::InternalClose(ErrorKind error, absl::string_view message) {
337 if (state_ != State::kClosed) {
338 t1_init_->Stop();
339 t1_cookie_->Stop();
340 t2_shutdown_->Stop();
341 tcb_ = nullptr;
342 cookie_echo_chunk_ = absl::nullopt;
343
344 if (error == ErrorKind::kNoError) {
345 callbacks_.OnClosed();
346 } else {
347 callbacks_.OnAborted(error, message);
348 }
349 SetState(State::kClosed, message);
350 }
351 // This method's purpose is to abort/close and make it consistent by ensuring
352 // that e.g. all timers really are stopped.
353 RTC_DCHECK(IsConsistent());
354}
355
356SendStatus DcSctpSocket::Send(DcSctpMessage message,
357 const SendOptions& send_options) {
358 if (message.payload().empty()) {
359 callbacks_.OnError(ErrorKind::kProtocolViolation,
360 "Unable to send empty message");
361 return SendStatus::kErrorMessageEmpty;
362 }
363 if (message.payload().size() > options_.max_message_size) {
364 callbacks_.OnError(ErrorKind::kProtocolViolation,
365 "Unable to send too large message");
366 return SendStatus::kErrorMessageTooLarge;
367 }
368 if (state_ == State::kShutdownPending || state_ == State::kShutdownSent ||
369 state_ == State::kShutdownReceived || state_ == State::kShutdownAckSent) {
370 // https://tools.ietf.org/html/rfc4960#section-9.2
371 // "An endpoint should reject any new data request from its upper layer
372 // if it is in the SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED, or
373 // SHUTDOWN-ACK-SENT state."
374 callbacks_.OnError(ErrorKind::kWrongSequence,
375 "Unable to send message as the socket is shutting down");
376 return SendStatus::kErrorShuttingDown;
377 }
378 if (send_queue_.IsFull()) {
379 callbacks_.OnError(ErrorKind::kResourceExhaustion,
380 "Unable to send message as the send queue is full");
381 return SendStatus::kErrorResourceExhaustion;
382 }
383
Victor Boivied3b186e2021-05-05 16:22:29 +0200384 TimeMs now = callbacks_.TimeMillis();
385 send_queue_.Add(now, std::move(message), send_options);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200386 if (tcb_ != nullptr) {
Victor Boivied3b186e2021-05-05 16:22:29 +0200387 tcb_->SendBufferedPackets(now);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200388 }
389
390 RTC_DCHECK(IsConsistent());
391 callbacks_.TriggerDeferred();
392 return SendStatus::kSuccess;
393}
394
395ResetStreamsStatus DcSctpSocket::ResetStreams(
396 rtc::ArrayView<const StreamID> outgoing_streams) {
397 if (tcb_ == nullptr) {
398 callbacks_.OnError(ErrorKind::kWrongSequence,
399 "Can't reset streams as the socket is not connected");
400 return ResetStreamsStatus::kNotConnected;
401 }
402 if (!tcb_->capabilities().reconfig) {
403 callbacks_.OnError(ErrorKind::kUnsupportedOperation,
404 "Can't reset streams as the peer doesn't support it");
405 return ResetStreamsStatus::kNotSupported;
406 }
407
408 tcb_->stream_reset_handler().ResetStreams(outgoing_streams);
409 absl::optional<ReConfigChunk> reconfig =
410 tcb_->stream_reset_handler().MakeStreamResetRequest();
411 if (reconfig.has_value()) {
412 SctpPacket::Builder builder = tcb_->PacketBuilder();
413 builder.Add(*reconfig);
414 SendPacket(builder);
415 }
416
417 RTC_DCHECK(IsConsistent());
418 callbacks_.TriggerDeferred();
419 return ResetStreamsStatus::kPerformed;
420}
421
422SocketState DcSctpSocket::state() const {
423 switch (state_) {
424 case State::kClosed:
425 return SocketState::kClosed;
426 case State::kCookieWait:
427 ABSL_FALLTHROUGH_INTENDED;
428 case State::kCookieEchoed:
429 return SocketState::kConnecting;
430 case State::kEstablished:
431 return SocketState::kConnected;
432 case State::kShutdownPending:
433 ABSL_FALLTHROUGH_INTENDED;
434 case State::kShutdownSent:
435 ABSL_FALLTHROUGH_INTENDED;
436 case State::kShutdownReceived:
437 ABSL_FALLTHROUGH_INTENDED;
438 case State::kShutdownAckSent:
439 return SocketState::kShuttingDown;
440 }
441}
442
Florent Castelli0810b052021-05-04 20:12:52 +0200443void DcSctpSocket::SetMaxMessageSize(size_t max_message_size) {
444 options_.max_message_size = max_message_size;
445}
446
Victor Boivie236ac502021-05-20 19:34:18 +0200447size_t DcSctpSocket::buffered_amount(StreamID stream_id) const {
448 return send_queue_.buffered_amount(stream_id);
449}
450
451size_t DcSctpSocket::buffered_amount_low_threshold(StreamID stream_id) const {
452 return send_queue_.buffered_amount_low_threshold(stream_id);
453}
454
455void DcSctpSocket::SetBufferedAmountLowThreshold(StreamID stream_id,
456 size_t bytes) {
457 send_queue_.SetBufferedAmountLowThreshold(stream_id, bytes);
458}
459
Victor Boivieb6580cc2021-04-08 09:56:59 +0200460void DcSctpSocket::MaybeSendShutdownOnPacketReceived(const SctpPacket& packet) {
461 if (state_ == State::kShutdownSent) {
462 bool has_data_chunk =
463 std::find_if(packet.descriptors().begin(), packet.descriptors().end(),
464 [](const SctpPacket::ChunkDescriptor& descriptor) {
465 return descriptor.type == DataChunk::kType;
466 }) != packet.descriptors().end();
467 if (has_data_chunk) {
468 // https://tools.ietf.org/html/rfc4960#section-9.2
469 // "While in the SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
470 // respond to each received packet containing one or more DATA chunks with
471 // a SHUTDOWN chunk and restart the T2-shutdown timer.""
472 SendShutdown();
473 t2_shutdown_->set_duration(tcb_->current_rto());
474 t2_shutdown_->Start();
475 }
476 }
477}
478
479bool DcSctpSocket::ValidatePacket(const SctpPacket& packet) {
480 const CommonHeader& header = packet.common_header();
481 VerificationTag my_verification_tag =
482 tcb_ != nullptr ? tcb_->my_verification_tag() : VerificationTag(0);
483
484 if (header.verification_tag == VerificationTag(0)) {
485 if (packet.descriptors().size() == 1 &&
486 packet.descriptors()[0].type == InitChunk::kType) {
487 // https://tools.ietf.org/html/rfc4960#section-8.5.1
488 // "When an endpoint receives an SCTP packet with the Verification Tag
489 // set to 0, it should verify that the packet contains only an INIT chunk.
490 // Otherwise, the receiver MUST silently discard the packet.""
491 return true;
492 }
493 callbacks_.OnError(
494 ErrorKind::kParseFailed,
495 "Only a single INIT chunk can be present in packets sent on "
496 "verification_tag = 0");
497 return false;
498 }
499
500 if (packet.descriptors().size() == 1 &&
501 packet.descriptors()[0].type == AbortChunk::kType) {
502 // https://tools.ietf.org/html/rfc4960#section-8.5.1
503 // "The receiver of an ABORT MUST accept the packet if the Verification
504 // Tag field of the packet matches its own tag and the T bit is not set OR
505 // if it is set to its peer's tag and the T bit is set in the Chunk Flags.
506 // Otherwise, the receiver MUST silently discard the packet and take no
507 // further action."
508 bool t_bit = (packet.descriptors()[0].flags & 0x01) != 0;
509 if (t_bit && tcb_ == nullptr) {
510 // Can't verify the tag - assume it's okey.
511 return true;
512 }
513 if ((!t_bit && header.verification_tag == my_verification_tag) ||
514 (t_bit && header.verification_tag == tcb_->peer_verification_tag())) {
515 return true;
516 }
517 callbacks_.OnError(ErrorKind::kParseFailed,
518 "ABORT chunk verification tag was wrong");
519 return false;
520 }
521
522 if (packet.descriptors()[0].type == InitAckChunk::kType) {
523 if (header.verification_tag == connect_params_.verification_tag) {
524 return true;
525 }
526 callbacks_.OnError(
527 ErrorKind::kParseFailed,
528 rtc::StringFormat(
529 "Packet has invalid verification tag: %08x, expected %08x",
530 *header.verification_tag, *connect_params_.verification_tag));
531 return false;
532 }
533
534 if (packet.descriptors()[0].type == CookieEchoChunk::kType) {
535 // Handled in chunk handler (due to RFC 4960, section 5.2.4).
536 return true;
537 }
538
539 if (packet.descriptors().size() == 1 &&
540 packet.descriptors()[0].type == ShutdownCompleteChunk::kType) {
541 // https://tools.ietf.org/html/rfc4960#section-8.5.1
542 // "The receiver of a SHUTDOWN COMPLETE shall accept the packet if the
543 // Verification Tag field of the packet matches its own tag and the T bit is
544 // not set OR if it is set to its peer's tag and the T bit is set in the
545 // Chunk Flags. Otherwise, the receiver MUST silently discard the packet
546 // and take no further action."
547 bool t_bit = (packet.descriptors()[0].flags & 0x01) != 0;
548 if (t_bit && tcb_ == nullptr) {
549 // Can't verify the tag - assume it's okey.
550 return true;
551 }
552 if ((!t_bit && header.verification_tag == my_verification_tag) ||
553 (t_bit && header.verification_tag == tcb_->peer_verification_tag())) {
554 return true;
555 }
556 callbacks_.OnError(ErrorKind::kParseFailed,
557 "SHUTDOWN_COMPLETE chunk verification tag was wrong");
558 return false;
559 }
560
561 // https://tools.ietf.org/html/rfc4960#section-8.5
562 // "When receiving an SCTP packet, the endpoint MUST ensure that the value
563 // in the Verification Tag field of the received SCTP packet matches its own
564 // tag. If the received Verification Tag value does not match the receiver's
565 // own tag value, the receiver shall silently discard the packet and shall not
566 // process it any further..."
567 if (header.verification_tag == my_verification_tag) {
568 return true;
569 }
570
571 callbacks_.OnError(
572 ErrorKind::kParseFailed,
573 rtc::StringFormat(
574 "Packet has invalid verification tag: %08x, expected %08x",
575 *header.verification_tag, *my_verification_tag));
576 return false;
577}
578
579void DcSctpSocket::HandleTimeout(TimeoutID timeout_id) {
580 timer_manager_.HandleTimeout(timeout_id);
581
582 if (tcb_ != nullptr && tcb_->HasTooManyTxErrors()) {
583 // Tearing down the TCB has to be done outside the handlers.
584 CloseConnectionBecauseOfTooManyTransmissionErrors();
585 }
586
587 RTC_DCHECK(IsConsistent());
588 callbacks_.TriggerDeferred();
589}
590
591void DcSctpSocket::ReceivePacket(rtc::ArrayView<const uint8_t> data) {
592 if (packet_observer_ != nullptr) {
593 packet_observer_->OnReceivedPacket(callbacks_.TimeMillis(), data);
594 }
595
596 absl::optional<SctpPacket> packet =
597 SctpPacket::Parse(data, options_.disable_checksum_verification);
598 if (!packet.has_value()) {
599 // https://tools.ietf.org/html/rfc4960#section-6.8
600 // "The default procedure for handling invalid SCTP packets is to
601 // silently discard them."
602 callbacks_.OnError(ErrorKind::kParseFailed,
603 "Failed to parse received SCTP packet");
604 RTC_DCHECK(IsConsistent());
605 callbacks_.TriggerDeferred();
606 return;
607 }
608
609 if (RTC_DLOG_IS_ON) {
610 for (const auto& descriptor : packet->descriptors()) {
611 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received "
612 << DebugConvertChunkToString(descriptor.data);
613 }
614 }
615
616 if (!ValidatePacket(*packet)) {
617 RTC_DLOG(LS_VERBOSE) << log_prefix()
618 << "Packet failed verification tag check - dropping";
619 RTC_DCHECK(IsConsistent());
620 callbacks_.TriggerDeferred();
621 return;
622 }
623
624 MaybeSendShutdownOnPacketReceived(*packet);
625
626 for (const auto& descriptor : packet->descriptors()) {
627 if (!Dispatch(packet->common_header(), descriptor)) {
628 break;
629 }
630 }
631
632 if (tcb_ != nullptr) {
633 tcb_->data_tracker().ObservePacketEnd();
634 tcb_->MaybeSendSack();
635 }
636
637 RTC_DCHECK(IsConsistent());
638 callbacks_.TriggerDeferred();
639}
640
641void DcSctpSocket::DebugPrintOutgoing(rtc::ArrayView<const uint8_t> payload) {
642 auto packet = SctpPacket::Parse(payload);
643 RTC_DCHECK(packet.has_value());
644
645 for (const auto& desc : packet->descriptors()) {
646 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Sent "
647 << DebugConvertChunkToString(desc.data);
648 }
649}
650
651bool DcSctpSocket::Dispatch(const CommonHeader& header,
652 const SctpPacket::ChunkDescriptor& descriptor) {
653 switch (descriptor.type) {
654 case DataChunk::kType:
655 HandleData(header, descriptor);
656 break;
657 case InitChunk::kType:
658 HandleInit(header, descriptor);
659 break;
660 case InitAckChunk::kType:
661 HandleInitAck(header, descriptor);
662 break;
663 case SackChunk::kType:
664 HandleSack(header, descriptor);
665 break;
666 case HeartbeatRequestChunk::kType:
667 HandleHeartbeatRequest(header, descriptor);
668 break;
669 case HeartbeatAckChunk::kType:
670 HandleHeartbeatAck(header, descriptor);
671 break;
672 case AbortChunk::kType:
673 HandleAbort(header, descriptor);
674 break;
675 case ErrorChunk::kType:
676 HandleError(header, descriptor);
677 break;
678 case CookieEchoChunk::kType:
679 HandleCookieEcho(header, descriptor);
680 break;
681 case CookieAckChunk::kType:
682 HandleCookieAck(header, descriptor);
683 break;
684 case ShutdownChunk::kType:
685 HandleShutdown(header, descriptor);
686 break;
687 case ShutdownAckChunk::kType:
688 HandleShutdownAck(header, descriptor);
689 break;
690 case ShutdownCompleteChunk::kType:
691 HandleShutdownComplete(header, descriptor);
692 break;
693 case ReConfigChunk::kType:
694 HandleReconfig(header, descriptor);
695 break;
696 case ForwardTsnChunk::kType:
697 HandleForwardTsn(header, descriptor);
698 break;
699 case IDataChunk::kType:
700 HandleIData(header, descriptor);
701 break;
702 case IForwardTsnChunk::kType:
703 HandleForwardTsn(header, descriptor);
704 break;
705 default:
706 return HandleUnrecognizedChunk(descriptor);
707 }
708 return true;
709}
710
711bool DcSctpSocket::HandleUnrecognizedChunk(
712 const SctpPacket::ChunkDescriptor& descriptor) {
713 bool report_as_error = (descriptor.type & 0x40) != 0;
714 bool continue_processing = (descriptor.type & 0x80) != 0;
715 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received unknown chunk: "
716 << static_cast<int>(descriptor.type);
717 if (report_as_error) {
718 rtc::StringBuilder sb;
719 sb << "Received unknown chunk of type: "
720 << static_cast<int>(descriptor.type) << " with report-error bit set";
721 callbacks_.OnError(ErrorKind::kParseFailed, sb.str());
722 RTC_DLOG(LS_VERBOSE)
723 << log_prefix()
724 << "Unknown chunk, with type indicating it should be reported.";
725
726 // https://tools.ietf.org/html/rfc4960#section-3.2
727 // "... report in an ERROR chunk using the 'Unrecognized Chunk Type'
728 // cause."
729 if (tcb_ != nullptr) {
730 // Need TCB - this chunk must be sent with a correct verification tag.
731 SendPacket(tcb_->PacketBuilder().Add(
732 ErrorChunk(Parameters::Builder()
733 .Add(UnrecognizedChunkTypeCause(std::vector<uint8_t>(
734 descriptor.data.begin(), descriptor.data.end())))
735 .Build())));
736 }
737 }
738 if (!continue_processing) {
739 // https://tools.ietf.org/html/rfc4960#section-3.2
740 // "Stop processing this SCTP packet and discard it, do not process any
741 // further chunks within it."
742 RTC_DLOG(LS_VERBOSE) << log_prefix()
743 << "Unknown chunk, with type indicating not to "
744 "process any further chunks";
745 }
746
747 return continue_processing;
748}
749
750absl::optional<DurationMs> DcSctpSocket::OnInitTimerExpiry() {
751 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t1_init_->name()
752 << " has expired: " << t1_init_->expiration_count()
753 << "/" << t1_init_->options().max_restarts;
754 RTC_DCHECK(state_ == State::kCookieWait);
755
756 if (t1_init_->is_running()) {
757 SendInit();
758 } else {
759 InternalClose(ErrorKind::kTooManyRetries, "No INIT_ACK received");
760 }
761 RTC_DCHECK(IsConsistent());
762 return absl::nullopt;
763}
764
765absl::optional<DurationMs> DcSctpSocket::OnCookieTimerExpiry() {
766 // https://tools.ietf.org/html/rfc4960#section-4
767 // "If the T1-cookie timer expires, the endpoint MUST retransmit COOKIE
768 // ECHO and restart the T1-cookie timer without changing state. This MUST
769 // be repeated up to 'Max.Init.Retransmits' times. After that, the endpoint
770 // MUST abort the initialization process and report the error to the SCTP
771 // user."
772 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t1_cookie_->name()
773 << " has expired: " << t1_cookie_->expiration_count()
774 << "/" << t1_cookie_->options().max_restarts;
775
776 RTC_DCHECK(state_ == State::kCookieEchoed);
777
778 if (t1_cookie_->is_running()) {
779 SendCookieEcho();
780 } else {
781 InternalClose(ErrorKind::kTooManyRetries, "No COOKIE_ACK received");
782 }
783
784 RTC_DCHECK(IsConsistent());
785 return absl::nullopt;
786}
787
788absl::optional<DurationMs> DcSctpSocket::OnShutdownTimerExpiry() {
789 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t2_shutdown_->name()
790 << " has expired: " << t2_shutdown_->expiration_count()
791 << "/" << t2_shutdown_->options().max_restarts;
792
Victor Boivie914925f2021-05-07 11:22:50 +0200793 if (!t2_shutdown_->is_running()) {
Victor Boivieb6580cc2021-04-08 09:56:59 +0200794 // https://tools.ietf.org/html/rfc4960#section-9.2
795 // "An endpoint should limit the number of retransmissions of the SHUTDOWN
796 // chunk to the protocol parameter 'Association.Max.Retrans'. If this
797 // threshold is exceeded, the endpoint should destroy the TCB..."
798
799 SendPacket(tcb_->PacketBuilder().Add(
800 AbortChunk(true, Parameters::Builder()
801 .Add(UserInitiatedAbortCause(
802 "Too many retransmissions of SHUTDOWN"))
803 .Build())));
804
805 InternalClose(ErrorKind::kTooManyRetries, "No SHUTDOWN_ACK received");
Victor Boivie914925f2021-05-07 11:22:50 +0200806 RTC_DCHECK(IsConsistent());
807 return absl::nullopt;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200808 }
Victor Boivie914925f2021-05-07 11:22:50 +0200809
810 // https://tools.ietf.org/html/rfc4960#section-9.2
811 // "If the timer expires, the endpoint must resend the SHUTDOWN with the
812 // updated last sequential TSN received from its peer."
813 SendShutdown();
Victor Boivieb6580cc2021-04-08 09:56:59 +0200814 RTC_DCHECK(IsConsistent());
815 return tcb_->current_rto();
816}
817
818void DcSctpSocket::SendPacket(SctpPacket::Builder& builder) {
819 if (builder.empty()) {
820 return;
821 }
822
823 std::vector<uint8_t> payload = builder.Build();
824
825 if (RTC_DLOG_IS_ON) {
826 DebugPrintOutgoing(payload);
827 }
828
829 // The heartbeat interval timer is restarted for every sent packet, to
830 // fire when the outgoing channel is inactive.
831 if (tcb_ != nullptr) {
832 tcb_->heartbeat_handler().RestartTimer();
833 }
834
835 if (packet_observer_ != nullptr) {
836 packet_observer_->OnSentPacket(callbacks_.TimeMillis(), payload);
837 }
838 callbacks_.SendPacket(payload);
839}
840
841bool DcSctpSocket::ValidateHasTCB() {
842 if (tcb_ != nullptr) {
843 return true;
844 }
845
846 callbacks_.OnError(
847 ErrorKind::kNotConnected,
848 "Received unexpected commands on socket that is not connected");
849 return false;
850}
851
852void DcSctpSocket::ReportFailedToParseChunk(int chunk_type) {
853 rtc::StringBuilder sb;
854 sb << "Failed to parse chunk of type: " << chunk_type;
855 callbacks_.OnError(ErrorKind::kParseFailed, sb.str());
856}
857
858void DcSctpSocket::HandleData(const CommonHeader& header,
859 const SctpPacket::ChunkDescriptor& descriptor) {
860 absl::optional<DataChunk> chunk = DataChunk::Parse(descriptor.data);
861 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
862 HandleDataCommon(*chunk);
863 }
864}
865
866void DcSctpSocket::HandleIData(const CommonHeader& header,
867 const SctpPacket::ChunkDescriptor& descriptor) {
868 absl::optional<IDataChunk> chunk = IDataChunk::Parse(descriptor.data);
869 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
870 HandleDataCommon(*chunk);
871 }
872}
873
874void DcSctpSocket::HandleDataCommon(AnyDataChunk& chunk) {
875 TSN tsn = chunk.tsn();
876 AnyDataChunk::ImmediateAckFlag immediate_ack = chunk.options().immediate_ack;
877 Data data = std::move(chunk).extract();
878
879 if (data.payload.empty()) {
880 // Empty DATA chunks are illegal.
881 SendPacket(tcb_->PacketBuilder().Add(
882 ErrorChunk(Parameters::Builder().Add(NoUserDataCause(tsn)).Build())));
883 callbacks_.OnError(ErrorKind::kProtocolViolation,
884 "Received DATA chunk with no user data");
885 return;
886 }
887
888 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Handle DATA, queue_size="
889 << tcb_->reassembly_queue().queued_bytes()
890 << ", water_mark="
891 << tcb_->reassembly_queue().watermark_bytes()
892 << ", full=" << tcb_->reassembly_queue().is_full()
893 << ", above="
894 << tcb_->reassembly_queue().is_above_watermark();
895
896 if (tcb_->reassembly_queue().is_full()) {
897 // If the reassembly queue is full, there is nothing that can be done. The
898 // specification only allows dropping gap-ack-blocks, and that's not
899 // likely to help as the socket has been trying to fill gaps since the
900 // watermark was reached.
901 SendPacket(tcb_->PacketBuilder().Add(AbortChunk(
902 true, Parameters::Builder().Add(OutOfResourceErrorCause()).Build())));
903 InternalClose(ErrorKind::kResourceExhaustion,
904 "Reassembly Queue is exhausted");
905 return;
906 }
907
908 if (tcb_->reassembly_queue().is_above_watermark()) {
909 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Is above high watermark";
910 // If the reassembly queue is above its high watermark, only accept data
911 // chunks that increase its cumulative ack tsn in an attempt to fill gaps
912 // to deliver messages.
913 if (!tcb_->data_tracker().will_increase_cum_ack_tsn(tsn)) {
914 RTC_DLOG(LS_VERBOSE) << log_prefix()
915 << "Rejected data because of exceeding watermark";
916 tcb_->data_tracker().ForceImmediateSack();
917 return;
918 }
919 }
920
921 if (!tcb_->data_tracker().IsTSNValid(tsn)) {
922 RTC_DLOG(LS_VERBOSE) << log_prefix()
923 << "Rejected data because of failing TSN validity";
924 return;
925 }
926
927 tcb_->data_tracker().Observe(tsn, immediate_ack);
928 tcb_->reassembly_queue().MaybeResetStreamsDeferred(
929 tcb_->data_tracker().last_cumulative_acked_tsn());
930 tcb_->reassembly_queue().Add(tsn, std::move(data));
931 DeliverReassembledMessages();
932}
933
934void DcSctpSocket::HandleInit(const CommonHeader& header,
935 const SctpPacket::ChunkDescriptor& descriptor) {
936 absl::optional<InitChunk> chunk = InitChunk::Parse(descriptor.data);
937 if (!ValidateParseSuccess(chunk)) {
938 return;
939 }
940
941 if (chunk->initiate_tag() == VerificationTag(0) ||
942 chunk->nbr_outbound_streams() == 0 || chunk->nbr_inbound_streams() == 0) {
943 // https://tools.ietf.org/html/rfc4960#section-3.3.2
944 // "If the value of the Initiate Tag in a received INIT chunk is found
945 // to be 0, the receiver MUST treat it as an error and close the
946 // association by transmitting an ABORT."
947
948 // "A receiver of an INIT with the OS value set to 0 SHOULD abort the
949 // association."
950
951 // "A receiver of an INIT with the MIS value of 0 SHOULD abort the
952 // association."
953
954 SendPacket(SctpPacket::Builder(VerificationTag(0), options_)
955 .Add(AbortChunk(
956 /*filled_in_verification_tag=*/false,
957 Parameters::Builder()
958 .Add(ProtocolViolationCause("INIT malformed"))
959 .Build())));
960 InternalClose(ErrorKind::kProtocolViolation, "Received invalid INIT");
961 return;
962 }
963
964 if (state_ == State::kShutdownAckSent) {
965 // https://tools.ietf.org/html/rfc4960#section-9.2
966 // "If an endpoint is in the SHUTDOWN-ACK-SENT state and receives an
967 // INIT chunk (e.g., if the SHUTDOWN COMPLETE was lost) with source and
968 // destination transport addresses (either in the IP addresses or in the
969 // INIT chunk) that belong to this association, it should discard the INIT
970 // chunk and retransmit the SHUTDOWN ACK chunk."
971 RTC_DLOG(LS_VERBOSE) << log_prefix()
972 << "Received Init indicating lost ShutdownComplete";
973 SendShutdownAck();
974 return;
975 }
976
977 TieTag tie_tag(0);
978 if (state_ == State::kClosed) {
979 RTC_DLOG(LS_VERBOSE) << log_prefix()
980 << "Received Init in closed state (normal)";
981
982 MakeConnectionParameters();
983 } else if (state_ == State::kCookieWait || state_ == State::kCookieEchoed) {
984 // https://tools.ietf.org/html/rfc4960#section-5.2.1
985 // "This usually indicates an initialization collision, i.e., each
986 // endpoint is attempting, at about the same time, to establish an
987 // association with the other endpoint. Upon receipt of an INIT in the
988 // COOKIE-WAIT state, an endpoint MUST respond with an INIT ACK using the
989 // same parameters it sent in its original INIT chunk (including its
990 // Initiate Tag, unchanged). When responding, the endpoint MUST send the
991 // INIT ACK back to the same address that the original INIT (sent by this
992 // endpoint) was sent."
993 RTC_DLOG(LS_VERBOSE) << log_prefix()
994 << "Received Init indicating simultaneous connections";
995 } else {
996 RTC_DCHECK(tcb_ != nullptr);
997 // https://tools.ietf.org/html/rfc4960#section-5.2.2
998 // "The outbound SCTP packet containing this INIT ACK MUST carry a
999 // Verification Tag value equal to the Initiate Tag found in the
1000 // unexpected INIT. And the INIT ACK MUST contain a new Initiate Tag
1001 // (randomly generated; see Section 5.3.1). Other parameters for the
1002 // endpoint SHOULD be copied from the existing parameters of the
1003 // association (e.g., number of outbound streams) into the INIT ACK and
1004 // cookie."
1005 RTC_DLOG(LS_VERBOSE) << log_prefix()
1006 << "Received Init indicating restarted connection";
1007 // Create a new verification tag - different from the previous one.
1008 for (int tries = 0; tries < 10; ++tries) {
1009 connect_params_.verification_tag = VerificationTag(
1010 callbacks_.GetRandomInt(kMinVerificationTag, kMaxVerificationTag));
1011 if (connect_params_.verification_tag != tcb_->my_verification_tag()) {
1012 break;
1013 }
1014 }
1015
1016 // Make the initial TSN make a large jump, so that there is no overlap
1017 // with the old and new association.
1018 connect_params_.initial_tsn =
1019 TSN(*tcb_->retransmission_queue().next_tsn() + 1000000);
1020 tie_tag = tcb_->tie_tag();
1021 }
1022
1023 RTC_DLOG(LS_VERBOSE)
1024 << log_prefix()
1025 << rtc::StringFormat(
1026 "Proceeding with connection. my_verification_tag=%08x, "
1027 "my_initial_tsn=%u, peer_verification_tag=%08x, "
1028 "peer_initial_tsn=%u",
1029 *connect_params_.verification_tag, *connect_params_.initial_tsn,
1030 *chunk->initiate_tag(), *chunk->initial_tsn());
1031
1032 Capabilities capabilities = GetCapabilities(options_, chunk->parameters());
1033
1034 SctpPacket::Builder b(chunk->initiate_tag(), options_);
1035 Parameters::Builder params_builder =
1036 Parameters::Builder().Add(StateCookieParameter(
1037 StateCookie(chunk->initiate_tag(), chunk->initial_tsn(),
1038 chunk->a_rwnd(), tie_tag, capabilities)
1039 .Serialize()));
1040 AddCapabilityParameters(options_, params_builder);
1041
1042 InitAckChunk init_ack(/*initiate_tag=*/connect_params_.verification_tag,
1043 options_.max_receiver_window_buffer_size,
1044 options_.announced_maximum_outgoing_streams,
1045 options_.announced_maximum_incoming_streams,
1046 connect_params_.initial_tsn, params_builder.Build());
1047 b.Add(init_ack);
1048 SendPacket(b);
1049}
1050
1051void DcSctpSocket::SendCookieEcho() {
1052 RTC_DCHECK(tcb_ != nullptr);
Victor Boivied3b186e2021-05-05 16:22:29 +02001053 TimeMs now = callbacks_.TimeMillis();
Victor Boivieb6580cc2021-04-08 09:56:59 +02001054 SctpPacket::Builder b = tcb_->PacketBuilder();
1055 b.Add(*cookie_echo_chunk_);
1056
1057 // https://tools.ietf.org/html/rfc4960#section-5.1
1058 // "The COOKIE ECHO chunk can be bundled with any pending outbound DATA
1059 // chunks, but it MUST be the first chunk in the packet and until the COOKIE
1060 // ACK is returned the sender MUST NOT send any other packets to the peer."
Victor Boivied3b186e2021-05-05 16:22:29 +02001061 tcb_->SendBufferedPackets(b, now, /*only_one_packet=*/true);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001062}
1063
1064void DcSctpSocket::HandleInitAck(
1065 const CommonHeader& header,
1066 const SctpPacket::ChunkDescriptor& descriptor) {
1067 absl::optional<InitAckChunk> chunk = InitAckChunk::Parse(descriptor.data);
1068 if (!ValidateParseSuccess(chunk)) {
1069 return;
1070 }
1071
1072 if (state_ != State::kCookieWait) {
1073 // https://tools.ietf.org/html/rfc4960#section-5.2.3
1074 // "If an INIT ACK is received by an endpoint in any state other than
1075 // the COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk."
1076 RTC_DLOG(LS_VERBOSE) << log_prefix()
1077 << "Received INIT_ACK in unexpected state";
1078 return;
1079 }
1080
1081 auto cookie = chunk->parameters().get<StateCookieParameter>();
1082 if (!cookie.has_value()) {
1083 SendPacket(SctpPacket::Builder(connect_params_.verification_tag, options_)
1084 .Add(AbortChunk(
1085 /*filled_in_verification_tag=*/false,
1086 Parameters::Builder()
1087 .Add(ProtocolViolationCause("INIT-ACK malformed"))
1088 .Build())));
1089 InternalClose(ErrorKind::kProtocolViolation,
1090 "InitAck chunk doesn't contain a cookie");
1091 return;
1092 }
1093 Capabilities capabilities = GetCapabilities(options_, chunk->parameters());
1094 t1_init_->Stop();
1095
1096 tcb_ = std::make_unique<TransmissionControlBlock>(
1097 timer_manager_, log_prefix_, options_, capabilities, callbacks_,
1098 send_queue_, connect_params_.verification_tag,
1099 connect_params_.initial_tsn, chunk->initiate_tag(), chunk->initial_tsn(),
1100 chunk->a_rwnd(), MakeTieTag(callbacks_),
1101 [this]() { return state_ == State::kEstablished; },
1102 [this](SctpPacket::Builder& builder) { return SendPacket(builder); });
1103 RTC_DLOG(LS_VERBOSE) << log_prefix()
1104 << "Created peer TCB: " << tcb_->ToString();
1105
1106 SetState(State::kCookieEchoed, "INIT_ACK received");
1107
1108 // The connection isn't fully established just yet.
1109 cookie_echo_chunk_ = CookieEchoChunk(cookie->data());
1110 SendCookieEcho();
1111 t1_cookie_->Start();
1112}
1113
1114void DcSctpSocket::HandleCookieEcho(
1115 const CommonHeader& header,
1116 const SctpPacket::ChunkDescriptor& descriptor) {
1117 absl::optional<CookieEchoChunk> chunk =
1118 CookieEchoChunk::Parse(descriptor.data);
1119 if (!ValidateParseSuccess(chunk)) {
1120 return;
1121 }
1122
1123 absl::optional<StateCookie> cookie =
1124 StateCookie::Deserialize(chunk->cookie());
1125 if (!cookie.has_value()) {
1126 callbacks_.OnError(ErrorKind::kParseFailed, "Failed to parse state cookie");
1127 return;
1128 }
1129
1130 if (tcb_ != nullptr) {
1131 if (!HandleCookieEchoWithTCB(header, *cookie)) {
1132 return;
1133 }
1134 } else {
1135 if (header.verification_tag != connect_params_.verification_tag) {
1136 callbacks_.OnError(
1137 ErrorKind::kParseFailed,
1138 rtc::StringFormat(
1139 "Received CookieEcho with invalid verification tag: %08x, "
1140 "expected %08x",
1141 *header.verification_tag, *connect_params_.verification_tag));
1142 return;
1143 }
1144 }
1145
1146 // The init timer can be running on simultaneous connections.
1147 t1_init_->Stop();
1148 t1_cookie_->Stop();
1149 if (state_ != State::kEstablished) {
1150 cookie_echo_chunk_ = absl::nullopt;
1151 SetState(State::kEstablished, "COOKIE_ECHO received");
1152 callbacks_.OnConnected();
1153 }
1154
1155 if (tcb_ == nullptr) {
1156 tcb_ = std::make_unique<TransmissionControlBlock>(
1157 timer_manager_, log_prefix_, options_, cookie->capabilities(),
1158 callbacks_, send_queue_, connect_params_.verification_tag,
1159 connect_params_.initial_tsn, cookie->initiate_tag(),
1160 cookie->initial_tsn(), cookie->a_rwnd(), MakeTieTag(callbacks_),
1161 [this]() { return state_ == State::kEstablished; },
1162 [this](SctpPacket::Builder& builder) { return SendPacket(builder); });
1163 RTC_DLOG(LS_VERBOSE) << log_prefix()
1164 << "Created peer TCB: " << tcb_->ToString();
1165 }
1166
1167 SctpPacket::Builder b = tcb_->PacketBuilder();
1168 b.Add(CookieAckChunk());
1169
1170 // https://tools.ietf.org/html/rfc4960#section-5.1
1171 // "A COOKIE ACK chunk may be bundled with any pending DATA chunks (and/or
1172 // SACK chunks), but the COOKIE ACK chunk MUST be the first chunk in the
1173 // packet."
Victor Boivied3b186e2021-05-05 16:22:29 +02001174 tcb_->SendBufferedPackets(b, callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +02001175}
1176
1177bool DcSctpSocket::HandleCookieEchoWithTCB(const CommonHeader& header,
1178 const StateCookie& cookie) {
1179 RTC_DLOG(LS_VERBOSE) << log_prefix()
1180 << "Handling CookieEchoChunk with TCB. local_tag="
1181 << *tcb_->my_verification_tag()
1182 << ", peer_tag=" << *header.verification_tag
1183 << ", tcb_tag=" << *tcb_->peer_verification_tag()
1184 << ", cookie_tag=" << *cookie.initiate_tag()
1185 << ", local_tie_tag=" << *tcb_->tie_tag()
1186 << ", peer_tie_tag=" << *cookie.tie_tag();
1187 // https://tools.ietf.org/html/rfc4960#section-5.2.4
1188 // "Handle a COOKIE ECHO when a TCB Exists"
1189 if (header.verification_tag != tcb_->my_verification_tag() &&
1190 tcb_->peer_verification_tag() != cookie.initiate_tag() &&
1191 cookie.tie_tag() == tcb_->tie_tag()) {
1192 // "A) In this case, the peer may have restarted."
1193 if (state_ == State::kShutdownAckSent) {
1194 // "If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
1195 // that the peer has restarted ... it MUST NOT set up a new association
1196 // but instead resend the SHUTDOWN ACK and send an ERROR chunk with a
1197 // "Cookie Received While Shutting Down" error cause to its peer."
1198 SctpPacket::Builder b(cookie.initiate_tag(), options_);
1199 b.Add(ShutdownAckChunk());
1200 b.Add(ErrorChunk(Parameters::Builder()
1201 .Add(CookieReceivedWhileShuttingDownCause())
1202 .Build()));
1203 SendPacket(b);
1204 callbacks_.OnError(ErrorKind::kWrongSequence,
1205 "Received COOKIE-ECHO while shutting down");
1206 return false;
1207 }
1208
1209 RTC_DLOG(LS_VERBOSE) << log_prefix()
1210 << "Received COOKIE-ECHO indicating a restarted peer";
1211
1212 // If a message was partly sent, and the peer restarted, resend it in
1213 // full by resetting the send queue.
1214 send_queue_.Reset();
1215 tcb_ = nullptr;
1216 callbacks_.OnConnectionRestarted();
1217 } else if (header.verification_tag == tcb_->my_verification_tag() &&
1218 tcb_->peer_verification_tag() != cookie.initiate_tag()) {
1219 // TODO(boivie): Handle the peer_tag == 0?
1220 // "B) In this case, both sides may be attempting to start an
1221 // association at about the same time, but the peer endpoint started its
1222 // INIT after responding to the local endpoint's INIT."
1223 RTC_DLOG(LS_VERBOSE)
1224 << log_prefix()
1225 << "Received COOKIE-ECHO indicating simultaneous connections";
1226 tcb_ = nullptr;
1227 } else if (header.verification_tag != tcb_->my_verification_tag() &&
1228 tcb_->peer_verification_tag() == cookie.initiate_tag() &&
1229 cookie.tie_tag() == TieTag(0)) {
1230 // "C) In this case, the local endpoint's cookie has arrived late.
1231 // Before it arrived, the local endpoint sent an INIT and received an
1232 // INIT ACK and finally sent a COOKIE ECHO with the peer's same tag but
1233 // a new tag of its own. The cookie should be silently discarded. The
1234 // endpoint SHOULD NOT change states and should leave any timers
1235 // running."
1236 RTC_DLOG(LS_VERBOSE)
1237 << log_prefix()
1238 << "Received COOKIE-ECHO indicating a late COOKIE-ECHO. Discarding";
1239 return false;
1240 } else if (header.verification_tag == tcb_->my_verification_tag() &&
1241 tcb_->peer_verification_tag() == cookie.initiate_tag()) {
1242 // "D) When both local and remote tags match, the endpoint should enter
1243 // the ESTABLISHED state, if it is in the COOKIE-ECHOED state. It
1244 // should stop any cookie timer that may be running and send a COOKIE
1245 // ACK."
1246 RTC_DLOG(LS_VERBOSE)
1247 << log_prefix()
1248 << "Received duplicate COOKIE-ECHO, probably because of peer not "
1249 "receiving COOKIE-ACK and retransmitting COOKIE-ECHO. Continuing.";
1250 }
1251 return true;
1252}
1253
1254void DcSctpSocket::HandleCookieAck(
1255 const CommonHeader& header,
1256 const SctpPacket::ChunkDescriptor& descriptor) {
1257 absl::optional<CookieAckChunk> chunk = CookieAckChunk::Parse(descriptor.data);
1258 if (!ValidateParseSuccess(chunk)) {
1259 return;
1260 }
1261
1262 if (state_ != State::kCookieEchoed) {
1263 // https://tools.ietf.org/html/rfc4960#section-5.2.5
1264 // "At any state other than COOKIE-ECHOED, an endpoint should silently
1265 // discard a received COOKIE ACK chunk."
1266 RTC_DLOG(LS_VERBOSE) << log_prefix()
1267 << "Received COOKIE_ACK not in COOKIE_ECHOED state";
1268 return;
1269 }
1270
1271 // RFC 4960, Errata ID: 4400
1272 t1_cookie_->Stop();
1273 cookie_echo_chunk_ = absl::nullopt;
1274 SetState(State::kEstablished, "COOKIE_ACK received");
Victor Boivied3b186e2021-05-05 16:22:29 +02001275 tcb_->SendBufferedPackets(callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +02001276 callbacks_.OnConnected();
1277}
1278
1279void DcSctpSocket::DeliverReassembledMessages() {
1280 if (tcb_->reassembly_queue().HasMessages()) {
1281 for (auto& message : tcb_->reassembly_queue().FlushMessages()) {
1282 callbacks_.OnMessageReceived(std::move(message));
1283 }
1284 }
1285}
1286
1287void DcSctpSocket::HandleSack(const CommonHeader& header,
1288 const SctpPacket::ChunkDescriptor& descriptor) {
1289 absl::optional<SackChunk> chunk = SackChunk::Parse(descriptor.data);
1290
1291 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
Victor Boivied3b186e2021-05-05 16:22:29 +02001292 TimeMs now = callbacks_.TimeMillis();
Victor Boivieb6580cc2021-04-08 09:56:59 +02001293 SackChunk sack = ChunkValidators::Clean(*std::move(chunk));
1294
Victor Boivied3b186e2021-05-05 16:22:29 +02001295 if (tcb_->retransmission_queue().HandleSack(now, sack)) {
Victor Boivieb6580cc2021-04-08 09:56:59 +02001296 MaybeSendShutdownOrAck();
1297 // Receiving an ACK will decrease outstanding bytes (maybe now below
1298 // cwnd?) or indicate packet loss that may result in sending FORWARD-TSN.
Victor Boivied3b186e2021-05-05 16:22:29 +02001299 tcb_->SendBufferedPackets(now);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001300 } else {
1301 RTC_DLOG(LS_VERBOSE) << log_prefix()
1302 << "Dropping out-of-order SACK with TSN "
1303 << *sack.cumulative_tsn_ack();
1304 }
1305 }
1306}
1307
1308void DcSctpSocket::HandleHeartbeatRequest(
1309 const CommonHeader& header,
1310 const SctpPacket::ChunkDescriptor& descriptor) {
1311 absl::optional<HeartbeatRequestChunk> chunk =
1312 HeartbeatRequestChunk::Parse(descriptor.data);
1313
1314 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1315 tcb_->heartbeat_handler().HandleHeartbeatRequest(*std::move(chunk));
1316 }
1317}
1318
1319void DcSctpSocket::HandleHeartbeatAck(
1320 const CommonHeader& header,
1321 const SctpPacket::ChunkDescriptor& descriptor) {
1322 absl::optional<HeartbeatAckChunk> chunk =
1323 HeartbeatAckChunk::Parse(descriptor.data);
1324
1325 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1326 tcb_->heartbeat_handler().HandleHeartbeatAck(*std::move(chunk));
1327 }
1328}
1329
1330void DcSctpSocket::HandleAbort(const CommonHeader& header,
1331 const SctpPacket::ChunkDescriptor& descriptor) {
1332 absl::optional<AbortChunk> chunk = AbortChunk::Parse(descriptor.data);
1333 if (ValidateParseSuccess(chunk)) {
1334 std::string error_string = ErrorCausesToString(chunk->error_causes());
1335 if (tcb_ == nullptr) {
1336 // https://tools.ietf.org/html/rfc4960#section-3.3.7
1337 // "If an endpoint receives an ABORT with a format error or no TCB is
1338 // found, it MUST silently discard it."
1339 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received ABORT (" << error_string
1340 << ") on a connection with no TCB. Ignoring";
1341 return;
1342 }
1343
1344 RTC_DLOG(LS_WARNING) << log_prefix() << "Received ABORT (" << error_string
1345 << ") - closing connection.";
1346 InternalClose(ErrorKind::kPeerReported, error_string);
1347 }
1348}
1349
1350void DcSctpSocket::HandleError(const CommonHeader& header,
1351 const SctpPacket::ChunkDescriptor& descriptor) {
1352 absl::optional<ErrorChunk> chunk = ErrorChunk::Parse(descriptor.data);
1353 if (ValidateParseSuccess(chunk)) {
1354 std::string error_string = ErrorCausesToString(chunk->error_causes());
1355 if (tcb_ == nullptr) {
1356 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received ERROR (" << error_string
1357 << ") on a connection with no TCB. Ignoring";
1358 return;
1359 }
1360
1361 RTC_DLOG(LS_WARNING) << log_prefix() << "Received ERROR: " << error_string;
1362 callbacks_.OnError(ErrorKind::kPeerReported,
1363 "Peer reported error: " + error_string);
1364 }
1365}
1366
1367void DcSctpSocket::HandleReconfig(
1368 const CommonHeader& header,
1369 const SctpPacket::ChunkDescriptor& descriptor) {
1370 absl::optional<ReConfigChunk> chunk = ReConfigChunk::Parse(descriptor.data);
1371 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1372 tcb_->stream_reset_handler().HandleReConfig(*std::move(chunk));
1373 }
1374}
1375
1376void DcSctpSocket::HandleShutdown(
1377 const CommonHeader& header,
1378 const SctpPacket::ChunkDescriptor& descriptor) {
1379 if (!ValidateParseSuccess(ShutdownChunk::Parse(descriptor.data))) {
1380 return;
1381 }
1382
1383 if (state_ == State::kClosed) {
1384 return;
1385 } else if (state_ == State::kCookieWait || state_ == State::kCookieEchoed) {
1386 // https://tools.ietf.org/html/rfc4960#section-9.2
1387 // "If a SHUTDOWN is received in the COOKIE-WAIT or COOKIE ECHOED state,
1388 // the SHUTDOWN chunk SHOULD be silently discarded."
1389 } else if (state_ == State::kShutdownSent) {
1390 // https://tools.ietf.org/html/rfc4960#section-9.2
1391 // "If an endpoint is in the SHUTDOWN-SENT state and receives a
1392 // SHUTDOWN chunk from its peer, the endpoint shall respond immediately
1393 // with a SHUTDOWN ACK to its peer, and move into the SHUTDOWN-ACK-SENT
1394 // state restarting its T2-shutdown timer."
1395 SendShutdownAck();
1396 SetState(State::kShutdownAckSent, "SHUTDOWN received");
Victor Boivie50a0b122021-05-06 21:07:49 +02001397 } else if (state_ == State::kShutdownAckSent) {
1398 // TODO(webrtc:12739): This condition should be removed and handled by the
1399 // next (state_ != State::kShutdownReceived).
1400 return;
Victor Boivieb6580cc2021-04-08 09:56:59 +02001401 } else if (state_ != State::kShutdownReceived) {
1402 RTC_DLOG(LS_VERBOSE) << log_prefix()
1403 << "Received SHUTDOWN - shutting down the socket";
1404 // https://tools.ietf.org/html/rfc4960#section-9.2
1405 // "Upon reception of the SHUTDOWN, the peer endpoint shall enter the
1406 // SHUTDOWN-RECEIVED state, stop accepting new data from its SCTP user,
1407 // and verify, by checking the Cumulative TSN Ack field of the chunk, that
1408 // all its outstanding DATA chunks have been received by the SHUTDOWN
1409 // sender."
1410 SetState(State::kShutdownReceived, "SHUTDOWN received");
1411 MaybeSendShutdownOrAck();
1412 }
1413}
1414
1415void DcSctpSocket::HandleShutdownAck(
1416 const CommonHeader& header,
1417 const SctpPacket::ChunkDescriptor& descriptor) {
1418 if (!ValidateParseSuccess(ShutdownAckChunk::Parse(descriptor.data))) {
1419 return;
1420 }
1421
1422 if (state_ == State::kShutdownSent || state_ == State::kShutdownAckSent) {
1423 // https://tools.ietf.org/html/rfc4960#section-9.2
1424 // "Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall stop
1425 // the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its peer, and
1426 // remove all record of the association."
1427
1428 // "If an endpoint is in the SHUTDOWN-ACK-SENT state and receives a
1429 // SHUTDOWN ACK, it shall stop the T2-shutdown timer, send a SHUTDOWN
1430 // COMPLETE chunk to its peer, and remove all record of the association."
1431
1432 SctpPacket::Builder b = tcb_->PacketBuilder();
1433 b.Add(ShutdownCompleteChunk(/*tag_reflected=*/false));
1434 SendPacket(b);
1435 InternalClose(ErrorKind::kNoError, "");
1436 } else {
1437 // https://tools.ietf.org/html/rfc4960#section-8.5.1
1438 // "If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state
1439 // the procedures in Section 8.4 SHOULD be followed; in other words, it
1440 // should be treated as an Out Of The Blue packet."
1441
1442 // https://tools.ietf.org/html/rfc4960#section-8.4
1443 // "If the packet contains a SHUTDOWN ACK chunk, the receiver
1444 // should respond to the sender of the OOTB packet with a SHUTDOWN
1445 // COMPLETE. When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
1446 // packet must fill in the Verification Tag field of the outbound packet
1447 // with the Verification Tag received in the SHUTDOWN ACK and set the T
1448 // bit in the Chunk Flags to indicate that the Verification Tag is
1449 // reflected."
1450
1451 SctpPacket::Builder b(header.verification_tag, options_);
1452 b.Add(ShutdownCompleteChunk(/*tag_reflected=*/true));
1453 SendPacket(b);
1454 }
1455}
1456
1457void DcSctpSocket::HandleShutdownComplete(
1458 const CommonHeader& header,
1459 const SctpPacket::ChunkDescriptor& descriptor) {
1460 if (!ValidateParseSuccess(ShutdownCompleteChunk::Parse(descriptor.data))) {
1461 return;
1462 }
1463
1464 if (state_ == State::kShutdownAckSent) {
1465 // https://tools.ietf.org/html/rfc4960#section-9.2
1466 // "Upon reception of the SHUTDOWN COMPLETE chunk, the endpoint will
1467 // verify that it is in the SHUTDOWN-ACK-SENT state; if it is not, the
1468 // chunk should be discarded. If the endpoint is in the SHUTDOWN-ACK-SENT
1469 // state, the endpoint should stop the T2-shutdown timer and remove all
1470 // knowledge of the association (and thus the association enters the
1471 // CLOSED state)."
1472 InternalClose(ErrorKind::kNoError, "");
1473 }
1474}
1475
1476void DcSctpSocket::HandleForwardTsn(
1477 const CommonHeader& header,
1478 const SctpPacket::ChunkDescriptor& descriptor) {
1479 absl::optional<ForwardTsnChunk> chunk =
1480 ForwardTsnChunk::Parse(descriptor.data);
1481 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1482 HandleForwardTsnCommon(*chunk);
1483 }
1484}
1485
1486void DcSctpSocket::HandleIForwardTsn(
1487 const CommonHeader& header,
1488 const SctpPacket::ChunkDescriptor& descriptor) {
1489 absl::optional<IForwardTsnChunk> chunk =
1490 IForwardTsnChunk::Parse(descriptor.data);
1491 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1492 HandleForwardTsnCommon(*chunk);
1493 }
1494}
1495
1496void DcSctpSocket::HandleForwardTsnCommon(const AnyForwardTsnChunk& chunk) {
1497 if (!tcb_->capabilities().partial_reliability) {
1498 SctpPacket::Builder b = tcb_->PacketBuilder();
1499 b.Add(AbortChunk(/*filled_in_verification_tag=*/true,
1500 Parameters::Builder()
1501 .Add(ProtocolViolationCause(
1502 "I-FORWARD-TSN received, but not indicated "
1503 "during connection establishment"))
1504 .Build()));
1505 SendPacket(b);
1506
1507 callbacks_.OnError(ErrorKind::kProtocolViolation,
1508 "Received a FORWARD_TSN without announced peer support");
1509 return;
1510 }
1511 tcb_->data_tracker().HandleForwardTsn(chunk.new_cumulative_tsn());
1512 tcb_->reassembly_queue().Handle(chunk);
1513 // A forward TSN - for ordered streams - may allow messages to be
1514 // delivered.
1515 DeliverReassembledMessages();
1516
1517 // Processing a FORWARD_TSN might result in sending a SACK.
1518 tcb_->MaybeSendSack();
1519}
1520
1521void DcSctpSocket::MaybeSendShutdownOrAck() {
1522 if (tcb_->retransmission_queue().outstanding_bytes() != 0) {
1523 return;
1524 }
1525
1526 if (state_ == State::kShutdownPending) {
1527 // https://tools.ietf.org/html/rfc4960#section-9.2
1528 // "Once all its outstanding data has been acknowledged, the endpoint
1529 // shall send a SHUTDOWN chunk to its peer including in the Cumulative TSN
1530 // Ack field the last sequential TSN it has received from the peer. It
1531 // shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT
1532 // state.""
1533
1534 SendShutdown();
1535 t2_shutdown_->set_duration(tcb_->current_rto());
1536 t2_shutdown_->Start();
1537 SetState(State::kShutdownSent, "No more outstanding data");
1538 } else if (state_ == State::kShutdownReceived) {
1539 // https://tools.ietf.org/html/rfc4960#section-9.2
1540 // "If the receiver of the SHUTDOWN has no more outstanding DATA
1541 // chunks, the SHUTDOWN receiver MUST send a SHUTDOWN ACK and start a
1542 // T2-shutdown timer of its own, entering the SHUTDOWN-ACK-SENT state. If
1543 // the timer expires, the endpoint must resend the SHUTDOWN ACK."
1544
1545 SendShutdownAck();
1546 SetState(State::kShutdownAckSent, "No more outstanding data");
1547 }
1548}
1549
1550void DcSctpSocket::SendShutdown() {
1551 SctpPacket::Builder b = tcb_->PacketBuilder();
1552 b.Add(ShutdownChunk(tcb_->data_tracker().last_cumulative_acked_tsn()));
1553 SendPacket(b);
1554}
1555
1556void DcSctpSocket::SendShutdownAck() {
1557 SendPacket(tcb_->PacketBuilder().Add(ShutdownAckChunk()));
1558 t2_shutdown_->set_duration(tcb_->current_rto());
1559 t2_shutdown_->Start();
1560}
1561
1562} // namespace dcsctp