// 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 Update string // a newer release, if one is known } // 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() }