| 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 | #include "pc/data_channel_controller.h" |
| 12 |
| 13 | #include <utility> |
| 14 |
| 15 | #include "absl/algorithm/container.h" |
| 16 | #include "api/peer_connection_interface.h" |
| 17 | #include "api/rtc_error.h" |
| 18 | #include "pc/peer_connection_internal.h" |
| 19 | #include "pc/sctp_utils.h" |
| 20 | #include "rtc_base/logging.h" |
| 21 |
| 22 | namespace webrtc { |
| 23 |
| 24 | DataChannelController::~DataChannelController() { |
| 25 | RTC_DCHECK(sctp_data_channels_n_.empty()) |
| 26 | << "Missing call to TeardownDataChannelTransport_n?"; |
| 27 | RTC_DCHECK(!signaling_safety_.flag()->alive()) |
| 28 | << "Missing call to PrepareForShutdown?"; |
| 29 | } |
| 30 |
| 31 | bool DataChannelController::HasDataChannels() const { |
| 32 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 33 | return channel_usage_ == DataChannelUsage::kInUse; |
| 34 | } |
| 35 |
| 36 | bool DataChannelController::HasUsedDataChannels() const { |
| 37 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 38 | return channel_usage_ != DataChannelUsage::kNeverUsed; |
| 39 | } |
| 40 |
| 41 | RTCError DataChannelController::SendData( |
| 42 | StreamId sid, |
| 43 | const SendDataParams& params, |
| 44 | const rtc::CopyOnWriteBuffer& payload) { |
| 45 | RTC_DCHECK_RUN_ON(network_thread()); |
| 46 | if (!data_channel_transport_) { |
| 47 | RTC_LOG(LS_ERROR) << "SendData called before transport is ready"; |
| 48 | return RTCError(RTCErrorType::INVALID_STATE); |
| 49 | } |
| 50 | return data_channel_transport_->SendData(sid.stream_id_int(), params, |
| 51 | payload); |
| 52 | } |
| 53 |
| 54 | void DataChannelController::AddSctpDataStream(StreamId sid) { |
| 55 | RTC_DCHECK_RUN_ON(network_thread()); |
| 56 | RTC_DCHECK(sid.HasValue()); |
| 57 | if (data_channel_transport_) { |
| 58 | data_channel_transport_->OpenChannel(sid.stream_id_int()); |
| 59 | } |
| 60 | } |
| 61 |
| 62 | void DataChannelController::RemoveSctpDataStream(StreamId sid) { |
| 63 | RTC_DCHECK_RUN_ON(network_thread()); |
| 64 | if (data_channel_transport_) { |
| 65 | data_channel_transport_->CloseChannel(sid.stream_id_int()); |
| 66 | } |
| 67 | } |
| 68 |
| 69 | void DataChannelController::OnChannelStateChanged( |
| 70 | SctpDataChannel* channel, |
| 71 | DataChannelInterface::DataState state) { |
| 72 | RTC_DCHECK_RUN_ON(network_thread()); |
| 73 |
| 74 | // Stash away the internal id here in case `OnSctpDataChannelClosed` ends up |
| 75 | // releasing the last reference to the channel. |
| 76 | const int channel_id = channel->internal_id(); |
| 77 |
| 78 | if (state == DataChannelInterface::DataState::kClosed) |
| 79 | OnSctpDataChannelClosed(channel); |
| 80 |
| 81 | DataChannelUsage channel_usage = sctp_data_channels_n_.empty() |
| 82 | ? DataChannelUsage::kHaveBeenUsed |
| 83 | : DataChannelUsage::kInUse; |
| 84 | signaling_thread()->PostTask(SafeTask( |
| 85 | signaling_safety_.flag(), [this, channel_id, state, channel_usage] { |
| 86 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 87 | channel_usage_ = channel_usage; |
| 88 | pc_->OnSctpDataChannelStateChanged(channel_id, state); |
| 89 | })); |
| 90 | } |
| 91 |
| 92 | void DataChannelController::OnDataReceived( |
| 93 | int channel_id, |
| 94 | DataMessageType type, |
| 95 | const rtc::CopyOnWriteBuffer& buffer) { |
| 96 | RTC_DCHECK_RUN_ON(network_thread()); |
| 97 |
| 98 | if (HandleOpenMessage_n(channel_id, type, buffer)) |
| 99 | return; |
| 100 |
| 101 | auto it = absl::c_find_if(sctp_data_channels_n_, [&](const auto& c) { |
| 102 | return c->sid_n().stream_id_int() == channel_id; |
| 103 | }); |
| 104 |
| 105 | if (it != sctp_data_channels_n_.end()) |
| 106 | (*it)->OnDataReceived(type, buffer); |
| 107 | } |
| 108 |
| 109 | void DataChannelController::OnChannelClosing(int channel_id) { |
| 110 | RTC_DCHECK_RUN_ON(network_thread()); |
| 111 | auto it = absl::c_find_if(sctp_data_channels_n_, [&](const auto& c) { |
| 112 | return c->sid_n().stream_id_int() == channel_id; |
| 113 | }); |
| 114 |
| 115 | if (it != sctp_data_channels_n_.end()) |
| 116 | (*it)->OnClosingProcedureStartedRemotely(); |
| 117 | } |
| 118 |
| 119 | void DataChannelController::OnChannelClosed(int channel_id) { |
| 120 | RTC_DCHECK_RUN_ON(network_thread()); |
| 121 | StreamId sid(channel_id); |
| 122 | sid_allocator_.ReleaseSid(sid); |
| 123 | auto it = absl::c_find_if(sctp_data_channels_n_, |
| 124 | [&](const auto& c) { return c->sid_n() == sid; }); |
| 125 |
| 126 | if (it != sctp_data_channels_n_.end()) { |
| 127 | rtc::scoped_refptr<SctpDataChannel> channel = std::move(*it); |
| 128 | sctp_data_channels_n_.erase(it); |
| 129 | channel->OnClosingProcedureComplete(); |
| 130 | } |
| 131 | } |
| 132 |
| 133 | void DataChannelController::OnReadyToSend() { |
| 134 | RTC_DCHECK_RUN_ON(network_thread()); |
| 135 | auto copy = sctp_data_channels_n_; |
| 136 | for (const auto& channel : copy) { |
| 137 | if (channel->sid_n().HasValue()) { |
| 138 | channel->OnTransportReady(); |
| 139 | } else { |
| 140 | // This happens for role==SSL_SERVER channels when we get notified by |
| 141 | // the transport *before* the SDP code calls `AllocateSctpSids` to |
| 142 | // trigger assignment of sids. In this case OnTransportReady() will be |
| 143 | // called from within `AllocateSctpSids` below. |
| 144 | RTC_LOG(LS_INFO) << "OnReadyToSend: Still waiting for an id for channel."; |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 |
| 149 | void DataChannelController::OnTransportClosed(RTCError error) { |
| 150 | RTC_DCHECK_RUN_ON(network_thread()); |
| 151 |
| 152 | // This loop will close all data channels and trigger a callback to |
| 153 | // `OnSctpDataChannelClosed`. We'll empty `sctp_data_channels_n_`, first |
| 154 | // and `OnSctpDataChannelClosed` will become a noop but we'll release the |
| 155 | // StreamId here. |
| 156 | std::vector<rtc::scoped_refptr<SctpDataChannel>> temp_sctp_dcs; |
| 157 | temp_sctp_dcs.swap(sctp_data_channels_n_); |
| 158 | for (const auto& channel : temp_sctp_dcs) { |
| 159 | channel->OnTransportChannelClosed(error); |
| 160 | sid_allocator_.ReleaseSid(channel->sid_n()); |
| 161 | } |
| 162 | } |
| 163 |
| 164 | void DataChannelController::SetupDataChannelTransport_n( |
| 165 | DataChannelTransportInterface* transport) { |
| 166 | RTC_DCHECK_RUN_ON(network_thread()); |
| 167 | RTC_DCHECK(transport); |
| 168 | set_data_channel_transport(transport); |
| 169 | } |
| 170 |
| 171 | void DataChannelController::PrepareForShutdown() { |
| 172 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 173 | signaling_safety_.reset(PendingTaskSafetyFlag::CreateDetachedInactive()); |
| 174 | if (channel_usage_ != DataChannelUsage::kNeverUsed) |
| 175 | channel_usage_ = DataChannelUsage::kHaveBeenUsed; |
| 176 | } |
| 177 |
| 178 | void DataChannelController::TeardownDataChannelTransport_n(RTCError error) { |
| 179 | RTC_DCHECK_RUN_ON(network_thread()); |
| 180 | OnTransportClosed(error); |
| 181 | set_data_channel_transport(nullptr); |
| 182 | RTC_DCHECK(sctp_data_channels_n_.empty()); |
| 183 | weak_factory_.InvalidateWeakPtrs(); |
| 184 | } |
| 185 |
| 186 | void DataChannelController::OnTransportChanged( |
| 187 | DataChannelTransportInterface* new_data_channel_transport) { |
| 188 | RTC_DCHECK_RUN_ON(network_thread()); |
| 189 | if (data_channel_transport_ && |
| 190 | data_channel_transport_ != new_data_channel_transport) { |
| 191 | // Changed which data channel transport is used for `sctp_mid_` (eg. now |
| 192 | // it's bundled). |
| 193 | set_data_channel_transport(new_data_channel_transport); |
| 194 | } |
| 195 | } |
| 196 |
| 197 | std::vector<DataChannelStats> DataChannelController::GetDataChannelStats() |
| 198 | const { |
| 199 | RTC_DCHECK_RUN_ON(network_thread()); |
| 200 | std::vector<DataChannelStats> stats; |
| 201 | stats.reserve(sctp_data_channels_n_.size()); |
| 202 | for (const auto& channel : sctp_data_channels_n_) |
| 203 | stats.push_back(channel->GetStats()); |
| 204 | return stats; |
| 205 | } |
| 206 |
| 207 | bool DataChannelController::HandleOpenMessage_n( |
| 208 | int channel_id, |
| 209 | DataMessageType type, |
| 210 | const rtc::CopyOnWriteBuffer& buffer) { |
| 211 | if (type != DataMessageType::kControl || !IsOpenMessage(buffer)) |
| 212 | return false; |
| 213 |
| 214 | // Received OPEN message; parse and signal that a new data channel should |
| 215 | // be created. |
| 216 | std::string label; |
| 217 | InternalDataChannelInit config; |
| 218 | config.id = channel_id; |
| 219 | if (!ParseDataChannelOpenMessage(buffer, &label, &config)) { |
| 220 | RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid " |
| 221 | << channel_id; |
| 222 | } else { |
| 223 | config.open_handshake_role = InternalDataChannelInit::kAcker; |
| 224 | auto channel_or_error = CreateDataChannel(label, config); |
| 225 | if (channel_or_error.ok()) { |
| 226 | signaling_thread()->PostTask(SafeTask( |
| 227 | signaling_safety_.flag(), |
| 228 | [this, channel = channel_or_error.MoveValue(), |
| 229 | ready_to_send = data_channel_transport_->IsReadyToSend()] { |
| 230 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 231 | OnDataChannelOpenMessage(std::move(channel), ready_to_send); |
| 232 | })); |
| 233 | } else { |
| 234 | RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message." |
| 235 | << ToString(channel_or_error.error().type()); |
| 236 | } |
| 237 | } |
| 238 | return true; |
| 239 | } |
| 240 |
| 241 | void DataChannelController::OnDataChannelOpenMessage( |
| 242 | rtc::scoped_refptr<SctpDataChannel> channel, |
| 243 | bool ready_to_send) { |
| 244 | channel_usage_ = DataChannelUsage::kInUse; |
| 245 | auto proxy = SctpDataChannel::CreateProxy(channel, signaling_safety_.flag()); |
| 246 |
| 247 | pc_->Observer()->OnDataChannel(proxy); |
| 248 | pc_->NoteDataAddedEvent(); |
| 249 |
| 250 | if (ready_to_send) { |
| 251 | network_thread()->PostTask([channel = std::move(channel)] { |
| 252 | if (channel->state() != DataChannelInterface::DataState::kClosed) |
| 253 | channel->OnTransportReady(); |
| 254 | }); |
| 255 | } |
| 256 | } |
| 257 |
| 258 | // RTC_RUN_ON(network_thread()) |
| 259 | RTCError DataChannelController::ReserveOrAllocateSid( |
| 260 | StreamId& sid, |
| 261 | absl::optional<rtc::SSLRole> fallback_ssl_role) { |
| 262 | if (sid.HasValue()) { |
| 263 | return sid_allocator_.ReserveSid(sid) |
| 264 | ? RTCError::OK() |
| 265 | : RTCError(RTCErrorType::INVALID_RANGE, |
| 266 | "StreamId out of range or reserved."); |
| 267 | } |
| 268 |
| 269 | // Attempt to allocate an ID based on the negotiated role. |
| 270 | absl::optional<rtc::SSLRole> role = pc_->GetSctpSslRole_n(); |
| 271 | if (!role) |
| 272 | role = fallback_ssl_role; |
| 273 | if (role) { |
| 274 | sid = sid_allocator_.AllocateSid(*role); |
| 275 | if (!sid.HasValue()) |
| 276 | return RTCError(RTCErrorType::RESOURCE_EXHAUSTED); |
| 277 | } |
| 278 | // When we get here, we may still not have an ID, but that's a supported case |
| 279 | // whereby an id will be assigned later. |
| 280 | RTC_DCHECK(sid.HasValue() || !role); |
| 281 | return RTCError::OK(); |
| 282 | } |
| 283 |
| 284 | // RTC_RUN_ON(network_thread()) |
| 285 | RTCErrorOr<rtc::scoped_refptr<SctpDataChannel>> |
| 286 | DataChannelController::CreateDataChannel(const std::string& label, |
| 287 | InternalDataChannelInit& config) { |
| 288 | StreamId sid(config.id); |
| 289 | RTCError err = ReserveOrAllocateSid(sid, config.fallback_ssl_role); |
| 290 | if (!err.ok()) |
| 291 | return err; |
| 292 |
| 293 | // In case `sid` has changed. Update `config` accordingly. |
| 294 | config.id = sid.stream_id_int(); |
| 295 |
| 296 | rtc::scoped_refptr<SctpDataChannel> channel = SctpDataChannel::Create( |
| 297 | weak_factory_.GetWeakPtr(), label, data_channel_transport_ != nullptr, |
| 298 | config, signaling_thread(), network_thread()); |
| 299 | RTC_DCHECK(channel); |
| 300 | sctp_data_channels_n_.push_back(channel); |
| 301 |
| 302 | // If we have an id already, notify the transport. |
| 303 | if (sid.HasValue()) |
| 304 | AddSctpDataStream(sid); |
| 305 |
| 306 | return channel; |
| 307 | } |
| 308 |
| 309 | RTCErrorOr<rtc::scoped_refptr<DataChannelInterface>> |
| 310 | DataChannelController::InternalCreateDataChannelWithProxy( |
| 311 | const std::string& label, |
| 312 | const InternalDataChannelInit& config) { |
| 313 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 314 | RTC_DCHECK(!pc_->IsClosed()); |
| 315 | if (!config.IsValid()) { |
| 316 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 317 | "Invalid DataChannelInit"); |
| 318 | } |
| 319 |
| 320 | bool ready_to_send = false; |
| 321 | InternalDataChannelInit new_config = config; |
| 322 | StreamId sid(new_config.id); |
| 323 | auto ret = network_thread()->BlockingCall( |
| 324 | [&]() -> RTCErrorOr<rtc::scoped_refptr<SctpDataChannel>> { |
| 325 | RTC_DCHECK_RUN_ON(network_thread()); |
| 326 | auto channel = CreateDataChannel(label, new_config); |
| 327 | if (!channel.ok()) |
| 328 | return channel; |
| 329 | ready_to_send = |
| 330 | data_channel_transport_ && data_channel_transport_->IsReadyToSend(); |
| 331 | if (ready_to_send) { |
| 332 | // If the transport is ready to send because the initial channel |
| 333 | // ready signal may have been sent before the DataChannel creation. |
| 334 | // This has to be done async because the upper layer objects (e.g. |
| 335 | // Chrome glue and WebKit) are not wired up properly until after |
| 336 | // `InternalCreateDataChannelWithProxy` returns. |
| 337 | network_thread()->PostTask([channel = channel.value()] { |
| 338 | if (channel->state() != DataChannelInterface::DataState::kClosed) |
| 339 | channel->OnTransportReady(); |
| 340 | }); |
| 341 | } |
| 342 |
| 343 | return channel; |
| 344 | }); |
| 345 |
| 346 | if (!ret.ok()) |
| 347 | return ret.MoveError(); |
| 348 |
| 349 | channel_usage_ = DataChannelUsage::kInUse; |
| 350 | return SctpDataChannel::CreateProxy(ret.MoveValue(), |
| 351 | signaling_safety_.flag()); |
| 352 | } |
| 353 |
| 354 | void DataChannelController::AllocateSctpSids(rtc::SSLRole role) { |
| 355 | RTC_DCHECK_RUN_ON(network_thread()); |
| 356 |
| 357 | const bool ready_to_send = |
| 358 | data_channel_transport_ && data_channel_transport_->IsReadyToSend(); |
| 359 |
| 360 | std::vector<std::pair<SctpDataChannel*, StreamId>> channels_to_update; |
| 361 | std::vector<rtc::scoped_refptr<SctpDataChannel>> channels_to_close; |
| 362 | for (auto it = sctp_data_channels_n_.begin(); |
| 363 | it != sctp_data_channels_n_.end();) { |
| 364 | if (!(*it)->sid_n().HasValue()) { |
| 365 | StreamId sid = sid_allocator_.AllocateSid(role); |
| 366 | if (sid.HasValue()) { |
| 367 | (*it)->SetSctpSid_n(sid); |
| 368 | AddSctpDataStream(sid); |
| 369 | if (ready_to_send) { |
| 370 | RTC_LOG(LS_INFO) << "AllocateSctpSids: Id assigned, ready to send."; |
| 371 | (*it)->OnTransportReady(); |
| 372 | } |
| 373 | channels_to_update.push_back(std::make_pair((*it).get(), sid)); |
| 374 | } else { |
| 375 | channels_to_close.push_back(std::move(*it)); |
| 376 | it = sctp_data_channels_n_.erase(it); |
| 377 | continue; |
| 378 | } |
| 379 | } |
| 380 | ++it; |
| 381 | } |
| 382 |
| 383 | // Since closing modifies the list of channels, we have to do the actual |
| 384 | // closing outside the loop. |
| 385 | for (const auto& channel : channels_to_close) { |
| 386 | channel->CloseAbruptlyWithDataChannelFailure("Failed to allocate SCTP SID"); |
| 387 | } |
| 388 | } |
| 389 |
| 390 | void DataChannelController::OnSctpDataChannelClosed(SctpDataChannel* channel) { |
| 391 | RTC_DCHECK_RUN_ON(network_thread()); |
| 392 | // After the closing procedure is done, it's safe to use this ID for |
| 393 | // another data channel. |
| 394 | if (channel->sid_n().HasValue()) { |
| 395 | sid_allocator_.ReleaseSid(channel->sid_n()); |
| 396 | } |
| 397 | auto it = absl::c_find_if(sctp_data_channels_n_, |
| 398 | [&](const auto& c) { return c.get() == channel; }); |
| 399 | if (it != sctp_data_channels_n_.end()) |
| 400 | sctp_data_channels_n_.erase(it); |
| 401 | } |
| 402 |
| 403 | void DataChannelController::set_data_channel_transport( |
| 404 | DataChannelTransportInterface* transport) { |
| 405 | RTC_DCHECK_RUN_ON(network_thread()); |
| 406 |
| 407 | if (data_channel_transport_) |
| 408 | data_channel_transport_->SetDataSink(nullptr); |
| 409 |
| 410 | data_channel_transport_ = transport; |
| 411 |
| 412 | if (data_channel_transport_) { |
| 413 | // There's a new data channel transport. This needs to be signaled to the |
| 414 | // `sctp_data_channels_n_` so that they can reopen and reconnect. This is |
| 415 | // necessary when bundling is applied. |
| 416 | NotifyDataChannelsOfTransportCreated(); |
| 417 | data_channel_transport_->SetDataSink(this); |
| 418 | } |
| 419 | } |
| 420 |
| 421 | void DataChannelController::NotifyDataChannelsOfTransportCreated() { |
| 422 | RTC_DCHECK_RUN_ON(network_thread()); |
| 423 | RTC_DCHECK(data_channel_transport_); |
| 424 |
| 425 | for (const auto& channel : sctp_data_channels_n_) { |
| 426 | if (channel->sid_n().HasValue()) |
| 427 | AddSctpDataStream(channel->sid_n()); |
| 428 | channel->OnTransportChannelCreated(); |
| 429 | } |
| 430 | } |
| 431 |
| 432 | rtc::Thread* DataChannelController::network_thread() const { |
| 433 | return pc_->network_thread(); |
| 434 | } |
| 435 |
| 436 | rtc::Thread* DataChannelController::signaling_thread() const { |
| 437 | return pc_->signaling_thread(); |
| 438 | } |
| 439 |
| 440 | } // namespace webrtc |
| 441 |