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