Skip to content

[bug] Redundant listener close in cleanup function #2070

@docker-agent

Description

@docker-agent

🟡 medium - bug

File: cmd/root/flags.go (line 154)

Code

func newListener(ctx context.Context, addr string) (net.Listener, func(), error) {
	ln, err := server.Listen(ctx, addr)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
	}
	stop := context.AfterFunc(ctx, func() {
		_ = ln.Close()
	})
	cleanup := func() {
		stop()
		_ = ln.Close()
	}
	return ln, cleanup, nil
}

Problem

The cleanup function, which is returned by newListener and intended to be deferred by the caller, closes the network listener (ln.Close()) twice. The first close happens indirectly when stop() is called. stop() is a context.AfterFunc that closes ln when the provided ctx is cancelled. The second close happens explicitly within the cleanup function. While calling Close() multiple times on a net.Listener might be harmless, it indicates redundant logic and could mask potential issues if ln.Close() had non-idempotent side effects.

Suggested Fix

Remove the redundant _ = ln.Close() call from the cleanup function. The listener is already handled by the context.AfterFunc triggered by stop().

func newListener(ctx context.Context, addr string) (net.Listener, func(), error) {
	ln, err := server.Listen(ctx, addr)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
	}
	stop := context.AfterFunc(ctx, func() {
		_ = ln.Close()
	})
	cleanup := func() {
		stop()
		// No need to close ln here, it's already handled by stop() when the context is cancelled.
	}
	return ln, cleanup, nil
}

Found by nightly codebase scan

Metadata

Metadata

Assignees

No one assigned

    Labels

    automatedIssues created by cagentkind/bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions