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