blob: a1cc12d1e14247e2451a9e07066993b03883d6de [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() {
284 if (state_ == State::kClosed) {
285 MakeConnectionParameters();
286 RTC_DLOG(LS_INFO)
287 << log_prefix()
288 << rtc::StringFormat(
289 "Connecting. my_verification_tag=%08x, my_initial_tsn=%u",
290 *connect_params_.verification_tag, *connect_params_.initial_tsn);
291 SendInit();
292 t1_init_->Start();
293 SetState(State::kCookieWait, "Connect called");
294 } else {
295 RTC_DLOG(LS_WARNING) << log_prefix()
296 << "Called Connect on a socket that is not closed";
297 }
298 RTC_DCHECK(IsConsistent());
299 callbacks_.TriggerDeferred();
300}
301
Sergey Sukhanov43972812021-09-17 15:32:48 +0200302void DcSctpSocket::RestoreFromState(const DcSctpSocketHandoverState& state) {
303 if (state_ != State::kClosed) {
304 callbacks_.OnError(ErrorKind::kUnsupportedOperation,
305 "Only closed socket can be restored from state");
306 } else {
307 if (state.socket_state ==
308 DcSctpSocketHandoverState::SocketState::kConnected) {
309 VerificationTag my_verification_tag =
310 VerificationTag(state.my_verification_tag);
311 connect_params_.verification_tag = my_verification_tag;
312
313 Capabilities capabilities;
314 capabilities.partial_reliability = state.capabilities.partial_reliability;
315 capabilities.message_interleaving =
316 state.capabilities.message_interleaving;
317 capabilities.reconfig = state.capabilities.reconfig;
318
Sergey Sukhanov72435322021-09-21 13:31:09 +0200319 send_queue_.RestoreFromState(state);
320
Sergey Sukhanov43972812021-09-17 15:32:48 +0200321 tcb_ = std::make_unique<TransmissionControlBlock>(
322 timer_manager_, log_prefix_, options_, capabilities, callbacks_,
323 send_queue_, my_verification_tag, TSN(state.my_initial_tsn),
324 VerificationTag(state.peer_verification_tag),
325 TSN(state.peer_initial_tsn), static_cast<size_t>(0),
326 TieTag(state.tie_tag), packet_sender_,
327 [this]() { return state_ == State::kEstablished; }, &state);
328 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Created peer TCB from state: "
329 << tcb_->ToString();
330
331 SetState(State::kEstablished, "restored from handover state");
332 callbacks_.OnConnected();
333 }
334 }
335
336 RTC_DCHECK(IsConsistent());
337 callbacks_.TriggerDeferred();
338}
339
Victor Boivieb6580cc2021-04-08 09:56:59 +0200340void DcSctpSocket::Shutdown() {
341 if (tcb_ != nullptr) {
342 // https://tools.ietf.org/html/rfc4960#section-9.2
343 // "Upon receipt of the SHUTDOWN primitive from its upper layer, the
344 // endpoint enters the SHUTDOWN-PENDING state and remains there until all
345 // outstanding data has been acknowledged by its peer."
Victor Boivie50a0b122021-05-06 21:07:49 +0200346
347 // TODO(webrtc:12739): Remove this check, as it just hides the problem that
348 // the socket can transition from ShutdownSent to ShutdownPending, or
349 // ShutdownAckSent to ShutdownPending which is illegal.
350 if (state_ != State::kShutdownSent && state_ != State::kShutdownAckSent) {
351 SetState(State::kShutdownPending, "Shutdown called");
352 t1_init_->Stop();
353 t1_cookie_->Stop();
354 MaybeSendShutdownOrAck();
355 }
Victor Boivieb6580cc2021-04-08 09:56:59 +0200356 } else {
357 // Connection closed before even starting to connect, or during the initial
358 // connection phase. There is no outstanding data, so the socket can just
359 // be closed (stopping any connection timers, if any), as this is the
360 // client's intention, by calling Shutdown.
361 InternalClose(ErrorKind::kNoError, "");
362 }
363 RTC_DCHECK(IsConsistent());
364 callbacks_.TriggerDeferred();
365}
366
367void DcSctpSocket::Close() {
368 if (state_ != State::kClosed) {
369 if (tcb_ != nullptr) {
370 SctpPacket::Builder b = tcb_->PacketBuilder();
371 b.Add(AbortChunk(/*filled_in_verification_tag=*/true,
372 Parameters::Builder()
373 .Add(UserInitiatedAbortCause("Close called"))
374 .Build()));
Victor Boivieabf61882021-08-12 15:57:49 +0200375 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200376 }
377 InternalClose(ErrorKind::kNoError, "");
378 } else {
379 RTC_DLOG(LS_INFO) << log_prefix() << "Called Close on a closed socket";
380 }
381 RTC_DCHECK(IsConsistent());
382 callbacks_.TriggerDeferred();
383}
384
385void DcSctpSocket::CloseConnectionBecauseOfTooManyTransmissionErrors() {
Victor Boivieabf61882021-08-12 15:57:49 +0200386 packet_sender_.Send(tcb_->PacketBuilder().Add(AbortChunk(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200387 true, Parameters::Builder()
388 .Add(UserInitiatedAbortCause("Too many retransmissions"))
389 .Build())));
390 InternalClose(ErrorKind::kTooManyRetries, "Too many retransmissions");
391}
392
393void DcSctpSocket::InternalClose(ErrorKind error, absl::string_view message) {
394 if (state_ != State::kClosed) {
395 t1_init_->Stop();
396 t1_cookie_->Stop();
397 t2_shutdown_->Stop();
398 tcb_ = nullptr;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200399
400 if (error == ErrorKind::kNoError) {
401 callbacks_.OnClosed();
402 } else {
403 callbacks_.OnAborted(error, message);
404 }
405 SetState(State::kClosed, message);
406 }
407 // This method's purpose is to abort/close and make it consistent by ensuring
408 // that e.g. all timers really are stopped.
409 RTC_DCHECK(IsConsistent());
410}
411
412SendStatus DcSctpSocket::Send(DcSctpMessage message,
413 const SendOptions& send_options) {
414 if (message.payload().empty()) {
415 callbacks_.OnError(ErrorKind::kProtocolViolation,
416 "Unable to send empty message");
417 return SendStatus::kErrorMessageEmpty;
418 }
419 if (message.payload().size() > options_.max_message_size) {
420 callbacks_.OnError(ErrorKind::kProtocolViolation,
421 "Unable to send too large message");
422 return SendStatus::kErrorMessageTooLarge;
423 }
424 if (state_ == State::kShutdownPending || state_ == State::kShutdownSent ||
425 state_ == State::kShutdownReceived || state_ == State::kShutdownAckSent) {
426 // https://tools.ietf.org/html/rfc4960#section-9.2
427 // "An endpoint should reject any new data request from its upper layer
428 // if it is in the SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED, or
429 // SHUTDOWN-ACK-SENT state."
430 callbacks_.OnError(ErrorKind::kWrongSequence,
431 "Unable to send message as the socket is shutting down");
432 return SendStatus::kErrorShuttingDown;
433 }
434 if (send_queue_.IsFull()) {
435 callbacks_.OnError(ErrorKind::kResourceExhaustion,
436 "Unable to send message as the send queue is full");
437 return SendStatus::kErrorResourceExhaustion;
438 }
439
Victor Boivied3b186e2021-05-05 16:22:29 +0200440 TimeMs now = callbacks_.TimeMillis();
Victor Boivied4716ea2021-08-09 12:26:32 +0200441 ++metrics_.tx_messages_count;
Victor Boivied3b186e2021-05-05 16:22:29 +0200442 send_queue_.Add(now, std::move(message), send_options);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200443 if (tcb_ != nullptr) {
Victor Boivied3b186e2021-05-05 16:22:29 +0200444 tcb_->SendBufferedPackets(now);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200445 }
446
447 RTC_DCHECK(IsConsistent());
448 callbacks_.TriggerDeferred();
449 return SendStatus::kSuccess;
450}
451
452ResetStreamsStatus DcSctpSocket::ResetStreams(
453 rtc::ArrayView<const StreamID> outgoing_streams) {
454 if (tcb_ == nullptr) {
455 callbacks_.OnError(ErrorKind::kWrongSequence,
456 "Can't reset streams as the socket is not connected");
457 return ResetStreamsStatus::kNotConnected;
458 }
459 if (!tcb_->capabilities().reconfig) {
460 callbacks_.OnError(ErrorKind::kUnsupportedOperation,
461 "Can't reset streams as the peer doesn't support it");
462 return ResetStreamsStatus::kNotSupported;
463 }
464
465 tcb_->stream_reset_handler().ResetStreams(outgoing_streams);
466 absl::optional<ReConfigChunk> reconfig =
467 tcb_->stream_reset_handler().MakeStreamResetRequest();
468 if (reconfig.has_value()) {
469 SctpPacket::Builder builder = tcb_->PacketBuilder();
470 builder.Add(*reconfig);
Victor Boivieabf61882021-08-12 15:57:49 +0200471 packet_sender_.Send(builder);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200472 }
473
474 RTC_DCHECK(IsConsistent());
475 callbacks_.TriggerDeferred();
476 return ResetStreamsStatus::kPerformed;
477}
478
479SocketState DcSctpSocket::state() const {
480 switch (state_) {
481 case State::kClosed:
482 return SocketState::kClosed;
483 case State::kCookieWait:
484 ABSL_FALLTHROUGH_INTENDED;
485 case State::kCookieEchoed:
486 return SocketState::kConnecting;
487 case State::kEstablished:
488 return SocketState::kConnected;
489 case State::kShutdownPending:
490 ABSL_FALLTHROUGH_INTENDED;
491 case State::kShutdownSent:
492 ABSL_FALLTHROUGH_INTENDED;
493 case State::kShutdownReceived:
494 ABSL_FALLTHROUGH_INTENDED;
495 case State::kShutdownAckSent:
496 return SocketState::kShuttingDown;
497 }
498}
499
Florent Castelli0810b052021-05-04 20:12:52 +0200500void DcSctpSocket::SetMaxMessageSize(size_t max_message_size) {
501 options_.max_message_size = max_message_size;
502}
503
Victor Boivie236ac502021-05-20 19:34:18 +0200504size_t DcSctpSocket::buffered_amount(StreamID stream_id) const {
505 return send_queue_.buffered_amount(stream_id);
506}
507
508size_t DcSctpSocket::buffered_amount_low_threshold(StreamID stream_id) const {
509 return send_queue_.buffered_amount_low_threshold(stream_id);
510}
511
512void DcSctpSocket::SetBufferedAmountLowThreshold(StreamID stream_id,
513 size_t bytes) {
514 send_queue_.SetBufferedAmountLowThreshold(stream_id, bytes);
515}
516
Victor Boivied4716ea2021-08-09 12:26:32 +0200517Metrics DcSctpSocket::GetMetrics() const {
518 Metrics metrics = metrics_;
519
520 if (tcb_ != nullptr) {
521 // Update the metrics with some stats that are extracted from
522 // sub-components.
523 metrics.cwnd_bytes = tcb_->cwnd();
524 metrics.srtt_ms = tcb_->current_srtt().value();
525 size_t packet_payload_size =
526 options_.mtu - SctpPacket::kHeaderSize - DataChunk::kHeaderSize;
527 metrics.unack_data_count =
528 tcb_->retransmission_queue().outstanding_items() +
529 (send_queue_.total_buffered_amount() + packet_payload_size - 1) /
530 packet_payload_size;
531 metrics.peer_rwnd_bytes = tcb_->retransmission_queue().rwnd();
532 }
533
534 return metrics;
535}
536
Victor Boivieb6580cc2021-04-08 09:56:59 +0200537void DcSctpSocket::MaybeSendShutdownOnPacketReceived(const SctpPacket& packet) {
538 if (state_ == State::kShutdownSent) {
539 bool has_data_chunk =
540 std::find_if(packet.descriptors().begin(), packet.descriptors().end(),
541 [](const SctpPacket::ChunkDescriptor& descriptor) {
542 return descriptor.type == DataChunk::kType;
543 }) != packet.descriptors().end();
544 if (has_data_chunk) {
545 // https://tools.ietf.org/html/rfc4960#section-9.2
546 // "While in the SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
547 // respond to each received packet containing one or more DATA chunks with
548 // a SHUTDOWN chunk and restart the T2-shutdown timer.""
549 SendShutdown();
550 t2_shutdown_->set_duration(tcb_->current_rto());
551 t2_shutdown_->Start();
552 }
553 }
554}
555
556bool DcSctpSocket::ValidatePacket(const SctpPacket& packet) {
557 const CommonHeader& header = packet.common_header();
558 VerificationTag my_verification_tag =
559 tcb_ != nullptr ? tcb_->my_verification_tag() : VerificationTag(0);
560
561 if (header.verification_tag == VerificationTag(0)) {
562 if (packet.descriptors().size() == 1 &&
563 packet.descriptors()[0].type == InitChunk::kType) {
564 // https://tools.ietf.org/html/rfc4960#section-8.5.1
565 // "When an endpoint receives an SCTP packet with the Verification Tag
566 // set to 0, it should verify that the packet contains only an INIT chunk.
567 // Otherwise, the receiver MUST silently discard the packet.""
568 return true;
569 }
570 callbacks_.OnError(
571 ErrorKind::kParseFailed,
572 "Only a single INIT chunk can be present in packets sent on "
573 "verification_tag = 0");
574 return false;
575 }
576
577 if (packet.descriptors().size() == 1 &&
578 packet.descriptors()[0].type == AbortChunk::kType) {
579 // https://tools.ietf.org/html/rfc4960#section-8.5.1
580 // "The receiver of an ABORT MUST accept the packet if the Verification
581 // Tag field of the packet matches its own tag and the T bit is not set OR
582 // if it is set to its peer's tag and the T bit is set in the Chunk Flags.
583 // Otherwise, the receiver MUST silently discard the packet and take no
584 // further action."
585 bool t_bit = (packet.descriptors()[0].flags & 0x01) != 0;
586 if (t_bit && tcb_ == nullptr) {
587 // Can't verify the tag - assume it's okey.
588 return true;
589 }
590 if ((!t_bit && header.verification_tag == my_verification_tag) ||
591 (t_bit && header.verification_tag == tcb_->peer_verification_tag())) {
592 return true;
593 }
594 callbacks_.OnError(ErrorKind::kParseFailed,
595 "ABORT chunk verification tag was wrong");
596 return false;
597 }
598
599 if (packet.descriptors()[0].type == InitAckChunk::kType) {
600 if (header.verification_tag == connect_params_.verification_tag) {
601 return true;
602 }
603 callbacks_.OnError(
604 ErrorKind::kParseFailed,
605 rtc::StringFormat(
606 "Packet has invalid verification tag: %08x, expected %08x",
607 *header.verification_tag, *connect_params_.verification_tag));
608 return false;
609 }
610
611 if (packet.descriptors()[0].type == CookieEchoChunk::kType) {
612 // Handled in chunk handler (due to RFC 4960, section 5.2.4).
613 return true;
614 }
615
616 if (packet.descriptors().size() == 1 &&
617 packet.descriptors()[0].type == ShutdownCompleteChunk::kType) {
618 // https://tools.ietf.org/html/rfc4960#section-8.5.1
619 // "The receiver of a SHUTDOWN COMPLETE shall accept the packet if the
620 // Verification Tag field of the packet matches its own tag and the T bit is
621 // not set OR if it is set to its peer's tag and the T bit is set in the
622 // Chunk Flags. Otherwise, the receiver MUST silently discard the packet
623 // and take no further action."
624 bool t_bit = (packet.descriptors()[0].flags & 0x01) != 0;
625 if (t_bit && tcb_ == nullptr) {
626 // Can't verify the tag - assume it's okey.
627 return true;
628 }
629 if ((!t_bit && header.verification_tag == my_verification_tag) ||
630 (t_bit && header.verification_tag == tcb_->peer_verification_tag())) {
631 return true;
632 }
633 callbacks_.OnError(ErrorKind::kParseFailed,
634 "SHUTDOWN_COMPLETE chunk verification tag was wrong");
635 return false;
636 }
637
638 // https://tools.ietf.org/html/rfc4960#section-8.5
639 // "When receiving an SCTP packet, the endpoint MUST ensure that the value
640 // in the Verification Tag field of the received SCTP packet matches its own
641 // tag. If the received Verification Tag value does not match the receiver's
642 // own tag value, the receiver shall silently discard the packet and shall not
643 // process it any further..."
644 if (header.verification_tag == my_verification_tag) {
645 return true;
646 }
647
648 callbacks_.OnError(
649 ErrorKind::kParseFailed,
650 rtc::StringFormat(
651 "Packet has invalid verification tag: %08x, expected %08x",
652 *header.verification_tag, *my_verification_tag));
653 return false;
654}
655
656void DcSctpSocket::HandleTimeout(TimeoutID timeout_id) {
657 timer_manager_.HandleTimeout(timeout_id);
658
659 if (tcb_ != nullptr && tcb_->HasTooManyTxErrors()) {
660 // Tearing down the TCB has to be done outside the handlers.
661 CloseConnectionBecauseOfTooManyTransmissionErrors();
662 }
663
664 RTC_DCHECK(IsConsistent());
665 callbacks_.TriggerDeferred();
666}
667
668void DcSctpSocket::ReceivePacket(rtc::ArrayView<const uint8_t> data) {
Victor Boivied4716ea2021-08-09 12:26:32 +0200669 ++metrics_.rx_packets_count;
670
Victor Boivieb6580cc2021-04-08 09:56:59 +0200671 if (packet_observer_ != nullptr) {
672 packet_observer_->OnReceivedPacket(callbacks_.TimeMillis(), data);
673 }
674
675 absl::optional<SctpPacket> packet =
676 SctpPacket::Parse(data, options_.disable_checksum_verification);
677 if (!packet.has_value()) {
678 // https://tools.ietf.org/html/rfc4960#section-6.8
679 // "The default procedure for handling invalid SCTP packets is to
680 // silently discard them."
681 callbacks_.OnError(ErrorKind::kParseFailed,
682 "Failed to parse received SCTP packet");
683 RTC_DCHECK(IsConsistent());
684 callbacks_.TriggerDeferred();
685 return;
686 }
687
688 if (RTC_DLOG_IS_ON) {
689 for (const auto& descriptor : packet->descriptors()) {
690 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received "
691 << DebugConvertChunkToString(descriptor.data);
692 }
693 }
694
695 if (!ValidatePacket(*packet)) {
696 RTC_DLOG(LS_VERBOSE) << log_prefix()
697 << "Packet failed verification tag check - dropping";
698 RTC_DCHECK(IsConsistent());
699 callbacks_.TriggerDeferred();
700 return;
701 }
702
703 MaybeSendShutdownOnPacketReceived(*packet);
704
705 for (const auto& descriptor : packet->descriptors()) {
706 if (!Dispatch(packet->common_header(), descriptor)) {
707 break;
708 }
709 }
710
711 if (tcb_ != nullptr) {
712 tcb_->data_tracker().ObservePacketEnd();
713 tcb_->MaybeSendSack();
714 }
715
716 RTC_DCHECK(IsConsistent());
717 callbacks_.TriggerDeferred();
718}
719
720void DcSctpSocket::DebugPrintOutgoing(rtc::ArrayView<const uint8_t> payload) {
721 auto packet = SctpPacket::Parse(payload);
722 RTC_DCHECK(packet.has_value());
723
724 for (const auto& desc : packet->descriptors()) {
725 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Sent "
726 << DebugConvertChunkToString(desc.data);
727 }
728}
729
730bool DcSctpSocket::Dispatch(const CommonHeader& header,
731 const SctpPacket::ChunkDescriptor& descriptor) {
732 switch (descriptor.type) {
733 case DataChunk::kType:
734 HandleData(header, descriptor);
735 break;
736 case InitChunk::kType:
737 HandleInit(header, descriptor);
738 break;
739 case InitAckChunk::kType:
740 HandleInitAck(header, descriptor);
741 break;
742 case SackChunk::kType:
743 HandleSack(header, descriptor);
744 break;
745 case HeartbeatRequestChunk::kType:
746 HandleHeartbeatRequest(header, descriptor);
747 break;
748 case HeartbeatAckChunk::kType:
749 HandleHeartbeatAck(header, descriptor);
750 break;
751 case AbortChunk::kType:
752 HandleAbort(header, descriptor);
753 break;
754 case ErrorChunk::kType:
755 HandleError(header, descriptor);
756 break;
757 case CookieEchoChunk::kType:
758 HandleCookieEcho(header, descriptor);
759 break;
760 case CookieAckChunk::kType:
761 HandleCookieAck(header, descriptor);
762 break;
763 case ShutdownChunk::kType:
764 HandleShutdown(header, descriptor);
765 break;
766 case ShutdownAckChunk::kType:
767 HandleShutdownAck(header, descriptor);
768 break;
769 case ShutdownCompleteChunk::kType:
770 HandleShutdownComplete(header, descriptor);
771 break;
772 case ReConfigChunk::kType:
773 HandleReconfig(header, descriptor);
774 break;
775 case ForwardTsnChunk::kType:
776 HandleForwardTsn(header, descriptor);
777 break;
778 case IDataChunk::kType:
779 HandleIData(header, descriptor);
780 break;
781 case IForwardTsnChunk::kType:
782 HandleForwardTsn(header, descriptor);
783 break;
784 default:
785 return HandleUnrecognizedChunk(descriptor);
786 }
787 return true;
788}
789
790bool DcSctpSocket::HandleUnrecognizedChunk(
791 const SctpPacket::ChunkDescriptor& descriptor) {
792 bool report_as_error = (descriptor.type & 0x40) != 0;
793 bool continue_processing = (descriptor.type & 0x80) != 0;
794 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received unknown chunk: "
795 << static_cast<int>(descriptor.type);
796 if (report_as_error) {
797 rtc::StringBuilder sb;
798 sb << "Received unknown chunk of type: "
799 << static_cast<int>(descriptor.type) << " with report-error bit set";
800 callbacks_.OnError(ErrorKind::kParseFailed, sb.str());
801 RTC_DLOG(LS_VERBOSE)
802 << log_prefix()
803 << "Unknown chunk, with type indicating it should be reported.";
804
805 // https://tools.ietf.org/html/rfc4960#section-3.2
806 // "... report in an ERROR chunk using the 'Unrecognized Chunk Type'
807 // cause."
808 if (tcb_ != nullptr) {
809 // Need TCB - this chunk must be sent with a correct verification tag.
Victor Boivieabf61882021-08-12 15:57:49 +0200810 packet_sender_.Send(tcb_->PacketBuilder().Add(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200811 ErrorChunk(Parameters::Builder()
812 .Add(UnrecognizedChunkTypeCause(std::vector<uint8_t>(
813 descriptor.data.begin(), descriptor.data.end())))
814 .Build())));
815 }
816 }
817 if (!continue_processing) {
818 // https://tools.ietf.org/html/rfc4960#section-3.2
819 // "Stop processing this SCTP packet and discard it, do not process any
820 // further chunks within it."
821 RTC_DLOG(LS_VERBOSE) << log_prefix()
822 << "Unknown chunk, with type indicating not to "
823 "process any further chunks";
824 }
825
826 return continue_processing;
827}
828
829absl::optional<DurationMs> DcSctpSocket::OnInitTimerExpiry() {
830 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t1_init_->name()
831 << " has expired: " << t1_init_->expiration_count()
Victor Boivie9680d292021-08-30 10:23:49 +0200832 << "/" << t1_init_->options().max_restarts.value_or(-1);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200833 RTC_DCHECK(state_ == State::kCookieWait);
834
835 if (t1_init_->is_running()) {
836 SendInit();
837 } else {
838 InternalClose(ErrorKind::kTooManyRetries, "No INIT_ACK received");
839 }
840 RTC_DCHECK(IsConsistent());
841 return absl::nullopt;
842}
843
844absl::optional<DurationMs> DcSctpSocket::OnCookieTimerExpiry() {
845 // https://tools.ietf.org/html/rfc4960#section-4
846 // "If the T1-cookie timer expires, the endpoint MUST retransmit COOKIE
847 // ECHO and restart the T1-cookie timer without changing state. This MUST
848 // be repeated up to 'Max.Init.Retransmits' times. After that, the endpoint
849 // MUST abort the initialization process and report the error to the SCTP
850 // user."
851 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t1_cookie_->name()
852 << " has expired: " << t1_cookie_->expiration_count()
Victor Boivie9680d292021-08-30 10:23:49 +0200853 << "/"
854 << t1_cookie_->options().max_restarts.value_or(-1);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200855
856 RTC_DCHECK(state_ == State::kCookieEchoed);
857
858 if (t1_cookie_->is_running()) {
Victor Boiviec20f1562021-06-16 12:52:42 +0200859 tcb_->SendBufferedPackets(callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +0200860 } else {
861 InternalClose(ErrorKind::kTooManyRetries, "No COOKIE_ACK received");
862 }
863
864 RTC_DCHECK(IsConsistent());
865 return absl::nullopt;
866}
867
868absl::optional<DurationMs> DcSctpSocket::OnShutdownTimerExpiry() {
869 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Timer " << t2_shutdown_->name()
870 << " has expired: " << t2_shutdown_->expiration_count()
Victor Boivie9680d292021-08-30 10:23:49 +0200871 << "/"
872 << t2_shutdown_->options().max_restarts.value_or(-1);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200873
Victor Boivie914925f2021-05-07 11:22:50 +0200874 if (!t2_shutdown_->is_running()) {
Victor Boivieb6580cc2021-04-08 09:56:59 +0200875 // https://tools.ietf.org/html/rfc4960#section-9.2
876 // "An endpoint should limit the number of retransmissions of the SHUTDOWN
877 // chunk to the protocol parameter 'Association.Max.Retrans'. If this
878 // threshold is exceeded, the endpoint should destroy the TCB..."
879
Victor Boivieabf61882021-08-12 15:57:49 +0200880 packet_sender_.Send(tcb_->PacketBuilder().Add(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200881 AbortChunk(true, Parameters::Builder()
882 .Add(UserInitiatedAbortCause(
883 "Too many retransmissions of SHUTDOWN"))
884 .Build())));
885
886 InternalClose(ErrorKind::kTooManyRetries, "No SHUTDOWN_ACK received");
Victor Boivie914925f2021-05-07 11:22:50 +0200887 RTC_DCHECK(IsConsistent());
888 return absl::nullopt;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200889 }
Victor Boivie914925f2021-05-07 11:22:50 +0200890
891 // https://tools.ietf.org/html/rfc4960#section-9.2
892 // "If the timer expires, the endpoint must resend the SHUTDOWN with the
893 // updated last sequential TSN received from its peer."
894 SendShutdown();
Victor Boivieb6580cc2021-04-08 09:56:59 +0200895 RTC_DCHECK(IsConsistent());
896 return tcb_->current_rto();
897}
898
Victor Boivieabf61882021-08-12 15:57:49 +0200899void DcSctpSocket::OnSentPacket(rtc::ArrayView<const uint8_t> packet,
900 SendPacketStatus status) {
901 // The packet observer is invoked even if the packet was failed to be sent, to
902 // indicate an attempt was made.
Victor Boivieb6580cc2021-04-08 09:56:59 +0200903 if (packet_observer_ != nullptr) {
Victor Boivieabf61882021-08-12 15:57:49 +0200904 packet_observer_->OnSentPacket(callbacks_.TimeMillis(), packet);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200905 }
Victor Boivieabf61882021-08-12 15:57:49 +0200906
907 if (status == SendPacketStatus::kSuccess) {
908 if (RTC_DLOG_IS_ON) {
909 DebugPrintOutgoing(packet);
910 }
911
912 // The heartbeat interval timer is restarted for every sent packet, to
913 // fire when the outgoing channel is inactive.
914 if (tcb_ != nullptr) {
915 tcb_->heartbeat_handler().RestartTimer();
916 }
917
918 ++metrics_.tx_packets_count;
919 }
Victor Boivieb6580cc2021-04-08 09:56:59 +0200920}
921
922bool DcSctpSocket::ValidateHasTCB() {
923 if (tcb_ != nullptr) {
924 return true;
925 }
926
927 callbacks_.OnError(
928 ErrorKind::kNotConnected,
929 "Received unexpected commands on socket that is not connected");
930 return false;
931}
932
933void DcSctpSocket::ReportFailedToParseChunk(int chunk_type) {
934 rtc::StringBuilder sb;
935 sb << "Failed to parse chunk of type: " << chunk_type;
936 callbacks_.OnError(ErrorKind::kParseFailed, sb.str());
937}
938
939void DcSctpSocket::HandleData(const CommonHeader& header,
940 const SctpPacket::ChunkDescriptor& descriptor) {
941 absl::optional<DataChunk> chunk = DataChunk::Parse(descriptor.data);
942 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
943 HandleDataCommon(*chunk);
944 }
945}
946
947void DcSctpSocket::HandleIData(const CommonHeader& header,
948 const SctpPacket::ChunkDescriptor& descriptor) {
949 absl::optional<IDataChunk> chunk = IDataChunk::Parse(descriptor.data);
950 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
951 HandleDataCommon(*chunk);
952 }
953}
954
955void DcSctpSocket::HandleDataCommon(AnyDataChunk& chunk) {
956 TSN tsn = chunk.tsn();
957 AnyDataChunk::ImmediateAckFlag immediate_ack = chunk.options().immediate_ack;
958 Data data = std::move(chunk).extract();
959
960 if (data.payload.empty()) {
961 // Empty DATA chunks are illegal.
Victor Boivieabf61882021-08-12 15:57:49 +0200962 packet_sender_.Send(tcb_->PacketBuilder().Add(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200963 ErrorChunk(Parameters::Builder().Add(NoUserDataCause(tsn)).Build())));
964 callbacks_.OnError(ErrorKind::kProtocolViolation,
965 "Received DATA chunk with no user data");
966 return;
967 }
968
969 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Handle DATA, queue_size="
970 << tcb_->reassembly_queue().queued_bytes()
971 << ", water_mark="
972 << tcb_->reassembly_queue().watermark_bytes()
973 << ", full=" << tcb_->reassembly_queue().is_full()
974 << ", above="
975 << tcb_->reassembly_queue().is_above_watermark();
976
977 if (tcb_->reassembly_queue().is_full()) {
978 // If the reassembly queue is full, there is nothing that can be done. The
979 // specification only allows dropping gap-ack-blocks, and that's not
980 // likely to help as the socket has been trying to fill gaps since the
981 // watermark was reached.
Victor Boivieabf61882021-08-12 15:57:49 +0200982 packet_sender_.Send(tcb_->PacketBuilder().Add(AbortChunk(
Victor Boivieb6580cc2021-04-08 09:56:59 +0200983 true, Parameters::Builder().Add(OutOfResourceErrorCause()).Build())));
984 InternalClose(ErrorKind::kResourceExhaustion,
985 "Reassembly Queue is exhausted");
986 return;
987 }
988
989 if (tcb_->reassembly_queue().is_above_watermark()) {
990 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Is above high watermark";
991 // If the reassembly queue is above its high watermark, only accept data
992 // chunks that increase its cumulative ack tsn in an attempt to fill gaps
993 // to deliver messages.
994 if (!tcb_->data_tracker().will_increase_cum_ack_tsn(tsn)) {
995 RTC_DLOG(LS_VERBOSE) << log_prefix()
996 << "Rejected data because of exceeding watermark";
997 tcb_->data_tracker().ForceImmediateSack();
998 return;
999 }
1000 }
1001
1002 if (!tcb_->data_tracker().IsTSNValid(tsn)) {
1003 RTC_DLOG(LS_VERBOSE) << log_prefix()
1004 << "Rejected data because of failing TSN validity";
1005 return;
1006 }
1007
1008 tcb_->data_tracker().Observe(tsn, immediate_ack);
1009 tcb_->reassembly_queue().MaybeResetStreamsDeferred(
1010 tcb_->data_tracker().last_cumulative_acked_tsn());
1011 tcb_->reassembly_queue().Add(tsn, std::move(data));
1012 DeliverReassembledMessages();
1013}
1014
1015void DcSctpSocket::HandleInit(const CommonHeader& header,
1016 const SctpPacket::ChunkDescriptor& descriptor) {
1017 absl::optional<InitChunk> chunk = InitChunk::Parse(descriptor.data);
1018 if (!ValidateParseSuccess(chunk)) {
1019 return;
1020 }
1021
1022 if (chunk->initiate_tag() == VerificationTag(0) ||
1023 chunk->nbr_outbound_streams() == 0 || chunk->nbr_inbound_streams() == 0) {
1024 // https://tools.ietf.org/html/rfc4960#section-3.3.2
1025 // "If the value of the Initiate Tag in a received INIT chunk is found
1026 // to be 0, the receiver MUST treat it as an error and close the
1027 // association by transmitting an ABORT."
1028
1029 // "A receiver of an INIT with the OS value set to 0 SHOULD abort the
1030 // association."
1031
1032 // "A receiver of an INIT with the MIS value of 0 SHOULD abort the
1033 // association."
1034
Victor Boivieabf61882021-08-12 15:57:49 +02001035 packet_sender_.Send(
1036 SctpPacket::Builder(VerificationTag(0), options_)
1037 .Add(AbortChunk(
1038 /*filled_in_verification_tag=*/false,
1039 Parameters::Builder()
1040 .Add(ProtocolViolationCause("INIT malformed"))
1041 .Build())));
Victor Boivieb6580cc2021-04-08 09:56:59 +02001042 InternalClose(ErrorKind::kProtocolViolation, "Received invalid INIT");
1043 return;
1044 }
1045
1046 if (state_ == State::kShutdownAckSent) {
1047 // https://tools.ietf.org/html/rfc4960#section-9.2
1048 // "If an endpoint is in the SHUTDOWN-ACK-SENT state and receives an
1049 // INIT chunk (e.g., if the SHUTDOWN COMPLETE was lost) with source and
1050 // destination transport addresses (either in the IP addresses or in the
1051 // INIT chunk) that belong to this association, it should discard the INIT
1052 // chunk and retransmit the SHUTDOWN ACK chunk."
1053 RTC_DLOG(LS_VERBOSE) << log_prefix()
1054 << "Received Init indicating lost ShutdownComplete";
1055 SendShutdownAck();
1056 return;
1057 }
1058
1059 TieTag tie_tag(0);
1060 if (state_ == State::kClosed) {
1061 RTC_DLOG(LS_VERBOSE) << log_prefix()
1062 << "Received Init in closed state (normal)";
1063
1064 MakeConnectionParameters();
1065 } else if (state_ == State::kCookieWait || state_ == State::kCookieEchoed) {
1066 // https://tools.ietf.org/html/rfc4960#section-5.2.1
1067 // "This usually indicates an initialization collision, i.e., each
1068 // endpoint is attempting, at about the same time, to establish an
1069 // association with the other endpoint. Upon receipt of an INIT in the
1070 // COOKIE-WAIT state, an endpoint MUST respond with an INIT ACK using the
1071 // same parameters it sent in its original INIT chunk (including its
1072 // Initiate Tag, unchanged). When responding, the endpoint MUST send the
1073 // INIT ACK back to the same address that the original INIT (sent by this
1074 // endpoint) was sent."
1075 RTC_DLOG(LS_VERBOSE) << log_prefix()
1076 << "Received Init indicating simultaneous connections";
1077 } else {
1078 RTC_DCHECK(tcb_ != nullptr);
1079 // https://tools.ietf.org/html/rfc4960#section-5.2.2
1080 // "The outbound SCTP packet containing this INIT ACK MUST carry a
1081 // Verification Tag value equal to the Initiate Tag found in the
1082 // unexpected INIT. And the INIT ACK MUST contain a new Initiate Tag
1083 // (randomly generated; see Section 5.3.1). Other parameters for the
1084 // endpoint SHOULD be copied from the existing parameters of the
1085 // association (e.g., number of outbound streams) into the INIT ACK and
1086 // cookie."
1087 RTC_DLOG(LS_VERBOSE) << log_prefix()
1088 << "Received Init indicating restarted connection";
1089 // Create a new verification tag - different from the previous one.
1090 for (int tries = 0; tries < 10; ++tries) {
1091 connect_params_.verification_tag = VerificationTag(
1092 callbacks_.GetRandomInt(kMinVerificationTag, kMaxVerificationTag));
1093 if (connect_params_.verification_tag != tcb_->my_verification_tag()) {
1094 break;
1095 }
1096 }
1097
1098 // Make the initial TSN make a large jump, so that there is no overlap
1099 // with the old and new association.
1100 connect_params_.initial_tsn =
1101 TSN(*tcb_->retransmission_queue().next_tsn() + 1000000);
1102 tie_tag = tcb_->tie_tag();
1103 }
1104
1105 RTC_DLOG(LS_VERBOSE)
1106 << log_prefix()
1107 << rtc::StringFormat(
1108 "Proceeding with connection. my_verification_tag=%08x, "
1109 "my_initial_tsn=%u, peer_verification_tag=%08x, "
1110 "peer_initial_tsn=%u",
1111 *connect_params_.verification_tag, *connect_params_.initial_tsn,
1112 *chunk->initiate_tag(), *chunk->initial_tsn());
1113
1114 Capabilities capabilities = GetCapabilities(options_, chunk->parameters());
1115
1116 SctpPacket::Builder b(chunk->initiate_tag(), options_);
1117 Parameters::Builder params_builder =
1118 Parameters::Builder().Add(StateCookieParameter(
1119 StateCookie(chunk->initiate_tag(), chunk->initial_tsn(),
1120 chunk->a_rwnd(), tie_tag, capabilities)
1121 .Serialize()));
1122 AddCapabilityParameters(options_, params_builder);
1123
1124 InitAckChunk init_ack(/*initiate_tag=*/connect_params_.verification_tag,
1125 options_.max_receiver_window_buffer_size,
1126 options_.announced_maximum_outgoing_streams,
1127 options_.announced_maximum_incoming_streams,
1128 connect_params_.initial_tsn, params_builder.Build());
1129 b.Add(init_ack);
Victor Boivieabf61882021-08-12 15:57:49 +02001130 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001131}
1132
Victor Boivieb6580cc2021-04-08 09:56:59 +02001133void DcSctpSocket::HandleInitAck(
1134 const CommonHeader& header,
1135 const SctpPacket::ChunkDescriptor& descriptor) {
1136 absl::optional<InitAckChunk> chunk = InitAckChunk::Parse(descriptor.data);
1137 if (!ValidateParseSuccess(chunk)) {
1138 return;
1139 }
1140
1141 if (state_ != State::kCookieWait) {
1142 // https://tools.ietf.org/html/rfc4960#section-5.2.3
1143 // "If an INIT ACK is received by an endpoint in any state other than
1144 // the COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk."
1145 RTC_DLOG(LS_VERBOSE) << log_prefix()
1146 << "Received INIT_ACK in unexpected state";
1147 return;
1148 }
1149
1150 auto cookie = chunk->parameters().get<StateCookieParameter>();
1151 if (!cookie.has_value()) {
Victor Boivieabf61882021-08-12 15:57:49 +02001152 packet_sender_.Send(
1153 SctpPacket::Builder(connect_params_.verification_tag, options_)
1154 .Add(AbortChunk(
1155 /*filled_in_verification_tag=*/false,
1156 Parameters::Builder()
1157 .Add(ProtocolViolationCause("INIT-ACK malformed"))
1158 .Build())));
Victor Boivieb6580cc2021-04-08 09:56:59 +02001159 InternalClose(ErrorKind::kProtocolViolation,
1160 "InitAck chunk doesn't contain a cookie");
1161 return;
1162 }
1163 Capabilities capabilities = GetCapabilities(options_, chunk->parameters());
1164 t1_init_->Stop();
1165
Victor Boivief4fa1662021-09-24 23:01:21 +02001166 peer_implementation_ = DeterminePeerImplementation(cookie->data());
1167
Victor Boivieb6580cc2021-04-08 09:56:59 +02001168 tcb_ = std::make_unique<TransmissionControlBlock>(
1169 timer_manager_, log_prefix_, options_, capabilities, callbacks_,
1170 send_queue_, connect_params_.verification_tag,
1171 connect_params_.initial_tsn, chunk->initiate_tag(), chunk->initial_tsn(),
Victor Boivieabf61882021-08-12 15:57:49 +02001172 chunk->a_rwnd(), MakeTieTag(callbacks_), packet_sender_,
1173 [this]() { return state_ == State::kEstablished; });
Victor Boivieb6580cc2021-04-08 09:56:59 +02001174 RTC_DLOG(LS_VERBOSE) << log_prefix()
1175 << "Created peer TCB: " << tcb_->ToString();
1176
1177 SetState(State::kCookieEchoed, "INIT_ACK received");
1178
1179 // The connection isn't fully established just yet.
Victor Boiviec20f1562021-06-16 12:52:42 +02001180 tcb_->SetCookieEchoChunk(CookieEchoChunk(cookie->data()));
1181 tcb_->SendBufferedPackets(callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +02001182 t1_cookie_->Start();
1183}
1184
1185void DcSctpSocket::HandleCookieEcho(
1186 const CommonHeader& header,
1187 const SctpPacket::ChunkDescriptor& descriptor) {
1188 absl::optional<CookieEchoChunk> chunk =
1189 CookieEchoChunk::Parse(descriptor.data);
1190 if (!ValidateParseSuccess(chunk)) {
1191 return;
1192 }
1193
1194 absl::optional<StateCookie> cookie =
1195 StateCookie::Deserialize(chunk->cookie());
1196 if (!cookie.has_value()) {
1197 callbacks_.OnError(ErrorKind::kParseFailed, "Failed to parse state cookie");
1198 return;
1199 }
1200
1201 if (tcb_ != nullptr) {
1202 if (!HandleCookieEchoWithTCB(header, *cookie)) {
1203 return;
1204 }
1205 } else {
1206 if (header.verification_tag != connect_params_.verification_tag) {
1207 callbacks_.OnError(
1208 ErrorKind::kParseFailed,
1209 rtc::StringFormat(
1210 "Received CookieEcho with invalid verification tag: %08x, "
1211 "expected %08x",
1212 *header.verification_tag, *connect_params_.verification_tag));
1213 return;
1214 }
1215 }
1216
1217 // The init timer can be running on simultaneous connections.
1218 t1_init_->Stop();
1219 t1_cookie_->Stop();
1220 if (state_ != State::kEstablished) {
Victor Boiviec20f1562021-06-16 12:52:42 +02001221 if (tcb_ != nullptr) {
1222 tcb_->ClearCookieEchoChunk();
1223 }
Victor Boivieb6580cc2021-04-08 09:56:59 +02001224 SetState(State::kEstablished, "COOKIE_ECHO received");
1225 callbacks_.OnConnected();
1226 }
1227
1228 if (tcb_ == nullptr) {
1229 tcb_ = std::make_unique<TransmissionControlBlock>(
1230 timer_manager_, log_prefix_, options_, cookie->capabilities(),
1231 callbacks_, send_queue_, connect_params_.verification_tag,
1232 connect_params_.initial_tsn, cookie->initiate_tag(),
1233 cookie->initial_tsn(), cookie->a_rwnd(), MakeTieTag(callbacks_),
Victor Boivieabf61882021-08-12 15:57:49 +02001234 packet_sender_, [this]() { return state_ == State::kEstablished; });
Victor Boivieb6580cc2021-04-08 09:56:59 +02001235 RTC_DLOG(LS_VERBOSE) << log_prefix()
1236 << "Created peer TCB: " << tcb_->ToString();
1237 }
1238
1239 SctpPacket::Builder b = tcb_->PacketBuilder();
1240 b.Add(CookieAckChunk());
1241
1242 // https://tools.ietf.org/html/rfc4960#section-5.1
1243 // "A COOKIE ACK chunk may be bundled with any pending DATA chunks (and/or
1244 // SACK chunks), but the COOKIE ACK chunk MUST be the first chunk in the
1245 // packet."
Victor Boivied3b186e2021-05-05 16:22:29 +02001246 tcb_->SendBufferedPackets(b, callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +02001247}
1248
1249bool DcSctpSocket::HandleCookieEchoWithTCB(const CommonHeader& header,
1250 const StateCookie& cookie) {
1251 RTC_DLOG(LS_VERBOSE) << log_prefix()
1252 << "Handling CookieEchoChunk with TCB. local_tag="
1253 << *tcb_->my_verification_tag()
1254 << ", peer_tag=" << *header.verification_tag
1255 << ", tcb_tag=" << *tcb_->peer_verification_tag()
1256 << ", cookie_tag=" << *cookie.initiate_tag()
1257 << ", local_tie_tag=" << *tcb_->tie_tag()
1258 << ", peer_tie_tag=" << *cookie.tie_tag();
1259 // https://tools.ietf.org/html/rfc4960#section-5.2.4
1260 // "Handle a COOKIE ECHO when a TCB Exists"
1261 if (header.verification_tag != tcb_->my_verification_tag() &&
1262 tcb_->peer_verification_tag() != cookie.initiate_tag() &&
1263 cookie.tie_tag() == tcb_->tie_tag()) {
1264 // "A) In this case, the peer may have restarted."
1265 if (state_ == State::kShutdownAckSent) {
1266 // "If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
1267 // that the peer has restarted ... it MUST NOT set up a new association
1268 // but instead resend the SHUTDOWN ACK and send an ERROR chunk with a
1269 // "Cookie Received While Shutting Down" error cause to its peer."
1270 SctpPacket::Builder b(cookie.initiate_tag(), options_);
1271 b.Add(ShutdownAckChunk());
1272 b.Add(ErrorChunk(Parameters::Builder()
1273 .Add(CookieReceivedWhileShuttingDownCause())
1274 .Build()));
Victor Boivieabf61882021-08-12 15:57:49 +02001275 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001276 callbacks_.OnError(ErrorKind::kWrongSequence,
1277 "Received COOKIE-ECHO while shutting down");
1278 return false;
1279 }
1280
1281 RTC_DLOG(LS_VERBOSE) << log_prefix()
1282 << "Received COOKIE-ECHO indicating a restarted peer";
1283
1284 // If a message was partly sent, and the peer restarted, resend it in
1285 // full by resetting the send queue.
1286 send_queue_.Reset();
1287 tcb_ = nullptr;
1288 callbacks_.OnConnectionRestarted();
1289 } else if (header.verification_tag == tcb_->my_verification_tag() &&
1290 tcb_->peer_verification_tag() != cookie.initiate_tag()) {
1291 // TODO(boivie): Handle the peer_tag == 0?
1292 // "B) In this case, both sides may be attempting to start an
1293 // association at about the same time, but the peer endpoint started its
1294 // INIT after responding to the local endpoint's INIT."
1295 RTC_DLOG(LS_VERBOSE)
1296 << log_prefix()
1297 << "Received COOKIE-ECHO indicating simultaneous connections";
1298 tcb_ = nullptr;
1299 } else if (header.verification_tag != tcb_->my_verification_tag() &&
1300 tcb_->peer_verification_tag() == cookie.initiate_tag() &&
1301 cookie.tie_tag() == TieTag(0)) {
1302 // "C) In this case, the local endpoint's cookie has arrived late.
1303 // Before it arrived, the local endpoint sent an INIT and received an
1304 // INIT ACK and finally sent a COOKIE ECHO with the peer's same tag but
1305 // a new tag of its own. The cookie should be silently discarded. The
1306 // endpoint SHOULD NOT change states and should leave any timers
1307 // running."
1308 RTC_DLOG(LS_VERBOSE)
1309 << log_prefix()
1310 << "Received COOKIE-ECHO indicating a late COOKIE-ECHO. Discarding";
1311 return false;
1312 } else if (header.verification_tag == tcb_->my_verification_tag() &&
1313 tcb_->peer_verification_tag() == cookie.initiate_tag()) {
1314 // "D) When both local and remote tags match, the endpoint should enter
1315 // the ESTABLISHED state, if it is in the COOKIE-ECHOED state. It
1316 // should stop any cookie timer that may be running and send a COOKIE
1317 // ACK."
1318 RTC_DLOG(LS_VERBOSE)
1319 << log_prefix()
1320 << "Received duplicate COOKIE-ECHO, probably because of peer not "
1321 "receiving COOKIE-ACK and retransmitting COOKIE-ECHO. Continuing.";
1322 }
1323 return true;
1324}
1325
1326void DcSctpSocket::HandleCookieAck(
1327 const CommonHeader& header,
1328 const SctpPacket::ChunkDescriptor& descriptor) {
1329 absl::optional<CookieAckChunk> chunk = CookieAckChunk::Parse(descriptor.data);
1330 if (!ValidateParseSuccess(chunk)) {
1331 return;
1332 }
1333
1334 if (state_ != State::kCookieEchoed) {
1335 // https://tools.ietf.org/html/rfc4960#section-5.2.5
1336 // "At any state other than COOKIE-ECHOED, an endpoint should silently
1337 // discard a received COOKIE ACK chunk."
1338 RTC_DLOG(LS_VERBOSE) << log_prefix()
1339 << "Received COOKIE_ACK not in COOKIE_ECHOED state";
1340 return;
1341 }
1342
1343 // RFC 4960, Errata ID: 4400
1344 t1_cookie_->Stop();
Victor Boiviec20f1562021-06-16 12:52:42 +02001345 tcb_->ClearCookieEchoChunk();
Victor Boivieb6580cc2021-04-08 09:56:59 +02001346 SetState(State::kEstablished, "COOKIE_ACK received");
Victor Boivied3b186e2021-05-05 16:22:29 +02001347 tcb_->SendBufferedPackets(callbacks_.TimeMillis());
Victor Boivieb6580cc2021-04-08 09:56:59 +02001348 callbacks_.OnConnected();
1349}
1350
1351void DcSctpSocket::DeliverReassembledMessages() {
1352 if (tcb_->reassembly_queue().HasMessages()) {
1353 for (auto& message : tcb_->reassembly_queue().FlushMessages()) {
Victor Boivied4716ea2021-08-09 12:26:32 +02001354 ++metrics_.rx_messages_count;
Victor Boivieb6580cc2021-04-08 09:56:59 +02001355 callbacks_.OnMessageReceived(std::move(message));
1356 }
1357 }
1358}
1359
1360void DcSctpSocket::HandleSack(const CommonHeader& header,
1361 const SctpPacket::ChunkDescriptor& descriptor) {
1362 absl::optional<SackChunk> chunk = SackChunk::Parse(descriptor.data);
1363
1364 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
Victor Boivied3b186e2021-05-05 16:22:29 +02001365 TimeMs now = callbacks_.TimeMillis();
Victor Boivieb6580cc2021-04-08 09:56:59 +02001366 SackChunk sack = ChunkValidators::Clean(*std::move(chunk));
1367
Victor Boivied3b186e2021-05-05 16:22:29 +02001368 if (tcb_->retransmission_queue().HandleSack(now, sack)) {
Victor Boivieb6580cc2021-04-08 09:56:59 +02001369 MaybeSendShutdownOrAck();
1370 // Receiving an ACK will decrease outstanding bytes (maybe now below
1371 // cwnd?) or indicate packet loss that may result in sending FORWARD-TSN.
Victor Boivied3b186e2021-05-05 16:22:29 +02001372 tcb_->SendBufferedPackets(now);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001373 } else {
1374 RTC_DLOG(LS_VERBOSE) << log_prefix()
1375 << "Dropping out-of-order SACK with TSN "
1376 << *sack.cumulative_tsn_ack();
1377 }
1378 }
1379}
1380
1381void DcSctpSocket::HandleHeartbeatRequest(
1382 const CommonHeader& header,
1383 const SctpPacket::ChunkDescriptor& descriptor) {
1384 absl::optional<HeartbeatRequestChunk> chunk =
1385 HeartbeatRequestChunk::Parse(descriptor.data);
1386
1387 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1388 tcb_->heartbeat_handler().HandleHeartbeatRequest(*std::move(chunk));
1389 }
1390}
1391
1392void DcSctpSocket::HandleHeartbeatAck(
1393 const CommonHeader& header,
1394 const SctpPacket::ChunkDescriptor& descriptor) {
1395 absl::optional<HeartbeatAckChunk> chunk =
1396 HeartbeatAckChunk::Parse(descriptor.data);
1397
1398 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1399 tcb_->heartbeat_handler().HandleHeartbeatAck(*std::move(chunk));
1400 }
1401}
1402
1403void DcSctpSocket::HandleAbort(const CommonHeader& header,
1404 const SctpPacket::ChunkDescriptor& descriptor) {
1405 absl::optional<AbortChunk> chunk = AbortChunk::Parse(descriptor.data);
1406 if (ValidateParseSuccess(chunk)) {
1407 std::string error_string = ErrorCausesToString(chunk->error_causes());
1408 if (tcb_ == nullptr) {
1409 // https://tools.ietf.org/html/rfc4960#section-3.3.7
1410 // "If an endpoint receives an ABORT with a format error or no TCB is
1411 // found, it MUST silently discard it."
1412 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received ABORT (" << error_string
1413 << ") on a connection with no TCB. Ignoring";
1414 return;
1415 }
1416
1417 RTC_DLOG(LS_WARNING) << log_prefix() << "Received ABORT (" << error_string
1418 << ") - closing connection.";
1419 InternalClose(ErrorKind::kPeerReported, error_string);
1420 }
1421}
1422
1423void DcSctpSocket::HandleError(const CommonHeader& header,
1424 const SctpPacket::ChunkDescriptor& descriptor) {
1425 absl::optional<ErrorChunk> chunk = ErrorChunk::Parse(descriptor.data);
1426 if (ValidateParseSuccess(chunk)) {
1427 std::string error_string = ErrorCausesToString(chunk->error_causes());
1428 if (tcb_ == nullptr) {
1429 RTC_DLOG(LS_VERBOSE) << log_prefix() << "Received ERROR (" << error_string
1430 << ") on a connection with no TCB. Ignoring";
1431 return;
1432 }
1433
1434 RTC_DLOG(LS_WARNING) << log_prefix() << "Received ERROR: " << error_string;
1435 callbacks_.OnError(ErrorKind::kPeerReported,
1436 "Peer reported error: " + error_string);
1437 }
1438}
1439
1440void DcSctpSocket::HandleReconfig(
1441 const CommonHeader& header,
1442 const SctpPacket::ChunkDescriptor& descriptor) {
1443 absl::optional<ReConfigChunk> chunk = ReConfigChunk::Parse(descriptor.data);
1444 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1445 tcb_->stream_reset_handler().HandleReConfig(*std::move(chunk));
1446 }
1447}
1448
1449void DcSctpSocket::HandleShutdown(
1450 const CommonHeader& header,
1451 const SctpPacket::ChunkDescriptor& descriptor) {
1452 if (!ValidateParseSuccess(ShutdownChunk::Parse(descriptor.data))) {
1453 return;
1454 }
1455
1456 if (state_ == State::kClosed) {
1457 return;
1458 } else if (state_ == State::kCookieWait || state_ == State::kCookieEchoed) {
1459 // https://tools.ietf.org/html/rfc4960#section-9.2
1460 // "If a SHUTDOWN is received in the COOKIE-WAIT or COOKIE ECHOED state,
1461 // the SHUTDOWN chunk SHOULD be silently discarded."
1462 } else if (state_ == State::kShutdownSent) {
1463 // https://tools.ietf.org/html/rfc4960#section-9.2
1464 // "If an endpoint is in the SHUTDOWN-SENT state and receives a
1465 // SHUTDOWN chunk from its peer, the endpoint shall respond immediately
1466 // with a SHUTDOWN ACK to its peer, and move into the SHUTDOWN-ACK-SENT
1467 // state restarting its T2-shutdown timer."
1468 SendShutdownAck();
1469 SetState(State::kShutdownAckSent, "SHUTDOWN received");
Victor Boivie50a0b122021-05-06 21:07:49 +02001470 } else if (state_ == State::kShutdownAckSent) {
1471 // TODO(webrtc:12739): This condition should be removed and handled by the
1472 // next (state_ != State::kShutdownReceived).
1473 return;
Victor Boivieb6580cc2021-04-08 09:56:59 +02001474 } else if (state_ != State::kShutdownReceived) {
1475 RTC_DLOG(LS_VERBOSE) << log_prefix()
1476 << "Received SHUTDOWN - shutting down the socket";
1477 // https://tools.ietf.org/html/rfc4960#section-9.2
1478 // "Upon reception of the SHUTDOWN, the peer endpoint shall enter the
1479 // SHUTDOWN-RECEIVED state, stop accepting new data from its SCTP user,
1480 // and verify, by checking the Cumulative TSN Ack field of the chunk, that
1481 // all its outstanding DATA chunks have been received by the SHUTDOWN
1482 // sender."
1483 SetState(State::kShutdownReceived, "SHUTDOWN received");
1484 MaybeSendShutdownOrAck();
1485 }
1486}
1487
1488void DcSctpSocket::HandleShutdownAck(
1489 const CommonHeader& header,
1490 const SctpPacket::ChunkDescriptor& descriptor) {
1491 if (!ValidateParseSuccess(ShutdownAckChunk::Parse(descriptor.data))) {
1492 return;
1493 }
1494
1495 if (state_ == State::kShutdownSent || state_ == State::kShutdownAckSent) {
1496 // https://tools.ietf.org/html/rfc4960#section-9.2
1497 // "Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall stop
1498 // the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its peer, and
1499 // remove all record of the association."
1500
1501 // "If an endpoint is in the SHUTDOWN-ACK-SENT state and receives a
1502 // SHUTDOWN ACK, it shall stop the T2-shutdown timer, send a SHUTDOWN
1503 // COMPLETE chunk to its peer, and remove all record of the association."
1504
1505 SctpPacket::Builder b = tcb_->PacketBuilder();
1506 b.Add(ShutdownCompleteChunk(/*tag_reflected=*/false));
Victor Boivieabf61882021-08-12 15:57:49 +02001507 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001508 InternalClose(ErrorKind::kNoError, "");
1509 } else {
1510 // https://tools.ietf.org/html/rfc4960#section-8.5.1
1511 // "If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state
1512 // the procedures in Section 8.4 SHOULD be followed; in other words, it
1513 // should be treated as an Out Of The Blue packet."
1514
1515 // https://tools.ietf.org/html/rfc4960#section-8.4
1516 // "If the packet contains a SHUTDOWN ACK chunk, the receiver
1517 // should respond to the sender of the OOTB packet with a SHUTDOWN
1518 // COMPLETE. When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
1519 // packet must fill in the Verification Tag field of the outbound packet
1520 // with the Verification Tag received in the SHUTDOWN ACK and set the T
1521 // bit in the Chunk Flags to indicate that the Verification Tag is
1522 // reflected."
1523
1524 SctpPacket::Builder b(header.verification_tag, options_);
1525 b.Add(ShutdownCompleteChunk(/*tag_reflected=*/true));
Victor Boivieabf61882021-08-12 15:57:49 +02001526 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001527 }
1528}
1529
1530void DcSctpSocket::HandleShutdownComplete(
1531 const CommonHeader& header,
1532 const SctpPacket::ChunkDescriptor& descriptor) {
1533 if (!ValidateParseSuccess(ShutdownCompleteChunk::Parse(descriptor.data))) {
1534 return;
1535 }
1536
1537 if (state_ == State::kShutdownAckSent) {
1538 // https://tools.ietf.org/html/rfc4960#section-9.2
1539 // "Upon reception of the SHUTDOWN COMPLETE chunk, the endpoint will
1540 // verify that it is in the SHUTDOWN-ACK-SENT state; if it is not, the
1541 // chunk should be discarded. If the endpoint is in the SHUTDOWN-ACK-SENT
1542 // state, the endpoint should stop the T2-shutdown timer and remove all
1543 // knowledge of the association (and thus the association enters the
1544 // CLOSED state)."
1545 InternalClose(ErrorKind::kNoError, "");
1546 }
1547}
1548
1549void DcSctpSocket::HandleForwardTsn(
1550 const CommonHeader& header,
1551 const SctpPacket::ChunkDescriptor& descriptor) {
1552 absl::optional<ForwardTsnChunk> chunk =
1553 ForwardTsnChunk::Parse(descriptor.data);
1554 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1555 HandleForwardTsnCommon(*chunk);
1556 }
1557}
1558
1559void DcSctpSocket::HandleIForwardTsn(
1560 const CommonHeader& header,
1561 const SctpPacket::ChunkDescriptor& descriptor) {
1562 absl::optional<IForwardTsnChunk> chunk =
1563 IForwardTsnChunk::Parse(descriptor.data);
1564 if (ValidateParseSuccess(chunk) && ValidateHasTCB()) {
1565 HandleForwardTsnCommon(*chunk);
1566 }
1567}
1568
1569void DcSctpSocket::HandleForwardTsnCommon(const AnyForwardTsnChunk& chunk) {
1570 if (!tcb_->capabilities().partial_reliability) {
1571 SctpPacket::Builder b = tcb_->PacketBuilder();
1572 b.Add(AbortChunk(/*filled_in_verification_tag=*/true,
1573 Parameters::Builder()
1574 .Add(ProtocolViolationCause(
1575 "I-FORWARD-TSN received, but not indicated "
1576 "during connection establishment"))
1577 .Build()));
Victor Boivieabf61882021-08-12 15:57:49 +02001578 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001579
1580 callbacks_.OnError(ErrorKind::kProtocolViolation,
1581 "Received a FORWARD_TSN without announced peer support");
1582 return;
1583 }
1584 tcb_->data_tracker().HandleForwardTsn(chunk.new_cumulative_tsn());
1585 tcb_->reassembly_queue().Handle(chunk);
1586 // A forward TSN - for ordered streams - may allow messages to be
1587 // delivered.
1588 DeliverReassembledMessages();
1589
1590 // Processing a FORWARD_TSN might result in sending a SACK.
1591 tcb_->MaybeSendSack();
1592}
1593
1594void DcSctpSocket::MaybeSendShutdownOrAck() {
1595 if (tcb_->retransmission_queue().outstanding_bytes() != 0) {
1596 return;
1597 }
1598
1599 if (state_ == State::kShutdownPending) {
1600 // https://tools.ietf.org/html/rfc4960#section-9.2
1601 // "Once all its outstanding data has been acknowledged, the endpoint
1602 // shall send a SHUTDOWN chunk to its peer including in the Cumulative TSN
1603 // Ack field the last sequential TSN it has received from the peer. It
1604 // shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT
1605 // state.""
1606
1607 SendShutdown();
1608 t2_shutdown_->set_duration(tcb_->current_rto());
1609 t2_shutdown_->Start();
1610 SetState(State::kShutdownSent, "No more outstanding data");
1611 } else if (state_ == State::kShutdownReceived) {
1612 // https://tools.ietf.org/html/rfc4960#section-9.2
1613 // "If the receiver of the SHUTDOWN has no more outstanding DATA
1614 // chunks, the SHUTDOWN receiver MUST send a SHUTDOWN ACK and start a
1615 // T2-shutdown timer of its own, entering the SHUTDOWN-ACK-SENT state. If
1616 // the timer expires, the endpoint must resend the SHUTDOWN ACK."
1617
1618 SendShutdownAck();
1619 SetState(State::kShutdownAckSent, "No more outstanding data");
1620 }
1621}
1622
1623void DcSctpSocket::SendShutdown() {
1624 SctpPacket::Builder b = tcb_->PacketBuilder();
1625 b.Add(ShutdownChunk(tcb_->data_tracker().last_cumulative_acked_tsn()));
Victor Boivieabf61882021-08-12 15:57:49 +02001626 packet_sender_.Send(b);
Victor Boivieb6580cc2021-04-08 09:56:59 +02001627}
1628
1629void DcSctpSocket::SendShutdownAck() {
Victor Boivieabf61882021-08-12 15:57:49 +02001630 packet_sender_.Send(tcb_->PacketBuilder().Add(ShutdownAckChunk()));
Victor Boivieb6580cc2021-04-08 09:56:59 +02001631 t2_shutdown_->set_duration(tcb_->current_rto());
1632 t2_shutdown_->Start();
1633}
1634
Sergey Sukhanov43972812021-09-17 15:32:48 +02001635HandoverReadinessStatus DcSctpSocket::GetHandoverReadiness() const {
1636 HandoverReadinessStatus status;
1637 if (state_ != State::kClosed && state_ != State::kEstablished) {
1638 status.Add(HandoverUnreadinessReason::kWrongConnectionState);
1639 }
Sergey Sukhanov72435322021-09-21 13:31:09 +02001640 status.Add(send_queue_.GetHandoverReadiness());
Sergey Sukhanov43972812021-09-17 15:32:48 +02001641 if (tcb_) {
1642 status.Add(tcb_->GetHandoverReadiness());
1643 }
1644 return status;
1645}
1646
1647absl::optional<DcSctpSocketHandoverState>
1648DcSctpSocket::GetHandoverStateAndClose() {
1649 if (!GetHandoverReadiness().IsReady()) {
1650 return absl::nullopt;
1651 }
1652
1653 DcSctpSocketHandoverState state;
1654
1655 if (state_ == State::kClosed) {
1656 state.socket_state = DcSctpSocketHandoverState::SocketState::kClosed;
1657 } else if (state_ == State::kEstablished) {
1658 state.socket_state = DcSctpSocketHandoverState::SocketState::kConnected;
1659 tcb_->AddHandoverState(state);
Sergey Sukhanov72435322021-09-21 13:31:09 +02001660 send_queue_.AddHandoverState(state);
Sergey Sukhanov43972812021-09-17 15:32:48 +02001661 InternalClose(ErrorKind::kNoError, "handover");
1662 callbacks_.TriggerDeferred();
1663 }
1664
1665 return std::move(state);
1666}
1667
Victor Boivieb6580cc2021-04-08 09:56:59 +02001668} // namespace dcsctp