blob: c249864182ed92175c35c04092e4376b4f2fa8d2 [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 Boivief4fa1662021-09-24 23:01:21 +0200104 SctpImplementation peer_implementation() const override {
105 return peer_implementation_;
106 }
Victor Boivieb6580cc2021-04-08 09:56:59 +0200107 // Returns this socket's verification tag, or zero if not yet connected.
108 VerificationTag verification_tag() const {
109 return tcb_ != nullptr ? tcb_->my_verification_tag() : VerificationTag(0);
110 }
111
112 private:
113 // Parameter proposals valid during the connect phase.
114 struct ConnectParameters {
115 TSN initial_tsn = TSN(0);
116 VerificationTag verification_tag = VerificationTag(0);
117 };
118
119 // Detailed state (separate from SocketState, which is the public state).
120 enum class State {
121 kClosed,
122 kCookieWait,
123 // TCB valid in these:
124 kCookieEchoed,
125 kEstablished,
126 kShutdownPending,
127 kShutdownSent,
128 kShutdownReceived,
129 kShutdownAckSent,
130 };
131
132 // Returns the log prefix used for debug logging.
133 std::string log_prefix() const;
134
135 bool IsConsistent() const;
136 static constexpr absl::string_view ToString(DcSctpSocket::State state);
137
138 // Changes the socket state, given a `reason` (for debugging/logging).
139 void SetState(State state, absl::string_view reason);
140 // Fills in `connect_params` with random verification tag and initial TSN.
141 void MakeConnectionParameters();
142 // Closes the association. Note that the TCB will not be valid past this call.
143 void InternalClose(ErrorKind error, absl::string_view message);
144 // Closes the association, because of too many retransmission errors.
145 void CloseConnectionBecauseOfTooManyTransmissionErrors();
146 // Timer expiration handlers
147 absl::optional<DurationMs> OnInitTimerExpiry();
148 absl::optional<DurationMs> OnCookieTimerExpiry();
149 absl::optional<DurationMs> OnShutdownTimerExpiry();
Victor Boivieabf61882021-08-12 15:57:49 +0200150 void OnSentPacket(rtc::ArrayView<const uint8_t> packet,
151 SendPacketStatus status);
Victor Boivieb6580cc2021-04-08 09:56:59 +0200152 // Sends SHUTDOWN or SHUTDOWN-ACK if the socket is shutting down and if all
153 // outstanding data has been acknowledged.
154 void MaybeSendShutdownOrAck();
155 // If the socket is shutting down, responds SHUTDOWN to any incoming DATA.
156 void MaybeSendShutdownOnPacketReceived(const SctpPacket& packet);
157 // Sends a INIT chunk.
158 void SendInit();
Victor Boivieb6580cc2021-04-08 09:56:59 +0200159 // Sends a SHUTDOWN chunk.
160 void SendShutdown();
161 // Sends a SHUTDOWN-ACK chunk.
162 void SendShutdownAck();
163 // Validates the SCTP packet, as a whole - not the validity of individual
164 // chunks within it, as that's done in the different chunk handlers.
165 bool ValidatePacket(const SctpPacket& packet);
166 // Parses `payload`, which is a serialized packet that is just going to be
167 // sent and prints all chunks.
168 void DebugPrintOutgoing(rtc::ArrayView<const uint8_t> payload);
169 // Called whenever there may be reassembled messages, and delivers those.
170 void DeliverReassembledMessages();
171 // Returns true if there is a TCB, and false otherwise (and reports an error).
172 bool ValidateHasTCB();
173
174 // Returns true if the parsing of a chunk of type `T` succeeded. If it didn't,
175 // it reports an error and returns false.
176 template <class T>
177 bool ValidateParseSuccess(const absl::optional<T>& c) {
178 if (c.has_value()) {
179 return true;
180 }
181
182 ReportFailedToParseChunk(T::kType);
183 return false;
184 }
185
186 // Reports failing to have parsed a chunk with the provided `chunk_type`.
187 void ReportFailedToParseChunk(int chunk_type);
188 // Called when unknown chunks are received. May report an error.
189 bool HandleUnrecognizedChunk(const SctpPacket::ChunkDescriptor& descriptor);
190
191 // Will dispatch more specific chunk handlers.
192 bool Dispatch(const CommonHeader& header,
193 const SctpPacket::ChunkDescriptor& descriptor);
194 // Handles incoming DATA chunks.
195 void HandleData(const CommonHeader& header,
196 const SctpPacket::ChunkDescriptor& descriptor);
197 // Handles incoming I-DATA chunks.
198 void HandleIData(const CommonHeader& header,
199 const SctpPacket::ChunkDescriptor& descriptor);
200 // Common handler for DATA and I-DATA chunks.
201 void HandleDataCommon(AnyDataChunk& chunk);
202 // Handles incoming INIT chunks.
203 void HandleInit(const CommonHeader& header,
204 const SctpPacket::ChunkDescriptor& descriptor);
205 // Handles incoming INIT-ACK chunks.
206 void HandleInitAck(const CommonHeader& header,
207 const SctpPacket::ChunkDescriptor& descriptor);
208 // Handles incoming SACK chunks.
209 void HandleSack(const CommonHeader& header,
210 const SctpPacket::ChunkDescriptor& descriptor);
211 // Handles incoming HEARTBEAT chunks.
212 void HandleHeartbeatRequest(const CommonHeader& header,
213 const SctpPacket::ChunkDescriptor& descriptor);
214 // Handles incoming HEARTBEAT-ACK chunks.
215 void HandleHeartbeatAck(const CommonHeader& header,
216 const SctpPacket::ChunkDescriptor& descriptor);
217 // Handles incoming ABORT chunks.
218 void HandleAbort(const CommonHeader& header,
219 const SctpPacket::ChunkDescriptor& descriptor);
220 // Handles incoming ERROR chunks.
221 void HandleError(const CommonHeader& header,
222 const SctpPacket::ChunkDescriptor& descriptor);
223 // Handles incoming COOKIE-ECHO chunks.
224 void HandleCookieEcho(const CommonHeader& header,
225 const SctpPacket::ChunkDescriptor& descriptor);
226 // Handles receiving COOKIE-ECHO when there already is a TCB. The return value
227 // indicates if the processing should continue.
228 bool HandleCookieEchoWithTCB(const CommonHeader& header,
229 const StateCookie& cookie);
230 // Handles incoming COOKIE-ACK chunks.
231 void HandleCookieAck(const CommonHeader& header,
232 const SctpPacket::ChunkDescriptor& descriptor);
233 // Handles incoming SHUTDOWN chunks.
234 void HandleShutdown(const CommonHeader& header,
235 const SctpPacket::ChunkDescriptor& descriptor);
236 // Handles incoming SHUTDOWN-ACK chunks.
237 void HandleShutdownAck(const CommonHeader& header,
238 const SctpPacket::ChunkDescriptor& descriptor);
239 // Handles incoming FORWARD-TSN chunks.
240 void HandleForwardTsn(const CommonHeader& header,
241 const SctpPacket::ChunkDescriptor& descriptor);
242 // Handles incoming I-FORWARD-TSN chunks.
243 void HandleIForwardTsn(const CommonHeader& header,
244 const SctpPacket::ChunkDescriptor& descriptor);
245 // Handles incoming RE-CONFIG chunks.
246 void HandleReconfig(const CommonHeader& header,
247 const SctpPacket::ChunkDescriptor& descriptor);
248 // Common handled for FORWARD-TSN/I-FORWARD-TSN.
249 void HandleForwardTsnCommon(const AnyForwardTsnChunk& chunk);
250 // Handles incoming SHUTDOWN-COMPLETE chunks
251 void HandleShutdownComplete(const CommonHeader& header,
252 const SctpPacket::ChunkDescriptor& descriptor);
253
254 const std::string log_prefix_;
255 const std::unique_ptr<PacketObserver> packet_observer_;
Victor Boivied4716ea2021-08-09 12:26:32 +0200256 Metrics metrics_;
Florent Castelli0810b052021-05-04 20:12:52 +0200257 DcSctpOptions options_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200258
259 // Enqueues callbacks and dispatches them just before returning to the caller.
260 CallbackDeferrer callbacks_;
261
262 TimerManager timer_manager_;
263 const std::unique_ptr<Timer> t1_init_;
264 const std::unique_ptr<Timer> t1_cookie_;
265 const std::unique_ptr<Timer> t2_shutdown_;
266
Victor Boivieabf61882021-08-12 15:57:49 +0200267 // Packets that failed to be sent, but should be retried.
268 PacketSender packet_sender_;
269
Victor Boivieb6580cc2021-04-08 09:56:59 +0200270 // The actual SendQueue implementation. As data can be sent on a socket before
271 // the connection is established, this component is not in the TCB.
Victor Boivie2440d342021-05-20 13:47:32 +0200272 RRSendQueue send_queue_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200273
Victor Boivieb6580cc2021-04-08 09:56:59 +0200274 // Contains verification tag and initial TSN between having sent the INIT
275 // until the connection is established (there is no TCB at this point).
276 ConnectParameters connect_params_;
277 // The socket state.
278 State state_ = State::kClosed;
279 // If the connection is established, contains a transmission control block.
280 std::unique_ptr<TransmissionControlBlock> tcb_;
Victor Boivief4fa1662021-09-24 23:01:21 +0200281
282 SctpImplementation peer_implementation_ = SctpImplementation::kUnknown;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200283};
284} // namespace dcsctp
285
286#endif // NET_DCSCTP_SOCKET_DCSCTP_SOCKET_H_