Skip to content

Commit

Permalink
fix(tm2/pkg/bft,os,p2p): close leaking resources (#3556)
Browse files Browse the repository at this point in the history
This change closes some leaking resources that were identified in a
preliminary code read.

Fixes #3029
Fixes #3030
Fixes #3031
  • Loading branch information
odeke-em authored Jan 20, 2025
1 parent b1352ac commit 09764ad
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
9 changes: 8 additions & 1 deletion tm2/pkg/bft/privval/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,21 @@ func IsConnTimeout(err error) bool {
}

// NewSignerListener creates a new SignerListenerEndpoint using the corresponding listen address
func NewSignerListener(listenAddr string, logger *slog.Logger) (*SignerListenerEndpoint, error) {
func NewSignerListener(listenAddr string, logger *slog.Logger) (_ *SignerListenerEndpoint, rerr error) {
var listener net.Listener

protocol, address := osm.ProtocolAndAddress(listenAddr)
ln, err := net.Listen(protocol, address)
if err != nil {
return nil, err
}

defer func() {
if rerr != nil {
ln.Close()
}
}()

switch protocol {
case "unix":
listener = NewUnixListener(ln)
Expand Down
11 changes: 7 additions & 4 deletions tm2/pkg/os/tempfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,17 @@ func WriteFileAtomic(filename string, data []byte, perm os.FileMode) (err error)
}
break
}

// Clean up in any case.
defer func() {
f.Close()
os.Remove(f.Name())
}()

if i == atomicWriteFileMaxNumWriteAttempts {
return fmt.Errorf("could not create atomic write file after %d attempts", i)
}

// Clean up in any case. Defer stacking order is last-in-first-out.
defer os.Remove(f.Name())
defer f.Close()

if n, err := f.Write(data); err != nil {
return err
} else if n < len(data) {
Expand Down
8 changes: 7 additions & 1 deletion tm2/pkg/p2p/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,19 @@ func (mt *MultiplexTransport) Close() error {
}

// Listen starts an active process of listening for incoming connections [NON-BLOCKING]
func (mt *MultiplexTransport) Listen(addr types.NetAddress) error {
func (mt *MultiplexTransport) Listen(addr types.NetAddress) (rerr error) {
// Reserve a port, and start listening
ln, err := net.Listen("tcp", addr.DialString())
if err != nil {
return fmt.Errorf("unable to listen on address, %w", err)
}

defer func() {
if rerr != nil {
ln.Close()
}
}()

if addr.Port == 0 {
// net.Listen on port 0 means the kernel will auto-allocate a port
// - find out which one has been given to us.
Expand Down

0 comments on commit 09764ad

Please sign in to comment.