Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

peer: Synchronize net.Conn with a mutex #3478

Merged
merged 1 commit into from
Mar 4, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions peer/peer.go
Original file line number Diff line number Diff line change
Expand Up @@ -460,10 +460,10 @@ type Peer struct {
bytesSent uint64
lastRecv int64
lastSend int64
connected int32
disconnect int32

conn net.Conn
conn net.Conn
connMtx sync.Mutex

// blake256Hasher is the hash.Hash object that is used by readMessage
// to calculate the hash of read mixing messages. Every peer's hasher
Expand Down Expand Up @@ -1918,23 +1918,27 @@ func (p *Peer) QueueInventoryImmediate(invVect *wire.InvVect) {
//
// This function is safe for concurrent access.
func (p *Peer) Connected() bool {
return atomic.LoadInt32(&p.connected) != 0 &&
atomic.LoadInt32(&p.disconnect) == 0
p.connMtx.Lock()
defer p.connMtx.Unlock()

return p.conn != nil && atomic.LoadInt32(&p.disconnect) == 0
}

// Disconnect disconnects the peer by closing the connection. Calling this
// function when the peer is already disconnected or in the process of
// disconnecting will have no effect.
func (p *Peer) Disconnect() {
if atomic.AddInt32(&p.disconnect, 1) != 1 {
return
}
p.connMtx.Lock()
defer p.connMtx.Unlock()

log.Tracef("Disconnecting %s", p)
if atomic.LoadInt32(&p.connected) != 0 {
if p.conn != nil {
p.conn.Close()
}
close(p.quit)

if atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {
close(p.quit)
}
}

// readRemoteVersionMsg waits for the next message to arrive from the remote
Expand Down Expand Up @@ -2146,13 +2150,20 @@ func (p *Peer) start() error {
// Calling this function when the peer is already connected will
// have no effect.
func (p *Peer) AssociateConnection(conn net.Conn) {
p.connMtx.Lock()

// Already connected?
if !atomic.CompareAndSwapInt32(&p.connected, 0, 1) {
if p.conn != nil {
p.connMtx.Unlock()
return
}

p.conn = conn
p.connMtx.Unlock()

p.statsMtx.Lock()
p.timeConnected = time.Now()
p.statsMtx.Unlock()

if p.inbound {
p.addr = p.conn.RemoteAddr().String()
Expand All @@ -2166,7 +2177,9 @@ func (p *Peer) AssociateConnection(conn net.Conn) {
p.Disconnect()
return
}
p.flagsMtx.Lock()
p.na = na
p.flagsMtx.Unlock()
}

go func(peer *Peer) {
Expand Down