[TCPConnection] Avoid dereferencing port() in OnClose().

Avoid de-referencing possibly gone port when posting tasks. Instead
use the network_thread() accessor for accessing the thread pointer.

Also including a safety check in OnClose callback as an extra check.

Bug: chromium:1316996
Change-Id: I8fa2c7b526a9db953f50bbbabb3e4b2fcef8221a
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/263900
Reviewed-by: Taylor Brandstetter <deadbeef@webrtc.org>
Commit-Queue: Tomas Gunnarsson <tommi@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#37013}
diff --git a/p2p/base/tcp_port.cc b/p2p/base/tcp_port.cc
index 2964c8b..433f087 100644
--- a/p2p/base/tcp_port.cc
+++ b/p2p/base/tcp_port.cc
@@ -506,7 +506,7 @@
     // We don't attempt reconnect right here. This is to avoid a case where the
     // shutdown is intentional and reconnect is not necessary. We only reconnect
     // when the connection is used to Send() or Ping().
-    port()->thread()->PostDelayedTask(
+    network_thread()->PostDelayedTask(
         webrtc::ToQueuedTask(network_safety_,
                              [this]() {
                                if (pretending_to_be_writable_) {
@@ -585,7 +585,7 @@
     // the StunRequests from the request_map_. And if this is in the stack
     // of Connection::Ping(), we are still using the request.
     // Unwind the stack and defer the FailAndPrune.
-    port()->thread()->PostTask(
+    network_thread()->PostTask(
         webrtc::ToQueuedTask(network_safety_, [this]() { FailAndPrune(); }));
   }
 }
@@ -596,8 +596,11 @@
   }
   socket->SignalReadPacket.connect(this, &TCPConnection::OnReadPacket);
   socket->SignalReadyToSend.connect(this, &TCPConnection::OnReadyToSend);
-  socket->SubscribeClose(
-      this, [this](rtc::AsyncPacketSocket* s, int err) { OnClose(s, err); });
+  socket->SubscribeClose(this, [this, safety = network_safety_.flag()](
+                                   rtc::AsyncPacketSocket* s, int err) {
+    if (safety->alive())
+      OnClose(s, err);
+  });
 }
 
 }  // namespace cricket