Close data channels when ID assignment fails.

This prevents crashes due to unassigned IDs.

Bug: chromium:945256
Change-Id: I63f3a17cc7dff07dab58a6bc59fe3606b23e8e18
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/129902
Reviewed-by: Seth Hampson <shampson@webrtc.org>
Commit-Queue: Harald Alvestrand <hta@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#27349}
diff --git a/pc/peer_connection.cc b/pc/peer_connection.cc
index 211c5a7..5b702e0 100644
--- a/pc/peer_connection.cc
+++ b/pc/peer_connection.cc
@@ -5102,16 +5102,23 @@
 }
 
 void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
+  std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
   for (const auto& channel : sctp_data_channels_) {
     if (channel->id() < 0) {
       int sid;
       if (!sid_allocator_.AllocateSid(role, &sid)) {
-        RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
+        RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
+        channels_to_close.push_back(channel);
         continue;
       }
       channel->SetSctpSid(sid);
     }
   }
+  // Since closing modifies the list of channels, we have to do the actual
+  // closing outside the loop.
+  for (const auto& channel : channels_to_close) {
+    channel->CloseAbruptly();
+  }
 }
 
 void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {