@@ -28,6 +28,7 @@ import (
2828 "errors"
2929 "flag"
3030 "fmt"
31+ "io"
3132 "math/rand/v2"
3233 "os"
3334 "os/signal"
@@ -160,20 +161,33 @@ type cliFlags struct {
160161 pool * dns.Pool // built from -r; nil means the single -dns-server
161162 excludes []string // -exclude and -exclude-file patterns, merged
162163 defaults * defaultsLoader // where config-file and env values came from; nil in tests
164+ stdin io.Reader // read for a "-" path; nil means os.Stdin
165+ }
166+
167+ // readLines reads path, or f.stdin when path is "-".
168+ func (f cliFlags ) readLines (path string ) ([]string , error ) {
169+ if path == wordlist .Stdin && f .stdin != nil {
170+ return wordlist .ReadLinesFrom (f .stdin )
171+ }
172+ return wordlist .ReadLines (path )
163173}
164174
165175// parseFlags parses args (without the program name). Flags may appear before or
166176// after the domain; the returned positionals are every non-flag argument.
167177func parseFlags (args []string ) (cliFlags , []string , * flag.FlagSet , error ) {
168- return parseFlagsWith (args , nil )
178+ return parseFlagsWith (args , nil , nil )
169179}
170180
171181// parseFlagsWith is parseFlags with applyDefaults run after the flags are
172182// defined and before the command line is parsed, so config-file and
173183// environment defaults sit between built-in defaults and explicit flags (#88).
174- func parseFlagsWith (args []string , applyDefaults func (* flag.FlagSet ) error ) (cliFlags , []string , * flag.FlagSet , error ) {
184+ // Parse errors and usage go to stderr; nil means os.Stderr.
185+ func parseFlagsWith (args []string , applyDefaults func (* flag.FlagSet ) error , stderr io.Writer ) (cliFlags , []string , * flag.FlagSet , error ) {
175186 var f cliFlags
176187 fs := flag .NewFlagSet (ProgramName , flag .ContinueOnError )
188+ if stderr != nil {
189+ fs .SetOutput (stderr )
190+ }
177191 fs .BoolVar (& f .tui , "tui" , false , "Launch the interactive terminal UI (all other flags are ignored)" )
178192 fs .BoolVar (& f .printConfig , "print-config" , false , "Print every setting's effective value and its source (flag, env, config or default), then exit" )
179193 fs .StringVar (& f .wordlistFile , "w" , "" , "Path to the wordlist file (- for stdin); omitted: the bundled top-5000 list" )
@@ -288,7 +302,6 @@ func validateArgs(f cliFlags, positionals []string, fs *flag.FlagSet, out *outpu
288302 if len (positionals ) == 0 && f .domainList == "" {
289303 // Say what is missing before the full flag list (#58).
290304 out .Error ("missing <domain> (or -dL <domains_file>)" )
291- fs .SetOutput (os .Stderr )
292305 fs .Usage ()
293306 return false
294307 }
@@ -371,7 +384,7 @@ func loadPool(f cliFlags, out *output.Writer) (*dns.Pool, int) {
371384 out .Info ("Note: -r is ignored in simulation mode, which sends no DNS queries" )
372385 return nil , exitOK
373386 }
374- lines , err := wordlist . ReadLines (f .resolvers )
387+ lines , err := f . readLines (f .resolvers )
375388 if err != nil {
376389 out .Error ("reading -r resolver list: %v" , err )
377390 return nil , exitFailure
@@ -416,7 +429,7 @@ func loadExcludes(f cliFlags) ([]string, error) {
416429 if f .excludeFile == "" {
417430 return patterns , nil
418431 }
419- lines , err := wordlist . ReadLines (f .excludeFile )
432+ lines , err := f . readLines (f .excludeFile )
420433 if err != nil {
421434 return nil , err
422435 }
@@ -435,7 +448,7 @@ func loadTargets(f cliFlags, domain string, out *output.Writer) ([]string, bool)
435448 if f .domainList == "" {
436449 return []string {domain }, true
437450 }
438- lines , err := wordlist . ReadLines (f .domainList )
451+ lines , err := f . readLines (f .domainList )
439452 if err != nil {
440453 out .Error ("reading domain list: %v" , err )
441454 return nil , false
@@ -478,13 +491,13 @@ func openOutputFile(path string, testMode bool, format output.Format, out *outpu
478491 return output .New (f .Writer , testMode , format ), f , true
479492}
480493
481- // stdoutIsTerminal reports whether stdout is an interactive terminal rather than
482- // a pipe or file .
483- func stdoutIsTerminal ( ) bool { return isTerminal ( os . Stdout ) }
484-
485- // isTerminal reports whether f is a character device (a terminal) rather than
486- // a pipe or file.
487- func isTerminal ( f * os. File ) bool {
494+ // isTerminal reports whether w is a character device (a terminal) rather than
495+ // a pipe, file or in-memory buffer .
496+ func isTerminal ( w io. Writer ) bool {
497+ f , ok := w .( * os. File )
498+ if ! ok {
499+ return false
500+ }
488501 fi , err := f .Stat ()
489502 return err == nil && fi .Mode ()& os .ModeCharDevice != 0
490503}
@@ -553,28 +566,43 @@ func logScanBreakdown(domain string, ev scan.Event, out *output.Writer) {
553566 }
554567}
555568
556- func run () (code int ) {
569+ // runArgs is the process environment a run reads: the arguments after the
570+ // program name and the standard streams. Tests pass their own, so they do
571+ // not swap os.Args, os.Stdin, os.Stdout and os.Stderr (#158).
572+ type runArgs struct {
573+ args []string
574+ stdin io.Reader
575+ stdout io.Writer
576+ stderr io.Writer
577+ }
578+
579+ func run () int {
580+ return runWith (runArgs {args : os .Args [1 :], stdin : os .Stdin , stdout : os .Stdout , stderr : os .Stderr })
581+ }
582+
583+ func runWith (a runArgs ) (code int ) {
557584 // completion, man (#88): handled before flag parsing.
558- if code , ok := runSubcommand (os . Args [ 1 :], os . Stdout , os . Stderr ); ok {
585+ if code , ok := runSubcommand (a . args , a . stdout , a . stderr ); ok {
559586 return code
560587 }
561588
562- args , resume , resumeErr := resumeArgs (os . Args [ 1 :] )
589+ args , resume , resumeErr := resumeArgs (a . args )
563590 if resumeErr != nil {
564- _ , _ = fmt .Fprintf (os . Stderr , "Error: %v\n " , resumeErr )
591+ _ , _ = fmt .Fprintf (a . stderr , "Error: %v\n " , resumeErr )
565592 return exitUsage
566593 }
567594 defaults := newDefaultsLoader ()
568- f , positionals , fs , parseErr := parseFlagsWith (args , defaults .apply )
595+ f , positionals , fs , parseErr := parseFlagsWith (args , defaults .apply , a . stderr )
569596 f .defaults = defaults
597+ f .stdin = a .stdin
570598 if errors .Is (parseErr , errConfig ) {
571599 // -version, -print-config and -tui stay usable with a broken config,
572600 // so the bad value can be found and fixed (#116).
573601 if ! f .showVersion && ! f .printConfig && ! f .tui {
574- _ , _ = fmt .Fprintf (os . Stderr , "Error: %v\n " , parseErr )
602+ _ , _ = fmt .Fprintf (a . stderr , "Error: %v\n " , parseErr )
575603 return exitUsage
576604 }
577- _ , _ = fmt .Fprintf (os . Stderr , "Warning: %v\n " , parseErr )
605+ _ , _ = fmt .Fprintf (a . stderr , "Warning: %v\n " , parseErr )
578606 parseErr = nil
579607 }
580608 if parseErr != nil {
@@ -589,26 +617,32 @@ func run() (code int) {
589617 // (-o -tui) or an argument after "--" (#58).
590618 if f .tui {
591619 if fs .NFlag () > 1 || len (positionals ) > 0 {
592- fmt .Fprintln (os . Stderr , "Warning: -tui ignores every other flag and argument; set them in the form instead" )
620+ _ , _ = fmt .Fprintln (a . stderr , "Warning: -tui ignores every other flag and argument; set them in the form instead" )
593621 }
594622 return tui .Start (tui.Options {Version : resolveVersion (), Settings : defaults .settings (fs )})
595623 }
596624
597625 if f .printConfig {
598- defaults .printConfig (os . Stdout , fs )
626+ defaults .printConfig (a . stdout , fs )
599627 return exitOK
600628 }
601629
602630 // -version answers before anything else prints, banners included (#58).
603631 if f .showVersion {
604- fmt .Println ( formatVersion ())
632+ _ , _ = fmt .Fprintln ( a . stdout , formatVersion ())
605633 return exitOK
606634 }
607635
608636 format , formatErr := output .ParseFormat (f .format )
609637 recordTypes , typesErr := dns .ParseTypes (f .recordTypes )
610638 maxAttempts , fromRetries , err := effectiveAttempts (f .attempts , f .retries , defaults .source (fs , "attempts" ), defaults .source (fs , "retries" ))
611- out := output .New (nil , f .testMode , format )
639+ // Every writer of the run uses the injected streams.
640+ wire := func (w * output.Writer ) * output.Writer {
641+ w .SetStdout (a .stdout )
642+ w .SetStderr (a .stderr )
643+ return w
644+ }
645+ out := wire (output .New (nil , f .testMode , format ))
612646 out .SetQuiet (f .silent )
613647 if fromRetries {
614648 out .Info ("Warning: -retries is deprecated, use -attempts instead" ) // quiet under -silent (#166)
@@ -751,6 +785,7 @@ func run() (code int) {
751785 if ! ok {
752786 return exitFailure
753787 }
788+ wire (combined )
754789 var outWriter * bufio.Writer
755790 if outFile != nil {
756791 outWriter = outFile .Writer
@@ -759,7 +794,7 @@ func run() (code int) {
759794 // the full current results, ready to be the next run's -diff input (#84).
760795 var fileOut * output.Writer
761796 if diff != nil && outFile != nil {
762- fileOut = output .NewFile (outFile .Writer , f .testMode , format )
797+ fileOut = wire ( output .NewFile (outFile .Writer , f .testMode , format ) )
763798 } else {
764799 out = combined
765800 }
@@ -770,7 +805,7 @@ func run() (code int) {
770805 }
771806 // Bare names when piped or -silent (no "Found:" banner), human-friendly
772807 // on a terminal.
773- w .SetPlain (f .silent || ! stdoutIsTerminal ( ))
808+ w .SetPlain (f .silent || ! isTerminal ( a . stdout ))
774809 w .SetQuiet (f .silent )
775810 w .SetShowRecords (f .showRecords )
776811 w .SetSeed (f .seed )
@@ -820,7 +855,7 @@ func run() (code int) {
820855 if f .silent {
821856 f .showProgress = false
822857 }
823- if ! isTerminal (os . Stderr ) {
858+ if ! isTerminal (a . stderr ) {
824859 if defaults .source (fs , "progress" ) != sourceDefault {
825860 out .SetProgressLines (true )
826861 } else {
0 commit comments