Skip to content

[bug] Potential resource leak due to unclosed listener in api.go #1934

@docker-agent

Description

@docker-agent

🟠 high - bug

File: cmd/root/api.go (line 88)

Code

ln, err := listenAndCloseOnCancel(ctx, f.listenAddr)
if err != nil {
	return err
}

Problem

The ln listener, created by listenAndCloseOnCancel, is not explicitly closed in the runAPICommand function. While listenAndCloseOnCancel itself spawns a goroutine to close the listener when the context is cancelled, if s.Serve(ctx, ln) returns an error before the context is cancelled, or if the Serve function does not explicitly close the listener itself, the listener may remain open, leading to a resource leak. This is a common pattern for resource leaks in Go where a resource is opened in one function and passed to another, and the original function doesn't ensure its closure.

Suggested Fix

Although listenAndCloseOnCancel attempts to close the listener on context cancellation, it's safer to add a defer ln.Close() right after the listener is successfully created in runAPICommand. This ensures the listener is closed regardless of how s.Serve exits or if the context is cancelled before s.Serve completes. This creates a redundant close if the listenAndCloseOnCancel goroutine or s.Serve closes it, but net.Listener.Close() is idempotent, so this is safe and defensive.


Found by nightly codebase scan

Metadata

Metadata

Assignees

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