feat(04-02): wire --filter and --read flags into CLI with branching run logic

- Add bpfFilter and readPath global vars with flag registration
- Add deriveOutputPath helper: capture.pcap -> capture.mp3 (D-05)
- run() validates mutual exclusion of --read and -i (D-03)
- run() pre-validates BPF filter via capture.ValidateBPFFilter before capture (CAPT-05)
- runLiveMode: extracts existing live pipeline, passes bpfFilter to StartCapture
- runPcapMode: reads pcap with ReadPcapFile, classifies with timestamps, AggregatePcap, encodes
- Bookend messages: 'Reading <file>...' at start, 'Saved...' at end (D-06)
- --verbose supported in pcap mode via onSnapshot callback (D-07)
- Empty pcap produces clear error with file path (Pitfall 4)
This commit is contained in:
2026-03-26 14:41:02 +01:00
parent 09e78bf151
commit 4adb3c4cb2
+113 -8
View File
@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"os" "os"
"os/signal" "os/signal"
"path/filepath"
"strings" "strings"
"sync/atomic" "sync/atomic"
"syscall" "syscall"
@@ -23,6 +24,8 @@ var (
listIfaces bool listIfaces bool
verbose bool verbose bool
outputPath string outputPath string
bpfFilter string // NEW: --filter flag (CAPT-05)
readPath string // NEW: --read flag (CAPT-06)
) )
func main() { func main() {
@@ -37,35 +40,69 @@ func main() {
rootCmd.Flags().BoolVar(&listIfaces, "list-interfaces", false, "List available network interfaces and exit") rootCmd.Flags().BoolVar(&listIfaces, "list-interfaces", false, "List available network interfaces and exit")
rootCmd.Flags().BoolVar(&verbose, "verbose", false, "Print per-window protocol activity to stderr") rootCmd.Flags().BoolVar(&verbose, "verbose", false, "Print per-window protocol activity to stderr")
rootCmd.Flags().StringVarP(&outputPath, "output", "o", "", "Output MP3 file path (default: netsynth-<timestamp>.mp3)") rootCmd.Flags().StringVarP(&outputPath, "output", "o", "", "Output MP3 file path (default: netsynth-<timestamp>.mp3)")
rootCmd.Flags().StringVar(&bpfFilter, "filter", "", "BPF filter expression (tcpdump syntax, e.g. \"port 53\")")
rootCmd.Flags().StringVar(&readPath, "read", "", "Read packets from pcap file instead of live capture")
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
os.Exit(1) os.Exit(1)
} }
} }
// deriveOutputPath replaces the file extension with .mp3 per D-05.
// "capture.pcap" -> "capture.mp3", "noext" -> "noext.mp3"
func deriveOutputPath(rPath string) string {
ext := filepath.Ext(rPath)
if ext == "" {
return rPath + ".mp3"
}
return strings.TrimSuffix(rPath, ext) + ".mp3"
}
func run(cmd *cobra.Command, args []string) error { func run(cmd *cobra.Command, args []string) error {
// --list-interfaces mode (CAPT-02) // --list-interfaces mode (CAPT-02)
if listIfaces { if listIfaces {
return runListInterfaces() return runListInterfaces()
} }
// Resolve default output path (D-15 / OUT-01) // D-03: --read and -i are mutually exclusive
if readPath != "" && ifaceName != "" {
return fmt.Errorf("--read and -i are mutually exclusive; use one or the other")
}
if readPath == "" && ifaceName == "" {
return fmt.Errorf("interface required: use -i <interface>, --read <file>, or --list-interfaces to see available interfaces")
}
// Pre-validate BPF filter before any capture (CAPT-05, Pitfall 1)
if bpfFilter != "" {
if err := capture.ValidateBPFFilter(bpfFilter); err != nil {
return err
}
}
// Resolve output path
if outputPath == "" { if outputPath == "" {
if readPath != "" {
outputPath = deriveOutputPath(readPath) // D-05
} else {
outputPath = fmt.Sprintf("netsynth-%s.mp3", time.Now().Format("20060102-150405")) outputPath = fmt.Sprintf("netsynth-%s.mp3", time.Now().Format("20060102-150405"))
} }
// Require -i flag
if ifaceName == "" {
return fmt.Errorf("interface required: use -i <interface> or --list-interfaces to see available interfaces")
} }
if readPath != "" {
return runPcapMode(cmd)
}
return runLiveMode(cmd)
}
// runLiveMode runs the live packet capture pipeline.
func runLiveMode(cmd *cobra.Command) error {
// Set up signal handling (Ctrl+C) // Set up signal handling (Ctrl+C)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop() defer stop()
// Stage 1: Capture (CAPT-01) // Stage 1: Capture (CAPT-01) with optional BPF filter (CAPT-05)
fmt.Fprintf(os.Stderr, "Starting capture on %s... (press Ctrl+C to stop)\n", ifaceName) fmt.Fprintf(os.Stderr, "Starting capture on %s... (press Ctrl+C to stop)\n", ifaceName)
packets, droppedPtr, err := capture.StartCapture(ctx, ifaceName, "") packets, droppedPtr, err := capture.StartCapture(ctx, ifaceName, bpfFilter)
if err != nil { if err != nil {
return err // CAPT-04: permission error already has platform-specific message return err // CAPT-04: permission error already has platform-specific message
} }
@@ -89,7 +126,7 @@ func run(cmd *cobra.Command, args []string) error {
} }
snapshots := aggregate.Aggregate(ctx.Done(), classified, aggregate.DefaultWindowMs, onSnapshot) snapshots := aggregate.Aggregate(ctx.Done(), classified, aggregate.DefaultWindowMs, onSnapshot)
// Accumulate snapshots for synthesis (Phase 3 will pass to encode.RunSynthesis) // Accumulate snapshots for synthesis
totals := make(map[classify.TrafficClass]int64) totals := make(map[classify.TrafficClass]int64)
var collectedSnapshots []classify.WindowSnapshot var collectedSnapshots []classify.WindowSnapshot
for snap := range snapshots { for snap := range snapshots {
@@ -123,6 +160,74 @@ func run(cmd *cobra.Command, args []string) error {
return nil return nil
} }
// runPcapMode runs the pcap file processing pipeline (CAPT-06).
func runPcapMode(cmd *cobra.Command) error {
// D-06: bookend start message
fmt.Fprintf(os.Stderr, "Reading %s...\n", readPath)
// Open pcap file with optional software BPF filter (D-04)
packets, err := capture.ReadPcapFile(readPath, bpfFilter)
if err != nil {
return err
}
// Classify packets (reuse same classifier)
classifier := classify.NewClassifier(classify.DefaultRules)
classified := make(chan classify.ClassifiedPacket, 1024)
go func() {
defer close(classified)
for pkt := range packets {
cp := classifier.Classify(pkt)
// Set timestamp from pcap metadata for D-01 window assignment
cp.Timestamp = pkt.Metadata().CaptureInfo.Timestamp
classified <- cp
}
}()
// D-07: --verbose callback (same as live mode)
var onSnapshot func(classify.WindowSnapshot)
if verbose {
onSnapshot = func(snap classify.WindowSnapshot) {
aggregate.PrintWindowLine(os.Stderr, snap)
}
}
// Timestamp-based aggregation (D-01, D-02)
collectedSnapshots := aggregate.AggregatePcap(classified, aggregate.DefaultWindowMs, onSnapshot)
// Accumulate totals for summary
totals := make(map[classify.TrafficClass]int64)
for _, snap := range collectedSnapshots {
aggregate.AccumulateTotals(totals, snap)
}
// D-06: protocol summary (same format as live mode)
aggregate.PrintSummary(os.Stderr, totals)
// Check for empty pcap (Pitfall 4: better error than generic "no packets captured")
if len(collectedSnapshots) == 0 {
return fmt.Errorf("pcap file %q contains no packets (after filtering)", readPath)
}
// Encode
fmt.Fprintf(os.Stderr, "Encoding %d windows to %s...\n", len(collectedSnapshots), outputPath)
encodeStart := time.Now()
if err := encode.RunSynthesis(collectedSnapshots, outputPath); err != nil {
return fmt.Errorf("synthesis failed: %w", err)
}
encodeElapsed := time.Since(encodeStart)
// D-06: bookend end message
audioDuration := float64(len(collectedSnapshots)) * float64(aggregate.DefaultWindowMs) / 1000.0
info, statErr := os.Stat(outputPath)
if statErr != nil {
return fmt.Errorf("stat output file: %w", statErr)
}
fmt.Fprintf(os.Stderr, "Saved %s (%.1fs, %d KB, encoded in %.1fs)\n",
outputPath, audioDuration, info.Size()/1024, encodeElapsed.Seconds())
return nil
}
func runListInterfaces() error { func runListInterfaces() error {
ifaces, err := capture.ListInterfaces() ifaces, err := capture.ListInterfaces()
if err != nil { if err != nil {