Skip to content

Commit 75face8

Browse files
TMHSDigitalclaude
andcommitted
fix(cli): consistent, documented exit codes; SIGTERM exits 143
- every usage error exits 2 (missing domain, bad -format, -t 0, ...) - -dL exits 3 when some targets failed and others completed - SIGTERM exits 143 without the Ctrl+C force-quit hint; SIGINT stays 130 - a reliability abort skips the remaining -dL targets unless -no-abort, and multi-target runs end with a per-target status list - -h and the README document the exit codes and the per-target scope of -max-queries, -rate and the guard Includes a Unix SIGTERM e2e test (verified on Linux via WSL). Fixes #82 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e67e1b9 commit 75face8

5 files changed

Lines changed: 165 additions & 28 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2323
- A wordlist line longer than 64 KB no longer aborts the run with `bufio.Scanner: token too long`. Overlong lines are truncated, skipped and counted with the other invalid entries (#56).
2424
- `tools/wordlist-gen` no longer overwrites an existing output file without the new `-f` flag, exits 1 instead of writing an empty file when nothing is generated, rejects `-combine` prefixes that are not valid DNS labels, and drops generated entries subenum would skip (for example combinations over 63 characters). `make wordlist` and `examples/demo.sh` pass `-f` for the files they own (#59).
2525
- CLI polish: `-h` shows the `-attempts` default, a missing `-w` or domain is named before the usage text, `-version` prints before the simulation banner, `-tui` is only honoured as a flag (not as `-o -tui` or after `--`) and warns that other flags are ignored, and the worker pool is capped at the number of jobs the scan can produce, with a warning above `-t 10000` (#58).
26+
- Exit codes are consistent and documented in the README and `-h`: 2 for every usage error (previously 1 for semantic ones such as a missing domain or bad `-format`), 3 when some `-dL` targets failed while others completed, and 143 instead of 130 for SIGTERM, without the Ctrl+C hint. With `-dL`, a reliability abort now skips the remaining targets instead of sending them to the same overloaded resolver (unless `-no-abort`), and a per-target status list is printed at the end (#82).
2627
- Release binaries are built with `CGO_ENABLED=0 -trimpath -s -w`, so `subenum-linux-amd64` is statically linked again and CI fails if a Linux asset is not (#46).
2728

2829
## [0.8.0] - 2026-10-04

‎README.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,20 @@ subenum -w <wordlist> [flags] -dL <domains_file>
317317

318318
</details>
319319

320-
Press `Ctrl+C` at any time to abort. In-flight queries drain, partial results are flushed, and the process exits with code 130. Interrupted lookups are not counted as resolver failures.
320+
Press `Ctrl+C` at any time to abort. In-flight queries drain, partial results are flushed, and the process exits with code 130 (143 for SIGTERM, as sent by `docker stop` or systemd). Interrupted lookups are not counted as resolver failures.
321+
322+
**Exit codes**
323+
324+
| Code | Meaning |
325+
|------|---------|
326+
| `0` | Success |
327+
| `1` | A scan, the wordlist, the domain list or the output file failed |
328+
| `2` | Invalid flags or arguments |
329+
| `3` | `-dL`: some targets failed while others completed |
330+
| `130` | Interrupted (SIGINT, `Ctrl+C`); partial results are kept |
331+
| `143` | Terminated (SIGTERM); partial results are kept |
332+
333+
With `-dL`, each domain is scanned in turn as an independent scan: `-max-queries`, `-rate` and the reliability guard apply per target. A failed target does not stop the others, but a reliability abort (the resolver looks overloaded) skips the remaining targets unless `-no-abort` is set. A per-target status list is printed at the end.
321334

322335
<br>
323336

‎main.go‎

Lines changed: 97 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,28 @@ const (
5050
highConcurrency = 10000
5151
)
5252

53+
// Exit codes, documented in the README and in -h (#82). A signal exits with
54+
// the shell convention 128+signum: 130 for SIGINT, 143 for SIGTERM.
55+
const (
56+
exitOK = 0
57+
exitFailure = 1 // a scan, the wordlist, the domain list or the output file failed
58+
exitUsage = 2 // invalid flags or arguments
59+
exitPartial = 3 // -dL: some targets failed while others completed
60+
)
61+
62+
const exitCodesHelp = `Exit codes:
63+
0 success
64+
1 a scan, the wordlist, the domain list or the output file failed
65+
2 invalid flags or arguments
66+
3 -dL: some targets failed while others completed
67+
130 interrupted (SIGINT, Ctrl+C); partial results are kept
68+
143 terminated (SIGTERM); partial results are kept
69+
`
70+
71+
// signalReady, when set by a test, is closed once run's signal handler is
72+
// installed.
73+
var signalReady chan struct{}
74+
5375
// Version is the release identifier. Makefile, CI and the Dockerfile set it
5476
// with -ldflags "-X main.Version=$(git describe --tags --dirty)". When it is
5577
// empty (go install, plain go build), the module version from the build info
@@ -138,6 +160,13 @@ func parseFlags(args []string) (cliFlags, []string, *flag.FlagSet, error) {
138160
fs.IntVar(&f.depth, "depth", 1, "Max recursion depth when -recursive is set (1 = no recursion)")
139161
fs.BoolVar(&f.noAbort, "no-abort", false, "Do not abort when the resolver failure rate exceeds 20% (warning is still emitted)")
140162
fs.IntVar(&f.maxQueries, "max-queries", 0, "Max candidate names to test (0 = unlimited); each name sends one query per record type, per attempt")
163+
fs.Usage = func() {
164+
w := fs.Output()
165+
fmt.Fprintln(w, "Usage: subenum -w <wordlist_file> [options] <domain>")
166+
fmt.Fprintln(w, " subenum -w <wordlist_file> [options] -dL <domains_file>")
167+
fs.PrintDefaults()
168+
_, _ = fmt.Fprint(w, "\n"+exitCodesHelp)
169+
}
141170
positionals, err := parseInterspersed(fs, args)
142171
return f, positionals, fs, err
143172
}
@@ -199,10 +228,8 @@ func validateFlags(f cliFlags, positionals []string, fs *flag.FlagSet, out *outp
199228
if len(positionals) == 0 && f.domainList == "" {
200229
out.Error("missing <domain> (or -dL <domains_file>)")
201230
}
202-
fmt.Fprintln(os.Stderr, "Usage: subenum -w <wordlist_file> [options] <domain>")
203-
fmt.Fprintln(os.Stderr, " subenum -w <wordlist_file> [options] -dL <domains_file>")
204231
fs.SetOutput(os.Stderr)
205-
fs.PrintDefaults()
232+
fs.Usage()
206233
return "", false
207234
}
208235
if f.domainList != "" && len(positionals) > 0 {
@@ -411,15 +438,15 @@ func run() (code int) {
411438
out := output.New(nil, f.testMode, format)
412439
if formatErr != nil {
413440
out.Error("%v", formatErr)
414-
return 1
441+
return exitUsage
415442
}
416443
if typesErr != nil {
417444
out.Error("%v", typesErr)
418-
return 1
445+
return exitUsage
419446
}
420447
if err != nil {
421448
out.Error("%v", err)
422-
return 1
449+
return exitUsage
423450
}
424451

425452
if f.testMode {
@@ -437,7 +464,7 @@ func run() (code int) {
437464

438465
domain, ok := validateFlags(f, positionals, fs, out, maxAttempts)
439466
if !ok {
440-
return 1
467+
return exitUsage
441468
}
442469

443470
targets, ok := loadTargets(f, domain, out)
@@ -514,23 +541,35 @@ func run() (code int) {
514541
sigCh := make(chan os.Signal, 1)
515542
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
516543
defer signal.Stop(sigCh)
517-
var interrupted atomic.Bool
544+
if signalReady != nil {
545+
close(signalReady)
546+
}
547+
var signalCode atomic.Int32 // 128+signum once a signal arrives
518548
go func() {
519549
select {
520-
case <-sigCh:
550+
case sig := <-sigCh:
521551
// Restore default handling so a second Ctrl+C force-quits a run
522552
// that is stuck draining (for example on a blocked stdout pipe).
523553
signal.Stop(sigCh)
524-
out.Info("Interrupt received, shutting down gracefully (Ctrl+C again to force quit)...")
525-
interrupted.Store(true)
554+
if sig == syscall.SIGTERM {
555+
out.Info("SIGTERM received, shutting down gracefully...")
556+
signalCode.Store(143)
557+
} else {
558+
out.Info("Interrupt received, shutting down gracefully (Ctrl+C again to force quit)...")
559+
signalCode.Store(130)
560+
}
526561
cancel()
527562
case <-ctx.Done():
528563
}
529564
}()
530565

531566
// Each target is an independent scan: its own preflight, wildcard check,
532-
// -max-queries budget and reliability guard. Results share one writer, so
533-
// -format json is a single array and CSV has a single header.
567+
// -max-queries budget, -rate limiter and reliability guard. Results share
568+
// one writer, so -format json is a single array and CSV has a single
569+
// header. A reliability abort means the resolver is overloaded, so the
570+
// remaining targets are skipped rather than sent to it too (#82).
571+
status := make([]string, len(targets))
572+
failedTargets := 0
534573
for i, target := range targets {
535574
if ctx.Err() != nil {
536575
break
@@ -551,11 +590,36 @@ func run() (code int) {
551590
if len(entries) == 0 {
552591
out.Error("no valid wordlist entries for %s", target)
553592
anyFailed = true
593+
status[i] = "failed"
594+
failedTargets++
554595
continue
555596
}
556-
done, failed := scanTarget(ctx, f, target, entries, maxAttempts, recordTypes, out, outWriter)
597+
done, failed, resolverAbort := scanTarget(ctx, f, target, entries, maxAttempts, recordTypes, out, outWriter)
557598
anyDone = anyDone || done
558599
anyFailed = anyFailed || failed
600+
status[i] = "ok"
601+
if failed {
602+
status[i] = "failed"
603+
failedTargets++
604+
}
605+
if resolverAbort && i < len(targets)-1 {
606+
out.Error("resolver %s looks overloaded; skipping the %d remaining targets (use -no-abort to continue)", f.dnsServer, len(targets)-1-i)
607+
for j := i + 1; j < len(targets); j++ {
608+
status[j] = "skipped"
609+
failedTargets++
610+
}
611+
break
612+
}
613+
}
614+
if len(targets) > 1 {
615+
out.Info("Targets:")
616+
for i, target := range targets {
617+
st := status[i]
618+
if st == "" {
619+
st = "not run"
620+
}
621+
out.Info(" %-8s %s", st, target)
622+
}
559623
}
560624

561625
// Finalize structured output only if at least one scan finished, so an
@@ -572,21 +636,27 @@ func run() (code int) {
572636
out.Info("NOTE: these results are SIMULATED; no DNS queries were sent (seed %d).", f.seed)
573637
}
574638
}
575-
if interrupted.Load() {
576-
// Shell convention for SIGINT (128+2): partial results were flushed above,
639+
if c := signalCode.Load(); c != 0 {
640+
// Shell convention 128+signum: partial results were flushed above,
577641
// but callers can tell an interrupted scan apart from success or failure.
578-
return 130
642+
return int(c)
579643
}
580-
if anyFailed || fileErrReported {
581-
return 1
644+
if fileErrReported {
645+
return exitFailure
646+
}
647+
if len(targets) > 1 && failedTargets > 0 && failedTargets < len(targets) {
648+
return exitPartial
649+
}
650+
if anyFailed {
651+
return exitFailure
582652
}
583-
return 0
653+
return exitOK
584654
}
585655

586656
// scanTarget runs one domain's scan and streams its events to out. It reports
587-
// whether the scan finished (EventDone arrived) and whether it should count as
588-
// a failure for the exit code.
589-
func scanTarget(ctx context.Context, f cliFlags, domain string, entries []string, maxAttempts int, recordTypes []string, out *output.Writer, outWriter *bufio.Writer) (sawDone, failed bool) {
657+
// whether the scan finished (EventDone arrived), whether it should count as a
658+
// failure for the exit code, and whether the reliability guard aborted it.
659+
func scanTarget(ctx context.Context, f cliFlags, domain string, entries []string, maxAttempts int, recordTypes []string, out *output.Writer, outWriter *bufio.Writer) (sawDone, failed, resolverAbort bool) {
590660
cfg := scan.Config{
591661
Domain: domain,
592662
Entries: entries,
@@ -648,7 +718,10 @@ func scanTarget(ctx context.Context, f cliFlags, domain string, entries []string
648718
}
649719
}
650720
// An error fails the run unless the scan finished under -no-abort.
651-
return sawDone, sawError && (!sawDone || !f.noAbort)
721+
// The reliability guard is the only error that still lets EventDone
722+
// arrive; without -no-abort it cancelled the scan.
723+
resolverAbort = sawDone && sawError && !f.noAbort
724+
return sawDone, sawError && (!sawDone || !f.noAbort), resolverAbort
652725
}
653726

654727
// resolveAttempts merges the -attempts and deprecated -retries flags.

‎main_e2e_test.go‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,16 +130,22 @@ func TestE2ESeedReproducible(t *testing.T) {
130130
func TestE2EExitCodes(t *testing.T) {
131131
wl := writeFile(t, "wl.txt", e2eWords)
132132
empty := writeFile(t, "empty.txt", "# only comments\n")
133+
// The second domain is so long that no wordlist entry fits under it, so
134+
// that target fails while the first completes.
135+
long := strings.Repeat("a", 63) + "." + strings.Repeat("b", 63) + "." + strings.Repeat("c", 63) + "." + strings.Repeat("d", 54) + ".com"
136+
partial := writeFile(t, "partial.txt", "example.com\n"+long+"\n")
133137
cases := []struct {
134138
name string
135139
args []string
136140
want int
137141
}{
138142
{"help", []string{"-h"}, 0},
139143
{"unknown flag", []string{"-nope"}, 2},
140-
{"missing domain", []string{"-w", wl}, 1},
141-
{"two domains", []string{"-simulate", "-w", wl, "a.example", "b.example"}, 1},
142-
{"invalid flag value after domain", []string{"-simulate", "-w", wl, "example.com", "-t", "0"}, 1},
144+
{"missing domain", []string{"-w", wl}, 2},
145+
{"two domains", []string{"-simulate", "-w", wl, "a.example", "b.example"}, 2},
146+
{"invalid flag value after domain", []string{"-simulate", "-w", wl, "example.com", "-t", "0"}, 2},
147+
{"invalid format", []string{"-simulate", "-format", "xml", "-w", wl, "example.com"}, 2},
148+
{"-dL partial failure", []string{"-simulate", "-progress=false", "-w", wl, "-dL", partial}, 3},
143149
{"wordlist without valid entries", []string{"-simulate", "-w", empty, "example.com"}, 1},
144150
{"domain list without valid domains", []string{"-simulate", "-w", wl, "-dL", empty}, 1},
145151
{"unwritable output file", []string{"-simulate", "-progress=false", "-w", wl, "-o", t.TempDir(), "example.com"}, 1},
@@ -300,3 +306,11 @@ func TestE2ECLIPolish(t *testing.T) {
300306
t.Errorf("-simulate -version: exit %d, output:\n%s", code, out)
301307
}
302308
}
309+
310+
// TestE2EHelpListsExitCodes covers #82: -h documents the exit codes.
311+
func TestE2EHelpListsExitCodes(t *testing.T) {
312+
code, out := runCLIMerged(t, "-h")
313+
if code != 0 || !strings.Contains(out, "Exit codes:") || !strings.Contains(out, "143") {
314+
t.Errorf("-h: exit %d, output missing the exit-code table:\n%s", code, out)
315+
}
316+
}

‎main_signal_unix_test.go‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//go:build unix
2+
3+
package main
4+
5+
import (
6+
"fmt"
7+
"strings"
8+
"syscall"
9+
"testing"
10+
"time"
11+
)
12+
13+
// TestE2ESIGTERMExits143 covers #82: SIGTERM (container stop, systemd) exits
14+
// 143, not the SIGINT code 130.
15+
func TestE2ESIGTERMExits143(t *testing.T) {
16+
var words strings.Builder
17+
for i := 0; i < 200; i++ {
18+
fmt.Fprintf(&words, "w%d\n", i)
19+
}
20+
wl := writeFile(t, "wl.txt", words.String())
21+
22+
ready := make(chan struct{})
23+
signalReady = ready
24+
t.Cleanup(func() { signalReady = nil })
25+
go func() {
26+
<-ready
27+
time.Sleep(200 * time.Millisecond) // let the scan start
28+
_ = syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
29+
}()
30+
31+
// 200 names at -rate 10 would take 20s; the signal ends it early.
32+
code, _ := runCLI(t, "", "-simulate", "-rate", "10", "-progress=false", "-w", wl, "example.com")
33+
if code != 143 {
34+
t.Fatalf("exit %d after SIGTERM, want 143", code)
35+
}
36+
}

0 commit comments

Comments
 (0)