Safeguard SctpDataChannel against detached controller

Since the lifetime of an SctpDataChannel is not strictly controlled
by its controller, the controller might go away before the channel
does. This CL guards against this.

Bug: webrtc:13931
Change-Id: I07046fe896d1a66bf89287429beb0587382a13a9
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/261940
Commit-Queue: Harald Alvestrand <hta@webrtc.org>
Reviewed-by: Florent Castelli <orphis@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#36852}
diff --git a/pc/data_channel_controller_unittest.cc b/pc/data_channel_controller_unittest.cc
index 16985f9..7a1f68a 100644
--- a/pc/data_channel_controller_unittest.cc
+++ b/pc/data_channel_controller_unittest.cc
@@ -13,6 +13,7 @@
 #include <memory>
 
 #include "pc/peer_connection_internal.h"
+#include "pc/sctp_data_channel.h"
 #include "pc/test/mock_peer_connection_internal.h"
 #include "test/gmock.h"
 #include "test/gtest.h"
@@ -44,7 +45,7 @@
   auto channel = dcc.InternalCreateDataChannelWithProxy(
       "label",
       std::make_unique<InternalDataChannelInit>(DataChannelInit()).get());
-  channel = nullptr;  // Should call destructor of channel
+  channel = nullptr;  // dcc holds a reference to channel, so not destroyed yet
 }
 
 TEST_F(DataChannelControllerTest, CreateDataChannelLateRelease) {
@@ -56,5 +57,19 @@
   channel = nullptr;
 }
 
+TEST_F(DataChannelControllerTest, CloseAfterControllerDestroyed) {
+  auto dcc = std::make_unique<DataChannelController>(pc_.get());
+  auto channel = dcc->InternalCreateDataChannelWithProxy(
+      "label",
+      std::make_unique<InternalDataChannelInit>(DataChannelInit()).get());
+  // Connect to provider
+  auto inner_channel =
+      DowncastProxiedDataChannelInterfaceToSctpDataChannelForTesting(
+          channel.get());
+  dcc->ConnectDataChannel(inner_channel);
+  dcc.reset();
+  channel->Close();
+}
+
 }  // namespace
 }  // namespace webrtc