blob: 32e89b50d102171d9d01222b8cce7816cdd57f85 [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"
Victor Boivieb6580cc2021-04-08 09:56:59 +020052#include "net/dcsctp/tx/retransmission_error_counter.h"
53#include "net/dcsctp/tx/retransmission_queue.h"
54#include "net/dcsctp/tx/retransmission_timeout.h"
Victor Boivie2440d342021-05-20 13:47:32 +020055#include "net/dcsctp/tx/rr_send_queue.h"
Victor Boivieb6580cc2021-04-08 09:56:59 +020056
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 Boivie236ac502021-05-20 19:34:18 +020096 size_t buffered_amount(StreamID stream_id) const override;
97 size_t buffered_amount_low_threshold(StreamID stream_id) const override;
98 void SetBufferedAmountLowThreshold(StreamID stream_id, size_t bytes) override;
Victor Boivieb6580cc2021-04-08 09:56:59 +020099 // Returns this socket's verification tag, or zero if not yet connected.
100 VerificationTag verification_tag() const {
101 return tcb_ != nullptr ? tcb_->my_verification_tag() : VerificationTag(0);
102 }
103
104 private:
105 // Parameter proposals valid during the connect phase.
106 struct ConnectParameters {
107 TSN initial_tsn = TSN(0);
108 VerificationTag verification_tag = VerificationTag(0);
109 };
110
111 // Detailed state (separate from SocketState, which is the public state).
112 enum class State {
113 kClosed,
114 kCookieWait,
115 // TCB valid in these:
116 kCookieEchoed,
117 kEstablished,
118 kShutdownPending,
119 kShutdownSent,
120 kShutdownReceived,
121 kShutdownAckSent,
122 };
123
124 // Returns the log prefix used for debug logging.
125 std::string log_prefix() const;
126
127 bool IsConsistent() const;
128 static constexpr absl::string_view ToString(DcSctpSocket::State state);
129
130 // Changes the socket state, given a `reason` (for debugging/logging).
131 void SetState(State state, absl::string_view reason);
132 // Fills in `connect_params` with random verification tag and initial TSN.
133 void MakeConnectionParameters();
134 // Closes the association. Note that the TCB will not be valid past this call.
135 void InternalClose(ErrorKind error, absl::string_view message);
136 // Closes the association, because of too many retransmission errors.
137 void CloseConnectionBecauseOfTooManyTransmissionErrors();
138 // Timer expiration handlers
139 absl::optional<DurationMs> OnInitTimerExpiry();
140 absl::optional<DurationMs> OnCookieTimerExpiry();
141 absl::optional<DurationMs> OnShutdownTimerExpiry();
142 // Builds the packet from `builder` and sends it (through callbacks).
143 void SendPacket(SctpPacket::Builder& builder);
144 // Sends SHUTDOWN or SHUTDOWN-ACK if the socket is shutting down and if all
145 // outstanding data has been acknowledged.
146 void MaybeSendShutdownOrAck();
147 // If the socket is shutting down, responds SHUTDOWN to any incoming DATA.
148 void MaybeSendShutdownOnPacketReceived(const SctpPacket& packet);
149 // Sends a INIT chunk.
150 void SendInit();
Victor Boivieb6580cc2021-04-08 09:56:59 +0200151 // 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.
Victor Boivie2440d342021-05-20 13:47:32 +0200260 RRSendQueue send_queue_;
Victor Boivieb6580cc2021-04-08 09:56:59 +0200261
Victor Boivieb6580cc2021-04-08 09:56:59 +0200262 // Contains verification tag and initial TSN between having sent the INIT
263 // until the connection is established (there is no TCB at this point).
264 ConnectParameters connect_params_;
265 // The socket state.
266 State state_ = State::kClosed;
267 // If the connection is established, contains a transmission control block.
268 std::unique_ptr<TransmissionControlBlock> tcb_;
269};
270} // namespace dcsctp
271
272#endif // NET_DCSCTP_SOCKET_DCSCTP_SOCKET_H_