blob: 24c0437b419c2fef9ba4e8cef2b7720993916bad [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"
49#include "net/dcsctp/socket/state_cookie.h"
50#include "net/dcsctp/socket/transmission_control_block.h"
51#include "net/dcsctp/timer/timer.h"
52#include "net/dcsctp/tx/fcfs_send_queue.h"
53#include "net/dcsctp/tx/retransmission_error_counter.h"
54#include "net/dcsctp/tx/retransmission_queue.h"
55#include "net/dcsctp/tx/retransmission_timeout.h"
56
57namespace dcsctp {
58
59// DcSctpSocket represents a single SCTP socket, to be used over DTLS.
60//
61// Every dcSCTP is completely isolated from any other socket.
62//
63// This class manages all packet and chunk dispatching and mainly handles the
64// connection sequences (connect, close, shutdown, etc) as well as managing
65// the Transmission Control Block (tcb).
66//
67// This class is thread-compatible.
68class DcSctpSocket : public DcSctpSocketInterface {
69 public:
70 // Instantiates a DcSctpSocket, which interacts with the world through the
71 // `callbacks` interface and is configured using `options`.
72 //
73 // For debugging, `log_prefix` will prefix all debug logs, and a
74 // `packet_observer` can be attached to e.g. dump sent and received packets.
75 DcSctpSocket(absl::string_view log_prefix,
76 DcSctpSocketCallbacks& callbacks,
77 std::unique_ptr<PacketObserver> packet_observer,
78 const DcSctpOptions& options);
79
80 DcSctpSocket(const DcSctpSocket&) = delete;
81 DcSctpSocket& operator=(const DcSctpSocket&) = delete;
82
83 // Implementation of `DcSctpSocketInterface`.
84 void ReceivePacket(rtc::ArrayView<const uint8_t> data) override;
85 void HandleTimeout(TimeoutID timeout_id) override;
86 void Connect() override;
87 void Shutdown() override;
88 void Close() override;
89 SendStatus Send(DcSctpMessage message,
90 const SendOptions& send_options) override;
91 ResetStreamsStatus ResetStreams(
92 rtc::ArrayView<const StreamID> outgoing_streams) override;
93 SocketState state() const override;
94 const DcSctpOptions& options() const override { return options_; }
Florent Castelli0810b052021-05-04 20:12:52 +020095 void SetMaxMessageSize(size_t max_message_size) override;
Victor Boivieb6580cc2021-04-08 09:56:59 +020096
97 // Returns this socket's verification tag, or zero if not yet connected.
98 VerificationTag verification_tag() const {
99 return tcb_ != nullptr ? tcb_->my_verification_tag() : VerificationTag(0);
100 }
101
102 private:
103 // Parameter proposals valid during the connect phase.
104 struct ConnectParameters {
105 TSN initial_tsn = TSN(0);
106 VerificationTag verification_tag = VerificationTag(0);
107 };
108
109 // Detailed state (separate from SocketState, which is the public state).
110 enum class State {
111 kClosed,
112 kCookieWait,
113 // TCB valid in these:
114 kCookieEchoed,
115 kEstablished,
116 kShutdownPending,
117 kShutdownSent,
118 kShutdownReceived,
119 kShutdownAckSent,
120 };
121
122 // Returns the log prefix used for debug logging.
123 std::string log_prefix() const;
124
125 bool IsConsistent() const;
126 static constexpr absl::string_view ToString(DcSctpSocket::State state);
127
128 // Changes the socket state, given a `reason` (for debugging/logging).
129 void SetState(State state, absl::string_view reason);
130 // Fills in `connect_params` with random verification tag and initial TSN.
131 void MakeConnectionParameters();
132 // Closes the association. Note that the TCB will not be valid past this call.
133 void InternalClose(ErrorKind error, absl::string_view message);
134 // Closes the association, because of too many retransmission errors.
135 void CloseConnectionBecauseOfTooManyTransmissionErrors();
136 // Timer expiration handlers
137 absl::optional<DurationMs> OnInitTimerExpiry();
138 absl::optional<DurationMs> OnCookieTimerExpiry();
139 absl::optional<DurationMs> OnShutdownTimerExpiry();
140 // Builds the packet from `builder` and sends it (through callbacks).
141 void SendPacket(SctpPacket::Builder& builder);
142 // Sends SHUTDOWN or SHUTDOWN-ACK if the socket is shutting down and if all
143 // outstanding data has been acknowledged.
144 void MaybeSendShutdownOrAck();
145 // If the socket is shutting down, responds SHUTDOWN to any incoming DATA.
146 void MaybeSendShutdownOnPacketReceived(const SctpPacket& packet);
147 // Sends a INIT chunk.
148 void SendInit();
149 // Sends a CookieEcho chunk.
150 void SendCookieEcho();
151 // Sends a SHUTDOWN chunk.
152 void SendShutdown();
153 // Sends a SHUTDOWN-ACK chunk.
154 void SendShutdownAck();
155 // Validates the SCTP packet, as a whole - not the validity of individual
156 // chunks within it, as that's done in the different chunk handlers.
157 bool ValidatePacket(const SctpPacket& packet);
158 // Parses `payload`, which is a serialized packet that is just going to be
159 // sent and prints all chunks.
160 void DebugPrintOutgoing(rtc::ArrayView<const uint8_t> payload);
161 // Called whenever there may be reassembled messages, and delivers those.
162 void DeliverReassembledMessages();
163 // Returns true if there is a TCB, and false otherwise (and reports an error).
164 bool ValidateHasTCB();
165
166 // Returns true if the parsing of a chunk of type `T` succeeded. If it didn't,
167 // it reports an error and returns false.
168 template <class T>
169 bool ValidateParseSuccess(const absl::optional<T>& c) {
170 if (c.has_value()) {
171 return true;
172 }
173
174 ReportFailedToParseChunk(T::kType);
175 return false;
176 }
177
178 // Reports failing to have parsed a chunk with the provided `chunk_type`.
179 void ReportFailedToParseChunk(int chunk_type);
180 // Called when unknown chunks are received. May report an error.
181 bool HandleUnrecognizedChunk(const SctpPacket::ChunkDescriptor& descriptor);
182
183 // Will dispatch more specific chunk handlers.
184 bool Dispatch(const CommonHeader& header,
185 const SctpPacket::ChunkDescriptor& descriptor);
186 // Handles incoming DATA chunks.
187 void HandleData(const CommonHeader& header,
188 const SctpPacket::ChunkDescriptor& descriptor);
189 // Handles incoming I-DATA chunks.
190 void HandleIData(const CommonHeader& header,
191 const SctpPacket::ChunkDescriptor& descriptor);
192 // Common handler for DATA and I-DATA chunks.
193 void HandleDataCommon(AnyDataChunk& chunk);
194 // Handles incoming INIT chunks.
195 void HandleInit(const CommonHeader& header,
196 const SctpPacket::ChunkDescriptor& descriptor);
197 // Handles incoming INIT-ACK chunks.
198 void HandleInitAck(const CommonHeader& header,
199 const SctpPacket::ChunkDescriptor& descriptor);
200 // Handles incoming SACK chunks.
201 void HandleSack(const CommonHeader& header,
202 const SctpPacket::ChunkDescriptor& descriptor);
203 // Handles incoming HEARTBEAT chunks.
204 void HandleHeartbeatRequest(const CommonHeader& header,
205 const SctpPacket::ChunkDescriptor& descriptor);
206 // Handles incoming HEARTBEAT-ACK chunks.
207 void HandleHeartbeatAck(const CommonHeader& header,
208 const SctpPacket::ChunkDescriptor& descriptor);
209 // Handles incoming ABORT chunks.
210 void HandleAbort(const CommonHeader& header,
211 const SctpPacket::ChunkDescriptor& descriptor);
212 // Handles incoming ERROR chunks.
213 void HandleError(const CommonHeader& header,
214 const SctpPacket::ChunkDescriptor& descriptor);
215 // Handles incoming COOKIE-ECHO chunks.
216 void HandleCookieEcho(const CommonHeader& header,
217 const SctpPacket::ChunkDescriptor& descriptor);
218 // Handles receiving COOKIE-ECHO when there already is a TCB. The return value
219 // indicates if the processing should continue.
220 bool HandleCookieEchoWithTCB(const CommonHeader& header,
221 const StateCookie& cookie);
222 // Handles incoming COOKIE-ACK chunks.
223 void HandleCookieAck(const CommonHeader& header,
224 const SctpPacket::ChunkDescriptor& descriptor);
225 // Handles incoming SHUTDOWN chunks.
226 void HandleShutdown(const CommonHeader& header,
227 const SctpPacket::ChunkDescriptor& descriptor);
228 // Handles incoming SHUTDOWN-ACK chunks.
229 void HandleShutdownAck(const CommonHeader& header,
230 const SctpPacket::ChunkDescriptor& descriptor);
231 // Handles incoming FORWARD-TSN chunks.
232 void HandleForwardTsn(const CommonHeader& header,
233 const SctpPacket::ChunkDescriptor& descriptor);
234 // Handles incoming I-FORWARD-TSN chunks.
235 void HandleIForwardTsn(const CommonHeader& header,
236 const SctpPacket::ChunkDescriptor& descriptor);
237 // Handles incoming RE-CONFIG chunks.
238 void HandleReconfig(const CommonHeader& header,
239 const SctpPacket::ChunkDescriptor& descriptor);
240 // Common handled for FORWARD-TSN/I-FORWARD-TSN.
241 void HandleForwardTsnCommon(const AnyForwardTsnChunk& chunk);
242 // Handles incoming SHUTDOWN-COMPLETE chunks
243 void HandleShutdownComplete(const CommonHeader& header,
244 const SctpPacket::ChunkDescriptor& descriptor);
245
246 const std::string log_prefix_;
247 const std::unique_ptr<PacketObserver> packet_observer_;
Florent Castelli0810b052021-05-04 20:12:52 +0200248 DcSctpOptions options_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200249
250 // Enqueues callbacks and dispatches them just before returning to the caller.
251 CallbackDeferrer callbacks_;
252
253 TimerManager timer_manager_;
254 const std::unique_ptr<Timer> t1_init_;
255 const std::unique_ptr<Timer> t1_cookie_;
256 const std::unique_ptr<Timer> t2_shutdown_;
257
258 // The actual SendQueue implementation. As data can be sent on a socket before
259 // the connection is established, this component is not in the TCB.
260 FCFSSendQueue send_queue_;
261
262 // Only valid when state == State::kCookieEchoed
263 // A cached Cookie Echo Chunk, to be re-sent on timer expiry.
264 absl::optional<CookieEchoChunk> cookie_echo_chunk_ = absl::nullopt;
265
266 // Contains verification tag and initial TSN between having sent the INIT
267 // until the connection is established (there is no TCB at this point).
268 ConnectParameters connect_params_;
269 // The socket state.
270 State state_ = State::kClosed;
271 // If the connection is established, contains a transmission control block.
272 std::unique_ptr<TransmissionControlBlock> tcb_;
273};
274} // namespace dcsctp
275
276#endif // NET_DCSCTP_SOCKET_DCSCTP_SOCKET_H_