| 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 |
| 11 | #ifndef PC_SCTP_DATA_CHANNEL_H_ |
| 12 | #define PC_SCTP_DATA_CHANNEL_H_ |
| 13 |
| 14 | #include <stdint.h> |
| 15 |
| 16 | #include <memory> |
| 17 | #include <set> |
| 18 | #include <string> |
| 19 |
| 20 | #include "absl/types/optional.h" |
| 21 | #include "api/data_channel_interface.h" |
| 22 | #include "api/priority.h" |
| 23 | #include "api/rtc_error.h" |
| 24 | #include "api/scoped_refptr.h" |
| 25 | #include "api/sequence_checker.h" |
| 26 | #include "api/task_queue/pending_task_safety_flag.h" |
| 27 | #include "api/transport/data_channel_transport_interface.h" |
| 28 | #include "pc/data_channel_utils.h" |
| 29 | #include "pc/sctp_utils.h" |
| 30 | #include "rtc_base/containers/flat_set.h" |
| 31 | #include "rtc_base/copy_on_write_buffer.h" |
| 32 | #include "rtc_base/ssl_stream_adapter.h" // For SSLRole |
| 33 | #include "rtc_base/system/no_unique_address.h" |
| 34 | #include "rtc_base/thread.h" |
| 35 | #include "rtc_base/thread_annotations.h" |
| 36 | #include "rtc_base/weak_ptr.h" |
| 37 |
| 38 | namespace webrtc { |
| 39 |
| 40 | class SctpDataChannel; |
| 41 |
| 42 | // Interface that acts as a bridge from the data channel to the transport. |
| 43 | // All methods in this interface need to be invoked on the network thread. |
| 44 | class SctpDataChannelControllerInterface { |
| 45 | public: |
| 46 | // Sends the data to the transport. |
| 47 | virtual RTCError SendData(StreamId sid, |
| 48 | const SendDataParams& params, |
| 49 | const rtc::CopyOnWriteBuffer& payload) = 0; |
| 50 | // Adds the data channel SID to the transport for SCTP. |
| 51 | virtual void AddSctpDataStream(StreamId sid) = 0; |
| 52 | // Begins the closing procedure by sending an outgoing stream reset. Still |
| 53 | // need to wait for callbacks to tell when this completes. |
| 54 | virtual void RemoveSctpDataStream(StreamId sid) = 0; |
| 55 | // Notifies the controller of state changes. |
| 56 | virtual void OnChannelStateChanged(SctpDataChannel* data_channel, |
| 57 | DataChannelInterface::DataState state) = 0; |
| 58 |
| 59 | protected: |
| 60 | virtual ~SctpDataChannelControllerInterface() {} |
| 61 | }; |
| 62 |
| 63 | struct InternalDataChannelInit : public DataChannelInit { |
| 64 | enum OpenHandshakeRole { kOpener, kAcker, kNone }; |
| 65 | // The default role is kOpener because the default `negotiated` is false. |
| 66 | InternalDataChannelInit() : open_handshake_role(kOpener) {} |
| 67 | explicit InternalDataChannelInit(const DataChannelInit& base); |
| 68 |
| 69 | // Does basic validation to determine if a data channel instance can be |
| 70 | // constructed using the configuration. |
| 71 | bool IsValid() const; |
| 72 |
| 73 | OpenHandshakeRole open_handshake_role; |
| 74 | // Optional fallback or backup flag from PC that's used for non-prenegotiated |
| 75 | // stream ids in situations where we cannot determine the SSL role from the |
| 76 | // transport for purposes of generating a stream ID. |
| 77 | // See: https://www.rfc-editor.org/rfc/rfc8832.html#name-protocol-overview |
| 78 | absl::optional<rtc::SSLRole> fallback_ssl_role; |
| 79 | }; |
| 80 |
| 81 | // Helper class to allocate unique IDs for SCTP DataChannels. |
| 82 | class SctpSidAllocator { |
| 83 | public: |
| 84 | SctpSidAllocator() = default; |
| 85 | // Gets the first unused odd/even id based on the DTLS role. If `role` is |
| 86 | // SSL_CLIENT, the allocated id starts from 0 and takes even numbers; |
| 87 | // otherwise, the id starts from 1 and takes odd numbers. |
| 88 | // If a `StreamId` cannot be allocated, `StreamId::HasValue()` will be false. |
| 89 | StreamId AllocateSid(rtc::SSLRole role); |
| 90 |
| 91 | // Attempts to reserve a specific sid. Returns false if it's unavailable. |
| 92 | bool ReserveSid(StreamId sid); |
| 93 |
| 94 | // Indicates that `sid` isn't in use any more, and is thus available again. |
| 95 | void ReleaseSid(StreamId sid); |
| 96 |
| 97 | private: |
| 98 | flat_set<StreamId> used_sids_ RTC_GUARDED_BY(&sequence_checker_); |
| 99 | RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_{ |
| 100 | SequenceChecker::kDetached}; |
| 101 | }; |
| 102 |
| 103 | // SctpDataChannel is an implementation of the DataChannelInterface based on |
| 104 | // SctpTransport. It provides an implementation of unreliable or |
| 105 | // reliable data channels. |
| 106 |
| 107 | // DataChannel states: |
| 108 | // kConnecting: The channel has been created the transport might not yet be |
| 109 | // ready. |
| 110 | // kOpen: The open handshake has been performed (if relevant) and the data |
| 111 | // channel is able to send messages. |
| 112 | // kClosing: DataChannelInterface::Close has been called, or the remote side |
| 113 | // initiated the closing procedure, but the closing procedure has not |
| 114 | // yet finished. |
| 115 | // kClosed: The closing handshake is finished (possibly initiated from this, |
| 116 | // side, possibly from the peer). |
| 117 | // |
| 118 | // How the closing procedure works for SCTP: |
| 119 | // 1. Alice calls Close(), state changes to kClosing. |
| 120 | // 2. Alice finishes sending any queued data. |
| 121 | // 3. Alice calls RemoveSctpDataStream, sends outgoing stream reset. |
| 122 | // 4. Bob receives incoming stream reset; OnClosingProcedureStartedRemotely |
| 123 | // called. |
| 124 | // 5. Bob sends outgoing stream reset. |
| 125 | // 6. Alice receives incoming reset, Bob receives acknowledgement. Both receive |
| 126 | // OnClosingProcedureComplete callback and transition to kClosed. |
| 127 | class SctpDataChannel : public DataChannelInterface { |
| 128 | public: |
| 129 | static rtc::scoped_refptr<SctpDataChannel> Create( |
| 130 | rtc::WeakPtr<SctpDataChannelControllerInterface> controller, |
| 131 | const std::string& label, |
| 132 | bool connected_to_transport, |
| 133 | const InternalDataChannelInit& config, |
| 134 | rtc::Thread* signaling_thread, |
| 135 | rtc::Thread* network_thread); |
| 136 |
| 137 | // Instantiates an API proxy for a SctpDataChannel instance that will be |
| 138 | // handed out to external callers. |
| 139 | // The `signaling_safety` flag is used for the ObserverAdapter callback proxy |
| 140 | // which delivers callbacks on the signaling thread but must not deliver such |
| 141 | // callbacks after the peerconnection has been closed. The data controller |
| 142 | // will update the flag when closed, which will cancel any pending event |
| 143 | // notifications. |
| 144 | static rtc::scoped_refptr<DataChannelInterface> CreateProxy( |
| 145 | rtc::scoped_refptr<SctpDataChannel> channel, |
| 146 | rtc::scoped_refptr<PendingTaskSafetyFlag> signaling_safety); |
| 147 |
| 148 | void RegisterObserver(DataChannelObserver* observer) override; |
| 149 | void UnregisterObserver() override; |
| 150 |
| 151 | std::string label() const override; |
| 152 | bool reliable() const override; |
| 153 | bool ordered() const override; |
| 154 |
| 155 | // Backwards compatible accessors |
| 156 | uint16_t maxRetransmitTime() const override; |
| 157 | uint16_t maxRetransmits() const override; |
| 158 |
| 159 | absl::optional<int> maxPacketLifeTime() const override; |
| 160 | absl::optional<int> maxRetransmitsOpt() const override; |
| 161 | std::string protocol() const override; |
| 162 | bool negotiated() const override; |
| 163 | int id() const override; |
| 164 | Priority priority() const override; |
| 165 |
| 166 | uint64_t buffered_amount() const override; |
| 167 | void Close() override; |
| 168 | DataState state() const override; |
| 169 | RTCError error() const override; |
| 170 | uint32_t messages_sent() const override; |
| 171 | uint64_t bytes_sent() const override; |
| 172 | uint32_t messages_received() const override; |
| 173 | uint64_t bytes_received() const override; |
| 174 | bool Send(const DataBuffer& buffer) override; |
| 175 | void SendAsync(DataBuffer buffer, |
| 176 | absl::AnyInvocable<void(RTCError) &&> on_complete) override; |
| 177 |
| 178 | // Close immediately, ignoring any queued data or closing procedure. |
| 179 | // This is called when the underlying SctpTransport is being destroyed. |
| 180 | // It is also called by the PeerConnection if SCTP ID assignment fails. |
| 181 | void CloseAbruptlyWithError(RTCError error); |
| 182 | // Specializations of CloseAbruptlyWithError |
| 183 | void CloseAbruptlyWithDataChannelFailure(const std::string& message); |
| 184 |
| 185 | // Called when the SctpTransport's ready to use. That can happen when we've |
| 186 | // finished negotiation, or if the channel was created after negotiation has |
| 187 | // already finished. |
| 188 | void OnTransportReady(); |
| 189 |
| 190 | void OnDataReceived(DataMessageType type, |
| 191 | const rtc::CopyOnWriteBuffer& payload); |
| 192 |
| 193 | // Sets the SCTP sid and adds to transport layer if not set yet. Should only |
| 194 | // be called once. |
| 195 | void SetSctpSid_n(StreamId sid); |
| 196 |
| 197 | // The remote side started the closing procedure by resetting its outgoing |
| 198 | // stream (our incoming stream). Sets state to kClosing. |
| 199 | void OnClosingProcedureStartedRemotely(); |
| 200 | // The closing procedure is complete; both incoming and outgoing stream |
| 201 | // resets are done and the channel can transition to kClosed. Called |
| 202 | // asynchronously after RemoveSctpDataStream. |
| 203 | void OnClosingProcedureComplete(); |
| 204 | // Called when the transport channel is created. |
| 205 | void OnTransportChannelCreated(); |
| 206 | // Called when the transport channel is unusable. |
| 207 | // This method makes sure the DataChannel is disconnected and changes state |
| 208 | // to kClosed. |
| 209 | void OnTransportChannelClosed(RTCError error); |
| 210 |
| 211 | DataChannelStats GetStats() const; |
| 212 |
| 213 | // Returns a unique identifier that's guaranteed to always be available, |
| 214 | // doesn't change throughout SctpDataChannel's lifetime and is used for |
| 215 | // stats purposes (see also `GetStats()`). |
| 216 | int internal_id() const { return internal_id_; } |
| 217 |
| 218 | StreamId sid_n() const { |
| 219 | RTC_DCHECK_RUN_ON(network_thread_); |
| 220 | return id_n_; |
| 221 | } |
| 222 |
| 223 | // Reset the allocator for internal ID values for testing, so that |
| 224 | // the internal IDs generated are predictable. Test only. |
| 225 | static void ResetInternalIdAllocatorForTesting(int new_value); |
| 226 |
| 227 | protected: |
| 228 | SctpDataChannel(const InternalDataChannelInit& config, |
| 229 | rtc::WeakPtr<SctpDataChannelControllerInterface> controller, |
| 230 | const std::string& label, |
| 231 | bool connected_to_transport, |
| 232 | rtc::Thread* signaling_thread, |
| 233 | rtc::Thread* network_thread); |
| 234 | ~SctpDataChannel() override; |
| 235 |
| 236 | private: |
| 237 | class ObserverAdapter; |
| 238 |
| 239 | // The OPEN(_ACK) signaling state. |
| 240 | enum HandshakeState { |
| 241 | kHandshakeInit, |
| 242 | kHandshakeShouldSendOpen, |
| 243 | kHandshakeShouldSendAck, |
| 244 | kHandshakeWaitingForAck, |
| 245 | kHandshakeReady |
| 246 | }; |
| 247 |
| 248 | RTCError SendImpl(DataBuffer buffer) RTC_RUN_ON(network_thread_); |
| 249 | void UpdateState() RTC_RUN_ON(network_thread_); |
| 250 | void SetState(DataState state) RTC_RUN_ON(network_thread_); |
| 251 |
| 252 | void DeliverQueuedReceivedData() RTC_RUN_ON(network_thread_); |
| 253 |
| 254 | void SendQueuedDataMessages() RTC_RUN_ON(network_thread_); |
| 255 | RTCError SendDataMessage(const DataBuffer& buffer, bool queue_if_blocked) |
| 256 | RTC_RUN_ON(network_thread_); |
| 257 | bool QueueSendDataMessage(const DataBuffer& buffer) |
| 258 | RTC_RUN_ON(network_thread_); |
| 259 |
| 260 | void SendQueuedControlMessages() RTC_RUN_ON(network_thread_); |
| 261 | bool SendControlMessage(const rtc::CopyOnWriteBuffer& buffer) |
| 262 | RTC_RUN_ON(network_thread_); |
| 263 |
| 264 | bool connected_to_transport() const RTC_RUN_ON(network_thread_) { |
| 265 | return network_safety_->alive(); |
| 266 | } |
| 267 |
| 268 | rtc::Thread* const signaling_thread_; |
| 269 | rtc::Thread* const network_thread_; |
| 270 | StreamId id_n_ RTC_GUARDED_BY(network_thread_); |
| 271 | const int internal_id_; |
| 272 | const std::string label_; |
| 273 | const std::string protocol_; |
| 274 | const absl::optional<int> max_retransmit_time_; |
| 275 | const absl::optional<int> max_retransmits_; |
| 276 | const absl::optional<Priority> priority_; |
| 277 | const bool negotiated_; |
| 278 | const bool ordered_; |
| 279 |
| 280 | DataChannelObserver* observer_ RTC_GUARDED_BY(network_thread_) = nullptr; |
| 281 | std::unique_ptr<ObserverAdapter> observer_adapter_; |
| 282 | DataState state_ RTC_GUARDED_BY(network_thread_) = kConnecting; |
| 283 | RTCError error_ RTC_GUARDED_BY(network_thread_); |
| 284 | uint32_t messages_sent_ RTC_GUARDED_BY(network_thread_) = 0; |
| 285 | uint64_t bytes_sent_ RTC_GUARDED_BY(network_thread_) = 0; |
| 286 | uint32_t messages_received_ RTC_GUARDED_BY(network_thread_) = 0; |
| 287 | uint64_t bytes_received_ RTC_GUARDED_BY(network_thread_) = 0; |
| 288 | rtc::WeakPtr<SctpDataChannelControllerInterface> controller_ |
| 289 | RTC_GUARDED_BY(network_thread_); |
| 290 | HandshakeState handshake_state_ RTC_GUARDED_BY(network_thread_) = |
| 291 | kHandshakeInit; |
| 292 | // Did we already start the graceful SCTP closing procedure? |
| 293 | bool started_closing_procedure_ RTC_GUARDED_BY(network_thread_) = false; |
| 294 | // Control messages that always have to get sent out before any queued |
| 295 | // data. |
| 296 | PacketQueue queued_control_data_ RTC_GUARDED_BY(network_thread_); |
| 297 | PacketQueue queued_received_data_ RTC_GUARDED_BY(network_thread_); |
| 298 | PacketQueue queued_send_data_ RTC_GUARDED_BY(network_thread_); |
| 299 | rtc::scoped_refptr<PendingTaskSafetyFlag> network_safety_ = |
| 300 | PendingTaskSafetyFlag::CreateDetachedInactive(); |
| 301 | }; |
| 302 |
| 303 | } // namespace webrtc |
| 304 |
| 305 | #endif // PC_SCTP_DATA_CHANNEL_H_ |
| 306 |