From: Matt Joiner <anacrolix@gmail.com>
Date: Fri, 22 Mar 2024 04:22:30 +0000 (+1100)
Subject: Fix deadlocking panic when checking for v2 upgrade when receiving handshake
X-Git-Tag: v1.56.0~35
X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=93f3f6f0db8e3b2eb2d4f18346dce8c04862da91;p=btrtrc.git

Fix deadlocking panic when checking for v2 upgrade when receiving handshake
---

diff --git a/client.go b/client.go
index 90a74d95..5e635f27 100644
--- a/client.go
+++ b/client.go
@@ -603,13 +603,12 @@ func (cl *Client) incomingConnection(nc net.Conn) {
 			network:         nc.RemoteAddr().Network(),
 			connString:      regularNetConnPeerConnConnString(nc),
 		})
-	defer func() {
-		cl.lock()
-		defer cl.unlock()
-		c.close()
-	}()
 	c.Discovery = PeerSourceIncoming
 	cl.runReceivedConn(c)
+
+	cl.lock()
+	c.close()
+	cl.unlock()
 }
 
 // Returns a handle to the given torrent, if it's present in the client.
@@ -1014,13 +1013,15 @@ func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
 	if err != nil {
 		return nil, fmt.Errorf("during bt handshake: %w", err)
 	}
+
 	cl.lock()
 	t = cl.torrentsByShortHash[ih]
-	if t.infoHashV2.Ok && *t.infoHashV2.Value.ToShort() == ih {
+	if t != nil && t.infoHashV2.Ok && *t.infoHashV2.Value.ToShort() == ih {
 		torrent.Add("v2 handshakes received", 1)
 		c.v2 = true
 	}
 	cl.unlock()
+
 	return
 }