blob: b1b3ea9d9ba037ec295c8a9188dc34d6c50bf35a [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 Boivied4716ea2021-08-09 12:26:32 +0200102 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 {
106 return peer_implementation_;
107 }
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);
158 // Sends a INIT chunk.
159 void SendInit();
Victor Boivieb6580cc2021-04-08 09:56:59 +0200160 // Sends a SHUTDOWN chunk.
161 void SendShutdown();
162 // Sends a SHUTDOWN-ACK chunk.
163 void SendShutdownAck();
164 // Validates the SCTP packet, as a whole - not the validity of individual
165 // chunks within it, as that's done in the different chunk handlers.
166 bool ValidatePacket(const SctpPacket& packet);
167 // Parses `payload`, which is a serialized packet that is just going to be
168 // sent and prints all chunks.
169 void DebugPrintOutgoing(rtc::ArrayView<const uint8_t> payload);
170 // Called whenever there may be reassembled messages, and delivers those.
171 void DeliverReassembledMessages();
172 // Returns true if there is a TCB, and false otherwise (and reports an error).
173 bool ValidateHasTCB();
174
175 // Returns true if the parsing of a chunk of type `T` succeeded. If it didn't,
176 // it reports an error and returns false.
177 template <class T>
178 bool ValidateParseSuccess(const absl::optional<T>& c) {
179 if (c.has_value()) {
180 return true;
181 }
182
183 ReportFailedToParseChunk(T::kType);
184 return false;
185 }
186
187 // Reports failing to have parsed a chunk with the provided `chunk_type`.
188 void ReportFailedToParseChunk(int chunk_type);
189 // Called when unknown chunks are received. May report an error.
190 bool HandleUnrecognizedChunk(const SctpPacket::ChunkDescriptor& descriptor);
191
192 // Will dispatch more specific chunk handlers.
193 bool Dispatch(const CommonHeader& header,
194 const SctpPacket::ChunkDescriptor& descriptor);
195 // Handles incoming DATA chunks.
196 void HandleData(const CommonHeader& header,
197 const SctpPacket::ChunkDescriptor& descriptor);
198 // Handles incoming I-DATA chunks.
199 void HandleIData(const CommonHeader& header,
200 const SctpPacket::ChunkDescriptor& descriptor);
201 // Common handler for DATA and I-DATA chunks.
202 void HandleDataCommon(AnyDataChunk& chunk);
203 // Handles incoming INIT chunks.
204 void HandleInit(const CommonHeader& header,
205 const SctpPacket::ChunkDescriptor& descriptor);
206 // Handles incoming INIT-ACK chunks.
207 void HandleInitAck(const CommonHeader& header,
208 const SctpPacket::ChunkDescriptor& descriptor);
209 // Handles incoming SACK chunks.
210 void HandleSack(const CommonHeader& header,
211 const SctpPacket::ChunkDescriptor& descriptor);
212 // Handles incoming HEARTBEAT chunks.
213 void HandleHeartbeatRequest(const CommonHeader& header,
214 const SctpPacket::ChunkDescriptor& descriptor);
215 // Handles incoming HEARTBEAT-ACK chunks.
216 void HandleHeartbeatAck(const CommonHeader& header,
217 const SctpPacket::ChunkDescriptor& descriptor);
218 // Handles incoming ABORT chunks.
219 void HandleAbort(const CommonHeader& header,
220 const SctpPacket::ChunkDescriptor& descriptor);
221 // Handles incoming ERROR chunks.
222 void HandleError(const CommonHeader& header,
223 const SctpPacket::ChunkDescriptor& descriptor);
224 // Handles incoming COOKIE-ECHO chunks.
225 void HandleCookieEcho(const CommonHeader& header,
226 const SctpPacket::ChunkDescriptor& descriptor);
227 // Handles receiving COOKIE-ECHO when there already is a TCB. The return value
228 // indicates if the processing should continue.
229 bool HandleCookieEchoWithTCB(const CommonHeader& header,
230 const StateCookie& cookie);
231 // Handles incoming COOKIE-ACK chunks.
232 void HandleCookieAck(const CommonHeader& header,
233 const SctpPacket::ChunkDescriptor& descriptor);
234 // Handles incoming SHUTDOWN chunks.
235 void HandleShutdown(const CommonHeader& header,
236 const SctpPacket::ChunkDescriptor& descriptor);
237 // Handles incoming SHUTDOWN-ACK chunks.
238 void HandleShutdownAck(const CommonHeader& header,
239 const SctpPacket::ChunkDescriptor& descriptor);
240 // Handles incoming FORWARD-TSN chunks.
241 void HandleForwardTsn(const CommonHeader& header,
242 const SctpPacket::ChunkDescriptor& descriptor);
243 // Handles incoming I-FORWARD-TSN chunks.
244 void HandleIForwardTsn(const CommonHeader& header,
245 const SctpPacket::ChunkDescriptor& descriptor);
246 // Handles incoming RE-CONFIG chunks.
247 void HandleReconfig(const CommonHeader& header,
248 const SctpPacket::ChunkDescriptor& descriptor);
249 // Common handled for FORWARD-TSN/I-FORWARD-TSN.
250 void HandleForwardTsnCommon(const AnyForwardTsnChunk& chunk);
251 // Handles incoming SHUTDOWN-COMPLETE chunks
252 void HandleShutdownComplete(const CommonHeader& header,
253 const SctpPacket::ChunkDescriptor& descriptor);
254
255 const std::string log_prefix_;
256 const std::unique_ptr<PacketObserver> packet_observer_;
Victor Boivie5755f3e2021-09-29 22:23:15 +0200257 RTC_NO_UNIQUE_ADDRESS webrtc::SequenceChecker thread_checker_;
Victor Boivied4716ea2021-08-09 12:26:32 +0200258 Metrics metrics_;
Florent Castelli0810b052021-05-04 20:12:52 +0200259 DcSctpOptions options_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200260
261 // Enqueues callbacks and dispatches them just before returning to the caller.
262 CallbackDeferrer callbacks_;
263
264 TimerManager timer_manager_;
265 const std::unique_ptr<Timer> t1_init_;
266 const std::unique_ptr<Timer> t1_cookie_;
267 const std::unique_ptr<Timer> t2_shutdown_;
268
Victor Boivieabf61882021-08-12 15:57:49 +0200269 // Packets that failed to be sent, but should be retried.
270 PacketSender packet_sender_;
271
Victor Boivieb6580cc2021-04-08 09:56:59 +0200272 // The actual SendQueue implementation. As data can be sent on a socket before
273 // the connection is established, this component is not in the TCB.
Victor Boivie2440d342021-05-20 13:47:32 +0200274 RRSendQueue send_queue_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200275
Victor Boivieb6580cc2021-04-08 09:56:59 +0200276 // Contains verification tag and initial TSN between having sent the INIT
277 // until the connection is established (there is no TCB at this point).
278 ConnectParameters connect_params_;
279 // The socket state.
280 State state_ = State::kClosed;
281 // If the connection is established, contains a transmission control block.
282 std::unique_ptr<TransmissionControlBlock> tcb_;
Victor Boivief4fa1662021-09-24 23:01:21 +0200283
284 SctpImplementation peer_implementation_ = SctpImplementation::kUnknown;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200285};
286} // namespace dcsctp
287
288#endif // NET_DCSCTP_SOCKET_DCSCTP_SOCKET_H_