blob: 07e760ab01e394deba45680ef1eacc588339acbb [file] [log] [blame]
Victor Boivieb6580cc2021-04-08 09:56:59 +02001/*
2 * Copyright (c) 2021 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10#ifndef NET_DCSCTP_SOCKET_DCSCTP_SOCKET_H_
11#define NET_DCSCTP_SOCKET_DCSCTP_SOCKET_H_
12
13#include <cstdint>
14#include <memory>
15#include <string>
16#include <utility>
17
18#include "absl/strings/string_view.h"
19#include "api/array_view.h"
Victor Boivie5755f3e2021-09-29 22:23:15 +020020#include "api/sequence_checker.h"
Victor Boivieb6580cc2021-04-08 09:56:59 +020021#include "net/dcsctp/packet/chunk/abort_chunk.h"
22#include "net/dcsctp/packet/chunk/chunk.h"
23#include "net/dcsctp/packet/chunk/cookie_ack_chunk.h"
24#include "net/dcsctp/packet/chunk/cookie_echo_chunk.h"
25#include "net/dcsctp/packet/chunk/data_chunk.h"
26#include "net/dcsctp/packet/chunk/data_common.h"
27#include "net/dcsctp/packet/chunk/error_chunk.h"
28#include "net/dcsctp/packet/chunk/forward_tsn_chunk.h"
29#include "net/dcsctp/packet/chunk/forward_tsn_common.h"
30#include "net/dcsctp/packet/chunk/heartbeat_ack_chunk.h"
31#include "net/dcsctp/packet/chunk/heartbeat_request_chunk.h"
32#include "net/dcsctp/packet/chunk/idata_chunk.h"
33#include "net/dcsctp/packet/chunk/iforward_tsn_chunk.h"
34#include "net/dcsctp/packet/chunk/init_ack_chunk.h"
35#include "net/dcsctp/packet/chunk/init_chunk.h"
36#include "net/dcsctp/packet/chunk/reconfig_chunk.h"
37#include "net/dcsctp/packet/chunk/sack_chunk.h"
38#include "net/dcsctp/packet/chunk/shutdown_ack_chunk.h"
39#include "net/dcsctp/packet/chunk/shutdown_chunk.h"
40#include "net/dcsctp/packet/chunk/shutdown_complete_chunk.h"
41#include "net/dcsctp/packet/data.h"
42#include "net/dcsctp/packet/sctp_packet.h"
43#include "net/dcsctp/public/dcsctp_message.h"
44#include "net/dcsctp/public/dcsctp_options.h"
45#include "net/dcsctp/public/dcsctp_socket.h"
46#include "net/dcsctp/public/packet_observer.h"
47#include "net/dcsctp/rx/data_tracker.h"
48#include "net/dcsctp/rx/reassembly_queue.h"
49#include "net/dcsctp/socket/callback_deferrer.h"
Victor Boivieabf61882021-08-12 15:57:49 +020050#include "net/dcsctp/socket/packet_sender.h"
Victor Boivieb6580cc2021-04-08 09:56:59 +020051#include "net/dcsctp/socket/state_cookie.h"
52#include "net/dcsctp/socket/transmission_control_block.h"
53#include "net/dcsctp/timer/timer.h"
Victor Boivieb6580cc2021-04-08 09:56:59 +020054#include "net/dcsctp/tx/retransmission_error_counter.h"
55#include "net/dcsctp/tx/retransmission_queue.h"
56#include "net/dcsctp/tx/retransmission_timeout.h"
Victor Boivie2440d342021-05-20 13:47:32 +020057#include "net/dcsctp/tx/rr_send_queue.h"
Victor Boivieb6580cc2021-04-08 09:56:59 +020058
59namespace dcsctp {
60
61// DcSctpSocket represents a single SCTP socket, to be used over DTLS.
62//
63// Every dcSCTP is completely isolated from any other socket.
64//
65// This class manages all packet and chunk dispatching and mainly handles the
66// connection sequences (connect, close, shutdown, etc) as well as managing
67// the Transmission Control Block (tcb).
68//
69// This class is thread-compatible.
70class DcSctpSocket : public DcSctpSocketInterface {
71 public:
72 // Instantiates a DcSctpSocket, which interacts with the world through the
73 // `callbacks` interface and is configured using `options`.
74 //
75 // For debugging, `log_prefix` will prefix all debug logs, and a
76 // `packet_observer` can be attached to e.g. dump sent and received packets.
77 DcSctpSocket(absl::string_view log_prefix,
78 DcSctpSocketCallbacks& callbacks,
79 std::unique_ptr<PacketObserver> packet_observer,
80 const DcSctpOptions& options);
81
82 DcSctpSocket(const DcSctpSocket&) = delete;
83 DcSctpSocket& operator=(const DcSctpSocket&) = delete;
84
85 // Implementation of `DcSctpSocketInterface`.
86 void ReceivePacket(rtc::ArrayView<const uint8_t> data) override;
87 void HandleTimeout(TimeoutID timeout_id) override;
88 void Connect() override;
Sergey Sukhanov43972812021-09-17 15:32:48 +020089 void RestoreFromState(const DcSctpSocketHandoverState& state) override;
Victor Boivieb6580cc2021-04-08 09:56:59 +020090 void Shutdown() override;
91 void Close() override;
92 SendStatus Send(DcSctpMessage message,
93 const SendOptions& send_options) override;
94 ResetStreamsStatus ResetStreams(
95 rtc::ArrayView<const StreamID> outgoing_streams) override;
96 SocketState state() const override;
97 const DcSctpOptions& options() const override { return options_; }
Florent Castelli0810b052021-05-04 20:12:52 +020098 void SetMaxMessageSize(size_t max_message_size) override;
Victor Boivie236ac502021-05-20 19:34:18 +020099 size_t buffered_amount(StreamID stream_id) const override;
100 size_t buffered_amount_low_threshold(StreamID stream_id) const override;
101 void SetBufferedAmountLowThreshold(StreamID stream_id, size_t bytes) override;
Victor Boivief7fc71d2022-05-13 14:27:55 +0200102 absl::optional<Metrics> GetMetrics() const override;
Sergey Sukhanov43972812021-09-17 15:32:48 +0200103 HandoverReadinessStatus GetHandoverReadiness() const override;
104 absl::optional<DcSctpSocketHandoverState> GetHandoverStateAndClose() override;
Victor Boivief4fa1662021-09-24 23:01:21 +0200105 SctpImplementation peer_implementation() const override {
Victor Boivief7fc71d2022-05-13 14:27:55 +0200106 return metrics_.peer_implementation;
Victor Boivief4fa1662021-09-24 23:01:21 +0200107 }
Victor Boivieb6580cc2021-04-08 09:56:59 +0200108 // Returns this socket's verification tag, or zero if not yet connected.
109 VerificationTag verification_tag() const {
110 return tcb_ != nullptr ? tcb_->my_verification_tag() : VerificationTag(0);
111 }
112
113 private:
114 // Parameter proposals valid during the connect phase.
115 struct ConnectParameters {
116 TSN initial_tsn = TSN(0);
117 VerificationTag verification_tag = VerificationTag(0);
118 };
119
120 // Detailed state (separate from SocketState, which is the public state).
121 enum class State {
122 kClosed,
123 kCookieWait,
124 // TCB valid in these:
125 kCookieEchoed,
126 kEstablished,
127 kShutdownPending,
128 kShutdownSent,
129 kShutdownReceived,
130 kShutdownAckSent,
131 };
132
133 // Returns the log prefix used for debug logging.
134 std::string log_prefix() const;
135
136 bool IsConsistent() const;
137 static constexpr absl::string_view ToString(DcSctpSocket::State state);
138
139 // Changes the socket state, given a `reason` (for debugging/logging).
140 void SetState(State state, absl::string_view reason);
141 // Fills in `connect_params` with random verification tag and initial TSN.
142 void MakeConnectionParameters();
143 // Closes the association. Note that the TCB will not be valid past this call.
144 void InternalClose(ErrorKind error, absl::string_view message);
145 // Closes the association, because of too many retransmission errors.
146 void CloseConnectionBecauseOfTooManyTransmissionErrors();
147 // Timer expiration handlers
148 absl::optional<DurationMs> OnInitTimerExpiry();
149 absl::optional<DurationMs> OnCookieTimerExpiry();
150 absl::optional<DurationMs> OnShutdownTimerExpiry();
Victor Boivieabf61882021-08-12 15:57:49 +0200151 void OnSentPacket(rtc::ArrayView<const uint8_t> packet,
152 SendPacketStatus status);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200153 // Sends SHUTDOWN or SHUTDOWN-ACK if the socket is shutting down and if all
154 // outstanding data has been acknowledged.
155 void MaybeSendShutdownOrAck();
156 // If the socket is shutting down, responds SHUTDOWN to any incoming DATA.
157 void MaybeSendShutdownOnPacketReceived(const SctpPacket& packet);
Victor Boivief9e116f2022-03-31 17:15:03 +0200158 // If there are streams pending to be reset, send a request to reset them.
159 void MaybeSendResetStreamsRequest();
Victor Boivieb6580cc2021-04-08 09:56:59 +0200160 // Sends a INIT chunk.
161 void SendInit();
Victor Boivieb6580cc2021-04-08 09:56:59 +0200162 // Sends a SHUTDOWN chunk.
163 void SendShutdown();
164 // Sends a SHUTDOWN-ACK chunk.
165 void SendShutdownAck();
166 // Validates the SCTP packet, as a whole - not the validity of individual
167 // chunks within it, as that's done in the different chunk handlers.
168 bool ValidatePacket(const SctpPacket& packet);
169 // Parses `payload`, which is a serialized packet that is just going to be
170 // sent and prints all chunks.
171 void DebugPrintOutgoing(rtc::ArrayView<const uint8_t> payload);
172 // Called whenever there may be reassembled messages, and delivers those.
173 void DeliverReassembledMessages();
174 // Returns true if there is a TCB, and false otherwise (and reports an error).
175 bool ValidateHasTCB();
176
177 // Returns true if the parsing of a chunk of type `T` succeeded. If it didn't,
178 // it reports an error and returns false.
179 template <class T>
180 bool ValidateParseSuccess(const absl::optional<T>& c) {
181 if (c.has_value()) {
182 return true;
183 }
184
185 ReportFailedToParseChunk(T::kType);
186 return false;
187 }
188
189 // Reports failing to have parsed a chunk with the provided `chunk_type`.
190 void ReportFailedToParseChunk(int chunk_type);
191 // Called when unknown chunks are received. May report an error.
192 bool HandleUnrecognizedChunk(const SctpPacket::ChunkDescriptor& descriptor);
193
194 // Will dispatch more specific chunk handlers.
195 bool Dispatch(const CommonHeader& header,
196 const SctpPacket::ChunkDescriptor& descriptor);
197 // Handles incoming DATA chunks.
198 void HandleData(const CommonHeader& header,
199 const SctpPacket::ChunkDescriptor& descriptor);
200 // Handles incoming I-DATA chunks.
201 void HandleIData(const CommonHeader& header,
202 const SctpPacket::ChunkDescriptor& descriptor);
203 // Common handler for DATA and I-DATA chunks.
204 void HandleDataCommon(AnyDataChunk& chunk);
205 // Handles incoming INIT chunks.
206 void HandleInit(const CommonHeader& header,
207 const SctpPacket::ChunkDescriptor& descriptor);
208 // Handles incoming INIT-ACK chunks.
209 void HandleInitAck(const CommonHeader& header,
210 const SctpPacket::ChunkDescriptor& descriptor);
211 // Handles incoming SACK chunks.
212 void HandleSack(const CommonHeader& header,
213 const SctpPacket::ChunkDescriptor& descriptor);
214 // Handles incoming HEARTBEAT chunks.
215 void HandleHeartbeatRequest(const CommonHeader& header,
216 const SctpPacket::ChunkDescriptor& descriptor);
217 // Handles incoming HEARTBEAT-ACK chunks.
218 void HandleHeartbeatAck(const CommonHeader& header,
219 const SctpPacket::ChunkDescriptor& descriptor);
220 // Handles incoming ABORT chunks.
221 void HandleAbort(const CommonHeader& header,
222 const SctpPacket::ChunkDescriptor& descriptor);
223 // Handles incoming ERROR chunks.
224 void HandleError(const CommonHeader& header,
225 const SctpPacket::ChunkDescriptor& descriptor);
226 // Handles incoming COOKIE-ECHO chunks.
227 void HandleCookieEcho(const CommonHeader& header,
228 const SctpPacket::ChunkDescriptor& descriptor);
229 // Handles receiving COOKIE-ECHO when there already is a TCB. The return value
230 // indicates if the processing should continue.
231 bool HandleCookieEchoWithTCB(const CommonHeader& header,
232 const StateCookie& cookie);
233 // Handles incoming COOKIE-ACK chunks.
234 void HandleCookieAck(const CommonHeader& header,
235 const SctpPacket::ChunkDescriptor& descriptor);
236 // Handles incoming SHUTDOWN chunks.
237 void HandleShutdown(const CommonHeader& header,
238 const SctpPacket::ChunkDescriptor& descriptor);
239 // Handles incoming SHUTDOWN-ACK chunks.
240 void HandleShutdownAck(const CommonHeader& header,
241 const SctpPacket::ChunkDescriptor& descriptor);
242 // Handles incoming FORWARD-TSN chunks.
243 void HandleForwardTsn(const CommonHeader& header,
244 const SctpPacket::ChunkDescriptor& descriptor);
245 // Handles incoming I-FORWARD-TSN chunks.
246 void HandleIForwardTsn(const CommonHeader& header,
247 const SctpPacket::ChunkDescriptor& descriptor);
248 // Handles incoming RE-CONFIG chunks.
249 void HandleReconfig(const CommonHeader& header,
250 const SctpPacket::ChunkDescriptor& descriptor);
251 // Common handled for FORWARD-TSN/I-FORWARD-TSN.
252 void HandleForwardTsnCommon(const AnyForwardTsnChunk& chunk);
253 // Handles incoming SHUTDOWN-COMPLETE chunks
254 void HandleShutdownComplete(const CommonHeader& header,
255 const SctpPacket::ChunkDescriptor& descriptor);
256
257 const std::string log_prefix_;
258 const std::unique_ptr<PacketObserver> packet_observer_;
Victor Boivie5755f3e2021-09-29 22:23:15 +0200259 RTC_NO_UNIQUE_ADDRESS webrtc::SequenceChecker thread_checker_;
Victor Boivied4716ea2021-08-09 12:26:32 +0200260 Metrics metrics_;
Florent Castelli0810b052021-05-04 20:12:52 +0200261 DcSctpOptions options_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200262
263 // Enqueues callbacks and dispatches them just before returning to the caller.
264 CallbackDeferrer callbacks_;
265
266 TimerManager timer_manager_;
267 const std::unique_ptr<Timer> t1_init_;
268 const std::unique_ptr<Timer> t1_cookie_;
269 const std::unique_ptr<Timer> t2_shutdown_;
270
Victor Boivieabf61882021-08-12 15:57:49 +0200271 // Packets that failed to be sent, but should be retried.
272 PacketSender packet_sender_;
273
Victor Boivieb6580cc2021-04-08 09:56:59 +0200274 // The actual SendQueue implementation. As data can be sent on a socket before
275 // the connection is established, this component is not in the TCB.
Victor Boivie2440d342021-05-20 13:47:32 +0200276 RRSendQueue send_queue_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200277
Victor Boivieb6580cc2021-04-08 09:56:59 +0200278 // Contains verification tag and initial TSN between having sent the INIT
279 // until the connection is established (there is no TCB at this point).
280 ConnectParameters connect_params_;
281 // The socket state.
282 State state_ = State::kClosed;
283 // If the connection is established, contains a transmission control block.
284 std::unique_ptr<TransmissionControlBlock> tcb_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200285};
286} // namespace dcsctp
287
288#endif // NET_DCSCTP_SOCKET_DCSCTP_SOCKET_H_