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

+458
View File
@@ -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
})
}
}