Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions internal/dns/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -473,10 +473,19 @@ func StderrLogf(format string, args ...any) {
// by the CLI, returning the resolved records for the requested types.
func (l Lookup) resolveWithLog(ctx context.Context, domain string) ([]Record, time.Duration, error) {
records, elapsed, err := l.ResolveTypes(ctx, domain)
if l.Logf != nil && len(records) > 0 {
l.Logf("Resolved: %s (%s: %s) in %s", domain, records[0].Type, records[0].Value, elapsed)
} else if l.Logf != nil {
l.Logf("Failed to resolve: %s (Error: %v) in %s", domain, err, elapsed)
if l.Logf != nil {
switch {
case len(records) > 0:
l.Logf("Resolved: %s (%s: %s) in %s", domain, records[0].Type, records[0].Value, elapsed)
case err == nil:
types := l.Types
if len(types) == 0 {
types = DefaultTypes
}
l.Logf("No records: %s (%s) in %s", domain, strings.Join(types, ","), elapsed)
default:
l.Logf("Failed to resolve: %s (Error: %v) in %s", domain, err, elapsed)
}
}
return records, elapsed, err
}
Expand Down
38 changes: 38 additions & 0 deletions internal/dns/resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"net"
"os"
"strings"
"testing"
"time"
)
Expand Down Expand Up @@ -227,6 +228,43 @@ func TestResolveDomainWithRetryCNAMENoData(t *testing.T) {
}
}

func TestResolveVerboseNoData(t *testing.T) {
srv := startTestDNS(t, map[string]testReply{
"www.example.com": {A: "192.0.2.10"},
"alias.example.com": {CNAME: "www.example.com"},
})
for _, tc := range []struct {
domain string
prefix string
outcome Outcome
}{
{"www.example.com", "No records: www.example.com (CNAME) in ", OutcomeNXDomain},
{"alias.example.com", "Resolved: alias.example.com (CNAME: www.example.com) in ", OutcomeFound},
{"missing.example.com", "Failed to resolve: missing.example.com (Error: ", OutcomeNXDomain},
} {
t.Run(tc.domain, func(t *testing.T) {
var lines []string
lookup := Lookup{
Resolver: srv.Resolver(time.Second), Timeout: time.Second,
Attempts: 1, Types: []string{"CNAME"},
Logf: func(format string, args ...any) {
lines = append(lines, fmt.Sprintf(format, args...))
},
}
_, outcome := lookup.Resolve(context.Background(), tc.domain)
if outcome != tc.outcome {
t.Errorf("outcome = %v, want %v", outcome, tc.outcome)
}
if len(lines) != 1 || !strings.HasPrefix(lines[0], tc.prefix) {
t.Fatalf("verbose lines = %q, want one beginning %q", lines, tc.prefix)
}
if strings.Contains(lines[0], "Error: <nil>") {
t.Errorf("successful NODATA lookup logged a nil error: %q", lines[0])
}
})
}
}

// TestCheckWildcardCNAMEFingerprint covers the second half of #28: with
// -type CNAME the wildcard fingerprint must carry the CNAME target, otherwise
// recordsSubset can never filter CNAME-wildcard answers under -force.
Expand Down
2 changes: 1 addition & 1 deletion internal/output/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Format int
const (
// FormatText is the default human-friendly streaming output.
FormatText Format = iota
// FormatJSON buffers results and emits a single JSON array at completion.
// FormatJSON streams results as array elements; Finish closes the array.
FormatJSON
// FormatCSV streams "subdomain,type,value" rows with a header.
FormatCSV
Expand Down
6 changes: 3 additions & 3 deletions internal/tui/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,8 @@ func (m Model) updateScan(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, svCmd
case ev.Kind == scan.EventDone:
// Successful completion (including user abort, which still drains and
// emits EventDone): finalize structured output so buffered JSON/CSV is
// written and partial results are flushed. A JSONL file ends with the
// emits EventDone): finalize structured output to close the streamed JSON
// array and flush CSV and partial results. A JSONL file ends with the
// run-quality summary, as the CLI's does (#118).
if m.out != nil {
m.out.Summary(m.summary(ev.Event))
Expand All @@ -343,7 +343,7 @@ func (m Model) updateScan(msg tea.Msg) (tea.Model, tea.Cmd) {
}

// finalizeOutput closes the optional output file. When finish is true the
// structured writer is finalized first (buffered JSON array emitted, CSV
// structured writer is finalized first (streamed JSON array closed, CSV
// flushed) and the file replaces any existing one; when false it is discarded
// and an existing results file is left untouched (#52).
// Safe to call when no output file is configured.
Expand Down
5 changes: 2 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,10 +300,9 @@ func validateArgs(f cliFlags, positionals []string, fs *flag.FlagSet, out *outpu
return true
}

// validateFlags checks options after validateArgs has checked the domain
// arguments. configure does that before reading any input files.
func validateFlags(f cliFlags, in *runtimeInputs, positionals []string, fs *flag.FlagSet, out *output.Writer) (string, bool) {
if !validateArgs(f, positionals, fs, out) {
return "", false
}
if f.wordlists.readsStdin() && f.domainList == wordlist.Stdin {
out.Error("-w and -dL cannot both read standard input")
return "", false
Expand Down
34 changes: 34 additions & 0 deletions main_logformat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ package main
import (
"bytes"
"encoding/json"
"path/filepath"
"strings"
"testing"

"github.com/TMHSDigital/subenum/internal/output"
)

// runCLIStreams runs the CLI with stdout and stderr captured apart.
Expand Down Expand Up @@ -178,3 +181,34 @@ func TestE2ELogFormatJSONProgress(t *testing.T) {
}
parseLogLines(t, stderr)
}

func TestTUIOptionsJSONWarnings(t *testing.T) {
d := &defaultsLoader{path: filepath.Join(t.TempDir(), "none.json"), getenv: func(string) string { return "" }}
f, pos, fs, err := parseFlagsWith([]string{
"-tui", "-log-format", "json", "-w", "first.txt", "-w", "extra.txt",
"-stats", "stats.json", "example.com", "other.example.com",
}, d.apply, nil)
if err != nil {
t.Fatal(err)
}
var stderr bytes.Buffer
diag := output.New(nil, false, output.FormatText)
diag.SetStderr(&stderr)
diag.SetLogFormat(output.LogJSON)
opts := tuiOptions(f, fs, pos, d, diag)
if opts.Domain != "example.com" || opts.Settings["w"] != "first.txt" {
t.Fatalf("TUI options = %+v", opts)
}
lines := parseLogLines(t, stderr.String())
if len(lines) != 2 {
t.Fatalf("diagnostics = %+v, want two warnings", lines)
}
for i, want := range []string{
"the TUI takes one wordlist; using first.txt",
"-tui has no form field for -log-format -stats other.example.com; ignored",
} {
if lines[i].Level != "warn" || lines[i].Kind != "message" || lines[i].Message != want {
t.Errorf("diagnostic %d = %+v, want a JSON warning with message %q", i, lines[i], want)
}
}
}
9 changes: 4 additions & 5 deletions main_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"errors"
"flag"
"fmt"
"io"
"math/rand/v2"
"os"
"os/signal"
Expand Down Expand Up @@ -189,7 +188,7 @@ func (s *session) parse() (code int, done bool) {
// -tui counts only as a real flag, not as the value of another flag
// (-o -tui) or an argument after "--" (#58).
if f.tui {
return tui.Start(tuiOptions(f, fs, positionals, defaults, a.stderr)), true
return tui.Start(tuiOptions(f, fs, positionals, defaults, diag)), true
}

if f.printConfig {
Expand All @@ -209,7 +208,7 @@ func (s *session) parse() (code int, done bool) {
// argument and every flag the form has a field for, over SUBENUM_* and config
// file values. Flags the form has no field for are named in a warning, as are
// extra domain arguments and extra -w files (the form takes one wordlist).
func tuiOptions(f cliFlags, fs *flag.FlagSet, positionals []string, defaults *defaultsLoader, stderr io.Writer) tui.Options {
func tuiOptions(f cliFlags, fs *flag.FlagSet, positionals []string, defaults *defaultsLoader, diag *output.Writer) tui.Options {
settings := defaults.settings(fs)
wired := map[string]bool{}
for _, name := range tui.Flags() {
Expand All @@ -227,7 +226,7 @@ func tuiOptions(f cliFlags, fs *flag.FlagSet, positionals []string, defaults *de
})
if len(f.wordlists.paths) > 1 {
settings["w"] = f.wordlists.paths[0]
_, _ = fmt.Fprintf(stderr, "Warning: the TUI takes one wordlist; using %s\n", f.wordlists.paths[0])
diag.Notice("Warning: the TUI takes one wordlist; using %s", f.wordlists.paths[0])
}
opts := tui.Options{Version: resolveVersion(), Settings: settings}
if len(positionals) > 0 {
Expand All @@ -237,7 +236,7 @@ func tuiOptions(f cliFlags, fs *flag.FlagSet, positionals []string, defaults *de
ignored = append(ignored, positionals[1:]...)
}
if len(ignored) > 0 {
_, _ = fmt.Fprintf(stderr, "Warning: -tui has no form field for %s; ignored\n", strings.Join(ignored, " "))
diag.Notice("Warning: -tui has no form field for %s; ignored", strings.Join(ignored, " "))
}
return opts
}
Expand Down
8 changes: 5 additions & 3 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func TestValidateFlagsDomainListConflicts(t *testing.T) {

f := base()
f.domainList = "d.txt"
if _, ok := validateFlags(f, &runtimeInputs{maxAttempts: 1}, []string{"example.com"}, fs, out); ok {
if validateArgs(f, []string{"example.com"}, fs, out) {
t.Error("domain argument plus -dL should be rejected")
}
f.wordlists.paths, f.domainList = []string{"-"}, "-"
Expand Down Expand Up @@ -335,7 +335,9 @@ func TestTUIOptionsFromFlags(t *testing.T) {
t.Fatal(err)
}
var stderr bytes.Buffer
opts := tuiOptions(f, fs, pos, d, &stderr)
diag := output.New(nil, false, output.FormatText)
diag.SetStderr(&stderr)
opts := tuiOptions(f, fs, pos, d, diag)
if opts.Domain != "example.com" {
t.Errorf("Domain = %q, want example.com", opts.Domain)
}
Expand All @@ -352,7 +354,7 @@ func TestTUIOptionsFromFlags(t *testing.T) {
// A bare -tui warns about nothing.
f, pos, fs, _ = parseFlagsWith([]string{"-tui"}, d.apply, nil)
stderr.Reset()
if opts := tuiOptions(f, fs, pos, d, &stderr); opts.Domain != "" || stderr.Len() != 0 {
if opts := tuiOptions(f, fs, pos, d, diag); opts.Domain != "" || stderr.Len() != 0 {
t.Errorf("bare -tui: Domain %q, stderr %q", opts.Domain, stderr.String())
}
}
Loading