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