commit e34ba75b7bfa7625f1bfcab80b0a4cf016754fed Author: Michael Wesemann Date: Mon Oct 26 15:52:55 2026 +0100 initial commit [141.14.140.180,mike] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e34759a --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +nscan +*.tmp +bin/ +.mgshrc +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..e730603 --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# nscan + +A network scanner for the terminal, modeled on [IP Scanner](https://10base-t.com/ipscanner/): +it finds the devices on the local network and shows name, IP, MAC, vendor, response time and +Bonjour services – as an interactive interface (TUI) or as a one-off table/JSON/CSV. + +## Build + +```sh +go build -o nscan . +./nscan # interactive interface +``` + +Requires Go 1.26 or newer. Runs on macOS and Linux, with limitations also on the BSDs and +Windows. No root privileges needed. + +## Features + +| IP Scanner | nscan | +|------------------------------|----------------------------------------------------------| +| Fast LAN scan | ICMP sweep + ARP cache, results appear live | +| Name, IP, MAC, Last Seen | plus vendor (OUI), ping time, Bonjour services | +| Custom names | `n` – stored permanently | +| Show/hide columns, sorting | `v` and `s`/`S` | +| Ping, port scan, Wake on LAN | `i`, `p`, `o` (also as `nscan ping/ports/wol`) | +| Bonjour services | DNS-SD discovery, listed in each device's details | +| Custom network ranges | `-r 10.0.0.0/24,10.0.5.10-50` or key `R` | +| Cumulative mode | `c` – also shows devices that are gone | +| Whitelist | `w` marks a device, `W` hides known devices | +| Track Device | `t` – terminal bell when a device misses 2 scans in a row or comes back | +| New device notifications | event line + bell | +| Network DVR (timeline) | `h` – one bar per hour/day, height = number of changes, `░` = not monitored | +| Open devices in browser/VNC | `b` browser, `x` SSH | +| Export | `e` writes JSON + CSV; `nscan scan -json/-csv` | + +## Colors + +The interface uses the [mwxcol](https://git.micw.org/mike/mwxcol) palette (`internal/tui/theme.go`): +green = online/new/ok, red = gone/error, yellow = tracked/warning, blue = headings, times and +keys, violet = accent and Bonjour services, grey = secondary text, `dark` = offline. The selection +is white on `darker` with a violet pointer, like the palette's fzf theme. Plain text and the +background come from the terminal – the mwxcol profile (background `#252528`) matches. + +## How it scans + +1. **ICMP echo** to every address (two rounds). On macOS and most Linux distributions this works + without root through unprivileged ICMP sockets. +2. **ARP cache**: every packet sent makes the kernel resolve the MAC address, so devices on the + local segment are found even if they ignore pings. +3. **TCP probe** (ports 80, 443, 22, 445, 139, 62078) for addresses outside the local segment. +4. **Names** via mDNS (a unicast query to each device), NetBIOS (Windows/Samba) and reverse DNS. +5. **Bonjour**: a DNS-SD query for all service types on the network. +6. **Models**: Apple devices announce their model (e.g. `MacBookAir10,1`) in a Bonjour + `_device-info` record, which nscan asks each named device for. + +Without `-r`, nscan scans the network of the interface with the default route; networks larger +than /20 are narrowed to the local /24. `nscan interfaces` lists the alternatives for `-i`. + +## Commands + +```text +nscan [-i en0] [-r 192.168.1.0/24] [-interval 1m] interactive interface +nscan scan [-json|-csv] scan once +nscan ping [-c 5] fritz.box ping +nscan ports [-p top|1-1024|all|22,80] 192.168.1.10 port scan +nscan wol aa:bb:cc:dd:ee:ff | "NAS" Wake-on-LAN (also by custom name) +nscan interfaces list interfaces +nscan oui update | import | lookup vendor database +``` + +## Vendor database + +The vendor column needs the IEEE list of MAC prefixes: + +```sh +./nscan oui update +``` + +If the IEEE server blocks the download, fetch + in a browser and import it: + +```sh +./nscan oui import ~/Downloads/oui.csv +``` + +Random ("private") MAC addresses, which iPhones, Macs and Android devices use per Wi-Fi +network, carry no vendor; nscan shows them as *Private address* even without the database. +If such a device announces an Apple model via Bonjour, the vendor column shows that instead, +e.g. *Apple MacBookAir10,1*. + +## Data + +Custom names, whitelist, tracking, first/last seen and the history (30 days) are kept in +`~/.config/nscan/` (or `$XDG_CONFIG_HOME/nscan`, or `$NSCAN_DIR`): +`devices.json`, `events.jsonl`, `oui.tsv`. + +## Notes + +- **macOS "Local Network"**: if nscan finds nothing but your own machine, your terminal app + needs permission under *System Settings → Privacy & Security → Local Network*. Without it, + macOS also returns an empty ARP cache. +- **ARP cache**: devices found only through the ARP cache ("via arp" in the details) may still + appear online for a few minutes after they leave, until the kernel drops the entry (macOS: up + to 20 minutes). +- **Linux without ICMP permission** (`net.ipv4.ping_group_range`): nscan falls back to UDP + packets to trigger ARP; ping times are missing then. +- Only scan networks you are allowed to scan. + +## Development + +```sh +go test ./... +``` diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..8fba452 --- /dev/null +++ b/build.sh @@ -0,0 +1,75 @@ +#!/bin/sh +# Build nscan for the usual platforms into ./bin, auto-incrementing the patch +# version by 0.0.1 on every build. +# +# version.txt holds the currently built version. Each run increments the patch +# component, then builds every platform with that one version injected via +# -ldflags, and writes it back. So version.txt always reflects the version of +# the binaries just built, and all of them carry the same one. The literal in +# version.go is only ever what a bare `go build` picks up. +# +# The files in ./bin are named nscan--; `mgsh release` attaches +# them to the release as they are. +# +# Override the platform list to build just one, or to add a platform: +# PLATFORMS="linux/amd64" ./build.sh +# PLATFORMS="windows/amd64" ./build.sh +# +# A plain run only ever steps the patch. A minor or major step is taken by +# naming the version outright, which is then written back like any other: +# VERSION=1.1.0 ./build.sh +# +# Windows is not in the default list: it compiles, but ICMP there needs +# administrator rights and nothing of it has been tested, so shipping it would +# promise more than nscan keeps. PLATFORMS can add it. +# +# -s -w drops the symbol table and DWARF info, -trimpath keeps build paths out +# of the binary; together they roughly halve it. Neither affects a panic trace. +set -e +cd "$(dirname "$0")" + +PLATFORMS=${PLATFORMS:-"darwin/arm64 darwin/amd64 linux/amd64 linux/arm64"} + +if [ -n "$VERSION" ]; then + NV="$VERSION" +else + V=$(cat version.txt 2>/dev/null || echo 1.0.0) + + # split MAJOR.MINOR.PATCH and increment PATCH (no carry: 1.0.9 -> 1.0.10) + MAJOR=${V%%.*} + REST=${V#*.} + MINOR=${REST%%.*} + PATCH=${REST#*.} + PATCH=$((PATCH + 1)) + NV="$MAJOR.$MINOR.$PATCH" +fi + +mkdir -p bin +HOST="$(go env GOOS)/$(go env GOARCH)" + +for p in $PLATFORMS; do + os=${p%/*} + arch=${p#*/} + ext="" + if [ "$os" = "windows" ]; then + ext=".exe" + fi + out="bin/nscan-$os-$arch$ext" + + # CGO_ENABLED=0 throughout: it makes the cross builds work without a + # toolchain per target and the binaries static. nscan talks to the network + # through its own sockets and reads the ARP table via sysctl or /proc, so + # nothing is lost by dropping cgo. + CGO_ENABLED=0 GOOS="$os" GOARCH="$arch" \ + go build -trimpath -ldflags "-s -w -X main.Version=$NV" -o "$out" . + + if [ "$p" = "$HOST" ]; then + ln -sf "nscan-$os-$arch$ext" bin/nscan # the one for this machine + echo " $out -> bin/nscan" + else + echo " $out" + fi +done + +echo "$NV" > version.txt +echo "built nscan v$NV" diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..de29cc6 --- /dev/null +++ b/go.mod @@ -0,0 +1,34 @@ +module nscan + +go 1.26.0 + +require ( + github.com/charmbracelet/bubbles v1.0.0 + github.com/charmbracelet/bubbletea v1.3.10 + github.com/charmbracelet/lipgloss v1.1.0 + github.com/charmbracelet/x/ansi v0.11.6 + github.com/mattn/go-runewidth v0.0.19 + golang.org/x/net v0.61.0 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/colorprofile v0.4.1 // indirect + github.com/charmbracelet/x/cellbuf v0.0.15 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.9.0 // indirect + github.com/clipperhouse/stringish v0.1.1 // indirect + github.com/clipperhouse/uax29/v2 v2.5.0 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/lucasb-eyer/go-colorful v1.3.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.16.0 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..1940e8a --- /dev/null +++ b/go.sum @@ -0,0 +1,54 @@ +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc= +github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E= +github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= +github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= +github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk= +github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk= +github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= +github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= +github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8= +github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ= +github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI= +github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA= +github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA= +github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs= +github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA= +github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U= +github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= +github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= +github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= +github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= +github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= diff --git a/internal/export/export.go b/internal/export/export.go new file mode 100644 index 0000000..7bc0438 --- /dev/null +++ b/internal/export/export.go @@ -0,0 +1,122 @@ +// Package export writes scan results as JSON or CSV. +package export + +import ( + "encoding/csv" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "nscan/internal/scanner" +) + +// Record is one device in an export. +type Record struct { + Name string `json:"name,omitempty"` + IP string `json:"ip"` + MAC string `json:"mac,omitempty"` + Vendor string `json:"vendor,omitempty"` + Model string `json:"model,omitempty"` + Online bool `json:"online"` + RTTms float64 `json:"rtt_ms,omitempty"` + MDNSName string `json:"mdns_name,omitempty"` + NetBIOSName string `json:"netbios_name,omitempty"` + DNSName string `json:"dns_name,omitempty"` + Services []scanner.Service `json:"services,omitempty"` + OpenPorts []scanner.PortResult `json:"open_ports,omitempty"` + Tracked bool `json:"tracked,omitempty"` + Whitelisted bool `json:"whitelisted,omitempty"` + FirstSeen time.Time `json:"first_seen,omitzero"` + LastSeen time.Time `json:"last_seen,omitzero"` +} + +// FromHost fills the scan-derived fields of a record. +func FromHost(h scanner.Host) Record { + r := Record{ + Name: h.Name(), + IP: h.IP.String(), + Vendor: h.Maker(), + Model: h.Model, + MDNSName: h.MDNSName, + NetBIOSName: h.NetBIOSName, + DNSName: h.DNSName, + Services: h.Services, + } + if len(h.MAC) > 0 { + r.MAC = h.MAC.String() + } + if h.RTT > 0 { + r.RTTms = float64(h.RTT.Microseconds()) / 1000 + } + return r +} + +// WriteJSON writes the records as an indented JSON array. +func WriteJSON(w io.Writer, recs []Record) error { + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(recs) +} + +// WriteCSV writes one row per record. +func WriteCSV(w io.Writer, recs []Record) error { + cw := csv.NewWriter(w) + cw.Write([]string{"name", "ip", "mac", "vendor", "model", "online", "rtt_ms", "mdns_name", + "netbios_name", "dns_name", "services", "open_ports", "tracked", "whitelisted", "first_seen", "last_seen"}) + for _, r := range recs { + var svcs, ports []string + for _, s := range r.Services { + svcs = append(svcs, fmt.Sprintf("%s:%d", s.Short(), s.Port)) + } + for _, p := range r.OpenPorts { + ports = append(ports, strconv.Itoa(p.Port)) + } + rtt := "" + if r.RTTms > 0 { + rtt = strconv.FormatFloat(r.RTTms, 'f', 2, 64) + } + cw.Write([]string{r.Name, r.IP, r.MAC, r.Vendor, r.Model, strconv.FormatBool(r.Online), rtt, r.MDNSName, + r.NetBIOSName, r.DNSName, strings.Join(svcs, " "), strings.Join(ports, " "), + strconv.FormatBool(r.Tracked), strconv.FormatBool(r.Whitelisted), timeOrEmpty(r.FirstSeen), timeOrEmpty(r.LastSeen)}) + } + cw.Flush() + return cw.Error() +} + +func timeOrEmpty(t time.Time) string { + if t.IsZero() { + return "" + } + return t.Format(time.RFC3339) +} + +// Files writes the records as /nscan-.json and .csv and +// returns both paths. +func Files(dir string, recs []Record, now time.Time) ([]string, error) { + base := filepath.Join(dir, "nscan-"+now.Format("20060102-150405")) + var paths []string + for _, f := range []struct { + ext string + write func(io.Writer, []Record) error + }{{".json", WriteJSON}, {".csv", WriteCSV}} { + path := base + f.ext + file, err := os.Create(path) + if err != nil { + return paths, err + } + err = f.write(file, recs) + if cerr := file.Close(); err == nil { + err = cerr + } + if err != nil { + return paths, err + } + paths = append(paths, path) + } + return paths, nil +} diff --git a/internal/oui/oui.go b/internal/oui/oui.go new file mode 100644 index 0000000..e848b33 --- /dev/null +++ b/internal/oui/oui.go @@ -0,0 +1,202 @@ +// Package oui maps MAC address prefixes to hardware vendors using the IEEE +// MA-L registry, which nscan keeps as a compact TSV file. +package oui + +import ( + "bufio" + "bytes" + "context" + "encoding/csv" + "encoding/hex" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" +) + +// SourceURL is the IEEE registry nscan downloads. +const SourceURL = "https://standards-oui.ieee.org/oui/oui.csv" + +// Private is reported for locally administered (randomized) MAC addresses, +// which phones and laptops use per Wi-Fi network. +const Private = "Private address" + +// DB maps 24-bit OUI prefixes to vendor names. A nil *DB is valid and only +// recognizes private addresses. +type DB struct { + m map[[3]byte]string +} + +// Lookup returns the vendor of mac or "" if unknown. +func (db *DB) Lookup(mac net.HardwareAddr) string { + if len(mac) < 3 { + return "" + } + if mac[0]&0x02 != 0 { + return Private + } + if db == nil { + return "" + } + return db.m[[3]byte{mac[0], mac[1], mac[2]}] +} + +// Len returns the number of known prefixes. +func (db *DB) Len() int { + if db == nil { + return 0 + } + return len(db.m) +} + +// Load reads a TSV file written by Install. +func Load(path string) (*DB, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + db := &DB{m: make(map[[3]byte]string, 40000)} + sc := bufio.NewScanner(f) + for sc.Scan() { + prefix, name, ok := strings.Cut(sc.Text(), "\t") + if k, valid := parsePrefix(prefix); ok && valid { + db.m[k] = name + } + } + return db, sc.Err() +} + +// Parse reads the IEEE registry in its CSV (oui.csv) or text (oui.txt) form. +func Parse(r io.Reader) (*DB, error) { + data, err := io.ReadAll(r) + if err != nil { + return nil, err + } + data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")) + db := &DB{m: make(map[[3]byte]string, 40000)} + if bytes.HasPrefix(data, []byte("Registry,")) { + cr := csv.NewReader(bytes.NewReader(data)) + cr.FieldsPerRecord = -1 + cr.LazyQuotes = true + for { + rec, err := cr.Read() + if err == io.EOF { + break + } + if err != nil { + return nil, err + } + if len(rec) < 3 { + continue + } + if k, ok := parsePrefix(rec[1]); ok { + db.m[k] = ShortName(rec[2]) + } + } + } else { + for _, m := range txtLine.FindAllSubmatch(data, -1) { + if k, ok := parsePrefix(string(m[1]) + string(m[2]) + string(m[3])); ok { + db.m[k] = ShortName(string(m[4])) + } + } + } + if len(db.m) == 0 { + return nil, errors.New("no OUI entries found – is this the IEEE oui.csv or oui.txt?") + } + return db, nil +} + +var txtLine = regexp.MustCompile(`(?m)^([0-9A-Fa-f]{2})-([0-9A-Fa-f]{2})-([0-9A-Fa-f]{2})\s+\(hex\)\s+(.+?)\s*$`) + +func parsePrefix(s string) ([3]byte, bool) { + var k [3]byte + b, err := hex.DecodeString(strings.TrimSpace(s)) + if err != nil || len(b) != 3 { + return k, false + } + copy(k[:], b) + return k, true +} + +// Install parses the registry from r and stores it at path. +func Install(r io.Reader, path string) (int, error) { + db, err := Parse(r) + if err != nil { + return 0, err + } + keys := make([][3]byte, 0, len(db.m)) + for k := range db.m { + keys = append(keys, k) + } + sort.Slice(keys, func(i, j int) bool { return bytes.Compare(keys[i][:], keys[j][:]) < 0 }) + var buf bytes.Buffer + for _, k := range keys { + fmt.Fprintf(&buf, "%X\t%s\n", k[:], db.m[k]) + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return 0, err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, buf.Bytes(), 0o644); err != nil { + return 0, err + } + return len(keys), os.Rename(tmp, path) +} + +// Download fetches the registry from the IEEE and installs it at path. +func Download(ctx context.Context, path string) (int, error) { + ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, SourceURL, nil) + if err != nil { + return 0, err + } + req.Header.Set("User-Agent", "nscan/1.0 (OUI vendor lookup)") + resp, err := http.DefaultClient.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return 0, fmt.Errorf("IEEE server responded with %s", resp.Status) + } + return Install(resp.Body, path) +} + +var legalSuffixes = []string{ + "inc", "inc.", "incorporated", "corp", "corp.", "corporation", "co", "co.", + "co.,ltd", "co.,ltd.", "co. ltd", "co. ltd.", "co., ltd", "co., ltd.", + "ltd", "ltd.", "limited", "llc", "l.l.c.", "gmbh", "gmbh & co. kg", "ag", + "se", "s.a.", "sa", "s.p.a.", "b.v.", "bv", "n.v.", "plc", "pty ltd", + "pty. ltd.", "oy", "ab", "as", "a/s", "kg", "sas", "s.r.l.", "srl", +} + +// ShortName strips legal-form suffixes ("Apple, Inc." → "Apple"). +func ShortName(name string) string { + name = strings.Join(strings.Fields(name), " ") + for changed := true; changed; { + changed = false + name = strings.TrimRight(name, " ,.") + lower := strings.ToLower(name) + for _, suf := range legalSuffixes { + suf = " " + strings.TrimSuffix(suf, ".") + if strings.HasSuffix(lower, suf) && len(name) > len(suf) { + name = name[:len(name)-len(suf)] + changed = true + break + } + } + } + if strings.HasPrefix(name, "AVM Audiovisuelles") { + return "AVM" + } + return name +} diff --git a/internal/oui/oui_test.go b/internal/oui/oui_test.go new file mode 100644 index 0000000..f8d11b5 --- /dev/null +++ b/internal/oui/oui_test.go @@ -0,0 +1,87 @@ +package oui + +import ( + "net" + "path/filepath" + "strings" + "testing" +) + +const sampleCSV = `Registry,Assignment,Organization Name,Organization Address +MA-L,3CA62F,AVM Audiovisuelles Marketing und Computersysteme GmbH,Alt-Moabit 95 Berlin DE 10559 +MA-L,F0189B,"Apple, Inc.",1 Infinite Loop Cupertino CA US 95014 +MA-L,B827EB,Raspberry Pi Foundation,Mitchell Wood House Caldecote GB CB23 7NU +` + +const sampleTXT = `OUI/MA-L Organization +company_id Organization + Address + +50-C7-BF (hex) TP-LINK TECHNOLOGIES CO.,LTD. +50C7BF (base 16) TP-LINK TECHNOLOGIES CO.,LTD. + Building 24 (floors 1,3,4,5) and 28 (floors1-4) +` + +func TestParseAndLookup(t *testing.T) { + db, err := Parse(strings.NewReader(sampleCSV)) + if err != nil { + t.Fatal(err) + } + for mac, want := range map[string]string{ + "3c:a6:2f:01:02:03": "AVM", + "f0:18:9b:aa:bb:cc": "Apple", + "b8:27:eb:00:00:01": "Raspberry Pi Foundation", + "00:00:00:00:00:01": "", + "da:a1:19:00:00:01": Private, + } { + hw, _ := net.ParseMAC(mac) + if got := db.Lookup(hw); got != want { + t.Errorf("Lookup(%s) = %q, want %q", mac, got, want) + } + } + + db, err = Parse(strings.NewReader(sampleTXT)) + if err != nil { + t.Fatal(err) + } + hw, _ := net.ParseMAC("50:c7:bf:11:22:33") + if got := db.Lookup(hw); got != "TP-LINK TECHNOLOGIES" { + t.Errorf("txt Lookup = %q", got) + } +} + +func TestInstallLoad(t *testing.T) { + path := filepath.Join(t.TempDir(), "oui.tsv") + n, err := Install(strings.NewReader(sampleCSV), path) + if err != nil || n != 3 { + t.Fatalf("Install = %d, %v", n, err) + } + db, err := Load(path) + if err != nil || db.Len() != 3 { + t.Fatalf("Load = %d, %v", db.Len(), err) + } + if _, err := Parse(strings.NewReader("blocked")); err == nil { + t.Error("Parse accepted garbage") + } +} + +func TestShortName(t *testing.T) { + for in, want := range map[string]string{ + "Apple, Inc.": "Apple", + "Samsung Electronics Co.,Ltd": "Samsung Electronics", + "Sonos, Inc.": "Sonos", + "Espressif Inc.": "Espressif", + "Synology Incorporated": "Synology", + "Hewlett Packard Enterprise, LLC.": "Hewlett Packard Enterprise", + "Ubiquiti Inc": "Ubiquiti", + " Intel Corporate ": "Intel Corporate", + } { + if got := ShortName(in); got != want { + t.Errorf("ShortName(%q) = %q, want %q", in, got, want) + } + } + var nilDB *DB + if nilDB.Lookup(net.HardwareAddr{0, 1, 2, 3, 4, 5}) != "" || nilDB.Len() != 0 { + t.Error("nil DB misbehaves") + } +} diff --git a/internal/scanner/arp_exec.go b/internal/scanner/arp_exec.go new file mode 100644 index 0000000..5a30760 --- /dev/null +++ b/internal/scanner/arp_exec.go @@ -0,0 +1,39 @@ +package scanner + +import ( + "net" + "net/netip" + "os/exec" + "regexp" + "runtime" +) + +var arpLine = regexp.MustCompile(`(\d+\.\d+\.\d+\.\d+)\D+?((?:[0-9a-fA-F]{1,2}[:-]){5}[0-9a-fA-F]{1,2})`) + +// readARPExec parses the output of arp(8), which looks similar enough on +// macOS, the BSDs and Windows. +func readARPExec() (map[netip.Addr]net.HardwareAddr, error) { + args := []string{"-an"} + if runtime.GOOS == "windows" { + args = []string{"-a"} + } + out, err := exec.Command("arp", args...).Output() + if err != nil { + return nil, err + } + return parseARPOutput(string(out)), nil +} + +func parseARPOutput(out string) map[netip.Addr]net.HardwareAddr { + table := make(map[netip.Addr]net.HardwareAddr) + for _, m := range arpLine.FindAllStringSubmatch(out, -1) { + ip, err := netip.ParseAddr(m[1]) + if err != nil { + continue + } + if mac, ok := parseLooseMAC(m[2]); ok { + table[ip] = mac + } + } + return table +} diff --git a/internal/scanner/bonjour.go b/internal/scanner/bonjour.go new file mode 100644 index 0000000..182bdaf --- /dev/null +++ b/internal/scanner/bonjour.go @@ -0,0 +1,195 @@ +package scanner + +import ( + "context" + "net" + "net/netip" + "sort" + "strings" + "time" + + "golang.org/x/net/dns/dnsmessage" + "golang.org/x/net/ipv4" +) + +// Service is a Bonjour (DNS-SD) service announced by a device. +type Service struct { + Type string `json:"type"` // e.g. "_airplay._tcp" + Instance string `json:"instance"` + Port uint16 `json:"port"` +} + +// Short returns the service type without underscores and protocol ("airplay"). +func (s Service) Short() string { + t, _, _ := strings.Cut(s.Type, ".") + return strings.TrimPrefix(t, "_") +} + +type bonjourResult struct { + services map[netip.Addr][]Service + hostnames map[netip.Addr]string +} + +type bonjourInstance struct { + name, typ string + target string + port uint16 + src netip.Addr + askedSRV bool +} + +var mdnsGroup = &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251), Port: 5353} + +// browseBonjour enumerates all DNS-SD service types on the link, then their +// instances, and resolves each to an address. Queries are sent from an +// ephemeral port, so responders answer by unicast (RFC 6762, 6.7) and we do +// not compete with the system's mDNS daemon for port 5353. +func browseBonjour(ctx context.Context, iface *net.Interface, wait time.Duration) bonjourResult { + res := bonjourResult{services: map[netip.Addr][]Service{}, hostnames: map[netip.Addr]string{}} + conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero}) + if err != nil { + return res + } + defer conn.Close() + context.AfterFunc(ctx, func() { conn.Close() }) + pc := ipv4.NewPacketConn(conn) + if iface != nil { + pc.SetMulticastInterface(iface) + } + pc.SetMulticastTTL(255) + + send := func(name string, t dnsmessage.Type) { + q, err := question(name, t) + if err != nil { + return + } + if b, err := buildQuery(0, q); err == nil { + pc.WriteTo(b, nil, mdnsGroup) + } + } + + const metaQuery = "_services._dns-sd._udp.local." + types := map[string]bool{} + instances := map[string]*bonjourInstance{} + addrs := map[string]netip.Addr{} + askedA := map[string]bool{} + instance := func(name string) *bonjourInstance { + key := strings.ToLower(name) + in := instances[key] + if in == nil { + in = &bonjourInstance{name: name, typ: serviceTypeOf(name)} + instances[key] = in + } + return in + } + + send(metaQuery, dnsmessage.TypePTR) + deadline := time.Now().Add(wait) + lastFollowUp := time.Now() + buf := make([]byte, 9000) + for time.Now().Before(deadline) && ctx.Err() == nil { + conn.SetReadDeadline(minTime(deadline, time.Now().Add(250*time.Millisecond))) + if n, src, err := conn.ReadFromUDPAddrPort(buf); err == nil { + for _, rr := range parseRecords(buf[:n]) { + name := rr.Header.Name.String() + switch body := rr.Body.(type) { + case *dnsmessage.PTRResource: + target := body.PTR.String() + if strings.EqualFold(name, metaQuery) { + if t := strings.ToLower(target); !types[t] { + types[t] = true + send(target, dnsmessage.TypePTR) + } + } else if strings.HasPrefix(name, "_") { + in := instance(target) + if !in.src.IsValid() { + in.src = src.Addr().Unmap() + } + } + case *dnsmessage.SRVResource: + in := instance(name) + in.target, in.port = body.Target.String(), body.Port + in.src = src.Addr().Unmap() + case *dnsmessage.AResource: + addrs[strings.ToLower(name)] = netip.AddrFrom4(body.A) + } + } + } + // Ask for whatever the responders did not include on their own. + if time.Since(lastFollowUp) > 300*time.Millisecond { + lastFollowUp = time.Now() + for _, in := range instances { + switch { + case in.target == "" && !in.askedSRV: + in.askedSRV = true + send(in.name, dnsmessage.TypeSRV) + case in.target != "": + t := strings.ToLower(in.target) + if _, ok := addrs[t]; !ok && !askedA[t] { + askedA[t] = true + send(in.target, dnsmessage.TypeA) + } + } + } + } + } + + for _, in := range instances { + if in.target == "" { + continue + } + ip, ok := addrs[strings.ToLower(in.target)] + if !ok { + ip = in.src + } + if !ip.Is4() { + continue + } + res.services[ip] = append(res.services[ip], Service{ + Type: strings.TrimSuffix(in.typ, ".local."), + Instance: instanceLabel(in.name, in.typ), + Port: in.port, + }) + if res.hostnames[ip] == "" { + res.hostnames[ip] = cleanHostname(in.target) + } + } + for host, ip := range addrs { + if res.hostnames[ip] == "" { + res.hostnames[ip] = cleanHostname(host) + } + } + for _, svcs := range res.services { + sort.Slice(svcs, func(i, j int) bool { + if svcs[i].Type != svcs[j].Type { + return svcs[i].Type < svcs[j].Type + } + return svcs[i].Instance < svcs[j].Instance + }) + } + return res +} + +// serviceTypeOf derives "_airplay._tcp.local." from an instance name such as +// "Living Room._airplay._tcp.local.". +func serviceTypeOf(instance string) string { + labels := strings.Split(strings.TrimSuffix(instance, "."), ".") + if len(labels) < 3 { + return instance + } + return strings.Join(labels[len(labels)-3:], ".") + "." +} + +func instanceLabel(instance, typ string) string { + if len(instance) > len(typ) && strings.EqualFold(instance[len(instance)-len(typ):], typ) { + return strings.TrimSuffix(instance[:len(instance)-len(typ)], ".") + } + return instance +} + +func minTime(a, b time.Time) time.Time { + if a.Before(b) { + return a + } + return b +} diff --git a/internal/scanner/devinfo.go b/internal/scanner/devinfo.go new file mode 100644 index 0000000..98e6bb0 --- /dev/null +++ b/internal/scanner/devinfo.go @@ -0,0 +1,102 @@ +package scanner + +import ( + "context" + "math/rand/v2" + "net" + "net/netip" + "regexp" + "strings" + "time" + + "golang.org/x/net/dns/dnsmessage" +) + +// appleModel matches the model identifiers Apple devices announce, such as +// "MacBookAir10,1", "Mac16,10", "iPhone15,3" or "AudioAccessory5,1" (HomePod). +var appleModel = regexp.MustCompile(`^(Mac|MacBook|MacBookAir|MacBookPro|Macmini|MacPro|iMac|iMacPro|iPhone|iPad|iPod|AppleTV|AudioAccessory|Watch|RealityDevice|AirPort)\d+,\d+$`) + +// PrivateMAC reports whether mac is locally administered, as the randomized +// addresses phones and laptops use per network are. Such addresses carry no +// vendor. +func PrivateMAC(mac net.HardwareAddr) bool { return len(mac) > 0 && mac[0]&0x02 != 0 } + +// Maker returns who made the device: the vendor registered for its MAC +// address or, for private addresses, the maker implied by the announced model. +func (h *Host) Maker() string { + if h.Model != "" && (h.Vendor == "" || PrivateMAC(h.MAC)) && appleModel.MatchString(h.Model) { + return "Apple" + } + return h.Vendor +} + +// VendorLabel is the maker followed by the model, e.g. "Apple Mac16,10". +func (h *Host) VendorLabel() string { + maker := h.Maker() + switch { + case h.Model == "": + return maker + case maker == "" || PrivateMAC(h.MAC) && maker == h.Vendor: + return h.Model + } + return maker + " " + h.Model +} + +// deviceModels asks hosts for their "._device-info._tcp.local." TXT +// record, in which Apple devices announce their model identifier. Each host +// is asked under all names it may use: its host name and its service names. +func deviceModels(ctx context.Context, names map[netip.Addr][]string, timeout time.Duration) map[netip.Addr]string { + conn, err := net.ListenUDP("udp4", nil) + if err != nil { + return nil + } + defer conn.Close() + context.AfterFunc(ctx, func() { conn.Close() }) + + asked := map[string]netip.Addr{} + for ip, ns := range names { + for _, n := range ns { + fq := n + "._device-info._tcp.local." + q, err := question(fq, dnsmessage.TypeTXT) + if err != nil { + continue + } + if b, err := buildQuery(uint16(rand.N(0xffff)+1), q); err == nil { + asked[strings.ToLower(fq)] = ip + conn.WriteToUDPAddrPort(b, netip.AddrPortFrom(ip, 5353)) + } + } + } + res := make(map[netip.Addr]string) + conn.SetReadDeadline(time.Now().Add(timeout)) + buf := make([]byte, 9000) + for len(res) < len(names) { + n, _, err := conn.ReadFromUDPAddrPort(buf) + if err != nil { + break + } + for _, rr := range parseRecords(buf[:n]) { + txt, ok := rr.Body.(*dnsmessage.TXTResource) + if !ok { + continue + } + ip, ok := asked[strings.ToLower(rr.Header.Name.String())] + if !ok { + continue + } + if model := txtValue(txt.TXT, "model"); model != "" { + res[ip] = model + } + } + } + return res +} + +func txtValue(txt []string, key string) string { + for _, kv := range txt { + if v, ok := strings.CutPrefix(kv, key+"="); ok { + return v + } + } + return "" +} diff --git a/internal/scanner/dns.go b/internal/scanner/dns.go new file mode 100644 index 0000000..f050a8f --- /dev/null +++ b/internal/scanner/dns.go @@ -0,0 +1,97 @@ +package scanner + +import ( + "fmt" + "net/netip" + "strings" + + "golang.org/x/net/dns/dnsmessage" +) + +func buildQuery(id uint16, qs ...dnsmessage.Question) ([]byte, error) { + b := dnsmessage.NewBuilder(make([]byte, 0, 512), dnsmessage.Header{ID: id}) + b.EnableCompression() + if err := b.StartQuestions(); err != nil { + return nil, err + } + for _, q := range qs { + if err := b.Question(q); err != nil { + return nil, err + } + } + return b.Finish() +} + +func question(name string, t dnsmessage.Type) (dnsmessage.Question, error) { + n, err := dnsmessage.NewName(name) + if err != nil { + return dnsmessage.Question{}, err + } + return dnsmessage.Question{Name: n, Type: t, Class: dnsmessage.ClassINET}, nil +} + +// parseRecords returns the answer and additional records of a DNS response. +// Parsing stops quietly at the first malformed record. +func parseRecords(b []byte) []dnsmessage.Resource { + var p dnsmessage.Parser + h, err := p.Start(b) + if err != nil || !h.Response { + return nil + } + if err := p.SkipAllQuestions(); err != nil { + return nil + } + var out []dnsmessage.Resource + for { + r, err := p.Answer() + if err != nil { + break + } + out = append(out, r) + } + if err := p.SkipAllAuthorities(); err != nil { + return out + } + for { + r, err := p.Additional() + if err != nil { + break + } + out = append(out, r) + } + return out +} + +// reverseName returns the in-addr.arpa name used for PTR lookups of ip. +func reverseName(ip netip.Addr) string { + b := ip.As4() + return fmt.Sprintf("%d.%d.%d.%d.in-addr.arpa.", b[3], b[2], b[1], b[0]) +} + +func parseReverseName(name string) (netip.Addr, bool) { + rest, ok := strings.CutSuffix(strings.ToLower(name), ".in-addr.arpa.") + if !ok { + return netip.Addr{}, false + } + parts := strings.Split(rest, ".") + if len(parts) != 4 { + return netip.Addr{}, false + } + ip, err := netip.ParseAddr(parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0]) + return ip, err == nil +} + +// localSuffixes are domains that add no information in a LAN listing. +var localSuffixes = []string{".local", ".lan", ".home", ".home.arpa", ".localdomain", ".fritz.box", ".internal"} + +// cleanHostname trims the trailing dot and well-known local domains. +func cleanHostname(s string) string { + s = strings.TrimSuffix(s, ".") + lower := strings.ToLower(s) + for _, suf := range localSuffixes { + if strings.HasSuffix(lower, suf) && len(s) > len(suf) { + return s[:len(s)-len(suf)] + } + } + return s +} diff --git a/internal/scanner/icmp.go b/internal/scanner/icmp.go new file mode 100644 index 0000000..1446366 --- /dev/null +++ b/internal/scanner/icmp.go @@ -0,0 +1,238 @@ +package scanner + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "net" + "net/netip" + "os" + "syscall" + "time" + + "golang.org/x/net/icmp" + "golang.org/x/net/ipv4" +) + +// icmpToken marks our echo requests so replies to other ping processes on the +// same machine are ignored. +var icmpToken = []byte("nscan\x00\x4e\x53") + +type icmpSocket struct { + conn *icmp.PacketConn + privileged bool +} + +// openICMP prefers unprivileged ICMP sockets (macOS, most Linux distros) and +// falls back to raw sockets, which need root. +func openICMP() (*icmpSocket, error) { + if c, err := icmp.ListenPacket("udp4", "0.0.0.0"); err == nil { + return &icmpSocket{conn: c}, nil + } + c, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0") + if err != nil { + return nil, err + } + return &icmpSocket{conn: c, privileged: true}, nil +} + +func (s *icmpSocket) Close() error { return s.conn.Close() } + +func (s *icmpSocket) sendEcho(dst netip.Addr, id, seq int) error { + data := make([]byte, 16) + copy(data, icmpToken) + binary.BigEndian.PutUint64(data[8:], uint64(time.Now().UnixNano())) + msg := icmp.Message{ + Type: ipv4.ICMPTypeEcho, + Body: &icmp.Echo{ID: id, Seq: seq, Data: data}, + } + b, err := msg.Marshal(nil) + if err != nil { + return err + } + var to net.Addr = &net.UDPAddr{IP: dst.AsSlice()} + if s.privileged { + to = &net.IPAddr{IP: dst.AsSlice()} + } + _, err = s.conn.WriteTo(b, to) + return err +} + +type echoReply struct { + From netip.Addr + Seq int + RTT time.Duration +} + +// readEcho blocks until one of our echo replies arrives or reading fails. +func (s *icmpSocket) readEcho(buf []byte) (echoReply, error) { + for { + n, peer, err := s.conn.ReadFrom(buf) + if err != nil { + return echoReply{}, err + } + m, err := icmp.ParseMessage(1, buf[:n]) + if err != nil || m.Type != ipv4.ICMPTypeEchoReply { + continue + } + e, ok := m.Body.(*icmp.Echo) + if !ok || len(e.Data) < 16 || !bytes.Equal(e.Data[:8], icmpToken) { + continue + } + sent := time.Unix(0, int64(binary.BigEndian.Uint64(e.Data[8:16]))) + return echoReply{From: addrOf(peer), Seq: e.Seq, RTT: time.Since(sent)}, nil + } +} + +func addrOf(a net.Addr) netip.Addr { + var ip net.IP + switch a := a.(type) { + case *net.UDPAddr: + ip = a.IP + case *net.IPAddr: + ip = a.IP + } + addr, _ := netip.AddrFromSlice(ip) + return addr.Unmap() +} + +// PingResult is the outcome of a single echo request. +type PingResult struct { + Seq int + RTT time.Duration + Timeout bool + Err error + Method string +} + +// Ping sends count echo requests (0 = until ctx is cancelled) and reports each +// result. Without ICMP permission it falls back to timing TCP connects. +func Ping(ctx context.Context, dst netip.Addr, count int, interval, timeout time.Duration, onResult func(PingResult)) error { + sock, err := openICMP() + if err != nil { + return tcpPing(ctx, dst, count, interval, timeout, onResult) + } + defer sock.Close() + context.AfterFunc(ctx, func() { sock.Close() }) + + replies := make(chan echoReply, 16) + go func() { + buf := make([]byte, 1500) + for { + r, err := sock.readEcho(buf) + if err != nil { + return + } + if r.From == dst { + select { + case replies <- r: + default: + } + } + } + }() + + id := os.Getpid() & 0xffff + for seq := 1; count == 0 || seq <= count; seq++ { + start := time.Now() + res := PingResult{Seq: seq, Method: "ICMP"} + if err := sock.sendEcho(dst, id, seq); err != nil { + if ctx.Err() != nil { + return nil + } + res.Err = err + } else { + res.Timeout = true + timer := time.NewTimer(timeout) + wait: + for { + select { + case r := <-replies: + if r.Seq == seq { + res.Timeout, res.RTT = false, r.RTT + break wait + } + case <-timer.C: + break wait + case <-ctx.Done(): + timer.Stop() + return nil + } + } + timer.Stop() + } + onResult(res) + if count != 0 && seq == count { + break + } + if !sleepCtx(ctx, interval-time.Since(start)) { + return nil + } + } + return nil +} + +func tcpPing(ctx context.Context, dst netip.Addr, count int, interval, timeout time.Duration, onResult func(PingResult)) error { + for seq := 1; count == 0 || seq <= count; seq++ { + start := time.Now() + rtt, ok := tcpAlive(ctx, dst, probePorts, timeout) + if ctx.Err() != nil { + return nil + } + onResult(PingResult{Seq: seq, RTT: rtt, Timeout: !ok, Method: "TCP"}) + if count != 0 && seq == count { + break + } + if !sleepCtx(ctx, interval-time.Since(start)) { + return nil + } + } + return nil +} + +// probePorts are tried when ICMP is unavailable or blocked. A refused +// connection proves the host is up just as well as an accepted one. +var probePorts = []int{80, 443, 22, 445, 139, 62078} + +func tcpAlive(ctx context.Context, ip netip.Addr, ports []int, timeout time.Duration) (time.Duration, bool) { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + type result struct { + rtt time.Duration + ok bool + } + ch := make(chan result, len(ports)) + start := time.Now() + for _, p := range ports { + go func(p int) { + var d net.Dialer + c, err := d.DialContext(ctx, "tcp4", netip.AddrPortFrom(ip, uint16(p)).String()) + if err == nil { + c.Close() + } + ch <- result{time.Since(start), err == nil || errors.Is(err, syscall.ECONNREFUSED)} + }(p) + } + for range ports { + if r := <-ch; r.ok { + return r.rtt, true + } + } + return 0, false +} + +// sleepCtx waits for d and reports false if ctx was cancelled meanwhile. +func sleepCtx(ctx context.Context, d time.Duration) bool { + if d <= 0 { + return ctx.Err() == nil + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-t.C: + return true + case <-ctx.Done(): + return false + } +} diff --git a/internal/scanner/names.go b/internal/scanner/names.go new file mode 100644 index 0000000..472ce68 --- /dev/null +++ b/internal/scanner/names.go @@ -0,0 +1,180 @@ +package scanner + +import ( + "context" + "encoding/binary" + "math/rand/v2" + "net" + "net/netip" + "os" + "strings" + "sync" + "time" + + "golang.org/x/net/dns/dnsmessage" +) + +// reverseDNS looks up PTR records via the system resolver. +func reverseDNS(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string { + var mu sync.Mutex + res := make(map[netip.Addr]string) + sem := make(chan struct{}, 32) + var wg sync.WaitGroup + for _, ip := range ips { + sem <- struct{}{} + wg.Add(1) + go func(ip netip.Addr) { + defer func() { <-sem; wg.Done() }() + lctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + names, err := net.DefaultResolver.LookupAddr(lctx, ip.String()) + if err != nil || len(names) == 0 { + return + } + mu.Lock() + res[ip] = cleanHostname(names[0]) + mu.Unlock() + }(ip) + } + wg.Wait() + return res +} + +// mdnsReverse asks every host directly (unicast to port 5353) for its own +// name. Apple devices and Linux machines running Avahi answer these queries. +func mdnsReverse(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string { + conn, err := net.ListenUDP("udp4", nil) + if err != nil { + return nil + } + defer conn.Close() + context.AfterFunc(ctx, func() { conn.Close() }) + + for _, ip := range ips { + q, err := question(reverseName(ip), dnsmessage.TypePTR) + if err != nil { + continue + } + if b, err := buildQuery(uint16(rand.N(0xffff)+1), q); err == nil { + conn.WriteToUDPAddrPort(b, netip.AddrPortFrom(ip, 5353)) + } + } + res := make(map[netip.Addr]string) + conn.SetReadDeadline(time.Now().Add(timeout)) + buf := make([]byte, 9000) + for len(res) < len(ips) { + n, from, err := conn.ReadFromUDPAddrPort(buf) + if err != nil { + break + } + for _, rr := range parseRecords(buf[:n]) { + ptr, ok := rr.Body.(*dnsmessage.PTRResource) + if !ok { + continue + } + ip, ok := parseReverseName(rr.Header.Name.String()) + if !ok { + ip = from.Addr().Unmap() + } + res[ip] = cleanHostname(ptr.PTR.String()) + } + } + return res +} + +// netbiosNames sends NetBIOS node status requests (UDP 137), which Windows +// machines and Samba servers answer with their computer name. +func netbiosNames(ctx context.Context, ips []netip.Addr, timeout time.Duration) map[netip.Addr]string { + conn, err := net.ListenUDP("udp4", nil) + if err != nil { + return nil + } + defer conn.Close() + context.AfterFunc(ctx, func() { conn.Close() }) + + for _, ip := range ips { + conn.WriteToUDPAddrPort(nbstatRequest(uint16(rand.N(0xffff))), netip.AddrPortFrom(ip, 137)) + } + res := make(map[netip.Addr]string) + conn.SetReadDeadline(time.Now().Add(timeout)) + buf := make([]byte, 1500) + for len(res) < len(ips) { + n, from, err := conn.ReadFromUDPAddrPort(buf) + if err != nil { + break + } + if name, ok := parseNBStat(buf[:n]); ok { + res[from.Addr().Unmap()] = name + } + } + return res +} + +func nbstatRequest(id uint16) []byte { + b := []byte{byte(id >> 8), byte(id), 0, 0, 0, 1, 0, 0, 0, 0, 0, 0} + // The wildcard name "*" padded to 16 bytes, first-level encoded. + b = append(b, 0x20) + name := [16]byte{'*'} + for _, c := range name { + b = append(b, 'A'+c>>4, 'A'+c&0x0f) + } + return append(b, 0, 0x00, 0x21, 0x00, 0x01) // NBSTAT, IN +} + +// parseNBStat extracts the unique workstation name from a node status response. +func parseNBStat(b []byte) (string, bool) { + if len(b) < 12 || b[2]&0x80 == 0 { + return "", false + } + qd := int(binary.BigEndian.Uint16(b[4:6])) + an := int(binary.BigEndian.Uint16(b[6:8])) + off := 12 + for range qd { + off = skipDNSName(b, off) + 4 + } + if an == 0 { + return "", false + } + off = skipDNSName(b, off) + if off+10 > len(b) || binary.BigEndian.Uint16(b[off:]) != 0x21 { + return "", false + } + off += 10 + if off >= len(b) { + return "", false + } + num := int(b[off]) + off++ + for i := 0; i < num && off+18 <= len(b); i++ { + name := strings.TrimRight(string(b[off:off+15]), " \x00") + suffix := b[off+15] + group := binary.BigEndian.Uint16(b[off+16:])&0x8000 != 0 + off += 18 + if suffix == 0x00 && !group && name != "" { + return name, true + } + } + return "", false +} + +func skipDNSName(b []byte, off int) int { + for off < len(b) { + l := int(b[off]) + switch { + case l == 0: + return off + 1 + case l&0xc0 == 0xc0: + return off + 2 + } + off += 1 + l + } + return len(b) +} + +func localHostname() string { + h, err := os.Hostname() + if err != nil { + return "" + } + return cleanHostname(h) +} diff --git a/internal/scanner/network.go b/internal/scanner/network.go new file mode 100644 index 0000000..97e9f33 --- /dev/null +++ b/internal/scanner/network.go @@ -0,0 +1,258 @@ +package scanner + +import ( + "encoding/binary" + "errors" + "fmt" + "net" + "net/netip" + "sort" + "strconv" + "strings" +) + +// maxTargets limits how many addresses a single scan may cover. +const maxTargets = 65536 + +// Network describes the local network segment a scan runs on. +type Network struct { + Iface *net.Interface + LocalIP netip.Addr + LocalMAC net.HardwareAddr + Prefix netip.Prefix + Gateway netip.Addr +} + +// OnLink reports whether ip is on the local segment, i.e. reachable via ARP. +func (n *Network) OnLink(ip netip.Addr) bool { + return n.Prefix.IsValid() && n.Prefix.Contains(ip) +} + +// Broadcast returns the directed broadcast address of the network. +func (n *Network) Broadcast() netip.Addr { + if !n.Prefix.IsValid() || !n.Prefix.Addr().Is4() || n.Prefix.Bits() >= 31 { + return netip.AddrFrom4([4]byte{255, 255, 255, 255}) + } + a := n.Prefix.Masked().Addr().As4() + v := binary.BigEndian.Uint32(a[:]) | ^uint32(0)>>n.Prefix.Bits() + binary.BigEndian.PutUint32(a[:], v) + return netip.AddrFrom4(a) +} + +// DefaultRange returns the prefix scanned when no range is given. Very large +// networks are narrowed to the /24 around the local address. +func (n *Network) DefaultRange() netip.Prefix { + if n.Prefix.Bits() < 20 { + p, _ := n.LocalIP.Prefix(24) + return p + } + return n.Prefix.Masked() +} + +// DetectNetwork finds the interface to scan. With an empty name it picks the +// interface that carries the default route. +func DetectNetwork(ifaceName string) (*Network, error) { + var iface *net.Interface + var err error + if ifaceName != "" { + iface, err = net.InterfaceByName(ifaceName) + if err != nil { + return nil, fmt.Errorf("interface %q: %w", ifaceName, err) + } + } else if iface, err = defaultInterface(); err != nil { + return nil, err + } + ip, prefix, ok := ipv4Of(iface) + if !ok { + return nil, fmt.Errorf("interface %s has no IPv4 address", iface.Name) + } + return &Network{ + Iface: iface, + LocalIP: ip, + LocalMAC: iface.HardwareAddr, + Prefix: prefix, + Gateway: defaultGateway(iface), + }, nil +} + +// Interfaces returns all interfaces that are up and have an IPv4 address. +func Interfaces() []*Network { + ifaces, _ := net.Interfaces() + var out []*Network + for i := range ifaces { + iface := &ifaces[i] + if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { + continue + } + if ip, prefix, ok := ipv4Of(iface); ok { + out = append(out, &Network{Iface: iface, LocalIP: ip, LocalMAC: iface.HardwareAddr, Prefix: prefix}) + } + } + return out +} + +func defaultInterface() (*net.Interface, error) { + // Connecting a UDP socket sends nothing, but makes the kernel pick the + // source address of the default route. + if c, err := net.Dial("udp4", "192.0.2.1:9"); err == nil { + local, _ := netip.AddrFromSlice(c.LocalAddr().(*net.UDPAddr).IP) + c.Close() + for _, n := range Interfaces() { + if n.LocalIP == local.Unmap() { + return n.Iface, nil + } + } + } + for _, n := range Interfaces() { + if n.LocalIP.IsPrivate() { + return n.Iface, nil + } + } + return nil, errors.New("no active network interface found (use -i)") +} + +func ipv4Of(iface *net.Interface) (netip.Addr, netip.Prefix, bool) { + addrs, err := iface.Addrs() + if err != nil { + return netip.Addr{}, netip.Prefix{}, false + } + for _, a := range addrs { + ipn, ok := a.(*net.IPNet) + if !ok || ipn.IP.To4() == nil { + continue + } + ip := netip.AddrFrom4([4]byte(ipn.IP.To4())) + if ip.IsLinkLocalUnicast() { + continue + } + bits, _ := ipn.Mask.Size() + return ip, netip.PrefixFrom(ip, bits), true + } + return netip.Addr{}, netip.Prefix{}, false +} + +// ParseRange accepts a CIDR prefix ("192.168.1.0/24"), a single address or an +// address range ("192.168.1.10-50", "192.168.1.10-192.168.1.80"). Several +// specs can be separated by commas. +func ParseRange(spec string) ([]netip.Addr, error) { + seen := make(map[netip.Addr]bool) + var out []netip.Addr + add := func(a netip.Addr) error { + if !seen[a] { + if len(out) >= maxTargets { + return fmt.Errorf("range too large (max. %d addresses)", maxTargets) + } + seen[a] = true + out = append(out, a) + } + return nil + } + for _, part := range strings.Split(spec, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + addrs, err := parseRangePart(part) + if err != nil { + return nil, err + } + for _, a := range addrs { + if err := add(a); err != nil { + return nil, err + } + } + } + if len(out) == 0 { + return nil, errors.New("empty address range") + } + sort.Slice(out, func(i, j int) bool { return out[i].Less(out[j]) }) + return out, nil +} + +func parseRangePart(part string) ([]netip.Addr, error) { + if strings.Contains(part, "/") { + p, err := netip.ParsePrefix(part) + if err != nil || !p.Addr().Is4() { + return nil, fmt.Errorf("invalid network %q", part) + } + return PrefixHosts(p) + } + from, to, isRange := strings.Cut(part, "-") + start, err := netip.ParseAddr(strings.TrimSpace(from)) + if err != nil || !start.Is4() { + return nil, fmt.Errorf("invalid address %q", from) + } + if !isRange { + return []netip.Addr{start}, nil + } + to = strings.TrimSpace(to) + end, err := netip.ParseAddr(to) + if err != nil { + // Short form: only the last octet is given. + n, convErr := strconv.Atoi(to) + if convErr != nil || n < 0 || n > 255 { + return nil, fmt.Errorf("invalid range end %q", to) + } + b := start.As4() + b[3] = byte(n) + end = netip.AddrFrom4(b) + } + if !end.Is4() || end.Less(start) { + return nil, fmt.Errorf("invalid range %q", part) + } + var out []netip.Addr + for a := start; a.Compare(end) <= 0 && a.IsValid(); a = a.Next() { + if len(out) >= maxTargets { + return nil, fmt.Errorf("range too large (max. %d addresses)", maxTargets) + } + out = append(out, a) + } + return out, nil +} + +// PrefixHosts lists the usable host addresses of an IPv4 prefix. +func PrefixHosts(p netip.Prefix) ([]netip.Addr, error) { + p = p.Masked() + if p.Bits() < 16 { + return nil, fmt.Errorf("network %s too large (at most /16)", p) + } + var out []netip.Addr + for a := p.Addr(); p.Contains(a); a = a.Next() { + out = append(out, a) + } + if p.Bits() < 31 && len(out) > 2 { + out = out[1 : len(out)-1] // network and broadcast address + } + return out, nil +} + +// validMAC filters out empty, broadcast and multicast link-layer addresses. +func validMAC(b []byte) bool { + if len(b) != 6 || b[0]&1 == 1 { + return false + } + for _, x := range b { + if x != 0 { + return true + } + } + return false +} + +// parseLooseMAC parses MACs whose octets may lack leading zeros ("0:1a:2:...") +// as printed by BSD arp(8). +func parseLooseMAC(s string) (net.HardwareAddr, bool) { + parts := strings.FieldsFunc(s, func(r rune) bool { return r == ':' || r == '-' }) + if len(parts) != 6 { + return nil, false + } + mac := make(net.HardwareAddr, 6) + for i, p := range parts { + v, err := strconv.ParseUint(p, 16, 8) + if err != nil { + return nil, false + } + mac[i] = byte(v) + } + return mac, validMAC(mac) +} diff --git a/internal/scanner/ports.go b/internal/scanner/ports.go new file mode 100644 index 0000000..f5ef7a8 --- /dev/null +++ b/internal/scanner/ports.go @@ -0,0 +1,136 @@ +package scanner + +import ( + "context" + "fmt" + "net" + "net/netip" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +// PortResult describes an open TCP port. +type PortResult struct { + Port int `json:"port"` + Service string `json:"service,omitempty"` + RTT time.Duration `json:"-"` +} + +var wellKnownPorts = map[int]string{ + 20: "ftp-data", 21: "ftp", 22: "ssh", 23: "telnet", 25: "smtp", 53: "dns", + 80: "http", 81: "http-alt", 88: "kerberos", 110: "pop3", 111: "rpcbind", + 135: "msrpc", 139: "netbios-ssn", 143: "imap", 179: "bgp", 389: "ldap", + 443: "https", 445: "smb", 465: "smtps", 515: "lpd", 548: "afp", 554: "rtsp", + 587: "submission", 631: "ipp", 636: "ldaps", 873: "rsync", 902: "vmware", + 993: "imaps", 995: "pop3s", 1080: "socks", 1194: "openvpn", 1400: "sonos", + 1433: "mssql", 1521: "oracle", 1723: "pptp", 1883: "mqtt", 2049: "nfs", + 2375: "docker", 2376: "docker-tls", 3000: "http-dev", 3128: "squid", + 3306: "mysql", 3389: "rdp", 3689: "daap", 4443: "https-alt", 5000: "upnp", + 5001: "synology", 5060: "sip", 5222: "xmpp", 5357: "wsd", 5432: "postgresql", + 5900: "vnc", 5985: "winrm", 6379: "redis", 6443: "kubernetes", 6881: "bittorrent", + 7000: "airplay", 7547: "tr-069", 8000: "http-alt", 8008: "http-alt", + 8009: "chromecast", 8080: "http-proxy", 8081: "http-alt", 8123: "home-assistant", + 8200: "dlna", 8443: "https-alt", 8554: "rtsp-alt", 8883: "mqtt-tls", + 8888: "http-alt", 9000: "http-alt", 9090: "http-alt", 9091: "transmission", + 9100: "jetdirect", 9200: "elasticsearch", 10000: "webmin", 11211: "memcached", + 27017: "mongodb", 32400: "plex", 49000: "tr-064", 62078: "iphone-sync", +} + +// ServiceName returns the conventional service on a TCP port, if known. +func ServiceName(port int) string { return wellKnownPorts[port] } + +// TopPorts returns the commonly used ports nscan knows by name. +func TopPorts() []int { + ports := make([]int, 0, len(wellKnownPorts)) + for p := range wellKnownPorts { + ports = append(ports, p) + } + sort.Ints(ports) + return ports +} + +// ParsePorts understands "top", "all" and lists like "22,80,8000-8100". +func ParsePorts(spec string) ([]int, error) { + switch strings.TrimSpace(spec) { + case "", "top": + return TopPorts(), nil + case "all": + spec = "1-65535" + } + seen := map[int]bool{} + var ports []int + for _, part := range strings.Split(spec, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + lo, hi, isRange := strings.Cut(part, "-") + a, err := strconv.Atoi(lo) + b := a + if err == nil && isRange { + b, err = strconv.Atoi(hi) + } + if err != nil || a < 1 || b > 65535 || b < a { + return nil, fmt.Errorf("invalid port spec %q", part) + } + for p := a; p <= b; p++ { + if !seen[p] { + seen[p] = true + ports = append(ports, p) + } + } + } + if len(ports) == 0 { + return nil, fmt.Errorf("no ports given") + } + sort.Ints(ports) + return ports, nil +} + +// ScanPorts probes ports with TCP connects. onOpen is called for every open +// port, onProgress roughly every percent; both may be called concurrently. +func ScanPorts(ctx context.Context, ip netip.Addr, ports []int, timeout time.Duration, workers int, + onOpen func(PortResult), onProgress func(done, total int)) { + if workers <= 0 { + workers = 200 + } + total := len(ports) + step := max(1, total/100) + var done atomic.Int64 + jobs := make(chan int) + var wg sync.WaitGroup + for range min(workers, total) { + wg.Add(1) + go func() { + defer wg.Done() + var d net.Dialer + for p := range jobs { + dctx, cancel := context.WithTimeout(ctx, timeout) + start := time.Now() + c, err := d.DialContext(dctx, "tcp4", netip.AddrPortFrom(ip, uint16(p)).String()) + cancel() + if err == nil { + c.Close() + onOpen(PortResult{Port: p, Service: ServiceName(p), RTT: time.Since(start)}) + } + if n := int(done.Add(1)); onProgress != nil && (n%step == 0 || n == total) { + onProgress(n, total) + } + } + }() + } +feed: + for _, p := range ports { + select { + case jobs <- p: + case <-ctx.Done(): + break feed + } + } + close(jobs) + wg.Wait() +} diff --git a/internal/scanner/route_darwin.go b/internal/scanner/route_darwin.go new file mode 100644 index 0000000..56fb85f --- /dev/null +++ b/internal/scanner/route_darwin.go @@ -0,0 +1,88 @@ +//go:build darwin + +package scanner + +import ( + "net" + "net/netip" + "slices" + "sync/atomic" + "syscall" + + "golang.org/x/net/route" +) + +// arpViaExec is set once the routing sysctl came back empty while arp(8) +// returned entries; from then on arp(8) is asked directly. +var arpViaExec atomic.Bool + +// readARPTable returns the complete entries of the kernel's ARP cache. +func readARPTable() (map[netip.Addr]net.HardwareAddr, error) { + if !arpViaExec.Load() { + if table, err := readARPSysctl(); err == nil && len(table) > 0 { + return table, nil + } + } + table, err := readARPExec() + if err == nil && len(table) > 0 { + arpViaExec.Store(true) + } + return table, err +} + +func readARPSysctl() (map[netip.Addr]net.HardwareAddr, error) { + b, err := route.FetchRIB(syscall.AF_INET, syscall.NET_RT_FLAGS, syscall.RTF_LLINFO) + if err != nil { + return nil, err + } + msgs, err := route.ParseRIB(syscall.NET_RT_FLAGS, b) + if err != nil { + return nil, err + } + table := make(map[netip.Addr]net.HardwareAddr) + for _, m := range msgs { + rm, ok := m.(*route.RouteMessage) + if !ok || len(rm.Addrs) <= syscall.RTAX_GATEWAY { + continue + } + dst, ok1 := rm.Addrs[syscall.RTAX_DST].(*route.Inet4Addr) + ll, ok2 := rm.Addrs[syscall.RTAX_GATEWAY].(*route.LinkAddr) + if !ok1 || !ok2 || !validMAC(ll.Addr) { + continue + } + table[netip.AddrFrom4(dst.IP)] = net.HardwareAddr(slices.Clone(ll.Addr)) + } + return table, nil +} + +// defaultGateway returns the IPv4 default gateway reached via iface. +func defaultGateway(iface *net.Interface) netip.Addr { + b, err := route.FetchRIB(syscall.AF_INET, route.RIBTypeRoute, 0) + if err != nil { + return netip.Addr{} + } + msgs, err := route.ParseRIB(route.RIBTypeRoute, b) + if err != nil { + return netip.Addr{} + } + for _, m := range msgs { + rm, ok := m.(*route.RouteMessage) + if !ok || rm.Flags&syscall.RTF_GATEWAY == 0 || len(rm.Addrs) <= syscall.RTAX_NETMASK { + continue + } + if iface != nil && rm.Index != iface.Index { + continue + } + dst, ok := rm.Addrs[syscall.RTAX_DST].(*route.Inet4Addr) + if !ok || dst.IP != [4]byte{} { + continue + } + if mask, ok := rm.Addrs[syscall.RTAX_NETMASK].(*route.Inet4Addr); ok && mask.IP != [4]byte{} { + continue + } + if gw, ok := rm.Addrs[syscall.RTAX_GATEWAY].(*route.Inet4Addr); ok { + return netip.AddrFrom4(gw.IP) + } + } + return netip.Addr{} +} diff --git a/internal/scanner/route_linux.go b/internal/scanner/route_linux.go new file mode 100644 index 0000000..9df6651 --- /dev/null +++ b/internal/scanner/route_linux.go @@ -0,0 +1,71 @@ +//go:build linux + +package scanner + +import ( + "bufio" + "encoding/binary" + "net" + "net/netip" + "os" + "strconv" + "strings" +) + +// readARPTable returns the complete entries of the kernel's ARP cache. +func readARPTable() (map[netip.Addr]net.HardwareAddr, error) { + f, err := os.Open("/proc/net/arp") + if err != nil { + return nil, err + } + defer f.Close() + table := make(map[netip.Addr]net.HardwareAddr) + sc := bufio.NewScanner(f) + sc.Scan() // header + for sc.Scan() { + fields := strings.Fields(sc.Text()) + if len(fields) < 4 { + continue + } + flags, _ := strconv.ParseUint(strings.TrimPrefix(fields[2], "0x"), 16, 32) + if flags&0x2 == 0 { // ATF_COM: entry is complete + continue + } + ip, err := netip.ParseAddr(fields[0]) + if err != nil { + continue + } + if mac, err := net.ParseMAC(fields[3]); err == nil && validMAC(mac) { + table[ip] = mac + } + } + return table, sc.Err() +} + +// defaultGateway returns the IPv4 default gateway reached via iface. +func defaultGateway(iface *net.Interface) netip.Addr { + f, err := os.Open("/proc/net/route") + if err != nil { + return netip.Addr{} + } + defer f.Close() + sc := bufio.NewScanner(f) + sc.Scan() // header + for sc.Scan() { + fields := strings.Fields(sc.Text()) + if len(fields) < 3 || fields[1] != "00000000" { + continue + } + if iface != nil && fields[0] != iface.Name { + continue + } + v, err := strconv.ParseUint(fields[2], 16, 32) + if err != nil || v == 0 { + continue + } + var b [4]byte + binary.LittleEndian.PutUint32(b[:], uint32(v)) + return netip.AddrFrom4(b) + } + return netip.Addr{} +} diff --git a/internal/scanner/route_other.go b/internal/scanner/route_other.go new file mode 100644 index 0000000..95c5a1e --- /dev/null +++ b/internal/scanner/route_other.go @@ -0,0 +1,12 @@ +//go:build !darwin && !linux + +package scanner + +import ( + "net" + "net/netip" +) + +func readARPTable() (map[netip.Addr]net.HardwareAddr, error) { return readARPExec() } + +func defaultGateway(*net.Interface) netip.Addr { return netip.Addr{} } diff --git a/internal/scanner/scan.go b/internal/scanner/scan.go new file mode 100644 index 0000000..ca6541c --- /dev/null +++ b/internal/scanner/scan.go @@ -0,0 +1,458 @@ +package scanner + +import ( + "bytes" + "context" + "net" + "net/netip" + "os" + "slices" + "sort" + "sync" + "time" +) + +// Host is a device discovered on the network. +type Host struct { + IP netip.Addr + MAC net.HardwareAddr + Vendor string + MDNSName string + NetBIOSName string + DNSName string + Services []Service + Model string // announced via Bonjour device-info, e.g. "MacBookAir10,1" + RTT time.Duration + Via string // how the host was found: self, icmp, arp, tcp, mdns + Self bool + Gateway bool +} + +// Name returns the most descriptive name discovered for the host. +func (h *Host) Name() string { + for _, n := range []string{h.MDNSName, h.NetBIOSName, h.DNSName} { + if n != "" { + return n + } + } + return "" +} + +func (h *Host) clone() Host { + c := *h + c.MAC = slices.Clone(h.MAC) + c.Services = slices.Clone(h.Services) + return c +} + +// Progress reports which phase a scan is in. +type Progress struct { + Phase string + Done int + Total int +} + +// Options configure a scan. +type Options struct { + Network *Network + Targets []netip.Addr + // Wait is how long to wait for late replies after the ping sweep. + Wait time.Duration + Names bool + Bonjour bool + Vendor func(net.HardwareAddr) string + + // OnHost is called whenever a host is found or learns new details. + OnHost func(Host) + OnProgress func(Progress) +} + +type scan struct { + opt Options + net *Network + targets map[netip.Addr]bool + + mu sync.Mutex + hosts map[netip.Addr]*Host +} + +// Scan discovers the hosts in opt.Targets. Discovery combines an ICMP echo +// sweep with the kernel's ARP cache, so devices that ignore pings are still +// found on the local segment; outside of it, TCP connects are tried instead. +func Scan(ctx context.Context, opt Options) ([]Host, error) { + if opt.Wait <= 0 { + opt.Wait = 1500 * time.Millisecond + } + s := &scan{ + opt: opt, + net: opt.Network, + targets: make(map[netip.Addr]bool, len(opt.Targets)), + hosts: make(map[netip.Addr]*Host), + } + for _, ip := range opt.Targets { + s.targets[ip] = true + } + + var bonjour bonjourResult + var bwg sync.WaitGroup + if opt.Bonjour && s.net.Iface != nil { + bwg.Add(1) + go func() { + defer bwg.Done() + bonjour = browseBonjour(ctx, s.net.Iface, opt.Wait+2*time.Second) + }() + } + + if s.targets[s.net.LocalIP] { + s.found(s.net.LocalIP, func(h *Host) bool { + h.Via, h.MDNSName = "self", localHostname() + s.setMAC(h, s.net.LocalMAC) + return true + }) + } + + s.sweep(ctx) + s.tcpSweep(ctx) + s.arpPass() + if ctx.Err() != nil { + return nil, ctx.Err() + } + if opt.Names { + s.resolveNames(ctx) + } + if opt.Bonjour { + s.progress("Bonjour", 0, 0) + } + bwg.Wait() + s.mergeBonjour(bonjour) + if opt.Names { + s.resolveModels(ctx) + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + + s.mu.Lock() + defer s.mu.Unlock() + out := make([]Host, 0, len(s.hosts)) + for _, h := range s.hosts { + out = append(out, h.clone()) + } + sort.Slice(out, func(i, j int) bool { return out[i].IP.Less(out[j].IP) }) + return out, nil +} + +// found creates or updates the host for ip. update reports whether it changed +// anything; only then (or for new hosts) OnHost fires. +func (s *scan) found(ip netip.Addr, update func(h *Host) bool) { + s.mu.Lock() + h, ok := s.hosts[ip] + if !ok { + h = &Host{IP: ip, Self: ip == s.net.LocalIP, Gateway: ip == s.net.Gateway} + s.hosts[ip] = h + } + changed := update(h) || !ok + snap := h.clone() + s.mu.Unlock() + if changed && s.opt.OnHost != nil { + s.opt.OnHost(snap) + } +} + +func (s *scan) has(ip netip.Addr) bool { + s.mu.Lock() + defer s.mu.Unlock() + _, ok := s.hosts[ip] + return ok +} + +func (s *scan) alive() []netip.Addr { + s.mu.Lock() + defer s.mu.Unlock() + ips := make([]netip.Addr, 0, len(s.hosts)) + for ip := range s.hosts { + ips = append(ips, ip) + } + return ips +} + +func (s *scan) setMAC(h *Host, mac net.HardwareAddr) bool { + if len(mac) == 0 || bytes.Equal(h.MAC, mac) { + return false + } + h.MAC = slices.Clone(mac) + if s.opt.Vendor != nil { + h.Vendor = s.opt.Vendor(mac) + } + return true +} + +func (s *scan) progress(phase string, done, total int) { + if s.opt.OnProgress != nil { + s.opt.OnProgress(Progress{Phase: phase, Done: done, Total: total}) + } +} + +// sweep sends two rounds of echo requests. Each request also makes the kernel +// resolve the target via ARP, so the ARP cache is polled in parallel. +func (s *scan) sweep(ctx context.Context) { + sock, err := openICMP() + var nudge *net.UDPConn + if err != nil { + // Without ICMP, any UDP datagram still triggers ARP resolution. + nudge, _ = net.ListenUDP("udp4", nil) + if nudge != nil { + defer nudge.Close() + } + } + + var rwg sync.WaitGroup + if sock != nil { + rwg.Add(1) + go func() { + defer rwg.Done() + buf := make([]byte, 1500) + for { + r, err := sock.readEcho(buf) + if err != nil { + return + } + if !s.targets[r.From] { + continue + } + s.found(r.From, func(h *Host) bool { + changed := false + if h.RTT == 0 || r.RTT < h.RTT { + h.RTT, changed = r.RTT, true + } + if h.Via == "" || h.Via == "arp" { + h.Via, changed = "icmp", true + } + return changed + }) + } + }() + } + + arpDone := make(chan struct{}) + var awg sync.WaitGroup + awg.Add(1) + go func() { + defer awg.Done() + t := time.NewTicker(600 * time.Millisecond) + defer t.Stop() + for { + select { + case <-arpDone: + return + case <-t.C: + s.arpPass() + } + } + }() + + id := os.Getpid() & 0xffff + total := len(s.opt.Targets) + for round := 1; round <= 2 && ctx.Err() == nil; round++ { + for i, ip := range s.opt.Targets { + if ctx.Err() != nil { + break + } + if round == 1 && (i%32 == 0 || i == total-1) { + s.progress("Ping", i+1, total) + } + if ip == s.net.LocalIP || (round == 2 && s.has(ip)) { + continue + } + switch { + case sock != nil: + sock.sendEcho(ip, id, round) + case nudge != nil && s.net.OnLink(ip): + nudge.WriteToUDPAddrPort([]byte{0}, netip.AddrPortFrom(ip, 9)) + } + if i%8 == 7 { + time.Sleep(3 * time.Millisecond) // ~2500 pps keeps ARP queues happy + } + } + if round == 1 { + s.progress("Waiting for replies", 0, 0) + sleepCtx(ctx, s.opt.Wait/2) + } + } + sleepCtx(ctx, s.opt.Wait) + + close(arpDone) + awg.Wait() + if sock != nil { + sock.Close() + rwg.Wait() + } +} + +// tcpSweep probes targets outside the local segment that stayed silent, +// since neither ARP nor (often) ICMP gets through routers and firewalls. +func (s *scan) tcpSweep(ctx context.Context) { + var pending []netip.Addr + for _, ip := range s.opt.Targets { + if !s.net.OnLink(ip) && !s.has(ip) { + pending = append(pending, ip) + } + } + if len(pending) == 0 { + return + } + sem := make(chan struct{}, 256) + var wg sync.WaitGroup + for i, ip := range pending { + select { + case sem <- struct{}{}: + case <-ctx.Done(): + wg.Wait() + return + } + if i%16 == 0 || i == len(pending)-1 { + s.progress("TCP probe", i+1, len(pending)) + } + wg.Add(1) + go func(ip netip.Addr) { + defer func() { <-sem; wg.Done() }() + if rtt, ok := tcpAlive(ctx, ip, probePorts, 800*time.Millisecond); ok { + s.found(ip, func(h *Host) bool { + h.RTT, h.Via = rtt, "tcp" + return true + }) + } + }(ip) + } + wg.Wait() +} + +// arpPass adds every complete ARP cache entry within the target set. +func (s *scan) arpPass() { + table, err := readARPTable() + if err != nil { + return + } + for ip, mac := range table { + if !s.targets[ip] || !s.net.OnLink(ip) { + continue + } + s.found(ip, func(h *Host) bool { + changed := s.setMAC(h, mac) + if h.Via == "" { + h.Via, changed = "arp", true + } + return changed + }) + } +} + +func (s *scan) resolveNames(ctx context.Context) { + ips := s.alive() + s.progress("Names", 0, len(ips)) + const timeout = 1500 * time.Millisecond + var wg sync.WaitGroup + apply := func(names map[netip.Addr]string, set func(h *Host, name string) bool) { + for ip, name := range names { + if name == "" { + continue + } + s.found(ip, func(h *Host) bool { return set(h, name) }) + } + } + wg.Add(3) + go func() { + defer wg.Done() + apply(mdnsReverse(ctx, ips, timeout), func(h *Host, n string) bool { + if h.MDNSName == n || h.Self { + return false + } + h.MDNSName = n + return true + }) + }() + go func() { + defer wg.Done() + apply(netbiosNames(ctx, ips, timeout), func(h *Host, n string) bool { + if h.NetBIOSName == n { + return false + } + h.NetBIOSName = n + return true + }) + }() + go func() { + defer wg.Done() + apply(reverseDNS(ctx, ips, 2*timeout), func(h *Host, n string) bool { + if h.DNSName == n { + return false + } + h.DNSName = n + return true + }) + }() + wg.Wait() +} + +// resolveModels asks every host with a known mDNS or service name for the +// model it announces; devices with private MAC addresses are otherwise +// anonymous. +func (s *scan) resolveModels(ctx context.Context) { + names := map[netip.Addr][]string{} + s.mu.Lock() + for ip, h := range s.hosts { + var ns []string + if h.MDNSName != "" { + ns = append(ns, h.MDNSName) + } + for _, svc := range h.Services { + if svc.Instance != "" && !slices.Contains(ns, svc.Instance) { + ns = append(ns, svc.Instance) + } + } + if len(ns) > 0 { + names[ip] = ns + } + } + s.mu.Unlock() + if len(names) == 0 { + return + } + s.progress("Models", 0, 0) + for ip, model := range deviceModels(ctx, names, time.Second) { + s.found(ip, func(h *Host) bool { + if h.Model == model { + return false + } + h.Model = model + return true + }) + } +} + +func (s *scan) mergeBonjour(b bonjourResult) { + for ip, svcs := range b.services { + if !s.targets[ip] { + continue + } + s.found(ip, func(h *Host) bool { + h.Services = svcs + if h.Via == "" { + h.Via = "mdns" + } + return true + }) + } + for ip, name := range b.hostnames { + if !s.targets[ip] || !s.has(ip) { + continue + } + s.found(ip, func(h *Host) bool { + if h.MDNSName != "" { + return false + } + h.MDNSName = name + return true + }) + } +} diff --git a/internal/scanner/scanner_test.go b/internal/scanner/scanner_test.go new file mode 100644 index 0000000..75d5f35 --- /dev/null +++ b/internal/scanner/scanner_test.go @@ -0,0 +1,262 @@ +package scanner + +import ( + "bytes" + "net" + "net/netip" + "testing" + "time" + + "golang.org/x/net/dns/dnsmessage" +) + +func TestParseRange(t *testing.T) { + tests := []struct { + spec string + n int + first, end string + }{ + {"192.168.1.0/24", 254, "192.168.1.1", "192.168.1.254"}, + {"192.168.1.77/30", 2, "192.168.1.77", "192.168.1.78"}, + {"10.0.0.5", 1, "10.0.0.5", "10.0.0.5"}, + {"10.0.0.10-20", 11, "10.0.0.10", "10.0.0.20"}, + {"10.0.0.250-10.0.1.3", 10, "10.0.0.250", "10.0.1.3"}, + {"10.0.0.3, 10.0.0.1-3", 3, "10.0.0.1", "10.0.0.3"}, + } + for _, tt := range tests { + got, err := ParseRange(tt.spec) + if err != nil { + t.Errorf("ParseRange(%q): %v", tt.spec, err) + continue + } + if len(got) != tt.n || got[0].String() != tt.first || got[len(got)-1].String() != tt.end { + t.Errorf("ParseRange(%q) = %d addrs %v…%v, want %d %s…%s", tt.spec, len(got), got[0], got[len(got)-1], tt.n, tt.first, tt.end) + } + } + for _, bad := range []string{"", "foo", "10.0.0.20-10", "10.0.0.0/8", "10.0.0.1-300", "::1"} { + if _, err := ParseRange(bad); err == nil { + t.Errorf("ParseRange(%q) succeeded, want error", bad) + } + } +} + +func TestNetworkHelpers(t *testing.T) { + n := &Network{Prefix: netip.MustParsePrefix("192.168.178.23/24"), LocalIP: netip.MustParseAddr("192.168.178.23")} + if got := n.Broadcast().String(); got != "192.168.178.255" { + t.Errorf("Broadcast = %s", got) + } + if !n.OnLink(netip.MustParseAddr("192.168.178.1")) || n.OnLink(netip.MustParseAddr("192.168.179.1")) { + t.Error("OnLink wrong") + } + big := &Network{Prefix: netip.MustParsePrefix("10.20.30.40/16"), LocalIP: netip.MustParseAddr("10.20.30.40")} + if got := big.DefaultRange().String(); got != "10.20.30.0/24" { + t.Errorf("DefaultRange of /16 = %s, want the local /24", got) + } + mid := &Network{Prefix: netip.MustParsePrefix("172.16.40.180/20"), LocalIP: netip.MustParseAddr("172.16.40.180")} + if got := mid.DefaultRange().String(); got != "172.16.32.0/20" { + t.Errorf("DefaultRange of /20 = %s", got) + } +} + +func TestParseLooseMAC(t *testing.T) { + mac, ok := parseLooseMAC("0:1a:2:b3:4:5") + if !ok || mac.String() != "00:1a:02:b3:04:05" { + t.Errorf("got %v %v", mac, ok) + } + if _, ok := parseLooseMAC("ff-ff-ff-ff-ff-ff"); ok { + t.Error("broadcast accepted") + } + if _, ok := parseLooseMAC("01:00:5e:00:00:fb"); ok { + t.Error("multicast accepted") + } +} + +func TestParseARPOutput(t *testing.T) { + out := `? (10.0.1.1) at 3c:22:fb:12:34:56 on en1 ifscope [ethernet] +? (10.0.1.2) at (incomplete) on en1 ifscope [ethernet] +? (10.0.1.205) at e:4f:6b:00:00:21 on en1 ifscope [ethernet] +? (10.0.1.255) at ff:ff:ff:ff:ff:ff on en1 ifscope [ethernet] +? (224.0.0.251) at 1:0:5e:0:0:fb on en1 ifscope permanent [ethernet] + 192.168.0.1 00-11-22-33-44-55 dynamic +` + table := parseARPOutput(out) + want := map[string]string{ + "10.0.1.1": "3c:22:fb:12:34:56", + "10.0.1.205": "0e:4f:6b:00:00:21", + "192.168.0.1": "00:11:22:33:44:55", + } + if len(table) != len(want) { + t.Fatalf("got %v", table) + } + for ip, mac := range want { + if got := table[netip.MustParseAddr(ip)].String(); got != mac { + t.Errorf("%s = %s, want %s", ip, got, mac) + } + } +} + +func TestParsePorts(t *testing.T) { + got, err := ParsePorts("443, 22,8000-8002,22") + if err != nil { + t.Fatal(err) + } + want := []int{22, 443, 8000, 8001, 8002} + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("got %v, want %v", got, want) + } + } + if all, _ := ParsePorts("all"); len(all) != 65535 { + t.Errorf("all = %d ports", len(all)) + } + for _, bad := range []string{"0", "70000", "20-10", "abc"} { + if _, err := ParsePorts(bad); err == nil { + t.Errorf("ParsePorts(%q) succeeded", bad) + } + } +} + +func TestReverseName(t *testing.T) { + ip := netip.MustParseAddr("192.168.1.42") + name := reverseName(ip) + if name != "42.1.168.192.in-addr.arpa." { + t.Fatalf("reverseName = %s", name) + } + if back, ok := parseReverseName(name); !ok || back != ip { + t.Errorf("parseReverseName = %v %v", back, ok) + } +} + +func TestCleanHostname(t *testing.T) { + for in, want := range map[string]string{ + "Mikes-MacBook-Pro.local.": "Mikes-MacBook-Pro", + "fritz.box.": "fritz.box", + "nas.fritz.box": "nas", + "host.example.org.": "host.example.org", + "printer.lan": "printer", + } { + if got := cleanHostname(in); got != want { + t.Errorf("cleanHostname(%q) = %q, want %q", in, got, want) + } + } +} + +func TestBonjourNames(t *testing.T) { + inst := "Living Room TV._airplay._tcp.local." + if got := serviceTypeOf(inst); got != "_airplay._tcp.local." { + t.Errorf("serviceTypeOf = %q", got) + } + if got := instanceLabel(inst, "_airplay._tcp.local."); got != "Living Room TV" { + t.Errorf("instanceLabel = %q", got) + } + if got := (Service{Type: "_googlecast._tcp"}).Short(); got != "googlecast" { + t.Errorf("Short = %q", got) + } +} + +func TestMDNSRoundTrip(t *testing.T) { + // A responder's answer to our reverse query must yield the host name. + name := dnsmessage.MustNewName(reverseName(netip.MustParseAddr("10.0.0.7"))) + b := dnsmessage.NewBuilder(nil, dnsmessage.Header{Response: true, Authoritative: true}) + b.StartAnswers() + b.PTRResource(dnsmessage.ResourceHeader{Name: name, Type: dnsmessage.TypePTR, Class: dnsmessage.ClassINET, TTL: 120}, + dnsmessage.PTRResource{PTR: dnsmessage.MustNewName("Apple-TV.local.")}) + msg, err := b.Finish() + if err != nil { + t.Fatal(err) + } + rrs := parseRecords(msg) + if len(rrs) != 1 { + t.Fatalf("got %d records", len(rrs)) + } + ptr := rrs[0].Body.(*dnsmessage.PTRResource) + if got := cleanHostname(ptr.PTR.String()); got != "Apple-TV" { + t.Errorf("name = %q", got) + } + + q, err := question("_services._dns-sd._udp.local.", dnsmessage.TypePTR) + if err != nil { + t.Fatal(err) + } + if _, err := buildQuery(0, q); err != nil { + t.Fatal(err) + } +} + +func TestNBStat(t *testing.T) { + req := nbstatRequest(0x1234) + if len(req) != 50 || req[12] != 0x20 || string(req[13:15]) != "CK" { + t.Fatalf("bad request % x", req) + } + + // Response: header, the queried name, NBSTAT RR with a group name first. + resp := []byte{0x12, 0x34, 0x84, 0x00, 0, 0, 0, 1, 0, 0, 0, 0} + resp = append(resp, req[12:46]...) + resp = append(resp, 0x00, 0x21, 0x00, 0x01, 0, 0, 0, 0) + entry := func(name string, suffix byte, flags uint16) []byte { + e := bytes.Repeat([]byte(" "), 15) + copy(e, name) + return append(e, suffix, byte(flags>>8), byte(flags)) + } + rdata := []byte{2} + rdata = append(rdata, entry("WORKGROUP", 0x00, 0x8400)...) + rdata = append(rdata, entry("DESKTOP-ABC", 0x00, 0x0400)...) + rdata = append(rdata, make([]byte, 6)...) + resp = append(resp, byte(len(rdata)>>8), byte(len(rdata))) + resp = append(resp, rdata...) + + name, ok := parseNBStat(resp) + if !ok || name != "DESKTOP-ABC" { + t.Errorf("parseNBStat = %q %v", name, ok) + } + if _, ok := parseNBStat(resp[:20]); ok { + t.Error("truncated response accepted") + } +} + +func TestMagicPacket(t *testing.T) { + mac, _ := net.ParseMAC("aa:bb:cc:dd:ee:ff") + p, err := MagicPacket(mac) + if err != nil { + t.Fatal(err) + } + if len(p) != 102 || !bytes.Equal(p[:6], bytes.Repeat([]byte{0xff}, 6)) || !bytes.Equal(p[96:], mac) { + t.Errorf("bad packet % x", p) + } +} + +func TestVendorLabel(t *testing.T) { + private, _ := net.ParseMAC("02:5a:7c:11:22:33") + apple, _ := net.ParseMAC("d0:11:e5:12:34:56") + tests := []struct { + h Host + maker, want string + }{ + {Host{MAC: private, Vendor: "Private address", Model: "MacBookAir10,1"}, "Apple", "Apple MacBookAir10,1"}, + {Host{MAC: private, Vendor: "Private address"}, "Private address", "Private address"}, + {Host{MAC: private, Vendor: "Private address", Model: "VMware7,1"}, "Private address", "VMware7,1"}, + {Host{MAC: apple, Vendor: "Apple", Model: "Mac16,10"}, "Apple", "Apple Mac16,10"}, + {Host{MAC: apple, Vendor: "Apple"}, "Apple", "Apple"}, + {Host{Model: "iPhone15,3"}, "Apple", "Apple iPhone15,3"}, + } + for _, tt := range tests { + if got := tt.h.Maker(); got != tt.maker { + t.Errorf("Maker(%v) = %q, want %q", tt.h.Model, got, tt.maker) + } + if got := tt.h.VendorLabel(); got != tt.want { + t.Errorf("VendorLabel(%v) = %q, want %q", tt.h.Model, got, tt.want) + } + } + if txtValue([]string{"model=Mac16,10", "osxvers=26"}, "model") != "Mac16,10" { + t.Error("txtValue") + } +} + +func TestDeviceModelsLoopback(t *testing.T) { + // The local mDNS responder answers for this machine, if there is one. + got := deviceModels(t.Context(), map[netip.Addr][]string{netip.MustParseAddr("127.0.0.1"): {localHostname()}}, 500*time.Millisecond) + t.Logf("loopback model: %q", got[netip.MustParseAddr("127.0.0.1")]) +} diff --git a/internal/scanner/wol.go b/internal/scanner/wol.go new file mode 100644 index 0000000..10c8b6b --- /dev/null +++ b/internal/scanner/wol.go @@ -0,0 +1,48 @@ +package scanner + +import ( + "bytes" + "fmt" + "net" + "net/netip" +) + +// MagicPacket builds a Wake-on-LAN packet: six 0xff bytes followed by the +// MAC address repeated 16 times. +func MagicPacket(mac net.HardwareAddr) ([]byte, error) { + if len(mac) != 6 { + return nil, fmt.Errorf("invalid MAC address %s", mac) + } + return append(bytes.Repeat([]byte{0xff}, 6), bytes.Repeat(mac, 16)...), nil +} + +// WakeOnLAN sends a magic packet to the limited broadcast address and, if +// given, to the directed broadcast address of the network. +func WakeOnLAN(mac net.HardwareAddr, broadcast netip.Addr) error { + pkt, err := MagicPacket(mac) + if err != nil { + return err + } + conn, err := net.ListenUDP("udp4", nil) + if err != nil { + return err + } + defer conn.Close() + targets := []netip.Addr{netip.AddrFrom4([4]byte{255, 255, 255, 255})} + if broadcast.IsValid() && broadcast != targets[0] { + targets = append(targets, broadcast) + } + var lastErr error + sent := 0 + for _, t := range targets { + if _, err := conn.WriteToUDPAddrPort(pkt, netip.AddrPortFrom(t, 9)); err != nil { + lastErr = err + continue + } + sent++ + } + if sent == 0 { + return lastErr + } + return nil +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..0cb7ab9 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,348 @@ +// Package store persists what nscan learns about devices across runs: custom +// names, whitelist and tracking flags, first/last sightings and the event +// history used by the timeline view. +package store + +import ( + "bufio" + "encoding/json" + "errors" + "io/fs" + "net/netip" + "os" + "path/filepath" + "sort" + "sync" + "time" +) + +const ( + devicesFile = "devices.json" + eventsFile = "events.jsonl" + + // Retention is how long events are kept. + Retention = 30 * 24 * time.Hour + // MissLimit is the number of consecutive scans a device must be missing + // before it counts as gone; single lost replies are common on Wi-Fi. + MissLimit = 2 +) + +// Dir returns the directory nscan keeps its state in. +func Dir() (string, error) { + if d := os.Getenv("NSCAN_DIR"); d != "" { + return d, nil + } + if d := os.Getenv("XDG_CONFIG_HOME"); d != "" { + return filepath.Join(d, "nscan"), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(home, ".config", "nscan"), nil +} + +// Device is everything remembered about one device. Devices are keyed by MAC +// address, or by "ip:" when no MAC is known (e.g. routed ranges). +type Device struct { + Key string `json:"key"` + MAC string `json:"mac,omitempty"` + IP string `json:"ip"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + Vendor string `json:"vendor,omitempty"` + Model string `json:"model,omitempty"` + Whitelisted bool `json:"whitelisted,omitempty"` + Tracked bool `json:"tracked,omitempty"` + FirstSeen time.Time `json:"first_seen"` + LastSeen time.Time `json:"last_seen"` +} + +// Label is the name shown for the device. +func (d *Device) Label() string { + switch { + case d.Name != "": + return d.Name + case d.Hostname != "": + return d.Hostname + } + return d.IP +} + +// EventKind classifies events. +type EventKind string + +const ( + EventScan EventKind = "scan" // a scan finished; marks monitoring coverage + EventNew EventKind = "new" // a device was seen for the first time ever + EventJoin EventKind = "join" // a known device came back + EventLeave EventKind = "leave" // a device was missing for MissLimit scans +) + +// Event is one entry of the history. +type Event struct { + Time time.Time `json:"time"` + Kind EventKind `json:"kind"` + Key string `json:"key,omitempty"` + IP string `json:"ip,omitempty"` + Label string `json:"label,omitempty"` + Online int `json:"online,omitempty"` + // Notify is set for new devices and for tracked devices coming or going. + Notify bool `json:"notify,omitempty"` +} + +// Sighting is a device seen in a scan. +type Sighting struct { + Key, IP, MAC, Hostname, Vendor, Model string +} + +type presence struct { + online bool + missed int +} + +// Store is safe for concurrent use. +type Store struct { + dir string + + mu sync.Mutex + devices map[string]*Device + events []Event + presence map[string]*presence + primed bool +} + +// Open loads the store from dir, creating the directory if necessary. +func Open(dir string) (*Store, error) { + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, err + } + s := &Store{dir: dir, devices: map[string]*Device{}, presence: map[string]*presence{}} + b, err := os.ReadFile(filepath.Join(dir, devicesFile)) + switch { + case err == nil: + var list []*Device + if err := json.Unmarshal(b, &list); err != nil { + return nil, err + } + for _, d := range list { + s.devices[d.Key] = d + } + case !errors.Is(err, fs.ErrNotExist): + return nil, err + } + if err := s.loadEvents(); err != nil { + return nil, err + } + return s, nil +} + +// Dir returns the directory the store lives in. +func (s *Store) Dir() string { return s.dir } + +func (s *Store) loadEvents() error { + path := filepath.Join(s.dir, eventsFile) + f, err := os.Open(path) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + cutoff := time.Now().Add(-Retention) + pruned := false + sc := bufio.NewScanner(f) + for sc.Scan() { + var e Event + if json.Unmarshal(sc.Bytes(), &e) != nil { + pruned = true + continue + } + if e.Time.Before(cutoff) { + pruned = true + continue + } + s.events = append(s.events, e) + } + f.Close() + if err := sc.Err(); err != nil { + return err + } + if pruned { + return s.rewriteEvents() + } + return nil +} + +func (s *Store) rewriteEvents() error { + path := filepath.Join(s.dir, eventsFile) + tmp := path + ".tmp" + f, err := os.Create(tmp) + if err != nil { + return err + } + w := bufio.NewWriter(f) + enc := json.NewEncoder(w) + for _, e := range s.events { + enc.Encode(e) + } + if err := w.Flush(); err != nil { + f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(tmp, path) +} + +func (s *Store) appendEvents(evs []Event) error { + f, err := os.OpenFile(filepath.Join(s.dir, eventsFile), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return err + } + enc := json.NewEncoder(f) + for _, e := range evs { + if err := enc.Encode(e); err != nil { + f.Close() + return err + } + } + return f.Close() +} + +func (s *Store) saveDevices() error { + list := make([]*Device, 0, len(s.devices)) + for _, d := range s.devices { + list = append(list, d) + } + sort.Slice(list, func(i, j int) bool { return list[i].Key < list[j].Key }) + b, err := json.MarshalIndent(list, "", " ") + if err != nil { + return err + } + path := filepath.Join(s.dir, devicesFile) + tmp := path + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// Device returns a copy of the device stored under key. +func (s *Store) Device(key string) (Device, bool) { + s.mu.Lock() + defer s.mu.Unlock() + d, ok := s.devices[key] + if !ok { + return Device{}, false + } + return *d, true +} + +// Devices returns copies of all stored devices. +func (s *Store) Devices() []Device { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]Device, 0, len(s.devices)) + for _, d := range s.devices { + out = append(out, *d) + } + return out +} + +// Update applies fn to the device under key, creating it if needed, and +// saves the result. +func (s *Store) Update(key string, fn func(d *Device)) error { + s.mu.Lock() + defer s.mu.Unlock() + d, ok := s.devices[key] + if !ok { + now := time.Now() + d = &Device{Key: key, FirstSeen: now, LastSeen: now} + s.devices[key] = d + } + fn(d) + return s.saveDevices() +} + +// Events returns the events since t, oldest first. +func (s *Store) Events(since time.Time) []Event { + s.mu.Lock() + defer s.mu.Unlock() + i := sort.Search(len(s.events), func(i int) bool { return !s.events[i].Time.Before(since) }) + return append([]Event(nil), s.events[i:]...) +} + +// Observe records the result of a scan and returns the resulting events. +// inScope reports whether an address was part of the scan, so devices outside +// a changed range are not reported as gone. +func (s *Store) Observe(now time.Time, seen []Sighting, inScope func(netip.Addr) bool) ([]Event, error) { + s.mu.Lock() + defer s.mu.Unlock() + + // On the very first run every device would be "new"; that is noise. + bootstrap := len(s.devices) == 0 + var evs []Event + present := make(map[string]bool, len(seen)) + for _, v := range seen { + present[v.Key] = true + d, known := s.devices[v.Key] + if !known { + d = &Device{Key: v.Key, FirstSeen: now} + s.devices[v.Key] = d + } + d.IP, d.LastSeen = v.IP, now + if v.MAC != "" { + d.MAC = v.MAC + } + if v.Hostname != "" { + d.Hostname = v.Hostname + } + if v.Vendor != "" { + d.Vendor = v.Vendor + } + if v.Model != "" { + d.Model = v.Model + } + + p := s.presence[v.Key] + if p == nil { + p = &presence{} + s.presence[v.Key] = p + } + switch { + case !known && !bootstrap: + evs = append(evs, s.event(now, EventNew, d, true)) + case known && s.primed && !p.online: + evs = append(evs, s.event(now, EventJoin, d, d.Tracked)) + } + p.online, p.missed = true, 0 + } + for key, p := range s.presence { + if !p.online || present[key] { + continue + } + d := s.devices[key] + if ip, err := netip.ParseAddr(d.IP); err == nil && inScope != nil && !inScope(ip) { + continue + } + if p.missed++; p.missed >= MissLimit { + p.online = false + evs = append(evs, s.event(now, EventLeave, d, d.Tracked)) + } + } + s.primed = true + + evs = append(evs, Event{Time: now, Kind: EventScan, Online: len(seen)}) + s.events = append(s.events, evs...) + err := s.appendEvents(evs) + if serr := s.saveDevices(); err == nil { + err = serr + } + return evs, err +} + +func (s *Store) event(now time.Time, kind EventKind, d *Device, notify bool) Event { + return Event{Time: now, Kind: kind, Key: d.Key, IP: d.IP, Label: d.Label(), Notify: notify} +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go new file mode 100644 index 0000000..b7677a8 --- /dev/null +++ b/internal/store/store_test.go @@ -0,0 +1,95 @@ +package store + +import ( + "net/netip" + "testing" + "time" +) + +func kinds(evs []Event) []EventKind { + var out []EventKind + for _, e := range evs { + if e.Kind != EventScan { + out = append(out, e.Kind) + } + } + return out +} + +func equal(a, b []EventKind) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestObserve(t *testing.T) { + dir := t.TempDir() + s, err := Open(dir) + if err != nil { + t.Fatal(err) + } + all := func(netip.Addr) bool { return true } + a := Sighting{Key: "aa:aa:aa:aa:aa:aa", IP: "10.0.0.2", MAC: "aa:aa:aa:aa:aa:aa"} + b := Sighting{Key: "bb:bb:bb:bb:bb:bb", IP: "10.0.0.3", MAC: "bb:bb:bb:bb:bb:bb", Hostname: "phone"} + c := Sighting{Key: "cc:cc:cc:cc:cc:cc", IP: "10.0.0.4"} + t0 := time.Now() + at := func(i int) time.Time { return t0.Add(time.Duration(i) * time.Minute) } + + steps := []struct { + seen []Sighting + want []EventKind + }{ + {[]Sighting{a, b}, nil}, // first run ever: no "new" flood + {[]Sighting{a, b, c}, []EventKind{EventNew}}, // c is new + {[]Sighting{a, c}, nil}, // b missed once: not gone yet + {[]Sighting{a, c}, []EventKind{EventLeave}}, // b missed twice: gone + {[]Sighting{a, c}, nil}, // no repeated leave + {[]Sighting{a, b, c}, []EventKind{EventJoin}}, + } + for i, st := range steps { + evs, err := s.Observe(at(i), st.seen, all) + if err != nil { + t.Fatal(err) + } + if got := kinds(evs); !equal(got, st.want) { + t.Errorf("step %d: events %v, want %v", i, got, st.want) + } + } + + // Tracking marks leave/join events for notification. + if err := s.Update(b.Key, func(d *Device) { d.Tracked, d.Name = true, "Anna's iPhone" }); err != nil { + t.Fatal(err) + } + s.Observe(at(10), []Sighting{a, c}, all) + evs, _ := s.Observe(at(11), []Sighting{a, c}, all) + if len(kinds(evs)) != 1 || !evs[0].Notify || evs[0].Label != "Anna's iPhone" { + t.Errorf("tracked leave = %+v", evs) + } + + // Out-of-scope devices are not reported as gone. + s.Observe(at(12), []Sighting{a, c}, all) + none := func(netip.Addr) bool { return false } + s.Observe(at(13), nil, none) + if evs, _ := s.Observe(at(14), nil, none); len(kinds(evs)) != 0 { + t.Errorf("out of scope events %v", kinds(evs)) + } + + // Everything survives a reload. + s2, err := Open(dir) + if err != nil { + t.Fatal(err) + } + d, ok := s2.Device(b.Key) + if !ok || d.Name != "Anna's iPhone" || !d.Tracked || d.Hostname != "phone" { + t.Errorf("reloaded device = %+v", d) + } + if got := len(s2.Events(t0.Add(-time.Hour))); got != len(s.Events(t0.Add(-time.Hour))) || got == 0 { + t.Errorf("reloaded %d events", got) + } +} diff --git a/internal/tui/history.go b/internal/tui/history.go new file mode 100644 index 0000000..47eec99 --- /dev/null +++ b/internal/tui/history.go @@ -0,0 +1,244 @@ +package tui + +import ( + "fmt" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "nscan/internal/store" +) + +// histState backs the timeline view: a ribbon with one bar per hour (or day) +// whose height shows how much changed on the network. +type histState struct { + daily bool + cursor int // selected bucket, counted from the newest (0) + events []store.Event +} + +type bucket struct { + start, end time.Time + scans int + news, joins, leaves int + events []store.Event +} + +func (b *bucket) changes() int { return b.news + b.joins + b.leaves } + +func (m *model) loadHistory() { + m.hist.events = m.cfg.Store.Events(time.Now().Add(-store.Retention)) +} + +func (m *model) handleHistoryKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + n, _ := m.bucketLayout() + switch msg.String() { + case "esc", "q", "h": + m.mode = viewList + case "left": + m.hist.cursor = min(n-1, m.hist.cursor+1) + case "right": + m.hist.cursor = max(0, m.hist.cursor-1) + case "home": + m.hist.cursor = n - 1 + case "end": + m.hist.cursor = 0 + case "z", "t": + m.hist.daily = !m.hist.daily + m.hist.cursor = 0 + } + return m, nil +} + +// bucketLayout returns how many buckets fit and how wide each is drawn. +func (m *model) bucketLayout() (n, width int) { + n = 48 + if m.hist.daily { + n = 30 + } + avail := max(10, m.w-4) + width = max(1, min(3, avail/n)) + return min(n, avail/width), width +} + +func (m *model) buckets(n int, now time.Time) []bucket { + step := time.Hour + end := now.Truncate(time.Hour).Add(time.Hour) + if m.hist.daily { + step = 24 * time.Hour + y, mo, d := now.Date() + end = time.Date(y, mo, d+1, 0, 0, 0, 0, now.Location()) + } + bs := make([]bucket, n) + for i := range bs { + // AddDate keeps days aligned to local midnight across DST changes. + var start time.Time + if m.hist.daily { + start = end.AddDate(0, 0, -(n - i)) + bs[i] = bucket{start: start, end: start.AddDate(0, 0, 1)} + } else { + start = end.Add(-time.Duration(n-i) * step) + bs[i] = bucket{start: start, end: start.Add(step)} + } + } + // Events are sorted by time, so buckets and events advance together. + first, i := bs[0].start, 0 + for _, e := range m.hist.events { + if e.Time.Before(first) { + continue + } + if !e.Time.Before(end) { + break + } + for !e.Time.Before(bs[i].end) { + i++ + } + b := &bs[i] + switch e.Kind { + case store.EventScan: + b.scans++ + case store.EventNew: + b.news++ + case store.EventJoin: + b.joins++ + case store.EventLeave: + b.leaves++ + } + if e.Kind != store.EventScan { + b.events = append(b.events, e) + } + } + return bs +} + +var ( + styleArrive = fg(mwxGreen) + styleDepart = fg(mwxRed) + styleMixed = fg(mwxBlue) + styleHatch = fg(mwxDarker) +) + +func (m *model) viewHistory() string { + now := time.Now() + n, bw := m.bucketLayout() + bs := m.buckets(n, now) + sel := n - 1 - min(m.hist.cursor, n-1) + + unit := fmt.Sprintf("hourly, last %d hours", n) + if m.hist.daily { + unit = fmt.Sprintf("daily, last %d days", n) + } + lines := []string{m.titleBar(""), "", " " + styleBold.Render("History") + styleDim.Render(" "+unit), ""} + + maxChanges := 1 + for i := range bs { + maxChanges = max(maxChanges, bs[i].changes()) + } + ribbonRows := max(2, min(6, m.h-14)) + levels := ribbonRows * 8 + blocks := []rune(" ▁▂▃▄▅▆▇█") + for row := ribbonRows - 1; row >= 0; row-- { + var b strings.Builder + b.WriteString(" ") + for i := range bs { + bk := &bs[i] + var cell string + if bk.scans == 0 { + cell = styleHatch.Render(strings.Repeat("░", bw)) + } else { + height := 0 + if c := bk.changes(); c > 0 { + height = max(1, c*levels/maxChanges) + } + fill := max(0, min(8, height-row*8)) + style := styleMixed + switch { + case bk.news+bk.joins > bk.leaves: + style = styleArrive + case bk.leaves > bk.news+bk.joins: + style = styleDepart + } + if i == sel { + style = onSel(style) + } + cell = style.Render(strings.Repeat(string(blocks[fill]), bw)) + } + b.WriteString(cell) + } + lines = append(lines, b.String()) + } + + // Axis with labels every 6 hours or every Monday. + axis := []rune(strings.Repeat("─", n*bw)) + labels := []rune(strings.Repeat(" ", n*bw+8)) + for i := range bs { + var label string + if m.hist.daily { + if bs[i].start.Weekday() == time.Monday { + label = bs[i].start.Format("Jan 2") + } + } else if bs[i].start.Hour()%6 == 0 { + label = bs[i].start.Format("15:04") + } + if label == "" { + continue + } + pos := i * bw + axis[pos] = '┴' + if free(labels, pos, len(label)+1) { + copy(labels[pos:], []rune(label)) + } + } + marker := []rune(strings.Repeat(" ", n*bw)) + for j := 0; j < bw; j++ { + marker[sel*bw+j] = '▲' + } + lines = append(lines, " "+styleRule.Render(string(axis)), " "+styleDim.Render(strings.TrimRight(string(labels), " ")), " "+styleAccent.Render(string(marker)), "") + + b := bs[sel] + span := b.start.Format("Mon Jan 2 15:04") + "–" + b.end.Format("15:04") + if m.hist.daily { + span = b.start.Format("Mon Jan 2 2006") + } + summary := " " + styleBold.Render(span) + if b.scans == 0 { + summary += styleMuted.Render(" · not monitored") + } else { + summary += styleDim.Render(fmt.Sprintf(" · %d scans · ", b.scans)) + fmt.Sprintf("%s · %s · %s", + styleNew.Render(fmt.Sprintf("%d new", b.news)), + styleArrive.Render(fmt.Sprintf("%d back", b.joins)), + styleDepart.Render(fmt.Sprintf("%d gone", b.leaves))) + } + lines = append(lines, summary, "") + + avail := max(0, m.h-len(lines)-3) + if len(b.events) == 0 && b.scans > 0 { + lines = append(lines, styleMuted.Render(" no changes")) + } + for i := len(b.events) - 1; i >= 0 && len(b.events)-1-i < avail; i-- { + e := b.events[i] + line := " " + renderEvent(e, false) + if e.IP != "" && e.Label != e.IP { + line += styleMuted.Render(" " + e.IP) + } + lines = append(lines, styleTime.Render(" "+e.Time.Format("15:04"))+line) + } + lines = append(padLines(lines, m.h-2), + styleDim.Render(" ")+styleArrive.Render("█")+styleDim.Render(" more arrivals ")+styleDepart.Render("█")+ + styleDim.Render(" more departures ")+styleMixed.Render("█")+styleDim.Render(" balanced ")+ + styleHatch.Render("░")+styleDim.Render(" not monitored · height = number of changes")) + return m.screen(lines, m.footer("←/→ select", "z hours/days", "esc back")) +} + +func free(line []rune, pos, n int) bool { + if pos+n > len(line) { + return false + } + for _, r := range line[pos : pos+n] { + if r != ' ' { + return false + } + } + return true +} diff --git a/internal/tui/model.go b/internal/tui/model.go new file mode 100644 index 0000000..daff402 --- /dev/null +++ b/internal/tui/model.go @@ -0,0 +1,962 @@ +// Package tui implements nscan's interactive terminal interface. +package tui + +import ( + "bytes" + "context" + "errors" + "fmt" + "net" + "net/netip" + "os" + "os/exec" + "runtime" + "sort" + "strings" + "time" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + + "nscan/internal/export" + "nscan/internal/oui" + "nscan/internal/scanner" + "nscan/internal/store" +) + +// Config holds everything the interface needs to run scans. +type Config struct { + Network *scanner.Network + Range string + Targets []netip.Addr + Auto bool + Interval time.Duration + Wait time.Duration + Names bool + Bonjour bool + Store *store.Store + OUI *oui.DB + ExportDir string + Version string // shown in the title bar and the help screen +} + +// Run starts the interface and blocks until the user quits. +func Run(cfg Config) error { + if cfg.Interval <= 0 { + cfg.Interval = time.Minute + } + m := newModel(cfg) + _, err := tea.NewProgram(m, tea.WithAltScreen()).Run() + m.stopAll() + return err +} + +type viewMode int + +const ( + viewList viewMode = iota + viewDetail + viewPorts + viewPing + viewHistory + viewHelp + viewColumns +) + +type inputKind int + +const ( + inputNone inputKind = iota + inputFilter + inputRename + inputRange +) + +// device is one row of the table. +type device struct { + key string + host scanner.Host + online bool + lastSeen time.Time + ports []scanner.PortResult + portsAt time.Time +} + +type model struct { + cfg Config + targetSet map[netip.Addr]bool + w, h int + + devs map[string]*device + meta map[string]store.Device + list []*device + cursor int + offset int + + mode viewMode + detailKey string + detailOff int + helpOff int + colCursor int + + input textinput.Model + inputKind inputKind + inputKey string + + scanning bool + scanNo int + scanCancel context.CancelFunc + pendingRescan bool + progress scanner.Progress + lastScan time.Time + lastDur time.Duration + nextScan time.Time + auto bool + + cumulative bool + hideWhitelisted bool + sortCol column + sortDesc bool + filter string + cols [numCols]bool + + events []store.Event + flash string + flashErr bool + flashAt time.Time + + toolID int + toolReturn viewMode + ports *portState + ping *pingState + hist histState +} + +func newModel(cfg Config) *model { + in := textinput.New() + in.CharLimit = 200 + m := &model{ + cfg: cfg, + devs: map[string]*device{}, + meta: map[string]store.Device{}, + input: in, + auto: cfg.Auto, + sortCol: colIP, + } + for c := range m.cols { + m.cols[c] = true + } + m.setTargets(cfg.Range, cfg.Targets) + return m +} + +// setTargets switches the scan range and shows the known devices within it. +func (m *model) setTargets(spec string, targets []netip.Addr) { + m.cfg.Range, m.cfg.Targets = spec, targets + m.targetSet = make(map[netip.Addr]bool, len(targets)) + for _, ip := range targets { + m.targetSet[ip] = true + } + for key, d := range m.devs { + if !m.targetSet[d.host.IP] { + delete(m.devs, key) + } + } + m.reloadMeta() + for _, sd := range m.meta { + ip, err := netip.ParseAddr(sd.IP) + if err != nil || !m.targetSet[ip] || m.devs[sd.Key] != nil { + continue + } + mac, _ := net.ParseMAC(sd.MAC) + vendor := m.cfg.OUI.Lookup(mac) + if vendor == "" { + vendor = sd.Vendor + } + m.devs[sd.Key] = &device{ + key: sd.Key, + host: scanner.Host{IP: ip, MAC: mac, Vendor: vendor, Model: sd.Model}, + lastSeen: sd.LastSeen, + } + } + m.refresh() +} + +func (m *model) reloadMeta() { + clear(m.meta) + for _, d := range m.cfg.Store.Devices() { + m.meta[d.Key] = d + } +} + +func (m *model) inScope(ip netip.Addr) bool { return m.targetSet[ip] } + +// --- messages ------------------------------------------------------------- + +type tickMsg time.Time + +type scanHostMsg struct { + no int + host scanner.Host +} + +type scanProgressMsg struct { + no int + p scanner.Progress +} + +type scanDoneMsg struct { + no int + hosts []scanner.Host + err error + dur time.Duration +} + +type flashMsg struct { + text string + err bool +} + +// chanMsg carries a message read from a background job's channel, so Update +// knows which channel to keep reading from. +type chanMsg struct { + ch <-chan tea.Msg + msg tea.Msg +} + +func pump(ch <-chan tea.Msg) tea.Cmd { + return func() tea.Msg { + msg, ok := <-ch + if !ok { + return nil + } + return chanMsg{ch, msg} + } +} + +func tick() tea.Cmd { + return tea.Tick(time.Second, func(t time.Time) tea.Msg { return tickMsg(t) }) +} + +func bell() tea.Msg { + fmt.Fprint(os.Stderr, "\a") + return nil +} + +// --- update --------------------------------------------------------------- + +func (m *model) Init() tea.Cmd { + return tea.Batch(tick(), m.startScan()) +} + +func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case chanMsg: + _, cmd := m.Update(msg.msg) + return m, tea.Batch(cmd, pump(msg.ch)) + + case tea.WindowSizeMsg: + m.w, m.h = msg.Width, msg.Height + m.input.Width = max(10, m.w-30) + m.ensureVisible() + + case tickMsg: + if m.auto && !m.scanning && !m.nextScan.IsZero() && !time.Time(msg).Before(m.nextScan) { + return m, tea.Batch(tick(), m.startScan()) + } + return m, tick() + + case scanHostMsg: + if msg.no == m.scanNo { + m.upsert(msg.host) + m.refresh() + } + + case scanProgressMsg: + if msg.no == m.scanNo { + m.progress = msg.p + } + + case scanDoneMsg: + if msg.no == m.scanNo { + return m, m.finishScan(msg) + } + + case flashMsg: + m.setFlash(msg.text, msg.err) + + case portOpenMsg, portProgressMsg, portDoneMsg, pingMsg, pingDoneMsg: + m.updateTools(msg) + + case tea.KeyMsg: + return m.handleKey(msg) + } + return m, nil +} + +func (m *model) setFlash(text string, isErr bool) { + m.flash, m.flashErr, m.flashAt = text, isErr, time.Now() +} + +func (m *model) startScan() tea.Cmd { + if m.scanning { + return nil + } + m.scanning = true + m.scanNo++ + m.progress = scanner.Progress{Phase: "Start"} + no := m.scanNo + ctx, cancel := context.WithCancel(context.Background()) + m.scanCancel = cancel + ch := make(chan tea.Msg, 512) + opt := scanner.Options{ + Network: m.cfg.Network, + Targets: m.cfg.Targets, + Wait: m.cfg.Wait, + Names: m.cfg.Names, + Bonjour: m.cfg.Bonjour, + Vendor: m.cfg.OUI.Lookup, + OnHost: func(h scanner.Host) { ch <- scanHostMsg{no, h} }, + OnProgress: func(p scanner.Progress) { + select { + case ch <- scanProgressMsg{no, p}: + default: + } + }, + } + go func() { + start := time.Now() + hosts, err := scanner.Scan(ctx, opt) + ch <- scanDoneMsg{no, hosts, err, time.Since(start)} + close(ch) + }() + return pump(ch) +} + +func deviceKey(h scanner.Host) string { + if len(h.MAC) > 0 { + return strings.ToLower(h.MAC.String()) + } + return "ip:" + h.IP.String() +} + +// upsert merges a scan result into the table. +func (m *model) upsert(h scanner.Host) *device { + key := deviceKey(h) + if len(h.MAC) > 0 { + // The host may already be listed by IP from before its MAC was known. + ipKey := "ip:" + h.IP.String() + if d, ok := m.devs[ipKey]; ok { + delete(m.devs, ipKey) + if m.devs[key] == nil { + d.key = key + m.devs[key] = d + } + m.rekey(ipKey, key) + } + } else if m.devs[key] == nil { + // Until ARP delivers the MAC, attribute the IP to the device that + // had it last time. + for _, d := range m.devs { + if d.host.IP == h.IP && len(d.host.MAC) > 0 { + key = d.key + break + } + } + } + d := m.devs[key] + if d == nil { + d = &device{key: key} + m.devs[key] = d + } + mergeHost(&d.host, h) + d.online, d.lastSeen = true, time.Now() + return d +} + +func (m *model) rekey(from, to string) { + if m.detailKey == from { + m.detailKey = to + } + if m.ports != nil && m.ports.key == from { + m.ports.key = to + } +} + +// mergeHost copies everything h knows into dst without dropping details an +// earlier, more complete result provided. +func mergeHost(dst *scanner.Host, h scanner.Host) { + dst.IP, dst.Self, dst.Gateway = h.IP, h.Self, h.Gateway + if len(h.MAC) > 0 { + dst.MAC, dst.Vendor = h.MAC, h.Vendor + } + if h.MDNSName != "" { + dst.MDNSName = h.MDNSName + } + if h.NetBIOSName != "" { + dst.NetBIOSName = h.NetBIOSName + } + if h.DNSName != "" { + dst.DNSName = h.DNSName + } + if len(h.Services) > 0 { + dst.Services = h.Services + } + if h.Model != "" { + dst.Model = h.Model + } + if h.RTT > 0 { + dst.RTT = h.RTT + } + if h.Via != "" { + dst.Via = h.Via + } +} + +func (m *model) finishScan(msg scanDoneMsg) tea.Cmd { + m.scanning, m.scanCancel = false, nil + now := time.Now() + m.nextScan = now.Add(m.cfg.Interval) + if msg.err != nil { + if !errors.Is(msg.err, context.Canceled) { + m.setFlash("Scan failed: "+msg.err.Error(), true) + } + if m.pendingRescan { + m.pendingRescan = false + return m.startScan() + } + return nil + } + m.lastScan, m.lastDur = now, msg.dur + + seen := map[string]bool{} + sightings := make([]store.Sighting, 0, len(msg.hosts)) + for _, h := range msg.hosts { + d := m.upsert(h) + seen[d.key] = true + s := store.Sighting{Key: d.key, IP: h.IP.String(), Hostname: h.Name(), Vendor: h.Vendor, Model: h.Model} + if len(h.MAC) > 0 { + s.MAC = h.MAC.String() + } + sightings = append(sightings, s) + } + for key, d := range m.devs { + if !seen[key] { + d.online = false + } + } + + evs, err := m.cfg.Store.Observe(now, sightings, m.inScope) + if err != nil { + m.setFlash("Saving failed: "+err.Error(), true) + } + m.reloadMeta() + notify := false + for _, e := range evs { + if e.Kind == store.EventScan { + continue + } + m.events = append(m.events, e) + notify = notify || e.Notify + } + if len(m.events) > 100 { + m.events = m.events[len(m.events)-100:] + } + if m.mode == viewHistory { + m.loadHistory() + } + if len(msg.hosts) <= 1 && runtime.GOOS == "darwin" { + m.setFlash("No devices found – your terminal may need \"Local Network\" access "+ + "(System Settings → Privacy & Security)", true) + } + m.refresh() + + var cmds []tea.Cmd + if notify { + cmds = append(cmds, bell) + } + if m.pendingRescan { + m.pendingRescan = false + cmds = append(cmds, m.startScan()) + } + return tea.Batch(cmds...) +} + +// --- table state ---------------------------------------------------------- + +func (m *model) label(d *device) string { + if n := m.meta[d.key].Name; n != "" { + return n + } + if n := d.host.Name(); n != "" { + return n + } + return m.meta[d.key].Hostname +} + +func (m *model) selected() *device { + if m.cursor >= 0 && m.cursor < len(m.list) { + return m.list[m.cursor] + } + return nil +} + +// refresh rebuilds the visible, sorted list and keeps the cursor on the same +// device. +func (m *model) refresh() { + var selKey string + if d := m.selected(); d != nil { + selKey = d.key + } + needle := strings.ToLower(m.filter) + m.list = m.list[:0] + for _, d := range m.devs { + if !d.online && !m.cumulative { + continue + } + if m.hideWhitelisted && m.meta[d.key].Whitelisted { + continue + } + if needle != "" && !m.matches(d, needle) { + continue + } + m.list = append(m.list, d) + } + sort.SliceStable(m.list, func(i, j int) bool { return m.less(m.list[i], m.list[j]) }) + for i, d := range m.list { + if d.key == selKey { + m.cursor = i + break + } + } + m.cursor = min(m.cursor, max(0, len(m.list)-1)) + m.ensureVisible() +} + +func (m *model) matches(d *device, needle string) bool { + fields := []string{m.label(d), d.host.IP.String(), d.host.VendorLabel(), d.host.DNSName, d.host.NetBIOSName, d.host.MDNSName} + if len(d.host.MAC) > 0 { + fields = append(fields, d.host.MAC.String()) + } + for _, s := range d.host.Services { + fields = append(fields, s.Short(), s.Instance) + } + for _, f := range fields { + if strings.Contains(strings.ToLower(f), needle) { + return true + } + } + return false +} + +func (m *model) less(a, b *device) bool { + var c int + switch m.sortCol { + case colName: + c = cmpEmptyLast(strings.ToLower(m.label(a)), strings.ToLower(m.label(b))) + case colMAC: + c = bytes.Compare(a.host.MAC, b.host.MAC) + case colVendor: + c = cmpEmptyLast(strings.ToLower(a.host.VendorLabel()), strings.ToLower(b.host.VendorLabel())) + case colLastSeen: + c = b.lastSeen.Compare(a.lastSeen) + case colRTT: + ra, rb := a.host.RTT, b.host.RTT + switch { + case ra == rb: + case ra == 0 || !a.online: + c = 1 + case rb == 0 || !b.online: + c = -1 + case ra < rb: + c = -1 + default: + c = 1 + } + } + if c == 0 { + c = a.host.IP.Compare(b.host.IP) + } + if m.sortDesc { + return c > 0 + } + return c < 0 +} + +func cmpEmptyLast(a, b string) int { + switch { + case a == b: + return 0 + case a == "": + return 1 + case b == "": + return -1 + } + return strings.Compare(a, b) +} + +func (m *model) tableHeight() int { + used := 5 + 1 // header block + footer + if n := len(m.events); n > 0 { + used += 1 + min(3, n) + } + return max(1, m.h-used) +} + +func (m *model) ensureVisible() { + h := m.tableHeight() + if m.cursor < m.offset { + m.offset = m.cursor + } + if m.cursor >= m.offset+h { + m.offset = m.cursor - h + 1 + } + m.offset = max(0, min(m.offset, len(m.list)-h)) +} + +func (m *model) moveCursor(delta int) { + m.cursor = max(0, min(len(m.list)-1, m.cursor+delta)) + m.ensureVisible() +} + +// --- keys ----------------------------------------------------------------- + +func (m *model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + if msg.String() == "ctrl+c" { + m.stopAll() + return m, tea.Quit + } + if m.inputKind != inputNone { + return m.handleInput(msg) + } + switch m.mode { + case viewDetail: + return m.handleDetailKey(msg) + case viewPorts, viewPing: + return m.handleToolKey(msg) + case viewHistory: + return m.handleHistoryKey(msg) + case viewHelp: + switch msg.String() { + case "esc", "q", "?", "enter": + m.mode = viewList + case "up", "k": + m.helpOff = max(0, m.helpOff-1) + case "down", "j": + m.helpOff++ + } + return m, nil + case viewColumns: + return m.handleColumnsKey(msg) + } + + switch msg.String() { + case "q": + m.stopAll() + return m, tea.Quit + case "up", "k": + m.moveCursor(-1) + case "down", "j": + m.moveCursor(1) + case "pgup", "ctrl+b": + m.moveCursor(-m.tableHeight()) + case "pgdown", "ctrl+f": + m.moveCursor(m.tableHeight()) + case "home", "g": + m.moveCursor(-len(m.list)) + case "end", "G": + m.moveCursor(len(m.list)) + case "r": + if m.scanning { + m.setFlash("A scan is already running", false) + return m, nil + } + return m, m.startScan() + case "a": + m.auto = !m.auto + if m.auto { + m.nextScan = time.Now().Add(m.cfg.Interval) + m.setFlash(fmt.Sprintf("Auto-scan on (every %s)", m.cfg.Interval), false) + } else { + m.setFlash("Auto-scan off", false) + } + case "c": + m.cumulative = !m.cumulative + m.refresh() + m.setFlash(onOff("Cumulative mode", m.cumulative), false) + case "s": + m.sortCol = nextSortColumn(m.sortCol) + m.refresh() + case "S": + m.sortDesc = !m.sortDesc + m.refresh() + case "/": + m.startInput(inputFilter, "Filter: ", m.filter, "") + case "esc": + if m.filter != "" { + m.filter = "" + m.refresh() + } + case "W": + m.hideWhitelisted = !m.hideWhitelisted + m.refresh() + m.setFlash(onOff("Hide whitelisted devices", m.hideWhitelisted), false) + case "R": + m.startInput(inputRange, "Range: ", m.cfg.Range, "") + case "e": + m.export() + case "h": + m.mode = viewHistory + m.loadHistory() + case "v": + m.mode = viewColumns + case "?": + m.mode = viewHelp + case "enter": + if d := m.selected(); d != nil { + m.mode, m.detailKey, m.detailOff = viewDetail, d.key, 0 + } + default: + if d := m.selected(); d != nil { + return m, m.deviceAction(d, msg.String()) + } + } + return m, nil +} + +// deviceAction handles the keys that act on a single device, shared by the +// list and the detail view. +func (m *model) deviceAction(d *device, key string) tea.Cmd { + switch key { + case "n": + m.startInput(inputRename, "Name: ", m.meta[d.key].Name, d.key) + case "t": + tracked := !m.meta[d.key].Tracked + m.updateMeta(d, func(sd *store.Device) { sd.Tracked = tracked }) + if tracked { + m.setFlash(m.labelOrIP(d)+" is tracked – you get notified when it leaves or returns", false) + } else { + m.setFlash(m.labelOrIP(d)+" is no longer tracked", false) + } + case "w": + wl := !m.meta[d.key].Whitelisted + m.updateMeta(d, func(sd *store.Device) { sd.Whitelisted = wl }) + if wl { + m.setFlash(m.labelOrIP(d)+" added to the whitelist", false) + } else { + m.setFlash(m.labelOrIP(d)+" removed from the whitelist", false) + } + m.refresh() + case "p": + return m.startPorts(d, "top") + case "i": + return m.startPing(d) + case "o": + if len(d.host.MAC) == 0 { + m.setFlash("No MAC address known – Wake-on-LAN not possible", true) + } else if err := scanner.WakeOnLAN(d.host.MAC, m.cfg.Network.Broadcast()); err != nil { + m.setFlash("Wake-on-LAN failed: "+err.Error(), true) + } else { + m.setFlash("Magic packet sent to "+d.host.MAC.String(), false) + } + case "b": + url := browserURL(d) + if err := openURL(url); err != nil { + m.setFlash("Could not open browser: "+err.Error(), true) + } else { + m.setFlash("Opening "+url, false) + } + case "x": + return tea.ExecProcess(exec.Command("ssh", d.host.IP.String()), func(err error) tea.Msg { + if err != nil { + return flashMsg{"ssh: " + err.Error(), true} + } + return nil + }) + } + return nil +} + +func (m *model) labelOrIP(d *device) string { + if l := m.label(d); l != "" { + return l + } + return d.host.IP.String() +} + +func (m *model) updateMeta(d *device, fn func(*store.Device)) { + err := m.cfg.Store.Update(d.key, func(sd *store.Device) { + sd.IP = d.host.IP.String() + if len(d.host.MAC) > 0 { + sd.MAC = d.host.MAC.String() + } + fn(sd) + }) + if err != nil { + m.setFlash("Saving failed: "+err.Error(), true) + } + m.reloadMeta() +} + +func (m *model) handleDetailKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + d := m.devs[m.detailKey] + if d == nil { + m.mode = viewList + return m, nil + } + switch k := msg.String(); k { + case "esc", "q", "enter", "backspace": + m.mode = viewList + case "up", "k": + m.detailOff = max(0, m.detailOff-1) + case "down", "j": + m.detailOff++ + default: + return m, m.deviceAction(d, k) + } + return m, nil +} + +func (m *model) handleColumnsKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "esc", "q", "v", "enter": + m.mode = viewList + case "up", "k": + m.colCursor = max(0, m.colCursor-1) + case "down", "j": + m.colCursor = min(int(numCols)-1, m.colCursor+1) + case " ", "x": + m.cols[m.colCursor] = !m.cols[m.colCursor] + } + return m, nil +} + +func (m *model) startInput(kind inputKind, prompt, value, key string) { + m.inputKind, m.inputKey = kind, key + m.input.Prompt = prompt + m.input.SetValue(value) + m.input.CursorEnd() + m.input.Focus() +} + +func (m *model) handleInput(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + kind := m.inputKind + switch msg.String() { + case "esc": + m.inputKind = inputNone + if kind == inputFilter { + m.filter = "" + m.refresh() + } + return m, nil + case "enter": + m.inputKind = inputNone + return m, m.commitInput(kind, strings.TrimSpace(m.input.Value())) + } + var cmd tea.Cmd + m.input, cmd = m.input.Update(msg) + if kind == inputFilter { + m.filter = m.input.Value() + m.refresh() + } + return m, cmd +} + +func (m *model) commitInput(kind inputKind, value string) tea.Cmd { + switch kind { + case inputFilter: + m.filter = value + m.refresh() + case inputRename: + if d := m.devs[m.inputKey]; d != nil { + m.updateMeta(d, func(sd *store.Device) { sd.Name = value }) + m.refresh() + } + case inputRange: + if value == "" || value == m.cfg.Range { + return nil + } + targets, err := scanner.ParseRange(value) + if err != nil { + m.setFlash(err.Error(), true) + return nil + } + m.setTargets(value, targets) + m.setFlash(fmt.Sprintf("New range %s (%s)", value, plural(len(targets), "address", "addresses")), false) + if m.scanning { + m.pendingRescan = true + m.scanCancel() + return nil + } + return m.startScan() + } + return nil +} + +func (m *model) export() { + recs := make([]export.Record, 0, len(m.list)) + for _, d := range m.list { + meta := m.meta[d.key] + r := export.FromHost(d.host) + r.Name = m.label(d) + r.Online = d.online + r.OpenPorts = d.ports + r.Tracked, r.Whitelisted = meta.Tracked, meta.Whitelisted + r.FirstSeen, r.LastSeen = meta.FirstSeen, d.lastSeen + recs = append(recs, r) + } + paths, err := export.Files(m.cfg.ExportDir, recs, time.Now()) + if err != nil { + m.setFlash("Export failed: "+err.Error(), true) + return + } + m.setFlash(fmt.Sprintf("Exported %s: %s", plural(len(recs), "device", "devices"), strings.Join(paths, ", ")), false) +} + +func (m *model) stopAll() { + if m.scanCancel != nil { + m.scanCancel() + } + m.stopTools() +} + +func onOff(what string, on bool) string { + if on { + return what + ": on" + } + return what + ": off" +} + +func browserURL(d *device) string { + ip := d.host.IP.String() + for _, s := range d.host.Services { + switch s.Type { + case "_https._tcp": + return fmt.Sprintf("https://%s:%d/", ip, s.Port) + case "_http._tcp": + if s.Port == 80 { + return "http://" + ip + "/" + } + return fmt.Sprintf("http://%s:%d/", ip, s.Port) + } + } + for _, p := range d.ports { + if p.Port == 443 { + return "https://" + ip + "/" + } + } + return "http://" + ip + "/" +} + +func openURL(url string) error { + var cmd *exec.Cmd + switch runtime.GOOS { + case "darwin": + cmd = exec.Command("open", url) + case "windows": + cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url) + default: + cmd = exec.Command("xdg-open", url) + } + return cmd.Start() +} diff --git a/internal/tui/model_test.go b/internal/tui/model_test.go new file mode 100644 index 0000000..7534bde --- /dev/null +++ b/internal/tui/model_test.go @@ -0,0 +1,179 @@ +package tui + +import ( + "net" + "net/netip" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + + "nscan/internal/oui" + "nscan/internal/scanner" + "nscan/internal/store" +) + +func testModel(t *testing.T) *model { + t.Helper() + st, err := store.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + targets, _ := scanner.ParseRange("192.168.1.0/24") + return newModel(Config{ + Network: &scanner.Network{ + Iface: &net.Interface{Name: "en0"}, + LocalIP: netip.MustParseAddr("192.168.1.10"), + Prefix: netip.MustParsePrefix("192.168.1.10/24"), + Gateway: netip.MustParseAddr("192.168.1.1"), + }, + Range: "192.168.1.0/24", + Targets: targets, + Interval: time.Minute, + Store: st, + }) +} + +func host(ip, mac string) scanner.Host { + h := scanner.Host{IP: netip.MustParseAddr(ip), RTT: 2 * time.Millisecond, Via: "icmp"} + if mac != "" { + h.MAC, _ = net.ParseMAC(mac) + } + return h +} + +func TestUpsertRekeysByMAC(t *testing.T) { + m := testModel(t) + m.upsert(host("192.168.1.20", "")) + if m.devs["ip:192.168.1.20"] == nil { + t.Fatal("ip-keyed row missing") + } + m.upsert(host("192.168.1.20", "aa:bb:cc:00:00:01")) + if m.devs["ip:192.168.1.20"] != nil || m.devs["aa:bb:cc:00:00:01"] == nil || len(m.devs) != 1 { + t.Fatalf("rows after MAC arrived: %v", keys(m)) + } + // A later ICMP-only result for the same IP lands on the MAC row. + m.upsert(scanner.Host{IP: netip.MustParseAddr("192.168.1.20"), MDNSName: "nas"}) + if len(m.devs) != 1 || m.devs["aa:bb:cc:00:00:01"].host.MDNSName != "nas" { + t.Fatalf("rows: %v", keys(m)) + } +} + +func keys(m *model) []string { + var ks []string + for k := range m.devs { + ks = append(ks, k) + } + return ks +} + +func TestScanCycleAndViews(t *testing.T) { + m := testModel(t) + m.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) + m.scanning, m.scanNo = true, 1 + hosts := []scanner.Host{ + host("192.168.1.1", "3c:a6:2f:00:00:01"), + host("192.168.1.10", "f0:18:9b:00:00:02"), + host("192.168.1.33", "b8:27:eb:00:00:03"), + } + hosts[0].Gateway = true + hosts[1].Self = true + hosts[2].MDNSName = "raspberrypi" + hosts[2].Services = []scanner.Service{{Type: "_ssh._tcp", Instance: "raspberrypi", Port: 22}} + for _, h := range hosts { + m.Update(scanHostMsg{1, h}) + } + m.Update(scanDoneMsg{no: 1, hosts: hosts, dur: time.Second}) + if len(m.list) != 3 { + t.Fatalf("list has %d rows", len(m.list)) + } + + // Second scan without the Pi: it goes offline and leaves the plain list. + m.scanning, m.scanNo = true, 2 + m.Update(scanDoneMsg{no: 2, hosts: hosts[:2], dur: time.Second}) + if len(m.list) != 2 { + t.Fatalf("list has %d rows after the Pi vanished", len(m.list)) + } + m.Update(key("c")) + if len(m.list) != 3 { + t.Fatalf("cumulative list has %d rows", len(m.list)) + } + + press := func(keys ...string) { + for _, k := range keys { + m.Update(key(k)) + } + } + for _, size := range [][2]int{{120, 30}, {80, 24}, {40, 12}, {200, 60}} { + m.Update(tea.WindowSizeMsg{Width: size[0], Height: size[1]}) + check := func(view string) { + t.Helper() + out := m.View() + lines := strings.Split(out, "\n") + for i, l := range lines { + if w := ansi.StringWidth(l); w > size[0] { + t.Errorf("%s at %dx%d: line %d is %d wide", view, size[0], size[1], i, w) + } + } + if len(lines) > size[1] { + t.Errorf("%s at %dx%d: %d lines", view, size[0], size[1], len(lines)) + } + } + check("list") + press("enter") + check("detail") + press("esc", "h") + check("history") + press("z") + check("history daily") + press("esc", "?") + check("help") + press("esc", "v") + check("columns") + press("esc") + } + + // Rename via the input line. + m.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) + press("home", "n") + for _, r := range "Router" { + m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}}) + } + m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + sel := m.selected() + if got := m.label(sel); !strings.HasPrefix(got, "Router") { + t.Errorf("label after rename = %q", got) + } + if !strings.Contains(m.View(), "Router") { + t.Error("renamed device not shown") + } +} + +func key(s string) tea.KeyMsg { + switch s { + case "enter": + return tea.KeyMsg{Type: tea.KeyEnter} + case "esc": + return tea.KeyMsg{Type: tea.KeyEsc} + case "home": + return tea.KeyMsg{Type: tea.KeyHome} + } + return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} +} + +func TestStoredDevicesGetVendor(t *testing.T) { + m := testModel(t) + m.cfg.Store.Update("da:a1:19:00:00:01", func(d *store.Device) { + d.IP, d.MAC, d.Vendor = "192.168.1.50", "da:a1:19:00:00:01", "Private Adresse" + }) + m.setTargets(m.cfg.Range, m.cfg.Targets) + if got := m.devs["da:a1:19:00:00:01"].host.Vendor; got != oui.Private { + t.Errorf("vendor of stored device = %q, want %q", got, oui.Private) + } + m.Update(tea.WindowSizeMsg{Width: 140, Height: 30}) + if !strings.Contains(m.View(), "Vendor database missing") { + t.Error("no hint about the missing vendor database") + } +} diff --git a/internal/tui/theme.go b/internal/tui/theme.go new file mode 100644 index 0000000..4f0575b --- /dev/null +++ b/internal/tui/theme.go @@ -0,0 +1,81 @@ +package tui + +import ( + "strings" + + "github.com/charmbracelet/lipgloss" +) + +// The mwxcol palette (https://git.micw.org/mike/mwxcol). It defines no +// background, so nscan draws on the terminal's own and uses darker where a +// surface is needed, as the palette's fzf and atuin themes do. Plain text +// keeps the terminal's foreground, which the mwxcol terminal profiles set to +// white. +var ( + mwxWhite = lipgloss.Color("#F0F0EA") // normal text + mwxYellow = lipgloss.Color("#F9E2AF") // change, warning + mwxRed = lipgloss.Color("#F38BA8") // error, removal + mwxGreen = lipgloss.Color("#94E2D5") // new, ok + mwxBlue = lipgloss.Color("#B4BEFE") // structure, dates, keys + mwxPink = lipgloss.Color("#F5B2F7") // matches + mwxViolet = lipgloss.Color("#CBA6F7") // accent, pointer + mwxGrey = lipgloss.Color("#AAAABB") // secondary text + mwxDark = lipgloss.Color("#777788") // disabled, offline + mwxDarker = lipgloss.Color("#444455") // separators, selection background + mwxSurface = lipgloss.Color("#2E2E35") // darker at 30% over the terminal background +) + +func fg(c lipgloss.Color) lipgloss.Style { return lipgloss.NewStyle().Foreground(c) } + +var ( + styleText = fg(mwxWhite) + styleBold = styleText.Bold(true) + styleDim = fg(mwxGrey) // labels, secondary text + styleMuted = fg(mwxDark) // offline devices, hints + styleRule = fg(mwxDarker) // separators, empty bar segments + styleHeader = fg(mwxBlue).Bold(true) + styleKey = fg(mwxBlue).Bold(true) + styleTime = fg(mwxBlue) + styleOnline = fg(mwxGreen) + styleNew = fg(mwxGreen).Bold(true) + styleGone = fg(mwxRed) + styleTracked = fg(mwxYellow) + styleWarn = fg(mwxYellow) + styleInfo = fg(mwxGreen) + styleErr = fg(mwxRed).Bold(true) + styleMatch = fg(mwxPink) + styleService = fg(mwxViolet) + styleAccent = fg(mwxViolet) + + styleBar = fg(mwxWhite).Background(mwxSurface) + styleBarName = fg(mwxViolet).Background(mwxSurface).Bold(true) + styleBarDim = fg(mwxGrey).Background(mwxSurface) + + // The selected row looks like fzf's current line: white on darker with a + // violet pointer. + styleSel = fg(mwxWhite).Background(mwxDarker) + styleSelPtr = fg(mwxViolet).Background(mwxDarker).Bold(true) +) + +// onSel puts s on the selection background. +func onSel(s lipgloss.Style) lipgloss.Style { return s.Background(mwxDarker) } + +// cellStyle colors the table cells of online devices; offline rows are muted. +var cellStyle = [numCols]lipgloss.Style{ + colName: styleText, + colIP: styleText, + colMAC: styleDim, + colVendor: styleDim, + colLastSeen: styleTime, + colRTT: styleDim, + colServices: styleService, +} + +// progressBar draws a bar of width w with done of total filled. +func progressBar(done, total, w int) string { + filled := 0 + if total > 0 { + filled = min(w, w*done/total) + } + return styleAccent.Render(strings.Repeat("█", max(0, filled))) + styleRule.Render(strings.Repeat("░", max(0, w-filled))) +} diff --git a/internal/tui/tools.go b/internal/tui/tools.go new file mode 100644 index 0000000..6dcbde6 --- /dev/null +++ b/internal/tui/tools.go @@ -0,0 +1,346 @@ +package tui + +import ( + "context" + "fmt" + "net/netip" + "sort" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" + + "nscan/internal/scanner" +) + +type portState struct { + id int + key string + ip netip.Addr + label string + spec string + cancel context.CancelFunc + running bool + done int + total int + open []scanner.PortResult + started time.Time + dur time.Duration + offset int +} + +type pingState struct { + id int + ip netip.Addr + label string + cancel context.CancelFunc + running bool + results []scanner.PingResult + sent int + recv int + min time.Duration + max time.Duration + sum time.Duration + method string + err error +} + +type portOpenMsg struct { + id int + r scanner.PortResult +} + +type portProgressMsg struct{ id, done, total int } + +type portDoneMsg struct{ id int } + +type pingMsg struct { + id int + r scanner.PingResult +} + +type pingDoneMsg struct { + id int + err error +} + +var portSpecs = map[string]string{ + "top": "well-known ports", + "1-1024": "ports 1–1024", + "1-65535": "all ports", +} + +func (m *model) stopTools() { + if m.ports != nil && m.ports.cancel != nil { + m.ports.cancel() + } + if m.ping != nil && m.ping.cancel != nil { + m.ping.cancel() + } +} + +func (m *model) startPorts(d *device, spec string) tea.Cmd { + ports, err := scanner.ParsePorts(spec) + if err != nil { + m.setFlash(err.Error(), true) + return nil + } + m.stopTools() + m.toolID++ + id := m.toolID + ctx, cancel := context.WithCancel(context.Background()) + m.rememberReturn() + m.ports = &portState{ + id: id, key: d.key, ip: d.host.IP, label: m.labelOrIP(d), spec: spec, + cancel: cancel, running: true, total: len(ports), started: time.Now(), + } + m.mode = viewPorts + ch := make(chan tea.Msg, 64) + go func() { + scanner.ScanPorts(ctx, d.host.IP, ports, 800*time.Millisecond, 200, + func(r scanner.PortResult) { ch <- portOpenMsg{id, r} }, + func(done, total int) { + select { + case ch <- portProgressMsg{id, done, total}: + default: + } + }) + ch <- portDoneMsg{id} + close(ch) + }() + return pump(ch) +} + +func (m *model) startPing(d *device) tea.Cmd { + m.stopTools() + m.toolID++ + id := m.toolID + ctx, cancel := context.WithCancel(context.Background()) + m.rememberReturn() + m.ping = &pingState{id: id, ip: d.host.IP, label: m.labelOrIP(d), cancel: cancel, running: true} + m.mode = viewPing + ch := make(chan tea.Msg, 16) + ip := d.host.IP + go func() { + err := scanner.Ping(ctx, ip, 0, time.Second, 2*time.Second, func(r scanner.PingResult) { ch <- pingMsg{id, r} }) + ch <- pingDoneMsg{id, err} + close(ch) + }() + return pump(ch) +} + +// rememberReturn notes the view esc goes back to from a tool view. +func (m *model) rememberReturn() { + if m.mode != viewPorts && m.mode != viewPing { + m.toolReturn = m.mode + } +} + +func (m *model) updateTools(msg tea.Msg) { + switch msg := msg.(type) { + case portOpenMsg: + if p := m.ports; p != nil && p.id == msg.id { + p.open = append(p.open, msg.r) + sort.Slice(p.open, func(i, j int) bool { return p.open[i].Port < p.open[j].Port }) + } + case portProgressMsg: + if p := m.ports; p != nil && p.id == msg.id { + p.done, p.total = msg.done, msg.total + } + case portDoneMsg: + if p := m.ports; p != nil && p.id == msg.id { + p.running, p.dur = false, time.Since(p.started) + // Only a complete scan replaces what the detail view shows. + if p.done == p.total { + if d := m.devs[p.key]; d != nil { + d.ports, d.portsAt = p.open, time.Now() + } + } + } + case pingMsg: + if p := m.ping; p != nil && p.id == msg.id { + r := msg.r + p.method = r.Method + p.sent++ + if !r.Timeout && r.Err == nil { + p.recv++ + p.sum += r.RTT + if p.min == 0 || r.RTT < p.min { + p.min = r.RTT + } + p.max = max(p.max, r.RTT) + } + p.results = append(p.results, r) + if len(p.results) > 500 { + p.results = p.results[len(p.results)-500:] + } + } + case pingDoneMsg: + if p := m.ping; p != nil && p.id == msg.id { + p.running, p.err = false, msg.err + } + } +} + +func (m *model) handleToolKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch k := msg.String(); k { + case "esc", "q", "backspace": + m.stopTools() + m.mode = m.toolReturn + if m.mode == viewDetail && m.devs[m.detailKey] == nil { + m.mode = viewList + } + case "up", "k": + if m.ports != nil { + m.ports.offset = max(0, m.ports.offset-1) + } + case "down", "j": + if m.ports != nil { + m.ports.offset++ + } + case "1", "2", "3", "r": + if m.mode != viewPorts || m.ports == nil { + if k == "r" && m.ping != nil { + if d := m.deviceByIP(m.ping.ip); d != nil { + return m, m.startPing(d) + } + } + return m, nil + } + spec := map[string]string{"1": "top", "2": "1-1024", "3": "1-65535", "r": m.ports.spec}[k] + if d := m.devs[m.ports.key]; d != nil { + return m, m.startPorts(d, spec) + } + case " ": + if m.mode == viewPing && m.ping != nil { + if m.ping.running { + m.ping.cancel() + } else if d := m.deviceByIP(m.ping.ip); d != nil { + return m, m.startPing(d) + } + } + } + return m, nil +} + +func (m *model) deviceByIP(ip netip.Addr) *device { + for _, d := range m.devs { + if d.host.IP == ip { + return d + } + } + return nil +} + +func (m *model) viewPorts() string { + p := m.ports + if p == nil { + return "" + } + lines := []string{m.titleBar(""), "", + " " + styleBold.Render(fmt.Sprintf("Port scan %s", p.label)) + styleDim.Render(fmt.Sprintf(" %s · %s (%d)", p.ip, portSpecs[p.spec], p.total)), ""} + if p.running { + lines = append(lines, fmt.Sprintf(" %s %s %s %s", progressBar(p.done, p.total, max(10, min(50, m.w-30))), + styleDim.Render(fmt.Sprintf("%d/%d", p.done, p.total)), styleOnline.Render(fmt.Sprint(len(p.open))), styleDim.Render("open"))) + } else { + state := "finished" + if p.done < p.total { + state = "cancelled" + } + lines = append(lines, styleDim.Render(fmt.Sprintf(" Scan %s after %.1fs – %d of %d ports checked", state, p.dur.Seconds(), p.done, p.total))+ + " "+styleOnline.Render(fmt.Sprintf("%d open", len(p.open)))) + } + lines = append(lines, "", styleHeader.Render(" "+fit("Port", 12)+fit("Service", 18)+"Response time")) + avail := max(1, m.h-len(lines)-1) + p.offset = min(p.offset, max(0, len(p.open)-avail)) + for _, r := range p.open[p.offset:min(len(p.open), p.offset+avail)] { + lines = append(lines, " "+styleOnline.Render(fit(fmt.Sprintf("%d/tcp", r.Port), 12))+fit(orDash(r.Service), 18)+styleDim.Render(formatRTT(r.RTT))) + } + if len(p.open) == 0 && !p.running { + lines = append(lines, styleMuted.Render(" no open ports found")) + } + return m.screen(lines, m.footer("1 well-known", "2 1–1024", "3 all", "r repeat", "esc back")) +} + +const sparkBlocks = "▁▂▃▄▅▆▇█" + +func (m *model) viewPing() string { + p := m.ping + if p == nil { + return "" + } + lines := []string{m.titleBar(""), "", " " + styleBold.Render("Ping "+p.label) + styleDim.Render(" "+p.ip.String()+" "+p.method), ""} + + loss := 0.0 + if p.sent > 0 { + loss = 100 * float64(p.sent-p.recv) / float64(p.sent) + } + lossStyle := styleOnline + if p.recv < p.sent { + lossStyle = styleWarn + } + stats := styleDim.Render(" sent ") + fmt.Sprint(p.sent) + styleDim.Render(" · received ") + fmt.Sprint(p.recv) + + styleDim.Render(" · loss ") + lossStyle.Render(fmt.Sprintf("%.0f%%", loss)) + if p.recv > 0 { + stats += styleDim.Render(" · min/avg/max ") + fmt.Sprintf("%s / %s / %s", formatRTT(p.min), formatRTT(p.sum/time.Duration(p.recv)), formatRTT(p.max)) + } + lines = append(lines, stats, "", " "+m.sparkline(max(10, m.w-2)), "") + + if p.err != nil { + lines = append(lines, styleErr.Render(" "+p.err.Error())) + } + avail := max(1, m.h-len(lines)-1) + start := max(0, len(p.results)-avail) + for _, r := range p.results[start:] { + switch { + case r.Err != nil: + lines = append(lines, styleErr.Render(fmt.Sprintf(" seq=%d error: %v", r.Seq, r.Err))) + case r.Timeout: + lines = append(lines, styleWarn.Render(fmt.Sprintf(" seq=%d timeout", r.Seq))) + default: + lines = append(lines, styleDim.Render(" reply from ")+p.ip.String()+styleDim.Render(fmt.Sprintf(": seq=%d time=", r.Seq))+styleOnline.Render(formatRTT(r.RTT))) + } + } + for len(lines) < m.h-1 { + lines = append(lines, "") + } + toggle := "space pause" + if !p.running { + toggle = "space resume" + } + lines = append(lines, m.footer(toggle, "esc back")) + return m.clipLines(lines) +} + +// sparkline draws the most recent round-trip times; lost packets show as ×. +func (m *model) sparkline(width int) string { + p := m.ping + rs := p.results[max(0, len(p.results)-width):] + if len(rs) == 0 { + return styleMuted.Render("waiting for replies …") + } + var lo, hi time.Duration + for _, r := range rs { + if r.Timeout || r.Err != nil { + continue + } + if lo == 0 || r.RTT < lo { + lo = r.RTT + } + hi = max(hi, r.RTT) + } + blocks := []rune(sparkBlocks) + var b strings.Builder + for _, r := range rs { + if r.Timeout || r.Err != nil { + b.WriteString(styleGone.Render("×")) + continue + } + level := 0 + if hi > lo { + level = int(float64(r.RTT-lo) / float64(hi-lo) * float64(len(blocks)-1)) + } + b.WriteString(styleOnline.Render(string(blocks[level]))) + } + return b.String() +} diff --git a/internal/tui/view.go b/internal/tui/view.go new file mode 100644 index 0000000..576e16f --- /dev/null +++ b/internal/tui/view.go @@ -0,0 +1,607 @@ +package tui + +import ( + "fmt" + "slices" + "strings" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "github.com/mattn/go-runewidth" + + "nscan/internal/scanner" + "nscan/internal/store" +) + +type column int + +const ( + colName column = iota + colIP + colMAC + colVendor + colLastSeen + colRTT + colServices + numCols +) + +var colTitles = [numCols]string{"Name", "IP address", "MAC address", "Vendor", "Last seen", "Ping", "Services"} + +// Fixed-width columns; the others share the remaining space by weight. +var ( + colFixed = map[column]int{colIP: 15, colMAC: 17, colLastSeen: 10, colRTT: 8} + colMin = map[column]int{colName: 14, colVendor: 10, colServices: 10} + colWeight = map[column]int{colName: 5, colVendor: 3, colServices: 3} +) + +var sortOrder = []column{colName, colIP, colMAC, colVendor, colLastSeen, colRTT} + +func nextSortColumn(c column) column { + i := slices.Index(sortOrder, c) + return sortOrder[(i+1)%len(sortOrder)] +} + +const rowPrefix = 6 // "▸ ●⚑✓ " + +func (m *model) layout() ([]column, []int) { + var cols []column + for c := range numCols { + if m.cols[c] { + cols = append(cols, c) + } + } + avail := m.w - rowPrefix - 2*max(0, len(cols)-1) + fixed, weights := 0, 0 + for _, c := range cols { + if w, ok := colFixed[c]; ok { + fixed += w + } else { + weights += colWeight[c] + } + } + flex := max(0, avail-fixed) + widths := make([]int, len(cols)) + lastFlex, used := -1, 0 + for i, c := range cols { + if w, ok := colFixed[c]; ok { + widths[i] = w + continue + } + widths[i] = max(colMin[c], flex*colWeight[c]/weights) + used += widths[i] + lastFlex = i + } + if lastFlex >= 0 && used < flex { + widths[lastFlex] += flex - used + } + return cols, widths +} + +// fit truncates or pads s to exactly w cells. +func fit(s string, w int) string { + if w <= 0 { + return "" + } + return runewidth.FillRight(runewidth.Truncate(s, w, "…"), w) +} + +// padLines truncates or pads lines to exactly n entries. +func padLines(lines []string, n int) []string { + n = max(0, n) + if len(lines) > n { + return lines[:n] + } + for len(lines) < n { + lines = append(lines, "") + } + return lines +} + +// screen fills the terminal: body lines on top, the footer on the last line. +func (m *model) screen(body []string, footer string) string { + return m.clipLines(append(padLines(body, m.h-1), footer)) +} + +// clipLines cuts every line to the terminal width. +func (m *model) clipLines(lines []string) string { + for i, l := range lines { + lines[i] = ansi.Truncate(l, m.w, "") + } + return strings.Join(lines, "\n") +} + +func (m *model) View() string { + if m.w == 0 { + return "" + } + switch m.mode { + case viewDetail: + return m.viewDetail() + case viewPorts: + return m.viewPorts() + case viewPing: + return m.viewPing() + case viewHistory: + return m.viewHistory() + case viewHelp: + return m.viewHelp() + case viewColumns: + return m.viewColumns() + } + return m.viewList() +} + +// --- list ----------------------------------------------------------------- + +func (m *model) titleBar(right string) string { + n := m.cfg.Network + left := styleBarName.Render(" nscan ") + if m.cfg.Version != "" { + left += styleBarDim.Render(m.cfg.Version + " ") + } + left += styleBar.Render(" ") + info := fmt.Sprintf("%s · %s", n.Iface.Name, m.cfg.Range) + if n.Gateway.IsValid() { + info += " · Gateway " + n.Gateway.String() + } + info += " · This host " + n.LocalIP.String() + if right != "" { + info += " " + right + } + return left + styleBar.Render(fit(info, max(0, m.w-lipgloss.Width(left)))) +} + +func (m *model) viewList() string { + now := time.Now() + lines := []string{m.titleBar("")} + + online, offline := 0, 0 + for _, d := range m.devs { + if d.online { + online++ + } else { + offline++ + } + } + status := styleOnline.Render("●") + fmt.Sprintf(" %d online ", online) + + styleMuted.Render("○") + fmt.Sprintf(" %d offline", offline) + arrow := "↑" + if m.sortDesc { + arrow = "↓" + } + status += styleDim.Render(" Sort: ") + colTitles[m.sortCol] + " " + arrow + if m.auto { + next := "" + if !m.scanning && !m.nextScan.IsZero() { + next = fmt.Sprintf(" (in %ds)", max(0, int(time.Until(m.nextScan).Seconds()+0.5))) + } + status += styleDim.Render(" Auto-scan: ") + "every " + shortDuration(m.cfg.Interval) + next + } else { + status += styleDim.Render(" Auto-scan: ") + "off" + } + if m.cumulative { + status += " " + styleWarn.Render("[Cumulative]") + } + if m.hideWhitelisted { + status += " " + styleWarn.Render("[Whitelist hidden]") + } + if m.filter != "" { + status += " " + styleMatch.Render("[Filter: "+m.filter+"]") + } + lines = append(lines, " "+status, " "+m.scanStatus(now), "") + + cols, widths := m.layout() + header := strings.Repeat(" ", rowPrefix) + for i, c := range cols { + title := colTitles[c] + if c == m.sortCol { + title += " " + arrow + } + if i > 0 { + header += " " + } + header += fit(title, widths[i]) + } + lines = append(lines, styleHeader.Render(header)) + + th := m.tableHeight() + switch { + case len(m.list) == 0 && m.scanning: + lines = append(lines, styleDim.Render(" Looking for devices …")) + case len(m.list) == 0 && m.filter != "": + lines = append(lines, styleDim.Render(" No device matches the filter (esc clears it)")) + case len(m.list) == 0: + lines = append(lines, styleDim.Render(" No devices found")) + } + for i := m.offset; i < len(m.list) && i < m.offset+th; i++ { + lines = append(lines, m.renderRow(m.list[i], cols, widths, i == m.cursor, now)) + } + for len(lines) < 5+th { + lines = append(lines, "") + } + + if len(m.events) > 0 { + lines = append(lines, styleRule.Render("─ ")+styleDim.Render("Events ")+styleRule.Render(strings.Repeat("─", max(0, m.w-10)))) + for _, e := range m.events[max(0, len(m.events)-3):] { + lines = append(lines, " "+renderEvent(e, true)) + } + } + return m.screen(lines, m.footer("r scan", "enter details", "p ports", "i ping", "o WoL", "n name", + "t track", "w whitelist", "c cumulative", "h history", "/ filter", "? help", "q quit")) +} + +func (m *model) scanStatus(now time.Time) string { + if m.scanning { + p := m.progress + text := styleDim.Render("Scanning … " + p.Phase) + if p.Total > 0 { + return fmt.Sprintf("%s %s %s", progressBar(p.Done, p.Total, 24), text, styleDim.Render(fmt.Sprintf("%d/%d", p.Done, p.Total))) + } + return styleAccent.Render(spinner(now)) + " " + text + } + status := styleDim.Render("No scan yet") + if !m.lastScan.IsZero() { + status = styleDim.Render(fmt.Sprintf("Last scan %s (%.1fs, %s)", + m.lastScan.Format("15:04:05"), m.lastDur.Seconds(), plural(len(m.cfg.Targets), "address", "addresses"))) + } + if m.cfg.OUI.Len() == 0 { + status += styleWarn.Render(" Vendor database missing – run: nscan oui update") + } + return status +} + +func spinner(now time.Time) string { + frames := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"} + return frames[now.UnixMilli()/100%int64(len(frames))] +} + +func (m *model) renderRow(d *device, cols []column, widths []int, selected bool, now time.Time) string { + meta := m.meta[d.key] + dot, dotStyle := "●", styleOnline + if !d.online { + dot, dotStyle = "○", styleMuted + } + flag, wl := " ", " " + if meta.Tracked { + flag = "⚑" + } + if meta.Whitelisted { + wl = "✓" + } + cells := make([]string, len(cols)) + for i, c := range cols { + cells[i] = fit(m.cellText(d, c, now), widths[i]) + } + if selected { + rest := fit(" "+strings.Join(cells, " "), max(0, m.w-5)) + return styleSelPtr.Render("▸ ") + onSel(dotStyle).Render(dot) + onSel(styleTracked).Render(flag) + + onSel(styleMuted).Render(wl) + styleSel.Render(rest) + } + var b strings.Builder + b.WriteString(" " + dotStyle.Render(dot) + styleTracked.Render(flag) + styleMuted.Render(wl) + " ") + for i, c := range cols { + if i > 0 { + b.WriteString(" ") + } + style := cellStyle[c] + if !d.online { + style = styleMuted + } + b.WriteString(style.Render(cells[i])) + } + return b.String() +} + +func (m *model) cellText(d *device, c column, now time.Time) string { + h := &d.host + switch c { + case colName: + name := m.label(d) + if name == "" { + name = "–" + } + switch { + case h.Self: + name += " (me)" + case h.Gateway: + name += " (Gateway)" + } + return name + case colIP: + return h.IP.String() + case colMAC: + if len(h.MAC) == 0 { + return "–" + } + return h.MAC.String() + case colVendor: + return orDash(h.VendorLabel()) + case colLastSeen: + if d.online { + return "now" + } + return ago(d.lastSeen, now) + case colRTT: + if !d.online || h.RTT <= 0 { + return "–" + } + return formatRTT(h.RTT) + case colServices: + return serviceSummary(h.Services) + } + return "" +} + +func serviceSummary(svcs []scanner.Service) string { + var names []string + for _, s := range svcs { + if n := s.Short(); !slices.Contains(names, n) { + names = append(names, n) + } + } + return strings.Join(names, ", ") +} + +func (m *model) footer(hints ...string) string { + if m.inputKind != inputNone { + return " " + m.input.View() + styleMuted.Render(" enter apply · esc cancel") + } + if m.flash != "" && time.Since(m.flashAt) < 6*time.Second { + if m.flashErr { + return " " + styleErr.Render(m.flash) + } + return " " + styleInfo.Render(m.flash) + } + var b strings.Builder + b.WriteString(" ") + for i, h := range hints { + key, label, _ := strings.Cut(h, " ") + if i > 0 { + b.WriteString(styleMuted.Render(" · ")) + } + b.WriteString(styleKey.Render(key) + " " + styleDim.Render(label)) + } + return b.String() +} + +func renderEvent(e store.Event, withTime bool) string { + label := e.Label + if label == "" { + label = e.IP + } + var sym, text string + var style lipgloss.Style + switch e.Kind { + case store.EventNew: + sym, text, style = "✚", "New device: "+label, styleNew + if e.IP != "" && e.IP != label { + text += styleDim.Render(" (" + e.IP + ")") + } + case store.EventJoin: + sym, text, style = "→", label+" is back", styleOnline + case store.EventLeave: + sym, text, style = "←", label+" left the network", styleGone + default: + return "" + } + if e.Notify { + sym = "⚑" + style = styleTracked.Bold(true) + } + out := style.Render(sym) + " " + text + if withTime { + out = styleTime.Render(e.Time.Format("15:04")) + " " + out + } + return out +} + +// --- detail --------------------------------------------------------------- + +func (m *model) viewDetail() string { + d := m.devs[m.detailKey] + if d == nil { + return "" + } + now := time.Now() + meta := m.meta[d.key] + h := &d.host + title := m.labelOrIP(d) + lines := []string{m.titleBar(""), "", " " + styleBold.Render(title), " " + styleRule.Render(strings.Repeat("─", runewidth.StringWidth(title))), ""} + + kv := func(k, v string) { lines = append(lines, " "+styleDim.Render(fit(k, 18))+v) } + if d.online { + kv("Status", styleOnline.Render("● online")) + } else { + kv("Status", styleMuted.Render("○ offline")+" – last seen "+styleTime.Render(ago(d.lastSeen, now))) + } + ip := styleText.Render(h.IP.String()) + if h.Self { + ip += styleMuted.Render(" (this device)") + } else if h.Gateway { + ip += styleMuted.Render(" (Gateway)") + } + kv("IP address", ip) + switch { + case scanner.PrivateMAC(h.MAC): + kv("MAC address", h.MAC.String()+styleMuted.Render(" (private, randomized)")) + case len(h.MAC) > 0: + kv("MAC address", h.MAC.String()) + default: + kv("MAC address", "–") + } + vendor := orDash(h.Maker()) + switch { + case h.Maker() != h.Vendor: + vendor += styleMuted.Render(" (from the model)") + case h.Vendor == "" && m.cfg.OUI.Len() == 0: + vendor += styleMuted.Render(" (vendor database missing: nscan oui update)") + } + kv("Vendor", vendor) + if h.Model != "" { + kv("Model", h.Model) + } + kv("Custom name", orDash(meta.Name)+styleMuted.Render(" (n to change)")) + kv("mDNS / Bonjour", orDash(h.MDNSName)) + kv("NetBIOS", orDash(h.NetBIOSName)) + kv("DNS", orDash(h.DNSName)) + if d.online && h.RTT > 0 { + kv("Response time", formatRTT(h.RTT)+styleMuted.Render(" via "+h.Via)) + } else if h.Via != "" { + kv("Found via", h.Via) + } + if !meta.FirstSeen.IsZero() { + kv("First seen", styleTime.Render(meta.FirstSeen.Format("2006-01-02 15:04"))) + } + if !d.lastSeen.IsZero() { + kv("Last seen", styleTime.Render(d.lastSeen.Format("2006-01-02 15:04:05"))) + } + kv("Tracked", flagValue(meta.Tracked, styleTracked)+styleMuted.Render(" (t)")) + kv("Whitelist", flagValue(meta.Whitelisted, styleOnline)+styleMuted.Render(" (w)")) + + lines = append(lines, "", " "+styleHeader.Render("Bonjour services")) + if len(h.Services) == 0 { + lines = append(lines, styleMuted.Render(" none announced")) + } + for _, s := range h.Services { + lines = append(lines, " "+styleService.Render(fit(s.Type, 24))+" "+fit(s.Instance, 36)+" "+styleDim.Render(fmt.Sprintf(":%d", s.Port))) + } + + lines = append(lines, "", " "+styleHeader.Render("Open ports")) + switch { + case d.portsAt.IsZero(): + lines = append(lines, styleMuted.Render(" not scanned yet – press p for a port scan")) + case len(d.ports) == 0: + lines = append(lines, styleMuted.Render(" no open ports found (scan "+d.portsAt.Format("15:04")+")")) + default: + for _, p := range d.ports { + lines = append(lines, " "+styleOnline.Render(fit(fmt.Sprintf("%d/tcp", p.Port), 10))+" "+orDash(p.Service)) + } + } + + body := lines[1:] + avail := max(1, m.h-2) + m.detailOff = min(m.detailOff, max(0, len(body)-avail)) + body = body[m.detailOff:min(len(body), m.detailOff+avail)] + return m.screen(append([]string{lines[0]}, body...), + m.footer("esc back", "p ports", "i ping", "o WoL", "b browser", "x ssh", "n name", "t track", "w whitelist")) +} + +// --- help & columns ------------------------------------------------------- + +var helpKeys = [][2]string{ + {"↑/↓ j/k", "Select device (PgUp/PgDn, g/G)"}, + {"enter", "Device details"}, + {"r", "Scan now"}, + {"a", "Auto-scan on/off"}, + {"c", "Cumulative mode: also show devices that are gone"}, + {"s / S", "Next sort column / reverse order"}, + {"/", "Filter (name, IP, MAC, vendor, service)"}, + {"n", "Set a custom name"}, + {"t", "Track device: notify when it leaves or returns"}, + {"w / W", "Toggle whitelist / hide whitelisted devices"}, + {"p", "Port scan"}, + {"i", "Continuous ping"}, + {"o", "Wake-on-LAN (magic packet)"}, + {"b", "Open in browser"}, + {"x", "Open SSH session"}, + {"h", "History (network timeline)"}, + {"v", "Show/hide columns"}, + {"R", "Scan a different address range"}, + {"e", "Export as JSON and CSV"}, + {"q", "Quit"}, +} + +func (m *model) viewHelp() string { + lines := []string{m.titleBar(""), "", " " + styleBold.Render("Keys"), ""} + for _, k := range helpKeys { + lines = append(lines, " "+styleKey.Render(fit(k[0], 10))+" "+k[1]) + } + lines = append(lines, "", + styleDim.Render(" Symbols: ")+styleOnline.Render("●")+" online "+styleMuted.Render("○")+" offline "+ + styleTracked.Render("⚑")+" tracked "+styleMuted.Render("✓")+" Whitelist", + styleDim.Render(" Data: ")+m.cfg.Store.Dir()) + if m.cfg.Version != "" { + lines = append(lines, styleDim.Render(" Version: ")+m.cfg.Version) + } + body := lines[1:] + m.helpOff = min(m.helpOff, max(0, len(body)-(m.h-2))) + return m.screen(append([]string{lines[0]}, body[m.helpOff:]...), m.footer("↑/↓ scroll", "esc back")) +} + +func (m *model) viewColumns() string { + lines := []string{m.titleBar(""), "", " " + styleBold.Render("Columns"), ""} + for c := range numCols { + box, boxStyle := "[ ]", styleMuted + if m.cols[c] { + box, boxStyle = "[x]", styleOnline + } + if int(c) == m.colCursor { + lines = append(lines, styleSelPtr.Render("▸ ")+onSel(boxStyle).Render(box)+styleSel.Render(fit(" "+colTitles[c], 26))) + continue + } + lines = append(lines, " "+boxStyle.Render(box)+" "+colTitles[c]) + } + return m.screen(lines, m.footer("space toggle", "esc done")) +} + +// --- formatting ----------------------------------------------------------- + +// plural formats a count with the matching noun ("1 device", "3 devices"). +func plural(n int, one, many string) string { + if n == 1 { + return "1 " + one + } + return fmt.Sprintf("%d %s", n, many) +} + +func orDash(s string) string { + if s == "" { + return "–" + } + return s +} + +func flagValue(b bool, on lipgloss.Style) string { + if b { + return on.Render("yes") + } + return styleMuted.Render("no") +} + +func formatRTT(d time.Duration) string { + ms := float64(d.Microseconds()) / 1000 + switch { + case ms < 10: + return fmt.Sprintf("%.2f ms", ms) + case ms < 100: + return fmt.Sprintf("%.1f ms", ms) + } + return fmt.Sprintf("%.0f ms", ms) +} + +func ago(t, now time.Time) string { + if t.IsZero() { + return "–" + } + d := now.Sub(t) + switch { + case d < time.Minute: + return "<1 min ago" + case d < time.Hour: + return fmt.Sprintf("%d min ago", int(d.Minutes())) + case d < 24*time.Hour: + return fmt.Sprintf("%d h ago", int(d.Hours())) + case d < 7*24*time.Hour: + return fmt.Sprintf("%d days ago", int(d.Hours()/24)) + } + return t.Format("2006-01-02") +} + +func shortDuration(d time.Duration) string { + if d%time.Minute == 0 { + return fmt.Sprintf("%d min", int(d.Minutes())) + } + return fmt.Sprintf("%ds", int(d.Seconds())) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..1e851d6 --- /dev/null +++ b/main.go @@ -0,0 +1,522 @@ +// Command nscan is a terminal network scanner: it lists the devices on the +// local network with name, IP, MAC, vendor and Bonjour services, and offers +// ping, port scan, Wake-on-LAN, device tracking and a change history. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "io/fs" + "net" + "net/netip" + "os" + "os/signal" + "path/filepath" + "strings" + "text/tabwriter" + "time" + + "nscan/internal/export" + "nscan/internal/oui" + "nscan/internal/scanner" + "nscan/internal/store" + "nscan/internal/tui" +) + +const usage = `Usage: + nscan [options] interactive interface (default) + nscan scan [options] scan once and print a table + nscan ping [-c N] ping (ICMP, falls back to TCP without permission) + nscan ports [-p top] TCP port scan + nscan wol send a Wake-on-LAN magic packet + nscan interfaces list network interfaces + nscan oui update download the vendor database from the IEEE + nscan oui import import oui.csv/oui.txt manually + nscan oui lookup show the vendor of a MAC address + nscan version print the version + +Options for the interface and "scan": + -i interface (default: the one with the default route) + -r address range, e.g. 192.168.1.0/24, 10.0.0.10-50 + -wait how long to wait for late replies (default 1.5s) + -no-names skip name resolution (mDNS, NetBIOS, DNS) + -no-bonjour skip Bonjour service discovery + -interval auto-scan interval of the interface, 0 = off (default 1m) + -export-dir export directory (key e, default: current directory) + -json / -csv output format of "scan" +` + +func main() { + if err := run(os.Args[1:]); err != nil { + if !errors.Is(err, flag.ErrHelp) { + fmt.Fprintln(os.Stderr, "nscan:", err) + } + os.Exit(1) + } +} + +func printUsage(w io.Writer) { + fmt.Fprintf(w, "nscan %s – network scanner for the terminal\n\n%s", Version, usage) +} + +func run(args []string) error { + cmd := "" + if len(args) > 0 { + switch args[0] { + case "-v", "-version", "--version": + args[0] = "version" + case "-h", "-help", "--help": + args[0] = "help" + } + } + if len(args) > 0 && !strings.HasPrefix(args[0], "-") { + cmd, args = args[0], args[1:] + } + switch cmd { + case "", "ui": + return runUI(args) + case "scan": + return runScan(args) + case "ping": + return runPing(args) + case "ports": + return runPorts(args) + case "wol": + return runWOL(args) + case "interfaces", "ifaces": + return runInterfaces() + case "oui": + return runOUI(args) + case "help": + printUsage(os.Stdout) + return nil + case "version": + fmt.Println("nscan " + Version) + return nil + } + return fmt.Errorf("unknown command %q (see nscan help)", cmd) +} + +func newFlags(name string) *flag.FlagSet { + fl := flag.NewFlagSet(name, flag.ContinueOnError) + fl.Usage = func() { printUsage(os.Stderr) } + return fl +} + +type scanFlags struct { + iface, rng string + wait time.Duration + noNames bool + noBonjour bool +} + +func (f *scanFlags) register(flags *flag.FlagSet) { + flags.StringVar(&f.iface, "i", "", "interface") + flags.StringVar(&f.rng, "r", "", "address range") + flags.DurationVar(&f.wait, "wait", 1500*time.Millisecond, "wait for late replies") + flags.BoolVar(&f.noNames, "no-names", false, "skip name resolution") + flags.BoolVar(&f.noBonjour, "no-bonjour", false, "skip Bonjour discovery") +} + +// resolve detects the network and the addresses to scan. +func (f *scanFlags) resolve() (*scanner.Network, string, []netip.Addr, error) { + n, err := scanner.DetectNetwork(f.iface) + if err != nil { + return nil, "", nil, err + } + spec := f.rng + if spec == "" { + spec = n.DefaultRange().String() + } + targets, err := scanner.ParseRange(spec) + if err != nil { + return nil, "", nil, err + } + return n, spec, targets, nil +} + +func openState() (*store.Store, *oui.DB, error) { + dir, err := store.Dir() + if err != nil { + return nil, nil, err + } + st, err := store.Open(dir) + if err != nil { + return nil, nil, fmt.Errorf("data in %s: %w", dir, err) + } + db, err := oui.Load(ouiPath(dir)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, nil, err + } + return st, db, nil +} + +func ouiPath(dir string) string { return filepath.Join(dir, "oui.tsv") } + +func runUI(args []string) error { + fl := newFlags("nscan") + var sf scanFlags + sf.register(fl) + interval := fl.Duration("interval", time.Minute, "auto-scan interval") + exportDir := fl.String("export-dir", ".", "export directory") + if err := fl.Parse(args); err != nil { + return err + } + n, spec, targets, err := sf.resolve() + if err != nil { + return err + } + st, db, err := openState() + if err != nil { + return err + } + return tui.Run(tui.Config{ + Network: n, + Range: spec, + Targets: targets, + Auto: *interval > 0, + Interval: *interval, + Wait: sf.wait, + Names: !sf.noNames, + Bonjour: !sf.noBonjour, + Store: st, + OUI: db, + ExportDir: *exportDir, + Version: Version, + }) +} + +func runScan(args []string) error { + fl := newFlags("scan") + var sf scanFlags + sf.register(fl) + asJSON := fl.Bool("json", false, "JSON output") + asCSV := fl.Bool("csv", false, "CSV output") + if err := fl.Parse(args); err != nil { + return err + } + n, spec, targets, err := sf.resolve() + if err != nil { + return err + } + st, db, err := openState() + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + + fmt.Fprintf(os.Stderr, "Scanning %s (%s) on %s …\n", spec, plural(len(targets), "address", "addresses"), n.Iface.Name) + start := time.Now() + hosts, err := scanner.Scan(ctx, scanner.Options{ + Network: n, Targets: targets, Wait: sf.wait, + Names: !sf.noNames, Bonjour: !sf.noBonjour, Vendor: db.Lookup, + }) + if err != nil { + return err + } + + targetSet := make(map[netip.Addr]bool, len(targets)) + for _, ip := range targets { + targetSet[ip] = true + } + sightings := make([]store.Sighting, 0, len(hosts)) + for _, h := range hosts { + sightings = append(sightings, sighting(h)) + } + if _, err := st.Observe(time.Now(), sightings, func(ip netip.Addr) bool { return targetSet[ip] }); err != nil { + fmt.Fprintln(os.Stderr, "warning:", err) + } + + recs := make([]export.Record, 0, len(hosts)) + for _, h := range hosts { + r := export.FromHost(h) + r.Online = true + if d, ok := st.Device(sighting(h).Key); ok { + if d.Name != "" { + r.Name = d.Name + } + r.Tracked, r.Whitelisted, r.FirstSeen, r.LastSeen = d.Tracked, d.Whitelisted, d.FirstSeen, d.LastSeen + } + recs = append(recs, r) + } + switch { + case *asJSON: + return export.WriteJSON(os.Stdout, recs) + case *asCSV: + return export.WriteCSV(os.Stdout, recs) + } + printTable(os.Stdout, recs) + fmt.Fprintf(os.Stderr, "%s in %.1fs\n", plural(len(recs), "device", "devices"), time.Since(start).Seconds()) + return nil +} + +func sighting(h scanner.Host) store.Sighting { + s := store.Sighting{IP: h.IP.String(), Hostname: h.Name(), Vendor: h.Vendor, Model: h.Model, Key: "ip:" + h.IP.String()} + if len(h.MAC) > 0 { + s.MAC = h.MAC.String() + s.Key = strings.ToLower(s.MAC) + } + return s +} + +func printTable(w io.Writer, recs []export.Record) { + tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, "IP ADDRESS\tMAC ADDRESS\tVENDOR\tNAME\tPING\tSERVICES") + for _, r := range recs { + rtt := "–" + if r.RTTms > 0 { + rtt = fmt.Sprintf("%.1f ms", r.RTTms) + } + var svcs []string + for _, s := range r.Services { + if short := s.Short(); !contains(svcs, short) { + svcs = append(svcs, short) + } + } + vendor := r.Vendor + if r.Model != "" { + if vendor == oui.Private { + vendor = "" + } + vendor = strings.TrimSpace(vendor + " " + r.Model) + } + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\n", r.IP, dash(r.MAC), dash(vendor), dash(r.Name), rtt, strings.Join(svcs, ",")) + } + tw.Flush() +} + +func contains(list []string, s string) bool { + for _, x := range list { + if x == s { + return true + } + } + return false +} + +// plural formats a count with the matching noun ("1 device", "3 devices"). +func plural(n int, one, many string) string { + if n == 1 { + return "1 " + one + } + return fmt.Sprintf("%d %s", n, many) +} + +func dash(s string) string { + if s == "" { + return "–" + } + return s +} + +func resolveHost(ctx context.Context, host string) (netip.Addr, error) { + if ip, err := netip.ParseAddr(host); err == nil { + return ip, nil + } + ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip4", host) + if err != nil { + return netip.Addr{}, err + } + if len(ips) == 0 { + return netip.Addr{}, fmt.Errorf("%s: no IPv4 address", host) + } + return ips[0].Unmap(), nil +} + +func runPing(args []string) error { + fl := newFlags("ping") + count := fl.Int("c", 0, "count (0 = until Ctrl+C)") + interval := fl.Duration("interval", time.Second, "interval between requests") + timeout := fl.Duration("W", 2*time.Second, "timeout per reply") + if err := fl.Parse(args); err != nil { + return err + } + if fl.NArg() != 1 { + return errors.New("usage: nscan ping [-c N] ") + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + ip, err := resolveHost(ctx, fl.Arg(0)) + if err != nil { + return err + } + var sent, recv int + var lo, hi, sum time.Duration + err = scanner.Ping(ctx, ip, *count, *interval, *timeout, func(r scanner.PingResult) { + sent++ + switch { + case r.Err != nil: + fmt.Printf("seq=%d error: %v\n", r.Seq, r.Err) + case r.Timeout: + fmt.Printf("seq=%d timeout\n", r.Seq) + default: + recv++ + sum += r.RTT + if lo == 0 || r.RTT < lo { + lo = r.RTT + } + hi = max(hi, r.RTT) + fmt.Printf("reply from %s: seq=%d time=%.2f ms (%s)\n", ip, r.Seq, ms(r.RTT), r.Method) + } + }) + if sent > 0 { + fmt.Printf("\n--- %s ---\n%d sent, %d received, %.0f%% loss\n", ip, sent, recv, 100*float64(sent-recv)/float64(sent)) + if recv > 0 { + fmt.Printf("min/avg/max = %.2f/%.2f/%.2f ms\n", ms(lo), ms(sum/time.Duration(recv)), ms(hi)) + } + } + return err +} + +func ms(d time.Duration) float64 { return float64(d.Microseconds()) / 1000 } + +func runPorts(args []string) error { + fl := newFlags("ports") + spec := fl.String("p", "top", "Ports: top, all, 1-1024, 22,80,443") + timeout := fl.Duration("t", 800*time.Millisecond, "timeout per connection") + workers := fl.Int("c", 200, "parallel connections") + if err := fl.Parse(args); err != nil { + return err + } + if fl.NArg() != 1 { + return errors.New("usage: nscan ports [-p top|all|1-1024] ") + } + ports, err := scanner.ParsePorts(*spec) + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + ip, err := resolveHost(ctx, fl.Arg(0)) + if err != nil { + return err + } + fmt.Fprintf(os.Stderr, "Scanning %s on %s …\n", plural(len(ports), "port", "ports"), ip) + start := time.Now() + found := 0 + results := make(chan scanner.PortResult) + done := make(chan struct{}) + go func() { + for r := range results { + found++ + fmt.Printf("%-10s %-16s %.2f ms\n", fmt.Sprintf("%d/tcp", r.Port), dash(r.Service), ms(r.RTT)) + } + close(done) + }() + scanner.ScanPorts(ctx, ip, ports, *timeout, *workers, func(r scanner.PortResult) { results <- r }, nil) + close(results) + <-done + fmt.Fprintf(os.Stderr, "%s in %.1fs\n", plural(found, "open port", "open ports"), time.Since(start).Seconds()) + return nil +} + +func runWOL(args []string) error { + fl := newFlags("wol") + iface := fl.String("i", "", "interface") + bcast := fl.String("b", "", "broadcast address") + if err := fl.Parse(args); err != nil { + return err + } + if fl.NArg() != 1 { + return errors.New("usage: nscan wol [-b broadcast] ") + } + target := fl.Arg(0) + mac, err := net.ParseMAC(target) + if err != nil { + // Allow the custom name given in the interface. + st, _, serr := openState() + if serr != nil { + return serr + } + for _, d := range st.Devices() { + if d.MAC != "" && (strings.EqualFold(d.Name, target) || strings.EqualFold(d.Hostname, target)) { + mac, err = net.ParseMAC(d.MAC) + break + } + } + if err != nil { + return fmt.Errorf("%q is neither a MAC address nor a known device", target) + } + } + var b netip.Addr + if *bcast != "" { + if b, err = netip.ParseAddr(*bcast); err != nil { + return err + } + } else if n, err := scanner.DetectNetwork(*iface); err == nil { + b = n.Broadcast() + } + if err := scanner.WakeOnLAN(mac, b); err != nil { + return err + } + fmt.Printf("magic packet sent to %s\n", mac) + return nil +} + +func runInterfaces() error { + def, _ := scanner.DetectNetwork("") + tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, "INTERFACE\tADDRESS\tNETWORK\tMAC\t") + for _, n := range scanner.Interfaces() { + mark := "" + if def != nil && def.Iface.Name == n.Iface.Name { + mark = "(default)" + } + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", n.Iface.Name, n.LocalIP, n.Prefix.Masked(), dash(n.LocalMAC.String()), mark) + } + return tw.Flush() +} + +func runOUI(args []string) error { + if len(args) == 0 { + return errors.New("usage: nscan oui update | import | lookup ") + } + dir, err := store.Dir() + if err != nil { + return err + } + path := ouiPath(dir) + switch args[0] { + case "update": + fmt.Fprintln(os.Stderr, "Downloading", oui.SourceURL, "…") + n, err := oui.Download(context.Background(), path) + if err != nil { + return fmt.Errorf("%w\nIf the download is blocked, fetch the file in a browser and run \"nscan oui import \"", err) + } + fmt.Printf("%d vendors saved to %s\n", n, path) + case "import": + if len(args) != 2 { + return errors.New("usage: nscan oui import ") + } + f, err := os.Open(args[1]) + if err != nil { + return err + } + defer f.Close() + n, err := oui.Install(f, path) + if err != nil { + return err + } + fmt.Printf("%d vendors saved to %s\n", n, path) + case "lookup": + if len(args) != 2 { + return errors.New("usage: nscan oui lookup ") + } + mac, err := net.ParseMAC(args[1]) + if err != nil { + return err + } + db, err := oui.Load(path) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + fmt.Println(dash(db.Lookup(mac))) + default: + return fmt.Errorf("unknown oui command %q", args[0]) + } + return nil +} diff --git a/version.go b/version.go new file mode 100644 index 0000000..a75bd83 --- /dev/null +++ b/version.go @@ -0,0 +1,6 @@ +package main + +// Version is a var, not a const, so build.sh can put the built number in via +// -ldflags "-X main.Version=…". The value here only shows up in a bare +// `go build`; the version actually built is the one in version.txt. +var Version = "1.0.0" diff --git a/version.txt b/version.txt new file mode 100644 index 0000000..3eefcb9 --- /dev/null +++ b/version.txt @@ -0,0 +1 @@ +1.0.0