From 09764ad0e5c6e7bc9671d27ead7ab8214b67e6c8 Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Mon, 20 Jan 2025 04:00:57 -0800 Subject: [PATCH] fix(tm2/pkg/bft,os,p2p): close leaking resources (#3556) This change closes some leaking resources that were identified in a preliminary code read. Fixes #3029 Fixes #3030 Fixes #3031 --- tm2/pkg/bft/privval/utils.go | 9 ++++++++- tm2/pkg/os/tempfile.go | 11 +++++++---- tm2/pkg/p2p/transport.go | 8 +++++++- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/tm2/pkg/bft/privval/utils.go b/tm2/pkg/bft/privval/utils.go index c759d9dde9d..a98a36ef04a 100644 --- a/tm2/pkg/bft/privval/utils.go +++ b/tm2/pkg/bft/privval/utils.go @@ -25,7 +25,7 @@ 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) @@ -33,6 +33,13 @@ func NewSignerListener(listenAddr string, logger *slog.Logger) (*SignerListenerE if err != nil { return nil, err } + + defer func() { + if rerr != nil { + ln.Close() + } + }() + switch protocol { case "unix": listener = NewUnixListener(ln) diff --git a/tm2/pkg/os/tempfile.go b/tm2/pkg/os/tempfile.go index 277813051fd..46d97739b80 100644 --- a/tm2/pkg/os/tempfile.go +++ b/tm2/pkg/os/tempfile.go @@ -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) { diff --git a/tm2/pkg/p2p/transport.go b/tm2/pkg/p2p/transport.go index 9edef9a15e5..150072ad5eb 100644 --- a/tm2/pkg/p2p/transport.go +++ b/tm2/pkg/p2p/transport.go @@ -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.