From 94fdcc95f407c80080e4b7d9b6f7dee03bde7430 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:12:01 +0000 Subject: [PATCH] fix(ports): prevent goroutine leak when context is cancelled in ScanPorts Co-authored-by: mendsec <12684528+mendsec@users.noreply.github.com> --- .jules/bolt.md | 3 +++ CHANGELOG.md | 3 +++ pkg/ports/scanner.go | 6 +++++- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.jules/bolt.md b/.jules/bolt.md index dfc62b8..e7c364e 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -45,3 +45,6 @@ ## 2026-07-28 - [Validating Context Cancellation for Blocking OS Executions] **Learning:** Functions that wrap long-running system operations (such as `exec.CommandContext` or `net.DialContext`) generally handle context cancellation automatically, but early aborts for network calls need explicit testing. Merely relying on lower-level Go standard library propagation does not automatically guarantee zero side-effects if the cancellation happens before execution logic completes in consumer boundaries. **Action:** Always include fine-grained tests that explicitly pass a pre-cancelled context to network discovery and connection routines (e.g. Ping, LookupAddr) to definitively prove zero leakage of OS processes or goroutines on early aborts. +## 2026-11-06 - [Prevent Goroutine Leak on Unbuffered Channel Sends] +**Learning:** Worker goroutines can leak when sending on an unbuffered or full channel if the consumer prematurely stops reading due to context cancellation. +**Action:** Always wrap channel send operations in a `select` statement with `ctx.Done()` to prevent goroutines from blocking indefinitely when the consumer aborts. diff --git a/CHANGELOG.md b/CHANGELOG.md index 012be8e..d8f96cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- **ports**: Prevented goroutine leak in `ScanPorts` when context is cancelled mid-scan and the consumer stops reading from the result channel. + ## [0.7.0] - 2026-07-30 ### Added diff --git a/pkg/ports/scanner.go b/pkg/ports/scanner.go index 1ea867c..296ff95 100644 --- a/pkg/ports/scanner.go +++ b/pkg/ports/scanner.go @@ -54,7 +54,11 @@ func ScanPorts(ctx context.Context, ip string, ports []int, timeoutMs int) <-cha conn, err := dialer.DialContext(ctx, "tcp", address) if err == nil { conn.Close() - out <- p + select { + case out <- p: + case <-ctx.Done(): + return + } } } }()