initial commit [141.14.140.180,mike]

This commit is contained in:
mike committed 2026-10-26 15:52:55 +01:00
commit e34ba75b7b
33 files changed
+6267

No files matched your search

+244
View File
@@ -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
}
+962
View File
@@ -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()
}
+179
View File
@@ -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")
}
}
+81
View File
@@ -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)))
}
+346
View File
@@ -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()
}
+607
View File
@@ -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()))
}