blob: 815391094122cbcc0b5e232bdfaaba92ba1d0011 [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
Victor Boivie600bb8c2021-08-12 15:43:13 +020020#include "absl/functional/bind_front.h"
Victor Boivieb6580cc2021-04-08 09:56:59 +020021#include "absl/memory/memory.h"
22#include "absl/strings/string_view.h"
23#include "absl/types/optional.h"
24#include "api/array_view.h"
25#include "net/dcsctp/packet/chunk/abort_chunk.h"
26#include "net/dcsctp/packet/chunk/chunk.h"
27#include "net/dcsctp/packet/chunk/cookie_ack_chunk.h"
28#include "net/dcsctp/packet/chunk/cookie_echo_chunk.h"
29#include "net/dcsctp/packet/chunk/data_chunk.h"
30#include "net/dcsctp/packet/chunk/data_common.h"
31#include "net/dcsctp/packet/chunk/error_chunk.h"
32#include "net/dcsctp/packet/chunk/forward_tsn_chunk.h"
33#include "net/dcsctp/packet/chunk/forward_tsn_common.h"
34#include "net/dcsctp/packet/chunk/heartbeat_ack_chunk.h"
35#include "net/dcsctp/packet/chunk/heartbeat_request_chunk.h"
36#include "net/dcsctp/packet/chunk/idata_chunk.h"
37#include "net/dcsctp/packet/chunk/iforward_tsn_chunk.h"
38#include "net/dcsctp/packet/chunk/init_ack_chunk.h"
39#include "net/dcsctp/packet/chunk/init_chunk.h"
40#include "net/dcsctp/packet/chunk/reconfig_chunk.h"
41#include "net/dcsctp/packet/chunk/sack_chunk.h"
42#include "net/dcsctp/packet/chunk/shutdown_ack_chunk.h"
43#include "net/dcsctp/packet/chunk/shutdown_chunk.h"
44#include "net/dcsctp/packet/chunk/shutdown_complete_chunk.h"
45#include "net/dcsctp/packet/chunk_validators.h"
46#include "net/dcsctp/packet/data.h"
47#include "net/dcsctp/packet/error_cause/cookie_received_while_shutting_down_cause.h"
48#include "net/dcsctp/packet/error_cause/error_cause.h"
49#include "net/dcsctp/packet/error_cause/no_user_data_cause.h"
50#include "net/dcsctp/packet/error_cause/out_of_resource_error_cause.h"
51#include "net/dcsctp/packet/error_cause/protocol_violation_cause.h"
52#include "net/dcsctp/packet/error_cause/unrecognized_chunk_type_cause.h"
53#include "net/dcsctp/packet/error_cause/user_initiated_abort_cause.h"
54#include "net/dcsctp/packet/parameter/forward_tsn_supported_parameter.h"
55#include "net/dcsctp/packet/parameter/parameter.h"
56#include "net/dcsctp/packet/parameter/state_cookie_parameter.h"
57#include "net/dcsctp/packet/parameter/supported_extensions_parameter.h"
58#include "net/dcsctp/packet/sctp_packet.h"
59#include "net/dcsctp/packet/tlv_trait.h"
60#include "net/dcsctp/public/dcsctp_message.h"
61#include "net/dcsctp/public/dcsctp_options.h"
62#include "net/dcsctp/public/dcsctp_socket.h"
63#include "net/dcsctp/public/packet_observer.h"
64#include "net/dcsctp/rx/data_tracker.h"
65#include "net/dcsctp/rx/reassembly_queue.h"
66#include "net/dcsctp/socket/callback_deferrer.h"
67#include "net/dcsctp/socket/capabilities.h"
68#include "net/dcsctp/socket/heartbeat_handler.h"
69#include "net/dcsctp/socket/state_cookie.h"
70#include "net/dcsctp/socket/stream_reset_handler.h"
71#include "net/dcsctp/socket/transmission_control_block.h"
72#include "net/dcsctp/timer/timer.h"
73#include "net/dcsctp/tx/retransmission_queue.h"
74#include "net/dcsctp/tx/send_queue.h"
75#include "rtc_base/checks.h"
76#include "rtc_base/logging.h"
77#include "rtc_base/strings/string_builder.h"
78#include "rtc_base/strings/string_format.h"
79
80namespace dcsctp {
81namespace {
82
83// https://tools.ietf.org/html/rfc4960#section-5.1
84constexpr uint32_t kMinVerificationTag = 1;
85constexpr uint32_t kMaxVerificationTag = std::numeric_limits<uint32_t>::max();
86
87// https://tools.ietf.org/html/rfc4960#section-3.3.2
88constexpr uint32_t kMinInitialTsn = 0;
89constexpr uint32_t kMaxInitialTsn = std::numeric_limits<uint32_t>::max();
90
91Capabilities GetCapabilities(const DcSctpOptions& options,
92 const Parameters& parameters) {
93 Capabilities capabilities;
94 absl::optional<SupportedExtensionsParameter> supported_extensions =
95 parameters.get<SupportedExtensionsParameter>();
96
97 if (options.enable_partial_reliability) {
98 capabilities.partial_reliability =
99 parameters.get<ForwardTsnSupportedParameter>().has_value();
100 if (supported_extensions.has_value()) {
101 capabilities.partial_reliability |=
102 supported_extensions->supports(ForwardTsnChunk::kType);
103 }
104 }
105
106 if (options.enable_message_interleaving && supported_extensions.has_value()) {
107 capabilities.message_interleaving =
108 supported_extensions->supports(IDataChunk::kType) &&
109 supported_extensions->supports(IForwardTsnChunk::kType);
110 }
111 if (supported_extensions.has_value() &&
112 supported_extensions->supports(ReConfigChunk::kType)) {
113 capabilities.reconfig = true;
114 }
115 return capabilities;
116}
117
118void AddCapabilityParameters(const DcSctpOptions& options,
119 Parameters::Builder& builder) {
120 std::vector<uint8_t> chunk_types = {ReConfigChunk::kType};
121
122 if (options.enable_partial_reliability) {
123 builder.Add(ForwardTsnSupportedParameter());
124 chunk_types.push_back(ForwardTsnChunk::kType);
125 }
126 if (options.enable_message_interleaving) {
127 chunk_types.push_back(IDataChunk::kType);
128 chunk_types.push_back(IForwardTsnChunk::kType);
129 }
130 builder.Add(SupportedExtensionsParameter(std::move(chunk_types)));
131}
132
133TieTag MakeTieTag(DcSctpSocketCallbacks& cb) {
134 uint32_t tie_tag_upper =
135 cb.GetRandomInt(0, std::numeric_limits<uint32_t>::max());
136 uint32_t tie_tag_lower =
137 cb.GetRandomInt(1, std::numeric_limits<uint32_t>::max());
138 return TieTag(static_cast<uint64_t>(tie_tag_upper) << 32 |
139 static_cast<uint64_t>(tie_tag_lower));
140}
Victor Boivief4fa1662021-09-24 23:01:21 +0200141
142SctpImplementation DeterminePeerImplementation(
143 rtc::ArrayView<const uint8_t> cookie) {
144 if (cookie.size() > 8) {
145 absl::string_view magic(reinterpret_cast<const char*>(cookie.data()), 8);
146 if (magic == "dcSCTP00") {
147 return SctpImplementation::kDcsctp;
148 }
149 if (magic == "KAME-BSD") {
150 return SctpImplementation::kUsrSctp;
151 }
152 }
153 return SctpImplementation::kOther;
154}
Victor Boivieb6580cc2021-04-08 09:56:59 +0200155} // namespace
156
157DcSctpSocket::DcSctpSocket(absl::string_view log_prefix,
158 DcSctpSocketCallbacks& callbacks,
159 std::unique_ptr<PacketObserver> packet_observer,
160 const DcSctpOptions& options)
161 : log_prefix_(std::string(log_prefix) + ": "),
162 packet_observer_(std::move(packet_observer)),
163 options_(options),
164 callbacks_(callbacks),
165 timer_manager_([this]() { return callbacks_.CreateTimeout(); }),
166 t1_init_(timer_manager_.CreateTimer(
167 "t1-init",
Victor Boivie600bb8c2021-08-12 15:43:13 +0200168 absl::bind_front(&DcSctpSocket::OnInitTimerExpiry, this),
Victor Boivieb6580cc2021-04-08 09:56:59 +0200169 TimerOptions(options.t1_init_timeout,
170 TimerBackoffAlgorithm::kExponential,
171 options.max_init_retransmits))),
172 t1_cookie_(timer_manager_.CreateTimer(
173 "t1-cookie",
Victor Boivie600bb8c2021-08-12 15:43:13 +0200174 absl::bind_front(&DcSctpSocket::OnCookieTimerExpiry, this),
Victor Boivieb6580cc2021-04-08 09:56:59 +0200175 TimerOptions(options.t1_cookie_timeout,
176 TimerBackoffAlgorithm::kExponential,
177 options.max_init_retransmits))),
178 t2_shutdown_(timer_manager_.CreateTimer(
179 "t2-shutdown",
Victor Boivie600bb8c2021-08-12 15:43:13 +0200180 absl::bind_front(&DcSctpSocket::OnShutdownTimerExpiry, this),
Victor Boivieb6580cc2021-04-08 09:56:59 +0200181 TimerOptions(options.t2_shutdown_timeout,
182 TimerBackoffAlgorithm::kExponential,
183 options.max_retransmissions))),
Victor Boivieabf61882021-08-12 15:57:49 +0200184 packet_sender_(callbacks_,
185 absl::bind_front(&DcSctpSocket::OnSentPacket, this)),
Victor Boiviebd9031b2021-05-26 19:48:55 +0200186 send_queue_(
187 log_prefix_,
188 options_.max_send_buffer_size,
Victor Boivie236ac502021-05-20 19:34:18 +0200189 [this](StreamID stream_id) {
190 callbacks_.OnBufferedAmountLow(stream_id);
191 },
192 options_.total_buffered_amount_low_threshold,
193 [this]() { callbacks_.OnTotalBufferedAmountLow(); }) {}
Victor Boivieb6580cc2021-04-08 09:56:59 +0200194
195std::string DcSctpSocket::log_prefix() const {
196 return log_prefix_ + "[" + std::string(ToString(state_)) + "] ";
197}
198
199bool DcSctpSocket::IsConsistent() const {
Victor Boivie54e4e352021-09-15 10:42:26 +0200200 if (tcb_ != nullptr && tcb_->reassembly_queue().HasMessages()) {
201 return false;
202 }
Victor Boivieb6580cc2021-04-08 09:56:59 +0200203 switch (state_) {
204 case State::kClosed:
205 return (tcb_ == nullptr && !t1_init_->is_running() &&
206 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
207 case State::kCookieWait:
208 return (tcb_ == nullptr && t1_init_->is_running() &&
209 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
210 case State::kCookieEchoed:
211 return (tcb_ != nullptr && !t1_init_->is_running() &&
212 t1_cookie_->is_running() && !t2_shutdown_->is_running() &&
Victor Boiviec20f1562021-06-16 12:52:42 +0200213 tcb_->has_cookie_echo_chunk());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200214 case State::kEstablished:
215 return (tcb_ != nullptr && !t1_init_->is_running() &&
216 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
217 case State::kShutdownPending:
218 return (tcb_ != nullptr && !t1_init_->is_running() &&
219 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
220 case State::kShutdownSent:
221 return (tcb_ != nullptr && !t1_init_->is_running() &&
222 !t1_cookie_->is_running() && t2_shutdown_->is_running());
223 case State::kShutdownReceived:
224 return (tcb_ != nullptr && !t1_init_->is_running() &&
225 !t1_cookie_->is_running() && !t2_shutdown_->is_running());
226 case State::kShutdownAckSent:
227 return (tcb_ != nullptr && !t1_init_->is_running() &&
228 !t1_cookie_->is_running() && t2_shutdown_->is_running());
229 }
230}
231
232constexpr absl::string_view DcSctpSocket::ToString(DcSctpSocket::State state) {
233 switch (state) {
234 case DcSctpSocket::State::kClosed:
235 return "CLOSED";
236 case DcSctpSocket::State::kCookieWait:
237 return "COOKIE_WAIT";
238 case DcSctpSocket::State::kCookieEchoed:
239 return "COOKIE_ECHOED";
240 case DcSctpSocket::State::kEstablished:
241 return "ESTABLISHED";
242 case DcSctpSocket::State::kShutdownPending:
243 return "SHUTDOWN_PENDING";
244 case DcSctpSocket::State::kShutdownSent:
245 return "SHUTDOWN_SENT";
246 case DcSctpSocket::State::kShutdownReceived:
247 return "SHUTDOWN_RECEIVED";
248 case DcSctpSocket::State::kShutdownAckSent:
249 return "SHUTDOWN_ACK_SENT";
250 }
251}
252
253void DcSctpSocket::SetState(State state, absl::string_view reason) {
254 if (state_ != state) {
255 RTC_DLOG(LS_VERBOSE) << log_prefix_ << "Socket state changed from "
256 << ToString(state_) << " to " << ToString(state)
257 << " due to " << reason;
258 state_ = state;
259 }
260}
261
262void DcSctpSocket::SendInit() {
263 Parameters::Builder params_builder;
264 AddCapabilityParameters(options_, params_builder);
265 InitChunk init(/*initiate_tag=*/connect_params_.verification_tag,
266 /*a_rwnd=*/options_.max_receiver_window_buffer_size,
267 options_.announced_maximum_outgoing_streams,
268 options_.announced_maximum_incoming_streams,
269 connect_params_.initial_tsn, params_builder.Build());
270 SctpPacket::Builder b(VerificationTag(0), options_);
271 b.Add(init);
Victor Boivieabf61882021-08-12 15:57:49 +0200272 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200273}
274
275void DcSctpSocket::MakeConnectionParameters() {
276 VerificationTag new_verification_tag(
277 callbacks_.GetRandomInt(kMinVerificationTag, kMaxVerificationTag));
278 TSN initial_tsn(callbacks_.GetRandomInt(kMinInitialTsn, kMaxInitialTsn));
279 connect_params_.initial_tsn = initial_tsn;
280 connect_params_.verification_tag = new_verification_tag;
281}
282
283void DcSctpSocket::Connect() {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200284 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +0200285 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
286
Victor Boivieb6580cc2021-04-08 09:56:59 +0200287 if (state_ == State::kClosed) {
288 MakeConnectionParameters();
289 RTC_DLOG(LS_INFO)
290 << log_prefix()
291 << rtc::StringFormat(
292 "Connecting. my_verification_tag=%08x, my_initial_tsn=%u",
293 *connect_params_.verification_tag, *connect_params_.initial_tsn);
294 SendInit();
295 t1_init_->Start();
296 SetState(State::kCookieWait, "Connect called");
297 } else {
298 RTC_DLOG(LS_WARNING) << log_prefix()
299 << "Called Connect on a socket that is not closed";
300 }
301 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200302}
303
Sergey Sukhanov43972812021-09-17 15:32:48 +0200304void DcSctpSocket::RestoreFromState(const DcSctpSocketHandoverState& state) {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200305 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +0200306 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
307
Sergey Sukhanov43972812021-09-17 15:32:48 +0200308 if (state_ != State::kClosed) {
309 callbacks_.OnError(ErrorKind::kUnsupportedOperation,
310 "Only closed socket can be restored from state");
311 } else {
312 if (state.socket_state ==
313 DcSctpSocketHandoverState::SocketState::kConnected) {
314 VerificationTag my_verification_tag =
315 VerificationTag(state.my_verification_tag);
316 connect_params_.verification_tag = my_verification_tag;
317
318 Capabilities capabilities;
319 capabilities.partial_reliability = state.capabilities.partial_reliability;
320 capabilities.message_interleaving =
321 state.capabilities.message_interleaving;
322 capabilities.reconfig = state.capabilities.reconfig;
323
Sergey Sukhanov72435322021-09-21 13:31:09 +0200324 send_queue_.RestoreFromState(state);
325
Sergey Sukhanov43972812021-09-17 15:32:48 +0200326 tcb_ = std::make_unique<TransmissionControlBlock>(
327 timer_manager_, log_prefix_, options_, capabilities, callbacks_,
328 send_queue_, my_verification_tag, TSN(state.my_initial_tsn),
329 VerificationTag(state.peer_verification_tag),
330 TSN(state.peer_initial_tsn), static_cast<size_t>(0),
331 TieTag(state.tie_tag), packet_sender_,
332 [this]() { return state_ == State::kEstablished; }, &state);
333 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Created peer TCB from state: "
334 << tcb_->ToString();
335
336 SetState(State::kEstablished, "restored from handover state");
337 callbacks_.OnConnected();
338 }
339 }
340
341 RTC_DCHECK(IsConsistent());
Sergey Sukhanov43972812021-09-17 15:32:48 +0200342}
343
Victor Boivieb6580cc2021-04-08 09:56:59 +0200344void DcSctpSocket::Shutdown() {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200345 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +0200346 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
347
Victor Boivieb6580cc2021-04-08 09:56:59 +0200348 if (tcb_ != nullptr) {
349 // https://tools.ietf.org/html/rfc4960#section-9.2
350 // "Upon receipt of the SHUTDOWN primitive from its upper layer, the
351 // endpoint enters the SHUTDOWN-PENDING state and remains there until all
352 // outstanding data has been acknowledged by its peer."
Victor Boivie50a0b122021-05-06 21:07:49 +0200353
354 // TODO(webrtc:12739): Remove this check, as it just hides the problem that
355 // the socket can transition from ShutdownSent to ShutdownPending, or
356 // ShutdownAckSent to ShutdownPending which is illegal.
357 if (state_ != State::kShutdownSent && state_ != State::kShutdownAckSent) {
358 SetState(State::kShutdownPending, "Shutdown called");
359 t1_init_->Stop();
360 t1_cookie_->Stop();
361 MaybeSendShutdownOrAck();
362 }
Victor Boivieb6580cc2021-04-08 09:56:59 +0200363 } else {
364 // Connection closed before even starting to connect, or during the initial
365 // connection phase. There is no outstanding data, so the socket can just
366 // be closed (stopping any connection timers, if any), as this is the
367 // client's intention, by calling Shutdown.
368 InternalClose(ErrorKind::kNoError, "");
369 }
370 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200371}
372
373void DcSctpSocket::Close() {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200374 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +0200375 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
376
Victor Boivieb6580cc2021-04-08 09:56:59 +0200377 if (state_ != State::kClosed) {
378 if (tcb_ != nullptr) {
379 SctpPacket::Builder b = tcb_->PacketBuilder();
380 b.Add(AbortChunk(/*filled_in_verification_tag=*/true,
381 Parameters::Builder()
382 .Add(UserInitiatedAbortCause("Close called"))
383 .Build()));
Victor Boivieabf61882021-08-12 15:57:49 +0200384 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200385 }
386 InternalClose(ErrorKind::kNoError, "");
387 } else {
388 RTC_DLOG(LS_INFO) << log_prefix() << "Called Close on a closed socket";
389 }
390 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200391}
392
393void DcSctpSocket::CloseConnectionBecauseOfTooManyTransmissionErrors() {
Victor Boivieabf61882021-08-12 15:57:49 +0200394 packet_sender_.Send(tcb_->PacketBuilder().Add(AbortChunk(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200395 true, Parameters::Builder()
396 .Add(UserInitiatedAbortCause("Too many retransmissions"))
397 .Build())));
398 InternalClose(ErrorKind::kTooManyRetries, "Too many retransmissions");
399}
400
401void DcSctpSocket::InternalClose(ErrorKind error, absl::string_view message) {
402 if (state_ != State::kClosed) {
403 t1_init_->Stop();
404 t1_cookie_->Stop();
405 t2_shutdown_->Stop();
406 tcb_ = nullptr;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200407
408 if (error == ErrorKind::kNoError) {
409 callbacks_.OnClosed();
410 } else {
411 callbacks_.OnAborted(error, message);
412 }
413 SetState(State::kClosed, message);
414 }
415 // This method's purpose is to abort/close and make it consistent by ensuring
416 // that e.g. all timers really are stopped.
417 RTC_DCHECK(IsConsistent());
418}
419
420SendStatus DcSctpSocket::Send(DcSctpMessage message,
421 const SendOptions& send_options) {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200422 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +0200423 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
424
Victor Boivieb6580cc2021-04-08 09:56:59 +0200425 if (message.payload().empty()) {
426 callbacks_.OnError(ErrorKind::kProtocolViolation,
427 "Unable to send empty message");
428 return SendStatus::kErrorMessageEmpty;
429 }
430 if (message.payload().size() > options_.max_message_size) {
431 callbacks_.OnError(ErrorKind::kProtocolViolation,
432 "Unable to send too large message");
433 return SendStatus::kErrorMessageTooLarge;
434 }
435 if (state_ == State::kShutdownPending || state_ == State::kShutdownSent ||
436 state_ == State::kShutdownReceived || state_ == State::kShutdownAckSent) {
437 // https://tools.ietf.org/html/rfc4960#section-9.2
438 // "An endpoint should reject any new data request from its upper layer
439 // if it is in the SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED, or
440 // SHUTDOWN-ACK-SENT state."
441 callbacks_.OnError(ErrorKind::kWrongSequence,
442 "Unable to send message as the socket is shutting down");
443 return SendStatus::kErrorShuttingDown;
444 }
445 if (send_queue_.IsFull()) {
446 callbacks_.OnError(ErrorKind::kResourceExhaustion,
447 "Unable to send message as the send queue is full");
448 return SendStatus::kErrorResourceExhaustion;
449 }
450
Victor Boivied3b186e2021-05-05 16:22:29 +0200451 TimeMs now = callbacks_.TimeMillis();
Victor Boivied4716ea2021-08-09 12:26:32 +0200452 ++metrics_.tx_messages_count;
Victor Boivied3b186e2021-05-05 16:22:29 +0200453 send_queue_.Add(now, std::move(message), send_options);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200454 if (tcb_ != nullptr) {
Victor Boivied3b186e2021-05-05 16:22:29 +0200455 tcb_->SendBufferedPackets(now);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200456 }
457
458 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200459 return SendStatus::kSuccess;
460}
461
462ResetStreamsStatus DcSctpSocket::ResetStreams(
463 rtc::ArrayView<const StreamID> outgoing_streams) {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200464 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +0200465 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
466
Victor Boivieb6580cc2021-04-08 09:56:59 +0200467 if (tcb_ == nullptr) {
468 callbacks_.OnError(ErrorKind::kWrongSequence,
469 "Can't reset streams as the socket is not connected");
470 return ResetStreamsStatus::kNotConnected;
471 }
472 if (!tcb_->capabilities().reconfig) {
473 callbacks_.OnError(ErrorKind::kUnsupportedOperation,
474 "Can't reset streams as the peer doesn't support it");
475 return ResetStreamsStatus::kNotSupported;
476 }
477
478 tcb_->stream_reset_handler().ResetStreams(outgoing_streams);
479 absl::optional<ReConfigChunk> reconfig =
480 tcb_->stream_reset_handler().MakeStreamResetRequest();
481 if (reconfig.has_value()) {
482 SctpPacket::Builder builder = tcb_->PacketBuilder();
483 builder.Add(*reconfig);
Victor Boivieabf61882021-08-12 15:57:49 +0200484 packet_sender_.Send(builder);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200485 }
486
487 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200488 return ResetStreamsStatus::kPerformed;
489}
490
491SocketState DcSctpSocket::state() const {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200492 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200493 switch (state_) {
494 case State::kClosed:
495 return SocketState::kClosed;
496 case State::kCookieWait:
497 ABSL_FALLTHROUGH_INTENDED;
498 case State::kCookieEchoed:
499 return SocketState::kConnecting;
500 case State::kEstablished:
501 return SocketState::kConnected;
502 case State::kShutdownPending:
503 ABSL_FALLTHROUGH_INTENDED;
504 case State::kShutdownSent:
505 ABSL_FALLTHROUGH_INTENDED;
506 case State::kShutdownReceived:
507 ABSL_FALLTHROUGH_INTENDED;
508 case State::kShutdownAckSent:
509 return SocketState::kShuttingDown;
510 }
511}
512
Florent Castelli0810b052021-05-04 20:12:52 +0200513void DcSctpSocket::SetMaxMessageSize(size_t max_message_size) {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200514 RTC_DCHECK_RUN_ON(&thread_checker_);
Florent Castelli0810b052021-05-04 20:12:52 +0200515 options_.max_message_size = max_message_size;
516}
517
Victor Boivie236ac502021-05-20 19:34:18 +0200518size_t DcSctpSocket::buffered_amount(StreamID stream_id) const {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200519 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie236ac502021-05-20 19:34:18 +0200520 return send_queue_.buffered_amount(stream_id);
521}
522
523size_t DcSctpSocket::buffered_amount_low_threshold(StreamID stream_id) const {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200524 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie236ac502021-05-20 19:34:18 +0200525 return send_queue_.buffered_amount_low_threshold(stream_id);
526}
527
528void DcSctpSocket::SetBufferedAmountLowThreshold(StreamID stream_id,
529 size_t bytes) {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200530 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie236ac502021-05-20 19:34:18 +0200531 send_queue_.SetBufferedAmountLowThreshold(stream_id, bytes);
532}
533
Victor Boivied4716ea2021-08-09 12:26:32 +0200534Metrics DcSctpSocket::GetMetrics() const {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200535 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivied4716ea2021-08-09 12:26:32 +0200536 Metrics metrics = metrics_;
537
538 if (tcb_ != nullptr) {
539 // Update the metrics with some stats that are extracted from
540 // sub-components.
541 metrics.cwnd_bytes = tcb_->cwnd();
542 metrics.srtt_ms = tcb_->current_srtt().value();
543 size_t packet_payload_size =
544 options_.mtu - SctpPacket::kHeaderSize - DataChunk::kHeaderSize;
545 metrics.unack_data_count =
546 tcb_->retransmission_queue().outstanding_items() +
547 (send_queue_.total_buffered_amount() + packet_payload_size - 1) /
548 packet_payload_size;
549 metrics.peer_rwnd_bytes = tcb_->retransmission_queue().rwnd();
550 }
551
552 return metrics;
553}
554
Victor Boivieb6580cc2021-04-08 09:56:59 +0200555void DcSctpSocket::MaybeSendShutdownOnPacketReceived(const SctpPacket& packet) {
556 if (state_ == State::kShutdownSent) {
557 bool has_data_chunk =
558 std::find_if(packet.descriptors().begin(), packet.descriptors().end(),
559 [](const SctpPacket::ChunkDescriptor& descriptor) {
560 return descriptor.type == DataChunk::kType;
561 }) != packet.descriptors().end();
562 if (has_data_chunk) {
563 // https://tools.ietf.org/html/rfc4960#section-9.2
564 // "While in the SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
565 // respond to each received packet containing one or more DATA chunks with
566 // a SHUTDOWN chunk and restart the T2-shutdown timer.""
567 SendShutdown();
568 t2_shutdown_->set_duration(tcb_->current_rto());
569 t2_shutdown_->Start();
570 }
571 }
572}
573
574bool DcSctpSocket::ValidatePacket(const SctpPacket& packet) {
575 const CommonHeader& header = packet.common_header();
576 VerificationTag my_verification_tag =
577 tcb_ != nullptr ? tcb_->my_verification_tag() : VerificationTag(0);
578
579 if (header.verification_tag == VerificationTag(0)) {
580 if (packet.descriptors().size() == 1 &&
581 packet.descriptors()[0].type == InitChunk::kType) {
582 // https://tools.ietf.org/html/rfc4960#section-8.5.1
583 // "When an endpoint receives an SCTP packet with the Verification Tag
584 // set to 0, it should verify that the packet contains only an INIT chunk.
585 // Otherwise, the receiver MUST silently discard the packet.""
586 return true;
587 }
588 callbacks_.OnError(
589 ErrorKind::kParseFailed,
590 "Only a single INIT chunk can be present in packets sent on "
591 "verification_tag = 0");
592 return false;
593 }
594
595 if (packet.descriptors().size() == 1 &&
596 packet.descriptors()[0].type == AbortChunk::kType) {
597 // https://tools.ietf.org/html/rfc4960#section-8.5.1
598 // "The receiver of an ABORT MUST accept the packet if the Verification
599 // Tag field of the packet matches its own tag and the T bit is not set OR
600 // if it is set to its peer's tag and the T bit is set in the Chunk Flags.
601 // Otherwise, the receiver MUST silently discard the packet and take no
602 // further action."
603 bool t_bit = (packet.descriptors()[0].flags & 0x01) != 0;
604 if (t_bit && tcb_ == nullptr) {
605 // Can't verify the tag - assume it's okey.
606 return true;
607 }
608 if ((!t_bit && header.verification_tag == my_verification_tag) ||
609 (t_bit && header.verification_tag == tcb_->peer_verification_tag())) {
610 return true;
611 }
612 callbacks_.OnError(ErrorKind::kParseFailed,
613 "ABORT chunk verification tag was wrong");
614 return false;
615 }
616
617 if (packet.descriptors()[0].type == InitAckChunk::kType) {
618 if (header.verification_tag == connect_params_.verification_tag) {
619 return true;
620 }
621 callbacks_.OnError(
622 ErrorKind::kParseFailed,
623 rtc::StringFormat(
624 "Packet has invalid verification tag: %08x, expected %08x",
625 *header.verification_tag, *connect_params_.verification_tag));
626 return false;
627 }
628
629 if (packet.descriptors()[0].type == CookieEchoChunk::kType) {
630 // Handled in chunk handler (due to RFC 4960, section 5.2.4).
631 return true;
632 }
633
634 if (packet.descriptors().size() == 1 &&
635 packet.descriptors()[0].type == ShutdownCompleteChunk::kType) {
636 // https://tools.ietf.org/html/rfc4960#section-8.5.1
637 // "The receiver of a SHUTDOWN COMPLETE shall accept the packet if the
638 // Verification Tag field of the packet matches its own tag and the T bit is
639 // not set OR if it is set to its peer's tag and the T bit is set in the
640 // Chunk Flags. Otherwise, the receiver MUST silently discard the packet
641 // and take no further action."
642 bool t_bit = (packet.descriptors()[0].flags & 0x01) != 0;
643 if (t_bit && tcb_ == nullptr) {
644 // Can't verify the tag - assume it's okey.
645 return true;
646 }
647 if ((!t_bit && header.verification_tag == my_verification_tag) ||
648 (t_bit && header.verification_tag == tcb_->peer_verification_tag())) {
649 return true;
650 }
651 callbacks_.OnError(ErrorKind::kParseFailed,
652 "SHUTDOWN_COMPLETE chunk verification tag was wrong");
653 return false;
654 }
655
656 // https://tools.ietf.org/html/rfc4960#section-8.5
657 // "When receiving an SCTP packet, the endpoint MUST ensure that the value
658 // in the Verification Tag field of the received SCTP packet matches its own
659 // tag. If the received Verification Tag value does not match the receiver's
660 // own tag value, the receiver shall silently discard the packet and shall not
661 // process it any further..."
662 if (header.verification_tag == my_verification_tag) {
663 return true;
664 }
665
666 callbacks_.OnError(
667 ErrorKind::kParseFailed,
668 rtc::StringFormat(
669 "Packet has invalid verification tag: %08x, expected %08x",
670 *header.verification_tag, *my_verification_tag));
671 return false;
672}
673
674void DcSctpSocket::HandleTimeout(TimeoutID timeout_id) {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200675 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +0200676 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
677
Victor Boivieb6580cc2021-04-08 09:56:59 +0200678 timer_manager_.HandleTimeout(timeout_id);
679
680 if (tcb_ != nullptr && tcb_->HasTooManyTxErrors()) {
681 // Tearing down the TCB has to be done outside the handlers.
682 CloseConnectionBecauseOfTooManyTransmissionErrors();
683 }
684
685 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200686}
687
688void DcSctpSocket::ReceivePacket(rtc::ArrayView<const uint8_t> data) {
Victor Boivie5755f3e2021-09-29 22:23:15 +0200689 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +0200690 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
691
Victor Boivied4716ea2021-08-09 12:26:32 +0200692 ++metrics_.rx_packets_count;
693
Victor Boivieb6580cc2021-04-08 09:56:59 +0200694 if (packet_observer_ != nullptr) {
695 packet_observer_->OnReceivedPacket(callbacks_.TimeMillis(), data);
696 }
697
698 absl::optional<SctpPacket> packet =
699 SctpPacket::Parse(data, options_.disable_checksum_verification);
700 if (!packet.has_value()) {
701 // https://tools.ietf.org/html/rfc4960#section-6.8
702 // "The default procedure for handling invalid SCTP packets is to
703 // silently discard them."
704 callbacks_.OnError(ErrorKind::kParseFailed,
705 "Failed to parse received SCTP packet");
706 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200707 return;
708 }
709
710 if (RTC_DLOG_IS_ON) {
711 for (const auto& descriptor : packet->descriptors()) {
712 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received "
713 << DebugConvertChunkToString(descriptor.data);
714 }
715 }
716
717 if (!ValidatePacket(*packet)) {
718 RTC_DLOG(LS_VERBOSE) << log_prefix()
719 << "Packet failed verification tag check - dropping";
720 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200721 return;
722 }
723
724 MaybeSendShutdownOnPacketReceived(*packet);
725
726 for (const auto& descriptor : packet->descriptors()) {
727 if (!Dispatch(packet->common_header(), descriptor)) {
728 break;
729 }
730 }
731
732 if (tcb_ != nullptr) {
733 tcb_->data_tracker().ObservePacketEnd();
734 tcb_->MaybeSendSack();
735 }
736
737 RTC_DCHECK(IsConsistent());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200738}
739
740void DcSctpSocket::DebugPrintOutgoing(rtc::ArrayView<const uint8_t> payload) {
741 auto packet = SctpPacket::Parse(payload);
742 RTC_DCHECK(packet.has_value());
743
744 for (const auto& desc : packet->descriptors()) {
745 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Sent "
746 << DebugConvertChunkToString(desc.data);
747 }
748}
749
750bool DcSctpSocket::Dispatch(const CommonHeader& header,
751 const SctpPacket::ChunkDescriptor& descriptor) {
752 switch (descriptor.type) {
753 case DataChunk::kType:
754 HandleData(header, descriptor);
755 break;
756 case InitChunk::kType:
757 HandleInit(header, descriptor);
758 break;
759 case InitAckChunk::kType:
760 HandleInitAck(header, descriptor);
761 break;
762 case SackChunk::kType:
763 HandleSack(header, descriptor);
764 break;
765 case HeartbeatRequestChunk::kType:
766 HandleHeartbeatRequest(header, descriptor);
767 break;
768 case HeartbeatAckChunk::kType:
769 HandleHeartbeatAck(header, descriptor);
770 break;
771 case AbortChunk::kType:
772 HandleAbort(header, descriptor);
773 break;
774 case ErrorChunk::kType:
775 HandleError(header, descriptor);
776 break;
777 case CookieEchoChunk::kType:
778 HandleCookieEcho(header, descriptor);
779 break;
780 case CookieAckChunk::kType:
781 HandleCookieAck(header, descriptor);
782 break;
783 case ShutdownChunk::kType:
784 HandleShutdown(header, descriptor);
785 break;
786 case ShutdownAckChunk::kType:
787 HandleShutdownAck(header, descriptor);
788 break;
789 case ShutdownCompleteChunk::kType:
790 HandleShutdownComplete(header, descriptor);
791 break;
792 case ReConfigChunk::kType:
793 HandleReconfig(header, descriptor);
794 break;
795 case ForwardTsnChunk::kType:
796 HandleForwardTsn(header, descriptor);
797 break;
798 case IDataChunk::kType:
799 HandleIData(header, descriptor);
800 break;
801 case IForwardTsnChunk::kType:
802 HandleForwardTsn(header, descriptor);
803 break;
804 default:
805 return HandleUnrecognizedChunk(descriptor);
806 }
807 return true;
808}
809
810bool DcSctpSocket::HandleUnrecognizedChunk(
811 const SctpPacket::ChunkDescriptor& descriptor) {
812 bool report_as_error = (descriptor.type & 0x40) != 0;
813 bool continue_processing = (descriptor.type & 0x80) != 0;
814 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received unknown chunk: "
815 << static_cast<int>(descriptor.type);
816 if (report_as_error) {
817 rtc::StringBuilder sb;
818 sb << "Received unknown chunk of type: "
819 << static_cast<int>(descriptor.type) << " with report-error bit set";
820 callbacks_.OnError(ErrorKind::kParseFailed, sb.str());
821 RTC_DLOG(LS_VERBOSE)
822 << log_prefix()
823 << "Unknown chunk, with type indicating it should be reported.";
824
825 // https://tools.ietf.org/html/rfc4960#section-3.2
826 // "... report in an ERROR chunk using the 'Unrecognized Chunk Type'
827 // cause."
828 if (tcb_ != nullptr) {
829 // Need TCB - this chunk must be sent with a correct verification tag.
Victor Boivieabf61882021-08-12 15:57:49 +0200830 packet_sender_.Send(tcb_->PacketBuilder().Add(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200831 ErrorChunk(Parameters::Builder()
832 .Add(UnrecognizedChunkTypeCause(std::vector<uint8_t>(
833 descriptor.data.begin(), descriptor.data.end())))
834 .Build())));
835 }
836 }
837 if (!continue_processing) {
838 // https://tools.ietf.org/html/rfc4960#section-3.2
839 // "Stop processing this SCTP packet and discard it, do not process any
840 // further chunks within it."
841 RTC_DLOG(LS_VERBOSE) << log_prefix()
842 << "Unknown chunk, with type indicating not to "
843 "process any further chunks";
844 }
845
846 return continue_processing;
847}
848
849absl::optional<DurationMs> DcSctpSocket::OnInitTimerExpiry() {
850 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t1_init_->name()
851 << " has expired: " << t1_init_->expiration_count()
Victor Boivie9680d292021-08-30 10:23:49 +0200852 << "/" << t1_init_->options().max_restarts.value_or(-1);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200853 RTC_DCHECK(state_ == State::kCookieWait);
854
855 if (t1_init_->is_running()) {
856 SendInit();
857 } else {
858 InternalClose(ErrorKind::kTooManyRetries, "No INIT_ACK received");
859 }
860 RTC_DCHECK(IsConsistent());
861 return absl::nullopt;
862}
863
864absl::optional<DurationMs> DcSctpSocket::OnCookieTimerExpiry() {
865 // https://tools.ietf.org/html/rfc4960#section-4
866 // "If the T1-cookie timer expires, the endpoint MUST retransmit COOKIE
867 // ECHO and restart the T1-cookie timer without changing state. This MUST
868 // be repeated up to 'Max.Init.Retransmits' times. After that, the endpoint
869 // MUST abort the initialization process and report the error to the SCTP
870 // user."
871 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t1_cookie_->name()
872 << " has expired: " << t1_cookie_->expiration_count()
Victor Boivie9680d292021-08-30 10:23:49 +0200873 << "/"
874 << t1_cookie_->options().max_restarts.value_or(-1);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200875
876 RTC_DCHECK(state_ == State::kCookieEchoed);
877
878 if (t1_cookie_->is_running()) {
Victor Boiviec20f1562021-06-16 12:52:42 +0200879 tcb_->SendBufferedPackets(callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200880 } else {
881 InternalClose(ErrorKind::kTooManyRetries, "No COOKIE_ACK received");
882 }
883
884 RTC_DCHECK(IsConsistent());
885 return absl::nullopt;
886}
887
888absl::optional<DurationMs> DcSctpSocket::OnShutdownTimerExpiry() {
889 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t2_shutdown_->name()
890 << " has expired: " << t2_shutdown_->expiration_count()
Victor Boivie9680d292021-08-30 10:23:49 +0200891 << "/"
892 << t2_shutdown_->options().max_restarts.value_or(-1);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200893
Victor Boivie914925f2021-05-07 11:22:50 +0200894 if (!t2_shutdown_->is_running()) {
Victor Boivieb6580cc2021-04-08 09:56:59 +0200895 // https://tools.ietf.org/html/rfc4960#section-9.2
896 // "An endpoint should limit the number of retransmissions of the SHUTDOWN
897 // chunk to the protocol parameter 'Association.Max.Retrans'. If this
898 // threshold is exceeded, the endpoint should destroy the TCB..."
899
Victor Boivieabf61882021-08-12 15:57:49 +0200900 packet_sender_.Send(tcb_->PacketBuilder().Add(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200901 AbortChunk(true, Parameters::Builder()
902 .Add(UserInitiatedAbortCause(
903 "Too many retransmissions of SHUTDOWN"))
904 .Build())));
905
906 InternalClose(ErrorKind::kTooManyRetries, "No SHUTDOWN_ACK received");
Victor Boivie914925f2021-05-07 11:22:50 +0200907 RTC_DCHECK(IsConsistent());
908 return absl::nullopt;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200909 }
Victor Boivie914925f2021-05-07 11:22:50 +0200910
911 // https://tools.ietf.org/html/rfc4960#section-9.2
912 // "If the timer expires, the endpoint must resend the SHUTDOWN with the
913 // updated last sequential TSN received from its peer."
914 SendShutdown();
Victor Boivieb6580cc2021-04-08 09:56:59 +0200915 RTC_DCHECK(IsConsistent());
916 return tcb_->current_rto();
917}
918
Victor Boivieabf61882021-08-12 15:57:49 +0200919void DcSctpSocket::OnSentPacket(rtc::ArrayView<const uint8_t> packet,
920 SendPacketStatus status) {
921 // The packet observer is invoked even if the packet was failed to be sent, to
922 // indicate an attempt was made.
Victor Boivieb6580cc2021-04-08 09:56:59 +0200923 if (packet_observer_ != nullptr) {
Victor Boivieabf61882021-08-12 15:57:49 +0200924 packet_observer_->OnSentPacket(callbacks_.TimeMillis(), packet);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200925 }
Victor Boivieabf61882021-08-12 15:57:49 +0200926
927 if (status == SendPacketStatus::kSuccess) {
928 if (RTC_DLOG_IS_ON) {
929 DebugPrintOutgoing(packet);
930 }
931
932 // The heartbeat interval timer is restarted for every sent packet, to
933 // fire when the outgoing channel is inactive.
934 if (tcb_ != nullptr) {
935 tcb_->heartbeat_handler().RestartTimer();
936 }
937
938 ++metrics_.tx_packets_count;
939 }
Victor Boivieb6580cc2021-04-08 09:56:59 +0200940}
941
942bool DcSctpSocket::ValidateHasTCB() {
943 if (tcb_ != nullptr) {
944 return true;
945 }
946
947 callbacks_.OnError(
948 ErrorKind::kNotConnected,
949 "Received unexpected commands on socket that is not connected");
950 return false;
951}
952
953void DcSctpSocket::ReportFailedToParseChunk(int chunk_type) {
954 rtc::StringBuilder sb;
955 sb << "Failed to parse chunk of type: " << chunk_type;
956 callbacks_.OnError(ErrorKind::kParseFailed, sb.str());
957}
958
959void DcSctpSocket::HandleData(const CommonHeader& header,
960 const SctpPacket::ChunkDescriptor& descriptor) {
961 absl::optional<DataChunk> chunk = DataChunk::Parse(descriptor.data);
962 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
963 HandleDataCommon(*chunk);
964 }
965}
966
967void DcSctpSocket::HandleIData(const CommonHeader& header,
968 const SctpPacket::ChunkDescriptor& descriptor) {
969 absl::optional<IDataChunk> chunk = IDataChunk::Parse(descriptor.data);
970 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
971 HandleDataCommon(*chunk);
972 }
973}
974
975void DcSctpSocket::HandleDataCommon(AnyDataChunk& chunk) {
976 TSN tsn = chunk.tsn();
977 AnyDataChunk::ImmediateAckFlag immediate_ack = chunk.options().immediate_ack;
978 Data data = std::move(chunk).extract();
979
Victor Boivie4b7024b2021-12-01 18:57:22 +0000980 if (data.payload.empty()) {
Victor Boivieb6580cc2021-04-08 09:56:59 +0200981 // Empty DATA chunks are illegal.
Victor Boivieabf61882021-08-12 15:57:49 +0200982 packet_sender_.Send(tcb_->PacketBuilder().Add(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200983 ErrorChunk(Parameters::Builder().Add(NoUserDataCause(tsn)).Build())));
984 callbacks_.OnError(ErrorKind::kProtocolViolation,
985 "Received DATA chunk with no user data");
986 return;
987 }
988
989 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Handle DATA, queue_size="
990 << tcb_->reassembly_queue().queued_bytes()
991 << ", water_mark="
992 << tcb_->reassembly_queue().watermark_bytes()
993 << ", full=" << tcb_->reassembly_queue().is_full()
994 << ", above="
995 << tcb_->reassembly_queue().is_above_watermark();
996
997 if (tcb_->reassembly_queue().is_full()) {
998 // If the reassembly queue is full, there is nothing that can be done. The
999 // specification only allows dropping gap-ack-blocks, and that's not
1000 // likely to help as the socket has been trying to fill gaps since the
1001 // watermark was reached.
Victor Boivieabf61882021-08-12 15:57:49 +02001002 packet_sender_.Send(tcb_->PacketBuilder().Add(AbortChunk(
Victor Boivieb6580cc2021-04-08 09:56:59 +02001003 true, Parameters::Builder().Add(OutOfResourceErrorCause()).Build())));
1004 InternalClose(ErrorKind::kResourceExhaustion,
1005 "Reassembly Queue is exhausted");
1006 return;
1007 }
1008
1009 if (tcb_->reassembly_queue().is_above_watermark()) {
1010 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Is above high watermark";
1011 // If the reassembly queue is above its high watermark, only accept data
1012 // chunks that increase its cumulative ack tsn in an attempt to fill gaps
1013 // to deliver messages.
1014 if (!tcb_->data_tracker().will_increase_cum_ack_tsn(tsn)) {
1015 RTC_DLOG(LS_VERBOSE) << log_prefix()
1016 << "Rejected data because of exceeding watermark";
1017 tcb_->data_tracker().ForceImmediateSack();
1018 return;
1019 }
1020 }
1021
1022 if (!tcb_->data_tracker().IsTSNValid(tsn)) {
1023 RTC_DLOG(LS_VERBOSE) << log_prefix()
1024 << "Rejected data because of failing TSN validity";
1025 return;
1026 }
1027
1028 tcb_->data_tracker().Observe(tsn, immediate_ack);
1029 tcb_->reassembly_queue().MaybeResetStreamsDeferred(
1030 tcb_->data_tracker().last_cumulative_acked_tsn());
1031 tcb_->reassembly_queue().Add(tsn, std::move(data));
1032 DeliverReassembledMessages();
1033}
1034
1035void DcSctpSocket::HandleInit(const CommonHeader& header,
1036 const SctpPacket::ChunkDescriptor& descriptor) {
1037 absl::optional<InitChunk> chunk = InitChunk::Parse(descriptor.data);
1038 if (!ValidateParseSuccess(chunk)) {
1039 return;
1040 }
1041
1042 if (chunk->initiate_tag() == VerificationTag(0) ||
1043 chunk->nbr_outbound_streams() == 0 || chunk->nbr_inbound_streams() == 0) {
1044 // https://tools.ietf.org/html/rfc4960#section-3.3.2
1045 // "If the value of the Initiate Tag in a received INIT chunk is found
1046 // to be 0, the receiver MUST treat it as an error and close the
1047 // association by transmitting an ABORT."
1048
1049 // "A receiver of an INIT with the OS value set to 0 SHOULD abort the
1050 // association."
1051
1052 // "A receiver of an INIT with the MIS value of 0 SHOULD abort the
1053 // association."
1054
Victor Boivieabf61882021-08-12 15:57:49 +02001055 packet_sender_.Send(
1056 SctpPacket::Builder(VerificationTag(0), options_)
1057 .Add(AbortChunk(
1058 /*filled_in_verification_tag=*/false,
1059 Parameters::Builder()
1060 .Add(ProtocolViolationCause("INIT malformed"))
1061 .Build())));
Victor Boivieb6580cc2021-04-08 09:56:59 +02001062 InternalClose(ErrorKind::kProtocolViolation, "Received invalid INIT");
1063 return;
1064 }
1065
1066 if (state_ == State::kShutdownAckSent) {
1067 // https://tools.ietf.org/html/rfc4960#section-9.2
1068 // "If an endpoint is in the SHUTDOWN-ACK-SENT state and receives an
1069 // INIT chunk (e.g., if the SHUTDOWN COMPLETE was lost) with source and
1070 // destination transport addresses (either in the IP addresses or in the
1071 // INIT chunk) that belong to this association, it should discard the INIT
1072 // chunk and retransmit the SHUTDOWN ACK chunk."
1073 RTC_DLOG(LS_VERBOSE) << log_prefix()
1074 << "Received Init indicating lost ShutdownComplete";
1075 SendShutdownAck();
1076 return;
1077 }
1078
1079 TieTag tie_tag(0);
1080 if (state_ == State::kClosed) {
1081 RTC_DLOG(LS_VERBOSE) << log_prefix()
1082 << "Received Init in closed state (normal)";
1083
1084 MakeConnectionParameters();
1085 } else if (state_ == State::kCookieWait || state_ == State::kCookieEchoed) {
1086 // https://tools.ietf.org/html/rfc4960#section-5.2.1
1087 // "This usually indicates an initialization collision, i.e., each
1088 // endpoint is attempting, at about the same time, to establish an
1089 // association with the other endpoint. Upon receipt of an INIT in the
1090 // COOKIE-WAIT state, an endpoint MUST respond with an INIT ACK using the
1091 // same parameters it sent in its original INIT chunk (including its
1092 // Initiate Tag, unchanged). When responding, the endpoint MUST send the
1093 // INIT ACK back to the same address that the original INIT (sent by this
1094 // endpoint) was sent."
1095 RTC_DLOG(LS_VERBOSE) << log_prefix()
1096 << "Received Init indicating simultaneous connections";
1097 } else {
1098 RTC_DCHECK(tcb_ != nullptr);
1099 // https://tools.ietf.org/html/rfc4960#section-5.2.2
1100 // "The outbound SCTP packet containing this INIT ACK MUST carry a
1101 // Verification Tag value equal to the Initiate Tag found in the
1102 // unexpected INIT. And the INIT ACK MUST contain a new Initiate Tag
1103 // (randomly generated; see Section 5.3.1). Other parameters for the
1104 // endpoint SHOULD be copied from the existing parameters of the
1105 // association (e.g., number of outbound streams) into the INIT ACK and
1106 // cookie."
1107 RTC_DLOG(LS_VERBOSE) << log_prefix()
1108 << "Received Init indicating restarted connection";
1109 // Create a new verification tag - different from the previous one.
1110 for (int tries = 0; tries < 10; ++tries) {
1111 connect_params_.verification_tag = VerificationTag(
1112 callbacks_.GetRandomInt(kMinVerificationTag, kMaxVerificationTag));
1113 if (connect_params_.verification_tag != tcb_->my_verification_tag()) {
1114 break;
1115 }
1116 }
1117
1118 // Make the initial TSN make a large jump, so that there is no overlap
1119 // with the old and new association.
1120 connect_params_.initial_tsn =
1121 TSN(*tcb_->retransmission_queue().next_tsn() + 1000000);
1122 tie_tag = tcb_->tie_tag();
1123 }
1124
1125 RTC_DLOG(LS_VERBOSE)
1126 << log_prefix()
1127 << rtc::StringFormat(
1128 "Proceeding with connection. my_verification_tag=%08x, "
1129 "my_initial_tsn=%u, peer_verification_tag=%08x, "
1130 "peer_initial_tsn=%u",
1131 *connect_params_.verification_tag, *connect_params_.initial_tsn,
1132 *chunk->initiate_tag(), *chunk->initial_tsn());
1133
1134 Capabilities capabilities = GetCapabilities(options_, chunk->parameters());
1135
1136 SctpPacket::Builder b(chunk->initiate_tag(), options_);
1137 Parameters::Builder params_builder =
1138 Parameters::Builder().Add(StateCookieParameter(
1139 StateCookie(chunk->initiate_tag(), chunk->initial_tsn(),
1140 chunk->a_rwnd(), tie_tag, capabilities)
1141 .Serialize()));
1142 AddCapabilityParameters(options_, params_builder);
1143
1144 InitAckChunk init_ack(/*initiate_tag=*/connect_params_.verification_tag,
1145 options_.max_receiver_window_buffer_size,
1146 options_.announced_maximum_outgoing_streams,
1147 options_.announced_maximum_incoming_streams,
1148 connect_params_.initial_tsn, params_builder.Build());
1149 b.Add(init_ack);
Victor Boivieabf61882021-08-12 15:57:49 +02001150 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001151}
1152
Victor Boivieb6580cc2021-04-08 09:56:59 +02001153void DcSctpSocket::HandleInitAck(
1154 const CommonHeader& header,
1155 const SctpPacket::ChunkDescriptor& descriptor) {
1156 absl::optional<InitAckChunk> chunk = InitAckChunk::Parse(descriptor.data);
1157 if (!ValidateParseSuccess(chunk)) {
1158 return;
1159 }
1160
1161 if (state_ != State::kCookieWait) {
1162 // https://tools.ietf.org/html/rfc4960#section-5.2.3
1163 // "If an INIT ACK is received by an endpoint in any state other than
1164 // the COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk."
1165 RTC_DLOG(LS_VERBOSE) << log_prefix()
1166 << "Received INIT_ACK in unexpected state";
1167 return;
1168 }
1169
1170 auto cookie = chunk->parameters().get<StateCookieParameter>();
1171 if (!cookie.has_value()) {
Victor Boivieabf61882021-08-12 15:57:49 +02001172 packet_sender_.Send(
1173 SctpPacket::Builder(connect_params_.verification_tag, options_)
1174 .Add(AbortChunk(
1175 /*filled_in_verification_tag=*/false,
1176 Parameters::Builder()
1177 .Add(ProtocolViolationCause("INIT-ACK malformed"))
1178 .Build())));
Victor Boivieb6580cc2021-04-08 09:56:59 +02001179 InternalClose(ErrorKind::kProtocolViolation,
1180 "InitAck chunk doesn't contain a cookie");
1181 return;
1182 }
1183 Capabilities capabilities = GetCapabilities(options_, chunk->parameters());
1184 t1_init_->Stop();
1185
Victor Boivief4fa1662021-09-24 23:01:21 +02001186 peer_implementation_ = DeterminePeerImplementation(cookie->data());
1187
Victor Boivieb6580cc2021-04-08 09:56:59 +02001188 tcb_ = std::make_unique<TransmissionControlBlock>(
1189 timer_manager_, log_prefix_, options_, capabilities, callbacks_,
1190 send_queue_, connect_params_.verification_tag,
1191 connect_params_.initial_tsn, chunk->initiate_tag(), chunk->initial_tsn(),
Victor Boivieabf61882021-08-12 15:57:49 +02001192 chunk->a_rwnd(), MakeTieTag(callbacks_), packet_sender_,
1193 [this]() { return state_ == State::kEstablished; });
Victor Boivieb6580cc2021-04-08 09:56:59 +02001194 RTC_DLOG(LS_VERBOSE) << log_prefix()
1195 << "Created peer TCB: " << tcb_->ToString();
1196
1197 SetState(State::kCookieEchoed, "INIT_ACK received");
1198
1199 // The connection isn't fully established just yet.
Victor Boiviec20f1562021-06-16 12:52:42 +02001200 tcb_->SetCookieEchoChunk(CookieEchoChunk(cookie->data()));
1201 tcb_->SendBufferedPackets(callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +02001202 t1_cookie_->Start();
1203}
1204
1205void DcSctpSocket::HandleCookieEcho(
1206 const CommonHeader& header,
1207 const SctpPacket::ChunkDescriptor& descriptor) {
1208 absl::optional<CookieEchoChunk> chunk =
1209 CookieEchoChunk::Parse(descriptor.data);
1210 if (!ValidateParseSuccess(chunk)) {
1211 return;
1212 }
1213
1214 absl::optional<StateCookie> cookie =
1215 StateCookie::Deserialize(chunk->cookie());
1216 if (!cookie.has_value()) {
1217 callbacks_.OnError(ErrorKind::kParseFailed, "Failed to parse state cookie");
1218 return;
1219 }
1220
1221 if (tcb_ != nullptr) {
1222 if (!HandleCookieEchoWithTCB(header, *cookie)) {
1223 return;
1224 }
1225 } else {
1226 if (header.verification_tag != connect_params_.verification_tag) {
1227 callbacks_.OnError(
1228 ErrorKind::kParseFailed,
1229 rtc::StringFormat(
1230 "Received CookieEcho with invalid verification tag: %08x, "
1231 "expected %08x",
1232 *header.verification_tag, *connect_params_.verification_tag));
1233 return;
1234 }
1235 }
1236
1237 // The init timer can be running on simultaneous connections.
1238 t1_init_->Stop();
1239 t1_cookie_->Stop();
1240 if (state_ != State::kEstablished) {
Victor Boiviec20f1562021-06-16 12:52:42 +02001241 if (tcb_ != nullptr) {
1242 tcb_->ClearCookieEchoChunk();
1243 }
Victor Boivieb6580cc2021-04-08 09:56:59 +02001244 SetState(State::kEstablished, "COOKIE_ECHO received");
1245 callbacks_.OnConnected();
1246 }
1247
1248 if (tcb_ == nullptr) {
1249 tcb_ = std::make_unique<TransmissionControlBlock>(
1250 timer_manager_, log_prefix_, options_, cookie->capabilities(),
1251 callbacks_, send_queue_, connect_params_.verification_tag,
1252 connect_params_.initial_tsn, cookie->initiate_tag(),
1253 cookie->initial_tsn(), cookie->a_rwnd(), MakeTieTag(callbacks_),
Victor Boivieabf61882021-08-12 15:57:49 +02001254 packet_sender_, [this]() { return state_ == State::kEstablished; });
Victor Boivieb6580cc2021-04-08 09:56:59 +02001255 RTC_DLOG(LS_VERBOSE) << log_prefix()
1256 << "Created peer TCB: " << tcb_->ToString();
1257 }
1258
1259 SctpPacket::Builder b = tcb_->PacketBuilder();
1260 b.Add(CookieAckChunk());
1261
1262 // https://tools.ietf.org/html/rfc4960#section-5.1
1263 // "A COOKIE ACK chunk may be bundled with any pending DATA chunks (and/or
1264 // SACK chunks), but the COOKIE ACK chunk MUST be the first chunk in the
1265 // packet."
Victor Boivied3b186e2021-05-05 16:22:29 +02001266 tcb_->SendBufferedPackets(b, callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +02001267}
1268
1269bool DcSctpSocket::HandleCookieEchoWithTCB(const CommonHeader& header,
1270 const StateCookie& cookie) {
1271 RTC_DLOG(LS_VERBOSE) << log_prefix()
1272 << "Handling CookieEchoChunk with TCB. local_tag="
1273 << *tcb_->my_verification_tag()
1274 << ", peer_tag=" << *header.verification_tag
1275 << ", tcb_tag=" << *tcb_->peer_verification_tag()
1276 << ", cookie_tag=" << *cookie.initiate_tag()
1277 << ", local_tie_tag=" << *tcb_->tie_tag()
1278 << ", peer_tie_tag=" << *cookie.tie_tag();
1279 // https://tools.ietf.org/html/rfc4960#section-5.2.4
1280 // "Handle a COOKIE ECHO when a TCB Exists"
1281 if (header.verification_tag != tcb_->my_verification_tag() &&
1282 tcb_->peer_verification_tag() != cookie.initiate_tag() &&
1283 cookie.tie_tag() == tcb_->tie_tag()) {
1284 // "A) In this case, the peer may have restarted."
1285 if (state_ == State::kShutdownAckSent) {
1286 // "If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
1287 // that the peer has restarted ... it MUST NOT set up a new association
1288 // but instead resend the SHUTDOWN ACK and send an ERROR chunk with a
1289 // "Cookie Received While Shutting Down" error cause to its peer."
1290 SctpPacket::Builder b(cookie.initiate_tag(), options_);
1291 b.Add(ShutdownAckChunk());
1292 b.Add(ErrorChunk(Parameters::Builder()
1293 .Add(CookieReceivedWhileShuttingDownCause())
1294 .Build()));
Victor Boivieabf61882021-08-12 15:57:49 +02001295 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001296 callbacks_.OnError(ErrorKind::kWrongSequence,
1297 "Received COOKIE-ECHO while shutting down");
1298 return false;
1299 }
1300
1301 RTC_DLOG(LS_VERBOSE) << log_prefix()
1302 << "Received COOKIE-ECHO indicating a restarted peer";
1303
1304 // If a message was partly sent, and the peer restarted, resend it in
1305 // full by resetting the send queue.
1306 send_queue_.Reset();
1307 tcb_ = nullptr;
1308 callbacks_.OnConnectionRestarted();
1309 } else if (header.verification_tag == tcb_->my_verification_tag() &&
1310 tcb_->peer_verification_tag() != cookie.initiate_tag()) {
1311 // TODO(boivie): Handle the peer_tag == 0?
1312 // "B) In this case, both sides may be attempting to start an
1313 // association at about the same time, but the peer endpoint started its
1314 // INIT after responding to the local endpoint's INIT."
1315 RTC_DLOG(LS_VERBOSE)
1316 << log_prefix()
1317 << "Received COOKIE-ECHO indicating simultaneous connections";
1318 tcb_ = nullptr;
1319 } else if (header.verification_tag != tcb_->my_verification_tag() &&
1320 tcb_->peer_verification_tag() == cookie.initiate_tag() &&
1321 cookie.tie_tag() == TieTag(0)) {
1322 // "C) In this case, the local endpoint's cookie has arrived late.
1323 // Before it arrived, the local endpoint sent an INIT and received an
1324 // INIT ACK and finally sent a COOKIE ECHO with the peer's same tag but
1325 // a new tag of its own. The cookie should be silently discarded. The
1326 // endpoint SHOULD NOT change states and should leave any timers
1327 // running."
1328 RTC_DLOG(LS_VERBOSE)
1329 << log_prefix()
1330 << "Received COOKIE-ECHO indicating a late COOKIE-ECHO. Discarding";
1331 return false;
1332 } else if (header.verification_tag == tcb_->my_verification_tag() &&
1333 tcb_->peer_verification_tag() == cookie.initiate_tag()) {
1334 // "D) When both local and remote tags match, the endpoint should enter
1335 // the ESTABLISHED state, if it is in the COOKIE-ECHOED state. It
1336 // should stop any cookie timer that may be running and send a COOKIE
1337 // ACK."
1338 RTC_DLOG(LS_VERBOSE)
1339 << log_prefix()
1340 << "Received duplicate COOKIE-ECHO, probably because of peer not "
1341 "receiving COOKIE-ACK and retransmitting COOKIE-ECHO. Continuing.";
1342 }
1343 return true;
1344}
1345
1346void DcSctpSocket::HandleCookieAck(
1347 const CommonHeader& header,
1348 const SctpPacket::ChunkDescriptor& descriptor) {
1349 absl::optional<CookieAckChunk> chunk = CookieAckChunk::Parse(descriptor.data);
1350 if (!ValidateParseSuccess(chunk)) {
1351 return;
1352 }
1353
1354 if (state_ != State::kCookieEchoed) {
1355 // https://tools.ietf.org/html/rfc4960#section-5.2.5
1356 // "At any state other than COOKIE-ECHOED, an endpoint should silently
1357 // discard a received COOKIE ACK chunk."
1358 RTC_DLOG(LS_VERBOSE) << log_prefix()
1359 << "Received COOKIE_ACK not in COOKIE_ECHOED state";
1360 return;
1361 }
1362
1363 // RFC 4960, Errata ID: 4400
1364 t1_cookie_->Stop();
Victor Boiviec20f1562021-06-16 12:52:42 +02001365 tcb_->ClearCookieEchoChunk();
Victor Boivieb6580cc2021-04-08 09:56:59 +02001366 SetState(State::kEstablished, "COOKIE_ACK received");
Victor Boivied3b186e2021-05-05 16:22:29 +02001367 tcb_->SendBufferedPackets(callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +02001368 callbacks_.OnConnected();
1369}
1370
1371void DcSctpSocket::DeliverReassembledMessages() {
1372 if (tcb_->reassembly_queue().HasMessages()) {
1373 for (auto& message : tcb_->reassembly_queue().FlushMessages()) {
Victor Boivied4716ea2021-08-09 12:26:32 +02001374 ++metrics_.rx_messages_count;
Victor Boivieb6580cc2021-04-08 09:56:59 +02001375 callbacks_.OnMessageReceived(std::move(message));
1376 }
1377 }
1378}
1379
1380void DcSctpSocket::HandleSack(const CommonHeader& header,
1381 const SctpPacket::ChunkDescriptor& descriptor) {
1382 absl::optional<SackChunk> chunk = SackChunk::Parse(descriptor.data);
1383
1384 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
Victor Boivied3b186e2021-05-05 16:22:29 +02001385 TimeMs now = callbacks_.TimeMillis();
Victor Boivieb6580cc2021-04-08 09:56:59 +02001386 SackChunk sack = ChunkValidators::Clean(*std::move(chunk));
1387
Victor Boivied3b186e2021-05-05 16:22:29 +02001388 if (tcb_->retransmission_queue().HandleSack(now, sack)) {
Victor Boivieb6580cc2021-04-08 09:56:59 +02001389 MaybeSendShutdownOrAck();
1390 // Receiving an ACK will decrease outstanding bytes (maybe now below
1391 // cwnd?) or indicate packet loss that may result in sending FORWARD-TSN.
Victor Boivied3b186e2021-05-05 16:22:29 +02001392 tcb_->SendBufferedPackets(now);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001393 } else {
1394 RTC_DLOG(LS_VERBOSE) << log_prefix()
1395 << "Dropping out-of-order SACK with TSN "
1396 << *sack.cumulative_tsn_ack();
1397 }
1398 }
1399}
1400
1401void DcSctpSocket::HandleHeartbeatRequest(
1402 const CommonHeader& header,
1403 const SctpPacket::ChunkDescriptor& descriptor) {
1404 absl::optional<HeartbeatRequestChunk> chunk =
1405 HeartbeatRequestChunk::Parse(descriptor.data);
1406
1407 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1408 tcb_->heartbeat_handler().HandleHeartbeatRequest(*std::move(chunk));
1409 }
1410}
1411
1412void DcSctpSocket::HandleHeartbeatAck(
1413 const CommonHeader& header,
1414 const SctpPacket::ChunkDescriptor& descriptor) {
1415 absl::optional<HeartbeatAckChunk> chunk =
1416 HeartbeatAckChunk::Parse(descriptor.data);
1417
1418 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1419 tcb_->heartbeat_handler().HandleHeartbeatAck(*std::move(chunk));
1420 }
1421}
1422
1423void DcSctpSocket::HandleAbort(const CommonHeader& header,
1424 const SctpPacket::ChunkDescriptor& descriptor) {
1425 absl::optional<AbortChunk> chunk = AbortChunk::Parse(descriptor.data);
1426 if (ValidateParseSuccess(chunk)) {
1427 std::string error_string = ErrorCausesToString(chunk->error_causes());
1428 if (tcb_ == nullptr) {
1429 // https://tools.ietf.org/html/rfc4960#section-3.3.7
1430 // "If an endpoint receives an ABORT with a format error or no TCB is
1431 // found, it MUST silently discard it."
1432 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received ABORT (" << error_string
1433 << ") on a connection with no TCB. Ignoring";
1434 return;
1435 }
1436
1437 RTC_DLOG(LS_WARNING) << log_prefix() << "Received ABORT (" << error_string
1438 << ") - closing connection.";
1439 InternalClose(ErrorKind::kPeerReported, error_string);
1440 }
1441}
1442
1443void DcSctpSocket::HandleError(const CommonHeader& header,
1444 const SctpPacket::ChunkDescriptor& descriptor) {
1445 absl::optional<ErrorChunk> chunk = ErrorChunk::Parse(descriptor.data);
1446 if (ValidateParseSuccess(chunk)) {
1447 std::string error_string = ErrorCausesToString(chunk->error_causes());
1448 if (tcb_ == nullptr) {
1449 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received ERROR (" << error_string
1450 << ") on a connection with no TCB. Ignoring";
1451 return;
1452 }
1453
1454 RTC_DLOG(LS_WARNING) << log_prefix() << "Received ERROR: " << error_string;
1455 callbacks_.OnError(ErrorKind::kPeerReported,
1456 "Peer reported error: " + error_string);
1457 }
1458}
1459
1460void DcSctpSocket::HandleReconfig(
1461 const CommonHeader& header,
1462 const SctpPacket::ChunkDescriptor& descriptor) {
1463 absl::optional<ReConfigChunk> chunk = ReConfigChunk::Parse(descriptor.data);
1464 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1465 tcb_->stream_reset_handler().HandleReConfig(*std::move(chunk));
1466 }
1467}
1468
1469void DcSctpSocket::HandleShutdown(
1470 const CommonHeader& header,
1471 const SctpPacket::ChunkDescriptor& descriptor) {
1472 if (!ValidateParseSuccess(ShutdownChunk::Parse(descriptor.data))) {
1473 return;
1474 }
1475
1476 if (state_ == State::kClosed) {
1477 return;
1478 } else if (state_ == State::kCookieWait || state_ == State::kCookieEchoed) {
1479 // https://tools.ietf.org/html/rfc4960#section-9.2
1480 // "If a SHUTDOWN is received in the COOKIE-WAIT or COOKIE ECHOED state,
1481 // the SHUTDOWN chunk SHOULD be silently discarded."
1482 } else if (state_ == State::kShutdownSent) {
1483 // https://tools.ietf.org/html/rfc4960#section-9.2
1484 // "If an endpoint is in the SHUTDOWN-SENT state and receives a
1485 // SHUTDOWN chunk from its peer, the endpoint shall respond immediately
1486 // with a SHUTDOWN ACK to its peer, and move into the SHUTDOWN-ACK-SENT
1487 // state restarting its T2-shutdown timer."
1488 SendShutdownAck();
1489 SetState(State::kShutdownAckSent, "SHUTDOWN received");
Victor Boivie50a0b122021-05-06 21:07:49 +02001490 } else if (state_ == State::kShutdownAckSent) {
1491 // TODO(webrtc:12739): This condition should be removed and handled by the
1492 // next (state_ != State::kShutdownReceived).
1493 return;
Victor Boivieb6580cc2021-04-08 09:56:59 +02001494 } else if (state_ != State::kShutdownReceived) {
1495 RTC_DLOG(LS_VERBOSE) << log_prefix()
1496 << "Received SHUTDOWN - shutting down the socket";
1497 // https://tools.ietf.org/html/rfc4960#section-9.2
1498 // "Upon reception of the SHUTDOWN, the peer endpoint shall enter the
1499 // SHUTDOWN-RECEIVED state, stop accepting new data from its SCTP user,
1500 // and verify, by checking the Cumulative TSN Ack field of the chunk, that
1501 // all its outstanding DATA chunks have been received by the SHUTDOWN
1502 // sender."
1503 SetState(State::kShutdownReceived, "SHUTDOWN received");
1504 MaybeSendShutdownOrAck();
1505 }
1506}
1507
1508void DcSctpSocket::HandleShutdownAck(
1509 const CommonHeader& header,
1510 const SctpPacket::ChunkDescriptor& descriptor) {
1511 if (!ValidateParseSuccess(ShutdownAckChunk::Parse(descriptor.data))) {
1512 return;
1513 }
1514
1515 if (state_ == State::kShutdownSent || state_ == State::kShutdownAckSent) {
1516 // https://tools.ietf.org/html/rfc4960#section-9.2
1517 // "Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall stop
1518 // the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its peer, and
1519 // remove all record of the association."
1520
1521 // "If an endpoint is in the SHUTDOWN-ACK-SENT state and receives a
1522 // SHUTDOWN ACK, it shall stop the T2-shutdown timer, send a SHUTDOWN
1523 // COMPLETE chunk to its peer, and remove all record of the association."
1524
1525 SctpPacket::Builder b = tcb_->PacketBuilder();
1526 b.Add(ShutdownCompleteChunk(/*tag_reflected=*/false));
Victor Boivieabf61882021-08-12 15:57:49 +02001527 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001528 InternalClose(ErrorKind::kNoError, "");
1529 } else {
1530 // https://tools.ietf.org/html/rfc4960#section-8.5.1
1531 // "If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state
1532 // the procedures in Section 8.4 SHOULD be followed; in other words, it
1533 // should be treated as an Out Of The Blue packet."
1534
1535 // https://tools.ietf.org/html/rfc4960#section-8.4
1536 // "If the packet contains a SHUTDOWN ACK chunk, the receiver
1537 // should respond to the sender of the OOTB packet with a SHUTDOWN
1538 // COMPLETE. When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
1539 // packet must fill in the Verification Tag field of the outbound packet
1540 // with the Verification Tag received in the SHUTDOWN ACK and set the T
1541 // bit in the Chunk Flags to indicate that the Verification Tag is
1542 // reflected."
1543
1544 SctpPacket::Builder b(header.verification_tag, options_);
1545 b.Add(ShutdownCompleteChunk(/*tag_reflected=*/true));
Victor Boivieabf61882021-08-12 15:57:49 +02001546 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001547 }
1548}
1549
1550void DcSctpSocket::HandleShutdownComplete(
1551 const CommonHeader& header,
1552 const SctpPacket::ChunkDescriptor& descriptor) {
1553 if (!ValidateParseSuccess(ShutdownCompleteChunk::Parse(descriptor.data))) {
1554 return;
1555 }
1556
1557 if (state_ == State::kShutdownAckSent) {
1558 // https://tools.ietf.org/html/rfc4960#section-9.2
1559 // "Upon reception of the SHUTDOWN COMPLETE chunk, the endpoint will
1560 // verify that it is in the SHUTDOWN-ACK-SENT state; if it is not, the
1561 // chunk should be discarded. If the endpoint is in the SHUTDOWN-ACK-SENT
1562 // state, the endpoint should stop the T2-shutdown timer and remove all
1563 // knowledge of the association (and thus the association enters the
1564 // CLOSED state)."
1565 InternalClose(ErrorKind::kNoError, "");
1566 }
1567}
1568
1569void DcSctpSocket::HandleForwardTsn(
1570 const CommonHeader& header,
1571 const SctpPacket::ChunkDescriptor& descriptor) {
1572 absl::optional<ForwardTsnChunk> chunk =
1573 ForwardTsnChunk::Parse(descriptor.data);
1574 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1575 HandleForwardTsnCommon(*chunk);
1576 }
1577}
1578
1579void DcSctpSocket::HandleIForwardTsn(
1580 const CommonHeader& header,
1581 const SctpPacket::ChunkDescriptor& descriptor) {
1582 absl::optional<IForwardTsnChunk> chunk =
1583 IForwardTsnChunk::Parse(descriptor.data);
1584 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1585 HandleForwardTsnCommon(*chunk);
1586 }
1587}
1588
1589void DcSctpSocket::HandleForwardTsnCommon(const AnyForwardTsnChunk& chunk) {
1590 if (!tcb_->capabilities().partial_reliability) {
1591 SctpPacket::Builder b = tcb_->PacketBuilder();
1592 b.Add(AbortChunk(/*filled_in_verification_tag=*/true,
1593 Parameters::Builder()
1594 .Add(ProtocolViolationCause(
1595 "I-FORWARD-TSN received, but not indicated "
1596 "during connection establishment"))
1597 .Build()));
Victor Boivieabf61882021-08-12 15:57:49 +02001598 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001599
1600 callbacks_.OnError(ErrorKind::kProtocolViolation,
1601 "Received a FORWARD_TSN without announced peer support");
1602 return;
1603 }
1604 tcb_->data_tracker().HandleForwardTsn(chunk.new_cumulative_tsn());
1605 tcb_->reassembly_queue().Handle(chunk);
1606 // A forward TSN - for ordered streams - may allow messages to be
1607 // delivered.
1608 DeliverReassembledMessages();
1609
1610 // Processing a FORWARD_TSN might result in sending a SACK.
1611 tcb_->MaybeSendSack();
1612}
1613
1614void DcSctpSocket::MaybeSendShutdownOrAck() {
1615 if (tcb_->retransmission_queue().outstanding_bytes() != 0) {
1616 return;
1617 }
1618
1619 if (state_ == State::kShutdownPending) {
1620 // https://tools.ietf.org/html/rfc4960#section-9.2
1621 // "Once all its outstanding data has been acknowledged, the endpoint
1622 // shall send a SHUTDOWN chunk to its peer including in the Cumulative TSN
1623 // Ack field the last sequential TSN it has received from the peer. It
1624 // shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT
1625 // state.""
1626
1627 SendShutdown();
1628 t2_shutdown_->set_duration(tcb_->current_rto());
1629 t2_shutdown_->Start();
1630 SetState(State::kShutdownSent, "No more outstanding data");
1631 } else if (state_ == State::kShutdownReceived) {
1632 // https://tools.ietf.org/html/rfc4960#section-9.2
1633 // "If the receiver of the SHUTDOWN has no more outstanding DATA
1634 // chunks, the SHUTDOWN receiver MUST send a SHUTDOWN ACK and start a
1635 // T2-shutdown timer of its own, entering the SHUTDOWN-ACK-SENT state. If
1636 // the timer expires, the endpoint must resend the SHUTDOWN ACK."
1637
1638 SendShutdownAck();
1639 SetState(State::kShutdownAckSent, "No more outstanding data");
1640 }
1641}
1642
1643void DcSctpSocket::SendShutdown() {
1644 SctpPacket::Builder b = tcb_->PacketBuilder();
1645 b.Add(ShutdownChunk(tcb_->data_tracker().last_cumulative_acked_tsn()));
Victor Boivieabf61882021-08-12 15:57:49 +02001646 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001647}
1648
1649void DcSctpSocket::SendShutdownAck() {
Victor Boivieabf61882021-08-12 15:57:49 +02001650 packet_sender_.Send(tcb_->PacketBuilder().Add(ShutdownAckChunk()));
Victor Boivieb6580cc2021-04-08 09:56:59 +02001651 t2_shutdown_->set_duration(tcb_->current_rto());
1652 t2_shutdown_->Start();
1653}
1654
Sergey Sukhanov43972812021-09-17 15:32:48 +02001655HandoverReadinessStatus DcSctpSocket::GetHandoverReadiness() const {
Victor Boivie5755f3e2021-09-29 22:23:15 +02001656 RTC_DCHECK_RUN_ON(&thread_checker_);
Sergey Sukhanov43972812021-09-17 15:32:48 +02001657 HandoverReadinessStatus status;
1658 if (state_ != State::kClosed && state_ != State::kEstablished) {
1659 status.Add(HandoverUnreadinessReason::kWrongConnectionState);
1660 }
Sergey Sukhanov72435322021-09-21 13:31:09 +02001661 status.Add(send_queue_.GetHandoverReadiness());
Sergey Sukhanov43972812021-09-17 15:32:48 +02001662 if (tcb_) {
1663 status.Add(tcb_->GetHandoverReadiness());
1664 }
1665 return status;
1666}
1667
1668absl::optional<DcSctpSocketHandoverState>
1669DcSctpSocket::GetHandoverStateAndClose() {
Victor Boivie5755f3e2021-09-29 22:23:15 +02001670 RTC_DCHECK_RUN_ON(&thread_checker_);
Victor Boivie15a0c882021-09-28 21:38:34 +02001671 CallbackDeferrer::ScopedDeferrer deferrer(callbacks_);
1672
Sergey Sukhanov43972812021-09-17 15:32:48 +02001673 if (!GetHandoverReadiness().IsReady()) {
1674 return absl::nullopt;
1675 }
1676
1677 DcSctpSocketHandoverState state;
1678
1679 if (state_ == State::kClosed) {
1680 state.socket_state = DcSctpSocketHandoverState::SocketState::kClosed;
1681 } else if (state_ == State::kEstablished) {
1682 state.socket_state = DcSctpSocketHandoverState::SocketState::kConnected;
1683 tcb_->AddHandoverState(state);
Sergey Sukhanov72435322021-09-21 13:31:09 +02001684 send_queue_.AddHandoverState(state);
Sergey Sukhanov43972812021-09-17 15:32:48 +02001685 InternalClose(ErrorKind::kNoError, "handover");
Sergey Sukhanov43972812021-09-17 15:32:48 +02001686 }
1687
1688 return std::move(state);
1689}
1690
Victor Boivieb6580cc2021-04-08 09:56:59 +02001691} // namespace dcsctp