From 25759b43a76da57444ed280941de2ff42d67209d Mon Sep 17 00:00:00 2001 From: Prateek Sharma Date: Sun, 6 Sep 2026 21:10:42 +0530 Subject: [PATCH 1/7] Validate the configured port range at load time port_range_start > port_range_end (or one set without the other) was previously undefined behavior -- nothing checked it. Config.Validate rejects it clearly at config load time instead, ahead of internal/portpool depending on the range actually being well-formed. --- internal/config/config.go | 28 ++++++++++++++++++ internal/config/config_test.go | 54 ++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 internal/config/config_test.go diff --git a/internal/config/config.go b/internal/config/config.go index 2f48364..1463912 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -75,9 +75,37 @@ func Load() (*Config, error) { if err := toml.Unmarshal(data, &cfg); err != nil { return nil, fmt.Errorf("parse config %s: %w", p, err) } + if err := cfg.Validate(); err != nil { + return nil, fmt.Errorf("invalid config %s: %w", p, err) + } return &cfg, nil } +// Validate reports whether cfg's fields are internally consistent. Load +// calls this after decoding config.toml, so a malformed port range (the +// only field pair with a relationship to check today) fails loudly at +// startup instead of producing undefined behavior later when +// internal/portpool tries to use it. +func (c Config) Validate() error { + if c.PortRangeStart < 0 || c.PortRangeEnd < 0 { + return fmt.Errorf("port_range_start and port_range_end must not be negative") + } + switch { + case c.PortRangeStart == 0 && c.PortRangeEnd == 0: + // Both unset: "let the OS pick", the documented zero-value + // convention. Nothing to validate. + return nil + case c.PortRangeStart == 0: + return fmt.Errorf("port_range_start must be set when port_range_end (%d) is set", c.PortRangeEnd) + case c.PortRangeEnd == 0: + return fmt.Errorf("port_range_end must be set when port_range_start (%d) is set", c.PortRangeStart) + case c.PortRangeStart > c.PortRangeEnd: + return fmt.Errorf("port_range_end (%d) must be >= port_range_start (%d)", c.PortRangeEnd, c.PortRangeStart) + default: + return nil + } +} + // Save writes cfg to ~/.tocli/config.toml. func Save(cfg *Config) error { p, err := path() diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..4e03da7 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,54 @@ +package config + +import "testing" + +// TestConfig_Validate covers the port-range checks Load now enforces: a +// malformed range (inverted, or half-specified) must be rejected clearly +// rather than left to produce undefined behavior later in +// internal/portpool. +func TestConfig_Validate(t *testing.T) { + tests := []struct { + name string + cfg Config + wantErr bool + }{ + {"both zero (let the OS pick)", Config{}, false}, + {"valid single-port range", Config{PortRangeStart: 42069, PortRangeEnd: 42069}, false}, + {"valid multi-port range", Config{PortRangeStart: 6000, PortRangeEnd: 6010}, false}, + {"inverted range", Config{PortRangeStart: 6010, PortRangeEnd: 6000}, true}, + {"start set, end zero", Config{PortRangeStart: 6000}, true}, + {"end set, start zero", Config{PortRangeEnd: 6000}, true}, + {"negative start", Config{PortRangeStart: -1, PortRangeEnd: 6000}, true}, + {"negative end", Config{PortRangeStart: 6000, PortRangeEnd: -1}, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.cfg.Validate() + if tt.wantErr && err == nil { + t.Fatalf("Validate() = nil, want an error for %+v", tt.cfg) + } + if !tt.wantErr && err != nil { + t.Fatalf("Validate() = %v, want nil for %+v", err, tt.cfg) + } + }) + } +} + +// TestLoad_RejectsInvertedPortRange confirms the check is actually wired +// into Load, not just Validate in isolation: a config.toml with +// port_range_start > port_range_end must fail to load with a clear error. +func TestLoad_RejectsInvertedPortRange(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + + cfg := Default() + cfg.PortRangeStart = 6010 + cfg.PortRangeEnd = 6000 + if err := Save(&cfg); err != nil { + t.Fatalf("save invalid config: %v", err) + } + + if _, err := Load(); err == nil { + t.Fatal("Load() succeeded on a config with port_range_start > port_range_end, want an error") + } +} From 3f00b9b0dfb3084e889809a8bb5fdc676b519bae Mon Sep 17 00:00:00 2001 From: Prateek Sharma Date: Sun, 6 Sep 2026 21:11:02 +0530 Subject: [PATCH 2/7] Add AcquireLockBlocking alongside the existing non-blocking AcquireLock Refactors the shared flock/open/release logic out of AcquireLock into a private acquireLock(path, flags) so the two variants share it rather than duplicating it. AcquireLock's non-blocking semantics fit its existing use (the per-torrent spawn lock: contention there means another process already owns this one, give up). A different, upcoming use -- coordinating access to a shared port registry file (internal/portpool) -- needs the opposite: brief, expected contention where waiting a moment is the right response, not failing immediately. Unused until that lands. --- internal/process/lock.go | 24 +++++++++++++++++++++++- internal/process/lock_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/internal/process/lock.go b/internal/process/lock.go index 2333dff..be1c1e4 100644 --- a/internal/process/lock.go +++ b/internal/process/lock.go @@ -32,13 +32,35 @@ var ErrLockHeld = errors.New("lock already held by another process") // still released when the process exits and the kernel closes its fds). On // failure, err is non-nil (wrapping ErrLockHeld when contended) and there // is nothing to release. +// +// Non-blocking is the right fit here because contention on this lock means +// "another process already owns this specific resource, give up" (e.g. the +// per-torrent lock in store.LockPath -- see its doc comment) rather than +// "briefly wait your turn". For the latter case, see AcquireLockBlocking. func AcquireLock(path string) (release func() error, err error) { + return acquireLock(path, syscall.LOCK_EX|syscall.LOCK_NB) +} + +// AcquireLockBlocking takes an exclusive advisory lock (flock) on the file +// at path, the same as AcquireLock, except it waits for the lock to become +// available rather than failing immediately if it's currently held. +// +// This fits a different kind of contention than AcquireLock's: brief, +// expected coordination over a shared resource (see internal/portpool's +// port registry file) where the right response to finding it locked is to +// wait a moment for the current holder to finish its quick read-modify- +// write, not to give up. +func AcquireLockBlocking(path string) (release func() error, err error) { + return acquireLock(path, syscall.LOCK_EX) +} + +func acquireLock(path string, flags int) (release func() error, err error) { f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644) if err != nil { return nil, fmt.Errorf("open lock file %s: %w", path, err) } - if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + if err := syscall.Flock(int(f.Fd()), flags); err != nil { f.Close() if errors.Is(err, syscall.EWOULDBLOCK) { return nil, fmt.Errorf("%s: %w", path, ErrLockHeld) diff --git a/internal/process/lock_test.go b/internal/process/lock_test.go index ae4cef0..5d93972 100644 --- a/internal/process/lock_test.go +++ b/internal/process/lock_test.go @@ -5,6 +5,7 @@ import ( "os" "path/filepath" "testing" + "time" ) func TestAcquireLock_ExclusiveAndReleasable(t *testing.T) { @@ -47,6 +48,35 @@ func TestAcquireLock_ReleaseIsIdempotent(t *testing.T) { } } +// TestAcquireLockBlocking_WaitsForRelease confirms the actual difference +// from AcquireLock: contention doesn't fail immediately, it waits until +// the current holder releases. +func TestAcquireLockBlocking_WaitsForRelease(t *testing.T) { + path := filepath.Join(t.TempDir(), "lock") + + release1, err := AcquireLock(path) + if err != nil { + t.Fatalf("first AcquireLock: %v", err) + } + + const holdTime = 200 * time.Millisecond + go func() { + time.Sleep(holdTime) + _ = release1() + }() + + start := time.Now() + release2, err := AcquireLockBlocking(path) + if err != nil { + t.Fatalf("AcquireLockBlocking: %v", err) + } + defer release2() + + if waited := time.Since(start); waited < holdTime { + t.Fatalf("AcquireLockBlocking returned after %s, want it to have waited at least %s for the first holder to release", waited, holdTime) + } +} + func TestAcquireLock_CreatesFileIfMissing(t *testing.T) { path := filepath.Join(t.TempDir(), "nested", "does-not-exist-yet", "lock") From 79bf8d21b0fe6957fd2067d5048579790f1e854d Mon Sep 17 00:00:00 2001 From: Prateek Sharma Date: Sun, 6 Sep 2026 21:11:09 +0530 Subject: [PATCH 3/7] Add store.PortRegistry: on-disk storage for claimed listen ports ~/.tocli/ports.json records which port in the configured range is currently claimed and by which torrent id; ~/.tocli/ports.lock guards read-check-claim-write access to it. Root-level, not per-torrent, since it's shared across every torrent rather than scoped to one -- contrast store.LockPath. Pure storage, following this package's existing convention (it owns all of ~/.tocli's on-disk state and serialization); the claim/release decision logic that will use this lands separately in internal/portpool. Unused until that lands. --- internal/store/port_registry.go | 82 +++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 internal/store/port_registry.go diff --git a/internal/store/port_registry.go b/internal/store/port_registry.go new file mode 100644 index 0000000..4a82cee --- /dev/null +++ b/internal/store/port_registry.go @@ -0,0 +1,82 @@ +package store + +import ( + "errors" + "os" + "path/filepath" +) + +// PortRegistry is the on-disk shape of ~/.tocli/ports.json: which ports in +// the configured [PortRangeStart, PortRangeEnd] range are currently +// claimed, and which torrent id holds each one. It's the shared state that +// lets tocli's independent per-torrent processes coordinate a +// non-colliding BitTorrent listen port without a daemon holding anything +// in memory -- see internal/portpool, which owns the actual claim/release +// decisions; this file only handles the registry's storage, the same way +// every other on-disk state in this package (config.json, state.json) is +// handled here rather than by its caller. +type PortRegistry struct { + // Ports maps a claimed port number to the id of the torrent holding it. + Ports map[int]string `json:"ports"` +} + +// portRegistryFileName and portRegistryLockFileName live at the root of +// ~/.tocli, not under any single torrent's directory (contrast +// store.LockPath), since the registry is shared across every torrent, not +// scoped to one. +const ( + portRegistryFileName = "ports.json" + portRegistryLockFileName = "ports.lock" +) + +// PortRegistryPath returns ~/.tocli/ports.json. +func PortRegistryPath() (string, error) { + root, err := Root() + if err != nil { + return "", err + } + return filepath.Join(root, portRegistryFileName), nil +} + +// PortRegistryLockPath returns ~/.tocli/ports.lock: the advisory lock +// guarding read-check-claim-write access to ports.json. Use +// process.AcquireLockBlocking on it, not process.AcquireLock -- contention +// here means "another torrent's process is in the middle of its own brief +// claim/release", worth waiting a moment for, not "give up". +func PortRegistryLockPath() (string, error) { + root, err := Root() + if err != nil { + return "", err + } + return filepath.Join(root, portRegistryLockFileName), nil +} + +// LoadPortRegistry reads ~/.tocli/ports.json, returning an empty registry +// (not an error) if it doesn't exist yet -- the normal state before any +// torrent has ever claimed a port. +func LoadPortRegistry() (*PortRegistry, error) { + path, err := PortRegistryPath() + if err != nil { + return nil, err + } + var reg PortRegistry + if err := readJSON(path, ®); err != nil { + if errors.Is(err, os.ErrNotExist) { + return &PortRegistry{Ports: map[int]string{}}, nil + } + return nil, err + } + if reg.Ports == nil { + reg.Ports = map[int]string{} + } + return ®, nil +} + +// SavePortRegistry writes reg to ~/.tocli/ports.json. +func SavePortRegistry(reg *PortRegistry) error { + path, err := PortRegistryPath() + if err != nil { + return err + } + return writeJSONAtomic(path, reg) +} From 77134fad296c28e69085e23a9e21e6e247dcd75c Mon Sep 17 00:00:00 2001 From: Prateek Sharma Date: Sun, 6 Sep 2026 21:11:19 +0530 Subject: [PATCH 4/7] Add internal/portpool: coordinate per-torrent listen ports across processes Claim assigns a torrent id the lowest available port in [PortRangeStart, PortRangeEnd], recording it in store.PortRegistry under process.AcquireLockBlocking so two concurrently-starting torrents can never claim the same one. Assignment is always lowest-available, not an arbitrary free port, so a range a user has forwarded on their router gets used predictably from the bottom up. No range configured (PortRangeStart <= 0) short-circuits before touching the registry at all, matching existing behavior exactly. Range exhaustion returns (0, ephemeral=true, nil) rather than an error, so the caller can fall back to an OS-assigned port instead of failing to start. Release frees a claimed port so a later torrent can reclaim it; safe to call for an id that never held one. Covered by unit tests in isolation (sequential assignment, exhaustion, release-then-reclaim, the no-range-configured short circuit); not yet wired into anything that calls it. --- internal/portpool/portpool.go | 114 +++++++++++++++++++++++++++ internal/portpool/portpool_test.go | 120 +++++++++++++++++++++++++++++ 2 files changed, 234 insertions(+) create mode 100644 internal/portpool/portpool.go create mode 100644 internal/portpool/portpool_test.go diff --git a/internal/portpool/portpool.go b/internal/portpool/portpool.go new file mode 100644 index 0000000..6217609 --- /dev/null +++ b/internal/portpool/portpool.go @@ -0,0 +1,114 @@ +// Package portpool assigns each running torrent a distinct BitTorrent +// listen port from the range configured in config.toml +// (PortRangeStart..PortRangeEnd), so that concurrently-running torrents -- +// each one a fully independent OS process, per tocli's process-per-torrent +// design -- never collide trying to bind the same port. +// +// There's no daemon holding shared in-memory state to arbitrate this, so +// coordination happens the same way everything else in tocli does: +// through a lock-protected file on disk (store.PortRegistry), guarded by +// the same flock-based primitive (process.AcquireLockBlocking) that +// internal/process already uses elsewhere, just in its blocking form +// rather than the per-torrent spawn lock's non-blocking one -- contention +// here is brief, expected coordination between processes doing a quick +// read-check-claim-write, not "someone else already owns this, give up". +package portpool + +import ( + "fmt" + + "github.com/pratts/tocli/internal/config" + "github.com/pratts/tocli/internal/process" + "github.com/pratts/tocli/internal/store" +) + +// Claim assigns id the lowest available port in [cfg.PortRangeStart, +// cfg.PortRangeEnd], recording the claim in the shared port registry so no +// other concurrently-starting torrent can claim the same one. Assignment +// is always lowest-available, not an arbitrary free port, so a range a +// user has forwarded on their router gets used predictably from the +// bottom up rather than scattered across it. +// +// If cfg.PortRangeStart is 0, no range is configured at all (see +// config.Config's doc comment: zero means "let the OS pick") -- Claim +// returns (0, false, nil) immediately without touching the registry, +// matching that existing behavior exactly. +// +// If the range is configured but every port in it is already claimed by +// another running torrent, Claim returns (0, true, nil): ephemeral is +// true, telling the caller to fall back to an OS-assigned port (and warn +// about why) rather than fail to start the torrent. +func Claim(id string, cfg config.Config) (port int, ephemeral bool, err error) { + if cfg.PortRangeStart <= 0 { + return 0, false, nil + } + + release, reg, err := lockAndLoadRegistry() + if err != nil { + return 0, false, err + } + defer release() + + for p := cfg.PortRangeStart; p <= cfg.PortRangeEnd; p++ { + if _, taken := reg.Ports[p]; taken { + continue + } + reg.Ports[p] = id + if err := store.SavePortRegistry(reg); err != nil { + return 0, false, fmt.Errorf("save port registry: %w", err) + } + return p, false, nil + } + // Every port in the configured range is already claimed by another + // running torrent -- the caller falls back to an OS-assigned port. + return 0, true, nil +} + +// Release frees id's claimed port, if any, so a subsequently-started +// torrent can claim it. Safe to call even if id never held a claim (it ran +// on an ephemeral fallback port, or no range is configured at all) -- a +// no-op in that case, not an error. +func Release(id string) error { + release, reg, err := lockAndLoadRegistry() + if err != nil { + return err + } + defer release() + + changed := false + for p, heldBy := range reg.Ports { + if heldBy == id { + delete(reg.Ports, p) + changed = true + } + } + if !changed { + return nil + } + if err := store.SavePortRegistry(reg); err != nil { + return fmt.Errorf("save port registry: %w", err) + } + return nil +} + +// lockAndLoadRegistry acquires the registry's lock (waiting for it, not +// failing on contention -- see process.AcquireLockBlocking) and loads its +// current contents. Callers must call the returned release once done, +// before the registry can reflect their change to any other process. +func lockAndLoadRegistry() (release func() error, reg *store.PortRegistry, err error) { + lockPath, err := store.PortRegistryLockPath() + if err != nil { + return nil, nil, err + } + release, err = process.AcquireLockBlocking(lockPath) + if err != nil { + return nil, nil, fmt.Errorf("lock port registry: %w", err) + } + + reg, err = store.LoadPortRegistry() + if err != nil { + release() + return nil, nil, err + } + return release, reg, nil +} diff --git a/internal/portpool/portpool_test.go b/internal/portpool/portpool_test.go new file mode 100644 index 0000000..c7e99fd --- /dev/null +++ b/internal/portpool/portpool_test.go @@ -0,0 +1,120 @@ +package portpool + +import ( + "testing" + + "github.com/pratts/tocli/internal/config" + "github.com/pratts/tocli/internal/store" +) + +// TestClaim_NoRangeConfiguredReturnsNoPort covers config.Config's +// documented zero-value convention (PortRangeStart 0 means "let the OS +// pick"): Claim must not touch the registry at all in that case. +func TestClaim_NoRangeConfiguredReturnsNoPort(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + + port, ephemeral, err := Claim("torrentA", config.Config{}) + if err != nil { + t.Fatalf("Claim returned an error: %v", err) + } + if port != 0 || ephemeral { + t.Fatalf("Claim(no range) = (%d, %v), want (0, false)", port, ephemeral) + } + + reg, err := store.LoadPortRegistry() + if err != nil { + t.Fatalf("load registry: %v", err) + } + if len(reg.Ports) != 0 { + t.Fatalf("expected an untouched registry, got %+v", reg.Ports) + } +} + +// TestClaim_SequentialLowestAvailable confirms assignment fills the +// configured range from the bottom up, in order -- not an arbitrary free +// port -- since that's the behavior that makes a user's router +// port-forwarding of a specific range actually work as expected. +func TestClaim_SequentialLowestAvailable(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + cfg := config.Config{PortRangeStart: 6000, PortRangeEnd: 6002} + + want := []int{6000, 6001, 6002} + for i, id := range []string{"t1", "t2", "t3"} { + port, ephemeral, err := Claim(id, cfg) + if err != nil { + t.Fatalf("Claim(%s): %v", id, err) + } + if ephemeral { + t.Fatalf("Claim(%s) unexpectedly ephemeral", id) + } + if port != want[i] { + t.Fatalf("Claim(%s) = port %d, want %d", id, port, want[i]) + } + } +} + +// TestClaim_RangeExhaustionReturnsEphemeral confirms Claim reports +// exhaustion distinctly (ephemeral=true, no error) rather than either +// erroring or silently reusing an already-claimed port. +func TestClaim_RangeExhaustionReturnsEphemeral(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + cfg := config.Config{PortRangeStart: 7000, PortRangeEnd: 7000} + + port, ephemeral, err := Claim("first", cfg) + if err != nil || ephemeral || port != 7000 { + t.Fatalf("first Claim = (%d, %v, %v), want (7000, false, nil)", port, ephemeral, err) + } + + port, ephemeral, err = Claim("second", cfg) + if err != nil { + t.Fatalf("second Claim returned an error: %v", err) + } + if !ephemeral || port != 0 { + t.Fatalf("second Claim = (%d, %v), want (0, true) once the range is exhausted", port, ephemeral) + } +} + +// TestReleaseThenClaim_FreedPortIsReclaimedFirst confirms a released port +// becomes genuinely available again -- lowest-available means it's handed +// out before any higher, never-yet-claimed port in the same range, rather +// than staying marked claimed or being skipped. +func TestReleaseThenClaim_FreedPortIsReclaimedFirst(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + cfg := config.Config{PortRangeStart: 8000, PortRangeEnd: 8001} + + if port, _, err := Claim("holder", cfg); err != nil || port != 8000 { + t.Fatalf("Claim(holder) = (%d, %v), want (8000, nil)", port, err) + } + + if err := Release("holder"); err != nil { + t.Fatalf("Release(holder): %v", err) + } + + reg, err := store.LoadPortRegistry() + if err != nil { + t.Fatalf("load registry: %v", err) + } + if _, stillClaimed := reg.Ports[8000]; stillClaimed { + t.Fatalf("expected port 8000 to be freed, registry: %+v", reg.Ports) + } + + port, ephemeral, err := Claim("next", cfg) + if err != nil { + t.Fatalf("Claim(next): %v", err) + } + if ephemeral || port != 8000 { + t.Fatalf("Claim(next) = (%d, %v), want the freed port 8000 reclaimed first", port, ephemeral) + } +} + +// TestRelease_UnclaimedIDIsANoOp confirms Release never errors for a +// torrent that never held a claim -- the ephemeral-fallback and +// no-range-configured cases in internal/engine.Run both call it +// unconditionally-safe-to-call-anyway in some configurations. +func TestRelease_UnclaimedIDIsANoOp(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + + if err := Release("never-claimed-anything"); err != nil { + t.Fatalf("Release on an id that never claimed a port returned an error: %v", err) + } +} From ef66bff8eef558179aff66a6636894aeab1fabd9 Mon Sep 17 00:00:00 2001 From: Prateek Sharma Date: Sun, 6 Sep 2026 21:11:31 +0530 Subject: [PATCH 5/7] Claim a distinct listen port per torrent instead of pinning them all to one Every internal/engine.Run process previously pinned its BitTorrent listen port to config.PortRangeStart unconditionally, so only the first concurrently-running torrent could ever actually bind it -- every one after it silently fell back to outbound-only (no inbound peer connections), with no visible symptom in list/logs, and defeating any router port-forwarding the user had set up for the range. port_range_end was pure dead config as a result. Run now claims a port via internal/portpool.Claim before creating the torrent.Client, using it as the listener port when one was actually claimed, and logging a clear warning when the configured range is exhausted and it falls back to an OS-assigned port instead (still starts normally -- exhaustion is not a failure to start). The claimed port is released via internal/portpool.Release as part of the same paths that already release the per-torrent lock: normal completion, the SIGTERM/pause handler, and (via defer) any early failure in between. Nothing is deferred at all for a torrent that never actually claimed a port (no range configured, or the ephemeral fallback), so the registry/lock file is never touched in that case. Tests spawn real, separate "tocli __run" processes (not goroutines) against a small configured range: concurrent torrents land on distinct ports with no collision, a freed port (previous holder exits via SIGTERM) is reclaimed by the next spawn rather than staying marked claimed, and range exhaustion falls back to an ephemeral port with the expected warning rather than failing to start. Manually verified end-to-end against the real binary: three concurrent "tocli __run" processes against a configured [49500-49502] range, confirmed via lsof to each be listening (TCP+UDP) on a distinct port matching the port registry exactly. Out of scope, tracked separately (see the pool/queue GitHub issue): no limit on concurrent torrents, no queueing when the range is exhausted -- it still starts immediately on an ephemeral port. --- internal/engine/portpool_concurrency_test.go | 245 +++++++++++++++++++ internal/engine/run.go | 33 ++- 2 files changed, 274 insertions(+), 4 deletions(-) create mode 100644 internal/engine/portpool_concurrency_test.go diff --git a/internal/engine/portpool_concurrency_test.go b/internal/engine/portpool_concurrency_test.go new file mode 100644 index 0000000..cc6d748 --- /dev/null +++ b/internal/engine/portpool_concurrency_test.go @@ -0,0 +1,245 @@ +package engine_test + +import ( + "bytes" + "fmt" + "os/exec" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/pratts/tocli/internal/config" + "github.com/pratts/tocli/internal/store" +) + +// syncBuffer is a bytes.Buffer safe for the concurrent write-while-reading +// pattern a live child process's stderr capture needs here: os/exec copies +// into it from a background goroutine for as long as the child is alive, +// while the test reads it from the main goroutine once a condition (e.g. +// "reached status running") is observed -- a plain bytes.Buffer would be a +// data race under -race for that combination. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// TestPortPool_ConcurrentTorrentsGetDistinctPorts spawns several real +// `__run` processes (genuine separate OS processes -- see +// buildTocliBinary's comment for why goroutines wouldn't faithfully +// exercise this) against a port range exactly as large as the number of +// torrents, and confirms every one lands on a distinct port within it with +// no collision -- proving the actual property under test (the shared +// registry file never double-assigns a port under real concurrent +// startup) by reading that registry back, rather than depending on +// platform-specific tools like lsof/netstat to observe the OS-level bind. +func TestPortPool_ConcurrentTorrentsGetDistinctPorts(t *testing.T) { + binPath, err := buildTocliBinary() + if err != nil { + t.Fatalf("build tocli: %v", err) + } + + t.Setenv("HOME", t.TempDir()) + cfg := config.Default() + const n = 3 + cfg.PortRangeStart = 41000 + cfg.PortRangeEnd = cfg.PortRangeStart + n - 1 + if err := config.Save(&cfg); err != nil { + t.Fatalf("save config: %v", err) + } + + ids := make([]string, n) + children := make([]*exec.Cmd, n) + for i := 0; i < n; i++ { + id := fmt.Sprintf("concport%02d", i) + ids[i] = id + setUpSyntheticTorrent(t, id) + + child := exec.Command(binPath, "__run", id) + if err := child.Start(); err != nil { + t.Fatalf("start child %s: %v", id, err) + } + children[i] = child + } + t.Cleanup(func() { + for _, c := range children { + _ = c.Process.Signal(syscall.SIGTERM) + _ = c.Wait() + } + }) + + for _, id := range ids { + waitForStatus(t, id, store.StatusRunning, 5*time.Second) + } + + reg, err := store.LoadPortRegistry() + if err != nil { + t.Fatalf("load port registry: %v", err) + } + if len(reg.Ports) != n { + t.Fatalf("expected %d claimed ports, got %d: %+v", n, len(reg.Ports), reg.Ports) + } + + seenIDs := make(map[string]bool, n) + for port, id := range reg.Ports { + if port < cfg.PortRangeStart || port > cfg.PortRangeEnd { + t.Errorf("claimed port %d outside configured range [%d-%d]", port, cfg.PortRangeStart, cfg.PortRangeEnd) + } + if seenIDs[id] { + t.Errorf("torrent %s appears to hold more than one port: %+v", id, reg.Ports) + } + seenIDs[id] = true + } + for _, id := range ids { + if !seenIDs[id] { + t.Errorf("torrent %s never claimed a port: %+v", id, reg.Ports) + } + } +} + +// TestPortPool_FreedPortBecomesAvailableToNextTorrent confirms a port +// released by its holder exiting (here, a graceful SIGTERM/pause) is +// genuinely available again -- not left marked claimed -- by spawning a +// second real torrent into a range with exactly one port and confirming it +// gets that same port back. +func TestPortPool_FreedPortBecomesAvailableToNextTorrent(t *testing.T) { + binPath, err := buildTocliBinary() + if err != nil { + t.Fatalf("build tocli: %v", err) + } + + t.Setenv("HOME", t.TempDir()) + cfg := config.Default() + cfg.PortRangeStart = 41200 + cfg.PortRangeEnd = 41200 + if err := config.Save(&cfg); err != nil { + t.Fatalf("save config: %v", err) + } + + id1 := "freedport1" + setUpSyntheticTorrent(t, id1) + first := exec.Command(binPath, "__run", id1) + if err := first.Start(); err != nil { + t.Fatalf("start first child: %v", err) + } + waitForStatus(t, id1, store.StatusRunning, 5*time.Second) + + reg, err := store.LoadPortRegistry() + if err != nil { + t.Fatalf("load port registry: %v", err) + } + if reg.Ports[cfg.PortRangeStart] != id1 { + t.Fatalf("expected port %d claimed by %s, registry: %+v", cfg.PortRangeStart, id1, reg.Ports) + } + + // Graceful stop (mirrors `tocli pause`): Run's SIGTERM path releases + // the port as one of its last actions before exiting, same as it + // already does for the per-torrent lock. + if err := first.Process.Signal(syscall.SIGTERM); err != nil { + t.Fatalf("signal first child: %v", err) + } + if err := first.Wait(); err != nil { + t.Fatalf("first child did not exit cleanly after SIGTERM: %v", err) + } + + id2 := "freedport2" + setUpSyntheticTorrent(t, id2) + second := exec.Command(binPath, "__run", id2) + if err := second.Start(); err != nil { + t.Fatalf("start second child: %v", err) + } + t.Cleanup(func() { + _ = second.Process.Signal(syscall.SIGTERM) + _ = second.Wait() + }) + waitForStatus(t, id2, store.StatusRunning, 5*time.Second) + + reg, err = store.LoadPortRegistry() + if err != nil { + t.Fatalf("load port registry: %v", err) + } + if reg.Ports[cfg.PortRangeStart] != id2 { + t.Fatalf("expected freed port %d to be reclaimed by %s, registry: %+v", cfg.PortRangeStart, id2, reg.Ports) + } +} + +// TestPortPool_RangeExhaustionFallsBackToEphemeralPort confirms that a +// second torrent starting once the (single-port) range is already fully +// claimed still reaches "running" -- exhaustion must change which port it +// listens on, not stop it from starting -- and that the exhaustion is +// logged clearly to its log.txt. +func TestPortPool_RangeExhaustionFallsBackToEphemeralPort(t *testing.T) { + binPath, err := buildTocliBinary() + if err != nil { + t.Fatalf("build tocli: %v", err) + } + + t.Setenv("HOME", t.TempDir()) + cfg := config.Default() + cfg.PortRangeStart = 41300 + cfg.PortRangeEnd = 41300 + if err := config.Save(&cfg); err != nil { + t.Fatalf("save config: %v", err) + } + + id1 := "exhaust01" + setUpSyntheticTorrent(t, id1) + first := exec.Command(binPath, "__run", id1) + if err := first.Start(); err != nil { + t.Fatalf("start first child: %v", err) + } + t.Cleanup(func() { + _ = first.Process.Signal(syscall.SIGTERM) + _ = first.Wait() + }) + waitForStatus(t, id1, store.StatusRunning, 5*time.Second) + + id2 := "exhaust02" + setUpSyntheticTorrent(t, id2) + second := exec.Command(binPath, "__run", id2) + // Run's log.Printf output only lands in log.txt when spawned via + // process.SpawnDetached (as `tocli start`/`resume` do); this test + // invokes `__run` directly, like the other tests in this file, so it + // captures the child's own stderr instead to observe the warning. + var stderr syncBuffer + second.Stderr = &stderr + if err := second.Start(); err != nil { + t.Fatalf("start second child: %v", err) + } + t.Cleanup(func() { + _ = second.Process.Signal(syscall.SIGTERM) + _ = second.Wait() + }) + + // Must still reach "running": exhaustion is a fallback, not a failure + // to start. + waitForStatus(t, id2, store.StatusRunning, 5*time.Second) + + got := stderr.String() + if !strings.Contains(got, "port range") || !strings.Contains(got, "exhausted") { + t.Fatalf("expected an exhaustion warning on stderr, got:\n%s", got) + } + + // The exhausted torrent must not have claimed the single port -- it's + // still (and only) held by the first torrent. + reg, err := store.LoadPortRegistry() + if err != nil { + t.Fatalf("load port registry: %v", err) + } + if len(reg.Ports) != 1 || reg.Ports[cfg.PortRangeStart] != id1 { + t.Fatalf("expected only %s to hold the single configured port, registry: %+v", id1, reg.Ports) + } +} diff --git a/internal/engine/run.go b/internal/engine/run.go index dddb3b1..550fba3 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -14,6 +14,7 @@ import ( "golang.org/x/time/rate" "github.com/pratts/tocli/internal/config" + "github.com/pratts/tocli/internal/portpool" "github.com/pratts/tocli/internal/process" "github.com/pratts/tocli/internal/store" ) @@ -78,11 +79,35 @@ func Run(id string) error { clientCfg := torrent.NewDefaultClientConfig() clientCfg.DataDir = tc.SavePath - if globalCfg.PortRangeStart > 0 { - // TODO: once bandwidth scheduling lands, rotate across - // [PortRangeStart, PortRangeEnd] instead of pinning the first port. - clientCfg.ListenPort = globalCfg.PortRangeStart + + // Claim a distinct port from the configured range so this process's + // inbound listener never collides with another concurrently-running + // torrent's -- see internal/portpool's package doc for why this needs + // filesystem coordination rather than in-memory state. + claimedPort, ephemeral, err := portpool.Claim(id, *globalCfg) + if err != nil { + return fmt.Errorf("claim listen port: %w", err) } + switch { + case ephemeral: + log.Printf("configured port range [%d-%d] exhausted; falling back to an OS-assigned port for this torrent", globalCfg.PortRangeStart, globalCfg.PortRangeEnd) + case claimedPort > 0: + clientCfg.ListenPort = claimedPort + // Deferred right away, not just alongside the graceful-shutdown + // paths further down: an early failure below (torrent.NewClient, + // AddTorrent, metadata resolution) must not leak the claim either. + // Only registered when a claim actually happened (not for the + // ephemeral fallback above, and not when no range is configured at + // all) -- Release is safe to call unconditionally, but there's no + // reason to touch the registry/lock file at all for a torrent that + // never claimed anything from it. + defer func() { + if err := portpool.Release(id); err != nil { + log.Printf("release claimed port: %v", err) + } + }() + } + if globalCfg.MaxDownloadBps > 0 { clientCfg.DownloadRateLimiter = rate.NewLimiter(rate.Limit(globalCfg.MaxDownloadBps), int(globalCfg.MaxDownloadBps)) } From 57e1338e9a1638f3438d55a730cd63bb9e0199b6 Mon Sep 17 00:00:00 2001 From: Prateek Sharma Date: Mon, 7 Sep 2026 09:20:46 +0530 Subject: [PATCH 6/7] Expand Config's doc comment to describe the per-torrent port-pool behavior Not stale (it never described the old single-port-pinning bug), just silent on what a configured port range actually does now that internal/portpool exists. This is the only place in the repo that documents these two fields, so it's worth it actually saying so. --- internal/config/config.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/internal/config/config.go b/internal/config/config.go index 1463912..bb62fd8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -17,7 +17,13 @@ const fileName = "config.toml" // Config holds the global defaults applied to every torrent unless // overridden per-torrent in a later pass. Zero values for the speed limits -// mean "unlimited"; zero for the port range means "let the OS pick". +// mean "unlimited". PortRangeStart/PortRangeEnd both zero means "let the OS +// pick" a port for every torrent, with no coordination between them at all. +// When set, each concurrently-running torrent claims a distinct, +// lowest-available port from [PortRangeStart, PortRangeEnd] -- see +// internal/portpool.Claim -- falling back to an OS-assigned port (recorded +// and surfaced as such, not just logged -- see +// store.TorrentConfig.PortEphemeral) once the range is exhausted. type Config struct { BaseDownloadDir string `toml:"base_download_dir"` MaxUploadBps int64 `toml:"max_upload_bps"` From c49c766c793d7bc972f88916028b33bf57850af1 Mon Sep 17 00:00:00 2001 From: Prateek Sharma Date: Mon, 7 Sep 2026 09:21:12 +0530 Subject: [PATCH 7/7] Surface the ephemeral-port fallback in list/dashboard, not just log.txt The exhaustion warning portpool.Claim's caller logs was only ever reaching log.txt -- invisible during normal use unless someone already suspects something's wrong and goes looking. That undercuts the whole point of this fix: the original bug's defining symptom was "no visible symptom anywhere in list or logs". store.TorrentConfig gets a new PortEphemeral field, set by Run alongside the existing PID/status bookkeeping whenever it falls back to an OS-assigned port, and cleared once the torrent stops actively running (paused/completed) since the claim -- or lack of one -- no longer applies once released. Surfaced in both places a user actually looks: `list`/`list --json` (a new port_ephemeral field, and "(ephemeral port)" appended to the STATUS column in `list --plain`) and the dashboard's STATUS column (widened from 12 to 20 to fit "running (ephemeral)" without truncating). Tests: the existing real-subprocess exhaustion test now also confirms the persisted config actually records PortEphemeral=true, and a new `list --plain` test confirms it renders visibly. --- internal/cli/list.go | 17 +++++++++-- internal/cli/list_test.go | 31 ++++++++++++++++++++ internal/engine/portpool_concurrency_test.go | 10 +++++++ internal/engine/run.go | 8 +++++ internal/store/torrent_config.go | 10 +++++++ internal/tui/dashboard/model.go | 5 ++++ internal/tui/dashboard/table.go | 14 +++++++-- 7 files changed, 89 insertions(+), 6 deletions(-) diff --git a/internal/cli/list.go b/internal/cli/list.go index f9b1688..4b30df8 100644 --- a/internal/cli/list.go +++ b/internal/cli/list.go @@ -47,7 +47,11 @@ type listEntry struct { DownloadRateBps float64 `json:"download_rate_bps"` ActivePeers int `json:"active_peers"` TotalPeers int `json:"total_peers"` - Error string `json:"error,omitempty"` + // PortEphemeral is true if this torrent is running on an OS-assigned + // fallback port because the configured port range was exhausted -- see + // store.TorrentConfig.PortEphemeral. + PortEphemeral bool `json:"port_ephemeral,omitempty"` + Error string `json:"error,omitempty"` } func loadListEntries() ([]listEntry, error) { @@ -66,7 +70,7 @@ func loadListEntries() ([]listEntry, error) { } _ = store.ReconcileLiveness(tc) - e := listEntry{ID: tc.ID, Name: tc.Name, Status: string(tc.Status)} + e := listEntry{ID: tc.ID, Name: tc.Name, Status: string(tc.Status), PortEphemeral: tc.PortEphemeral} if st, err := store.LoadState(id); err == nil { e.Percent = st.Percent e.DownloadRateBps = st.DownloadRateBps @@ -117,7 +121,14 @@ func runListTable(cmd *cobra.Command) error { percent := fmt.Sprintf("%.1f%%", e.Percent) rate := humanize.Rate(e.DownloadRateBps) peers := fmt.Sprintf("%d/%d", e.ActivePeers, e.TotalPeers) - fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", e.ID, e.Name, e.Status, percent, rate, peers) + status := e.Status + if e.PortEphemeral { + // Visible here, not just logged to log.txt: an unreachable + // inbound listener silently degrading a running torrent is + // exactly the failure mode this needs to surface, not hide. + status += " (ephemeral port)" + } + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", e.ID, e.Name, status, percent, rate, peers) } return w.Flush() } diff --git a/internal/cli/list_test.go b/internal/cli/list_test.go index 8c7349a..2d68e7e 100644 --- a/internal/cli/list_test.go +++ b/internal/cli/list_test.go @@ -3,6 +3,7 @@ package cli import ( "bytes" "os/exec" + "strings" "testing" "time" @@ -72,6 +73,36 @@ func TestList_SelfCorrectsCrashedStatus(t *testing.T) { } } +// TestList_SurfacesEphemeralPortFallback confirms a torrent running on an +// OS-assigned fallback port (store.TorrentConfig.PortEphemeral) is visibly +// flagged in `list --plain` output, not just recorded silently -- the +// whole point of persisting this rather than only logging it. +func TestList_SurfacesEphemeralPortFallback(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + + id := "ephemeral1" + if err := store.InitTorrentDir(id); err != nil { + t.Fatalf("init torrent dir: %v", err) + } + tc := &store.TorrentConfig{ID: id, Name: "port-exhausted", Status: store.StatusRunning, PortEphemeral: true} + if err := store.SaveTorrentConfig(tc); err != nil { + t.Fatalf("save torrent config: %v", err) + } + + out := new(bytes.Buffer) + root := NewRootCmd("test") + root.SetArgs([]string{"list", "--plain"}) + root.SetOut(out) + if err := root.Execute(); err != nil { + t.Fatalf("run list: %v", err) + } + + got := out.String() + if !strings.Contains(got, "ephemeral1") || !strings.Contains(got, "ephemeral port") { + t.Fatalf("list output missing an ephemeral-port note for a torrent with PortEphemeral=true:\n%s", got) + } +} + // TestPause_AlreadyCrashedReportsCleanly ensures pausing a torrent whose // process has already died reports a sensible status instead of trying (and // failing) to signal a dead pid. diff --git a/internal/engine/portpool_concurrency_test.go b/internal/engine/portpool_concurrency_test.go index cc6d748..8cace0e 100644 --- a/internal/engine/portpool_concurrency_test.go +++ b/internal/engine/portpool_concurrency_test.go @@ -242,4 +242,14 @@ func TestPortPool_RangeExhaustionFallsBackToEphemeralPort(t *testing.T) { if len(reg.Ports) != 1 || reg.Ports[cfg.PortRangeStart] != id1 { t.Fatalf("expected only %s to hold the single configured port, registry: %+v", id1, reg.Ports) } + + // Not just logged to stderr: this must be visible in normal use + // (`list`, the dashboard) too -- see store.TorrentConfig.PortEphemeral. + tc2, err := store.LoadTorrentConfig(id2) + if err != nil { + t.Fatalf("load torrent config for %s: %v", id2, err) + } + if !tc2.PortEphemeral { + t.Fatalf("expected %s's persisted config to record PortEphemeral=true, got %+v", id2, tc2) + } } diff --git a/internal/engine/run.go b/internal/engine/run.go index 550fba3..a576963 100644 --- a/internal/engine/run.go +++ b/internal/engine/run.go @@ -88,6 +88,12 @@ func Run(id string) error { if err != nil { return fmt.Errorf("claim listen port: %w", err) } + // Recorded in config.json, not just logged: a warning that only ever + // reaches log.txt is exactly the "no visible symptom" failure mode this + // whole port-pool fix exists to close. `list`/the dashboard surface + // this so it's visible during normal use, not just to someone who + // already suspects something's wrong and goes looking in the logs. + tc.PortEphemeral = ephemeral switch { case ephemeral: log.Printf("configured port range [%d-%d] exhausted; falling back to an OS-assigned port for this torrent", globalCfg.PortRangeStart, globalCfg.PortRangeEnd) @@ -174,6 +180,7 @@ func Run(id string) error { writeState() tc.Status = store.StatusCompleted tc.PID = 0 + tc.PortEphemeral = false // the port claim, if any, is about to be released below if err := store.SaveTorrentConfig(tc); err != nil { return fmt.Errorf("record completed status: %w", err) } @@ -200,6 +207,7 @@ func Run(id string) error { writeState() tc.Status = store.StatusPaused tc.PID = 0 + tc.PortEphemeral = false // the port claim, if any, is about to be released below if err := store.SaveTorrentConfig(tc); err != nil { return fmt.Errorf("record paused status: %w", err) } diff --git a/internal/store/torrent_config.go b/internal/store/torrent_config.go index d9e7026..116556a 100644 --- a/internal/store/torrent_config.go +++ b/internal/store/torrent_config.go @@ -61,6 +61,16 @@ type TorrentConfig struct { // trusted -- it may have been reassigned to an unrelated process. BootID string `json:"boot_id"` AddedAt time.Time `json:"added_at"` + // PortEphemeral is true only while this torrent is running and its + // process fell back to an OS-assigned port because the configured + // [PortRangeStart, PortRangeEnd] range was exhausted (see + // internal/portpool.Claim) -- meaning it's currently accepting inbound + // peer connections on an unpredictable port rather than the reserved + // range, which matters to anyone who's port-forwarded that range on + // their router. Reset to false whenever the torrent isn't actively + // running (paused/completed/etc.), since the port claim -- or lack of + // one -- no longer applies once it's released. + PortEphemeral bool `json:"port_ephemeral,omitempty"` } func LoadTorrentConfig(id string) (*TorrentConfig, error) { diff --git a/internal/tui/dashboard/model.go b/internal/tui/dashboard/model.go index baab29c..851436c 100644 --- a/internal/tui/dashboard/model.go +++ b/internal/tui/dashboard/model.go @@ -46,6 +46,10 @@ type rowData struct { Rate string Peers string Broken bool // config.json failed to load + // PortEphemeral mirrors store.TorrentConfig.PortEphemeral: true if this + // torrent is running on an OS-assigned fallback port because the + // configured port range was exhausted. + PortEphemeral bool } // Model is the dashboard's tea.Model. @@ -291,6 +295,7 @@ func loadRows() []rowData { rows = append(rows, rowData{ ID: tc.ID, Name: tc.Name, Status: tc.Status, Percent: percent, Rate: rate, Peers: peers, + PortEphemeral: tc.PortEphemeral, }) } return rows diff --git a/internal/tui/dashboard/table.go b/internal/tui/dashboard/table.go index 8f205da..a775b26 100644 --- a/internal/tui/dashboard/table.go +++ b/internal/tui/dashboard/table.go @@ -23,8 +23,10 @@ func newTable() table.Model { // a ragged edge or truncating names unnecessarily on wide terminals. func columnsForWidth(width int) []table.Column { const ( - idW = 12 - statusW = 12 + idW = 12 + // Wide enough for "running (ephemeral)" -- see rowsToTable -- not + // just the bare status word. + statusW = 20 percentW = 8 rateW = 12 peersW = 10 @@ -50,7 +52,13 @@ func rowsToTable(rows []rowData) []table.Row { out[i] = table.Row{r.ID, "error: unreadable config", "-", "-", "-", "-"} continue } - out[i] = table.Row{r.ID, r.Name, string(r.Status), r.Percent, r.Rate, r.Peers} + status := string(r.Status) + if r.PortEphemeral { + // Visible here, not just logged to log.txt -- see + // store.TorrentConfig.PortEphemeral's doc comment for why. + status += " (ephemeral)" + } + out[i] = table.Row{r.ID, r.Name, status, r.Percent, r.Rate, r.Peers} } return out }