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