From 3d1bbf57a6a1cf0adb820b11c9b7621f04fd5e1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=BA=90=E6=96=87=E9=9B=A8?= <41315874+fumiama@users.noreply.github.com> Date: Fri, 21 Feb 2025 01:26:30 +0900 Subject: [PATCH] fix(tcp): close handing --- gold/p2p/tcp/tcp.go | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/gold/p2p/tcp/tcp.go b/gold/p2p/tcp/tcp.go index 6033ba5..8d2f1a2 100644 --- a/gold/p2p/tcp/tcp.go +++ b/gold/p2p/tcp/tcp.go @@ -158,6 +158,10 @@ func delsubs(i int, subs []*subconn) []*subconn { } func (conn *Conn) receive(tcpconn *net.TCPConn, hasvalidated bool) { + if conn.peers == nil { + return + } + ep, _ := newEndpoint(tcpconn.RemoteAddr().String(), &Config{ DialTimeout: conn.addr.dialtimeout, PeersTimeout: conn.addr.peerstimeout, @@ -186,6 +190,9 @@ func (conn *Conn) receive(tcpconn *net.TCPConn, hasvalidated bool) { conn.subs = append(conn.subs, &subconn{conn: tcpconn}) conn.sblk.Unlock() } else { + if conn.peers == nil { + return + } conn.peers.Set(ep.String(), tcpconn) } } @@ -202,6 +209,9 @@ func (conn *Conn) receive(tcpconn *net.TCPConn, hasvalidated bool) { conn.sblk.Unlock() }() } else { + if conn.peers == nil { + return + } defer conn.peers.Delete(ep.String()) } @@ -279,7 +289,7 @@ func (conn *Conn) keep(ep *EndPoint) { t := time.NewTicker(keepinterval) defer t.Stop() for range t.C { - if conn.addr == nil { + if conn.addr == nil || conn.peers == nil { return } tcpconn := conn.peers.Get(ep.String()) @@ -312,19 +322,24 @@ func (conn *Conn) keep(ep *EndPoint) { } func (conn *Conn) Close() error { - if conn.lstn != nil { - _ = conn.lstn.Close() - } - if conn.peers != nil { - conn.peers.Destroy() - } - if conn.recv != nil { - close(conn.recv) - } + lstn := conn.lstn + peers := conn.peers + recv := conn.recv conn.addr = nil conn.lstn = nil conn.peers = nil conn.recv = nil + + if lstn != nil { + _ = lstn.Close() + } + if peers != nil { + peers.Destroy() + } + if recv != nil { + close(recv) + } + return nil } @@ -343,6 +358,9 @@ func (conn *Conn) ReadFromPeer(b []byte) (int, p2p.EndPoint, error) { if p == nil { return 0, nil, net.ErrClosed } + if conn.peers == nil { + return 0, nil, net.ErrClosed + } conn.peers.Set(p.addr.String(), p.conn) if p.pckt.typ == packetTypeNormal { break