// local.go — prober local del agente: ejecuta EN EL ROUTER los mismos // comandos que el servidor lanza por SSH (constantes Cmd* de probe.go) y // construye el Payload con los shapes parseados. Cada sonda es best-effort: // si un comando no existe (ubus, iwinfo, brctl...) la sección queda ausente // y el servidor conserva el último dato bueno (anti-parpadeo). package probe import ( "context" "encoding/json" "errors" "fmt" "log/slog" "net" "os" "os/exec" "sort" "strings" "sync" "time" ) // Runner ejecuta un comando de shell local y devuelve su stdout. // timeout 0 = default corto de sonda. type Runner interface { Run(ctx context.Context, cmd string, timeout time.Duration) (string, error) } // ShellRunner ejecuta con /bin/sh -c (BusyBox ash en OpenWrt). type ShellRunner struct { DefaultTimeout time.Duration } // Run implementa Runner. func (s ShellRunner) Run(ctx context.Context, cmd string, timeout time.Duration) (string, error) { if timeout <= 0 { timeout = s.DefaultTimeout if timeout <= 0 { timeout = 5 * time.Second } } cctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() out, err := exec.CommandContext(cctx, "/bin/sh", "-c", cmd).Output() if err != nil { // #1839: iw escribe el motivo en stderr ("command failed: Operation // not supported (-95)") y Output() lo tira. Sin el, un scan rechazado // y un scan vacio llegan al servidor exactamente igual. var ee *exec.ExitError if errors.As(err, &ee) { if msg := lastLine(ee.Stderr); msg != "" { return "", fmt.Errorf("%w: %s", err, msg) } } return "", err } return string(out), nil } // lastLine devuelve la ultima linea no vacia de b. func lastLine(b []byte) string { lines := strings.Split(strings.TrimSpace(string(b)), "\n") for i := len(lines) - 1; i >= 0; i-- { if line := strings.TrimSpace(lines[i]); line != "" { return line } } return "" } // Options configura las sondas opcionales del prober. type Options struct { // WanPingTarget: si no está vacío, ping WAN (latencia + pérdida) — gateway. WanPingTarget string // GwPingTarget: si no está vacío, ping corto al gateway (latencia) — AP. GwPingTarget string // ScanInterval: mínimo entre scans de vecinos (#591/#699). 0 = usar // DefaultScanInterval; negativo (ScanDisabled) = sin scans periódicos, // solo on-demand vía ForceScan (env NETPULSE_SCAN_INTERVAL). ScanInterval time.Duration // ActiveUplink names the uplink a policy manager is steering traffic // through, when the embedder knows. nil or "" = decide from the routes, // as before. ActiveUplink func() string } // Prober sondea el equipo local y construye payloads. Mantiene el estado de // deltas (/proc/stat y /proc/net/dev) entre muestras — es el único estado // del agente y vive solo en RAM. type Prober struct { run Runner opts Options lastStat *CPUSample lastNetRx float64 lastNetTx float64 lastNetAt time.Time hasLastNet bool // lastNetRaw conserva el último output de /proc/net/dev de probeSystem // para derivar la sección NetIf (contadores por iface, #305) sin un // segundo cat. lastNetRaw string // lastNetIf/lastNetIfAt: contadores por interfaz del ciclo anterior, para // publicar la tasa de la WAN y no la suma de todas las bocas (#2048). lastNetIf map[string]IfCounters lastNetIfAt time.Time // lastWan: uplink del último Build, para que probeFDB marque la boca por // la que sale internet sin repetir la llamada a ubus. lastWan *WanInfo // netIfUpdated indica si el último ciclo de probeSystem consiguió // refrescar /proc/net/dev. Build solo incluye NetIf cuando es true, // evitando enviar contadores repetidos si CmdNetDev falla o tarda. netIfUpdated bool // radiosCache (#368): el resumen de radios (canal/htmode/txpower) cambia // tan poco que no merece iwinfo en cada ciclo NI en el path de eventos: // se refresca cada radiosTTL en el sondeo completo y el resto de las // llamadas reutilizan la última. radiosMu sync.Mutex radiosCache []Radio radiosAt time.Time // scanMu protege el throttle del scan pasivo de vecinos (#591): el scan // activo (`iw dev scan`) saca la radio del canal y degrada a los clientes // si se repite en cada sondeo (cada ~30 s). Se ejecuta como mucho cada // scanInterval, o antes si el server pide un refresh explícito. scanMu sync.Mutex lastScanAt time.Time scanForced bool scanInterval time.Duration // Survey en vivo (#1214): throttle propio de 5 min. No saca la radio // del canal, pero el texto crudo engorda el push: no va en cada ciclo. surveyMu sync.Mutex surveyForced bool surveyAt time.Time // Config wireless cruda (#1450): `uci show wireless` para que el server // pinte 802.11r en flotas agent-only. Se refresca cada uciWirelessTTL // (la config cambia a mano, no sola) y el valor cacheado se emite en // TODOS los pushes: un push de evento (BuildWireless) no debe dejar al // server sin la sección mientras llega el siguiente sondeo completo. uciWirelessMu sync.Mutex uciWirelessRaw string uciWirelessAt time.Time // stalePing (#2073): recheck activo de vecinos ARP en STALE. El ping a // cada IP sale del throttle como mucho cada stalePingInterval; el sondeo // del agente es cada ~30 s y una entrada STALE cambia despacio. stalePingMu sync.Mutex stalePingAt time.Time // presenceAt (#2110): última ronda del barrido de subredes enrutadas. presenceMu sync.Mutex presenceAt time.Time } // surveyInterval: mínimo entre `iw survey dump` si no hay force (#1214). const surveyInterval = 5 * time.Minute // uciWirelessTTL: mínimo entre lecturas de `uci show wireless` (#1450). // Leer /etc/config/wireless es barato, pero la configuración solo cambia // cuando alguien la edita: con 5 min el panel sigue fresco y el push no // engorda en cada ciclo. const uciWirelessTTL = 5 * time.Minute const radiosTTL = 5 * time.Minute const ( // ScanDisabled: sin scans periódicos (solo on-demand vía ForceScan). // Lo selecciona NETPULSE_SCAN_INTERVAL=0; en un AP con clientes Intel // cada off-channel gap puede costar un deauth por beacon-loss (#699). ScanDisabled = -1 * time.Second // DefaultScanInterval: mínimo entre scans de vecinos si no se configura // NETPULSE_SCAN_INTERVAL. Los datos de "Análisis de canales" apenas // cambian; 30 minutos mantienen el mapa razonablemente fresco sin // martillear el aire con off-channel scans (#591/#699). DefaultScanInterval = 30 * time.Minute ) // NewProber crea el prober con el runner dado. func NewProber(run Runner, opts Options) *Prober { si := opts.ScanInterval if si == 0 { si = DefaultScanInterval } return &Prober{run: run, opts: opts, scanInterval: si} } // activeUplink asks the embedder which uplink is carrying traffic. Never // panics on a callback that does: the WAN section is not worth an agent. func (p *Prober) activeUplink() string { if p.opts.ActiveUplink == nil { return "" } defer func() { _ = recover() }() return p.opts.ActiveUplink() } // ForceScan pide un scan en el próximo Build (lo usa el runtime cuando el // server envía "refresh" por SSE): no espera al intervalo del throttle. func (p *Prober) ForceScan() { p.scanMu.Lock() p.scanForced = true p.scanMu.Unlock() } // ForceSurvey pide un survey en el próximo Build (#1214): el runtime lo // llama cuando el server envía "refresh" por SSE. func (p *Prober) ForceSurvey() { p.surveyMu.Lock() p.surveyForced = true p.surveyMu.Unlock() } // surveyDue decide si toca lanzar CmdSurvey en este sondeo completo: true si // hay force pendiente o si pasó surveyInterval desde el último intento. Al // devolver true registra el intento para no repetirlo. func (p *Prober) surveyDue() bool { p.surveyMu.Lock() defer p.surveyMu.Unlock() if p.surveyForced { p.surveyForced = false p.surveyAt = time.Now() return true } if p.surveyAt.IsZero() || time.Since(p.surveyAt) >= surveyInterval { p.surveyAt = time.Now() return true } return false } // refreshUciWireless lee `uci show wireless` si toca (#1450) y lo deja en // caché para el resto de pushes. Marca el intento aunque falle: un equipo sin // uci (o un switch sin sección wireless) no reintenta en cada sondeo. func (p *Prober) refreshUciWireless(ctx context.Context) { p.uciWirelessMu.Lock() due := p.uciWirelessAt.IsZero() || time.Since(p.uciWirelessAt) >= uciWirelessTTL p.uciWirelessMu.Unlock() if !due { return } out := p.runBest(ctx, CmdUciWireless, 3*time.Second) p.uciWirelessMu.Lock() p.uciWirelessAt = time.Now() if out != "" { p.uciWirelessRaw = out } p.uciWirelessMu.Unlock() } // uciWirelessCached devuelve el último volcado bueno de la config wireless // ("" si nunca se pudo leer). func (p *Prober) uciWirelessCached() string { p.uciWirelessMu.Lock() defer p.uciWirelessMu.Unlock() return p.uciWirelessRaw } // scanDue decide si toca lanzar CmdScan en este sondeo completo: true si hay // un force pendiente (refresh del server) o si pasó scanInterval desde el // último intento. Con ScanDisabled los periódicos no corren nunca (solo // force). La primera Build tras arrancar también escanea (lastScanAt cero), // salvo desactivado. Al devolver true registra el intento para no repetirlo. func (p *Prober) scanDue() bool { p.scanMu.Lock() defer p.scanMu.Unlock() if p.scanForced { p.scanForced = false p.lastScanAt = time.Now() return true } if p.scanInterval < 0 { return false } if p.lastScanAt.IsZero() || time.Since(p.lastScanAt) >= p.scanInterval { p.lastScanAt = time.Now() return true } return false } // scanNeighbours runs one `iw dev scan` per physical radio (#1560) // and logs every cycle (#1559). // // The scan is the only probe that takes a radio off-channel, so it is also // the only one that can drop clients (#1557). Until now it left no trace in // the log, which made that correlation impossible from a router: the log line // carries the interfaces, per-radio duration and BSS count to line a drop up // against the scan that caused it. func (p *Prober) scanNeighbours(ctx context.Context, iwDev string) ([]ScanResult, []ScanOutcome) { ifaces := ParseIwDevDetailed(iwDev) targets := IwDevScanTargets(ifaces) if len(targets) == 0 { return nil, nil } names := make([]string, len(targets)) for i, t := range targets { names[i] = t.Iface } start := time.Now() slog.Info("neighbor scan start", "radios", len(targets), "ifaces", strings.Join(names, ",")) var scans []ScanResult outcomes := make([]ScanOutcome, 0, len(targets)) for _, t := range targets { at := time.Now() used, out, err := p.scanWithFallback(ctx, ifaces, t) got := ParseScan("==IFACE==" + used.Iface + "\n" + out) scans = append(scans, got...) oc := ScanOutcome{Iface: used.Iface, Phy: used.Phy, BSS: len(got)} if err != nil { oc.Error = err.Error() } outcomes = append(outcomes, oc) slog.Info("neighbor scan radio", "iface", used.Iface, "phy", used.Phy, "bss", len(got), "duration_ms", time.Since(at).Milliseconds(), "error", oc.Error) } slog.Info("neighbor scan done", "bss", len(scans), "duration_ms", time.Since(start).Milliseconds(), "empty", len(scans) == 0) return scans, outcomes } // scanWithFallback scans the interface chosen for the radio and, when it // refuses (#1839: on Asuswrt/dhd the AP VAP answers NL80211_CMD_TRIGGER_SCAN // with "Operation not supported"), tries the other interfaces of the same phy // in the same cycle. Nothing is remembered between cycles: caching a failure // would turn one bad scan into a permanent choice. func (p *Prober) scanWithFallback(ctx context.Context, ifaces []IwDevIface, chosen IwDevIface) (IwDevIface, string, error) { out, err := p.run.Run(ctx, CmdScanIface(chosen.Iface), scanIfaceTimeout) if err == nil { return chosen, out, nil } used, lastErr := chosen, err for i, alt := range IwDevScanAlternates(ifaces, chosen) { if i >= maxScanFallbacks { break } out, err = p.run.Run(ctx, CmdScanIface(alt.Iface), scanIfaceTimeout) if err == nil { slog.Info("neighbor scan fallback", "from", chosen.Iface, "to", alt.Iface, "phy", alt.Phy, "reason", lastErr.Error()) return alt, out, nil } used, lastErr = alt, err } return used, "", lastErr } // probeVlans reports the bridge VLANs, merging what the kernel says with what // the configuration declares. // // The section has existed in the payload since VLANs were added, but // nothing ever filled it: only the server's own SSH probe did, and a router // reached through its agent never takes that path, so its VLAN panel has // always been empty. // // Neither source is enough on its own. `bridge` lives in an optional package, // so plenty of routers have VLANs only the configuration knows about. And a // box that segments with 802.1Q subinterfaces (eth0.999 into br-iot) answers // with every port on VLAN 1, a valid-looking answer that says nothing about // the real layout. The two views are therefore merged always, the kernel // owning the flags and the configuration the names, subnets and the VLANs // that only exist as subinterfaces (#1757). func (p *Prober) probeVlans(ctx context.Context) ([]VlanPort, []UciNetwork) { var kernel []VlanPort if out := p.runBest(ctx, CmdBridgeVlan, 0); out != "" { kernel = ParseBridgeVlan(out) } var declared []VlanPort var networks []UciNetwork if out := p.runBest(ctx, CmdUciBridgeVlan, 0); out != "" { // La misma configuracion alimenta las dos vistas (#1889): una sola // lectura de `uci show network` por ronda. // A router uses one model or the other, so the two UCI parsers // never describe the same port: bridge-vlan sections name bridge // ports, the subinterface model names bridges and their parents. declared = MergeVlanPorts(ParseUciBridgeVlans(out), ParseUciNetworkVlans(out)) networks = ParseUciNetworks(out) } return MergeVlanPorts(kernel, declared), networks } // runBest es best-effort: error → "" (la sección queda ausente). func (p *Prober) runBest(ctx context.Context, cmd string, timeout time.Duration) string { out, err := p.run.Run(ctx, cmd, timeout) if err != nil { return "" } return out } // Build ejecuta una ronda de sondas y devuelve el payload listo para empujar. // router/version los rellena el caller (main) o van aquí por comodidad. func (p *Prober) Build(ctx context.Context, router, version string) *Payload { pl := &Payload{ Router: router, Ts: time.Now().Unix(), Version: version, } // Wan antes que FDB: probeFDB usa la boca del uplink para marcarla. pl.Data.Wan = p.probeWan(ctx) pl.Data.Vlans, pl.Data.Networks = p.probeVlans(ctx) pl.Data.System = p.probeSystem(ctx) pl.Data.Wireless = p.probeWireless(ctx, true) pl.Data.DHCP = p.probeDHCP(ctx) // LLDP antes que FDB (#1500): los puertos con vecino LLDP deciden qué // miembro de un bridge es el uplink del AP. Una sola sonda por push: // el resultado se reusa para el payload. lldpData := p.probeLldp(ctx) pl.Data.Lldp = lldpData lldpPorts := map[string]bool{} if lldpData != nil { for _, nb := range lldpData.Neighbors { if nb.Port != "" { lldpPorts[nb.Port] = true } } } pl.Data.FDB = p.probeFDB(ctx, lldpPorts, pl.Data.Wireless.GetRadios()) pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx) pl.Data.Dawn = p.probeDawn(ctx) pl.Data.Usteer = p.probeUsteer(ctx) pl.Data.LuCI = p.probeLuCI(ctx) // ClientBw (#551): tráfico por cliente desde nlbwmon (solo si instalado). pl.Data.ClientBw = p.probeClientBw(ctx) // Discovery (#338): mDNS services + randomized MAC detection. pl.Data.Discovery = p.probeDiscovery(ctx, pl.Data.Wireless) // NetIf (#305): contadores por iface desde el MISMO /proc/net/dev que // leyó probeSystem (sin segundo cat). Solo se incluyen si el ciclo actual // refrescó la muestra; si no, el payload se envía sin NetIf para que el // servidor no inserte deltas 0 con contadores repetidos (#408). if p.netIfUpdated { pl.Data.NetIf = ParseNetDevIfaces(p.lastNetRaw) p.netIfUpdated = false } return pl } // BuildWireless es un sondeo rápido de solo wireless + DHCP (Fase 7.1: // disparado por eventos ubus assoc/disassoc). El servidor conserva el último // dato bueno de system y FDB (parpadeo suprimido por secciones nil). func (p *Prober) BuildWireless(ctx context.Context, router, version string) *Payload { pl := &Payload{ Router: router, Ts: time.Now().Unix(), Version: version, } pl.Data.Wireless = p.probeWireless(ctx, false) pl.Data.DHCP = p.probeDHCP(ctx) pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx) return pl } // probeSystem: sysinfo + board + cpu/temp + netdev + pings + backhaul + MAC // del bridge. Devuelve nil solo si TODAS las sondas fallaron (equipo sin // ubus y sin /proc — no pasa en OpenWrt; cubre al fake runner de tests). func (p *Prober) probeSystem(ctx context.Context) *SystemData { sd := &SystemData{} any := false if out := p.runBest(ctx, CmdUbusSystemInfo, 0); out != "" { var si SysInfo if err := json.Unmarshal([]byte(out), &si); err == nil { if si.Memory.Total > 0 { // ubus system info no expone la caché de ficheros, la lee el // agente de /proc/meminfo (fallback silencioso si no existe). if cached := readMeminfoCachedKB(); cached > 0 { si.Memory.Cached = float64(cached) * 1024 } // Y el uso real (lo que el usuario percibe) es la memoria de // los procesos; así el server no sobreestima en ubifs (#513). if rss := sumProcRSS(); rss > 0 && rss < si.Memory.Total { si.Memory.Used = rss } } sd.SysInfo = &si any = true } } // #1481: fallback portable de uptime sin ubus (Asuswrt, Linux genérico): // el primer campo de /proc/uptime. Solo rellena el uptime; el resto de // SysInfo sigue viniendo de ubus cuando existe. if sd.SysInfo == nil || sd.SysInfo.Uptime == 0 { if out := p.runBest(ctx, CmdProcUptime, 0); out != "" { if sec := ParseUptimeSec(out); sec > 0 { if sd.SysInfo == nil { sd.SysInfo = &SysInfo{} } sd.SysInfo.Uptime = sec any = true } } } // #1500: memoria portable de /proc/meminfo cuando ubus no la dio (sin // esto la ficha pinta RAM 0% en todo target sin ubus). Se rellenan los // campos crudos y NUNCA Used: el server aplica su fórmula clásica // (total-free-buffered-cached), la misma semántica que en unidades con // ubus donde Used es la suma de RSS (#513). if m := readMeminfoFieldsKB(); m.total > 0 { if sd.SysInfo == nil { sd.SysInfo = &SysInfo{} } if sd.SysInfo.Memory.Total == 0 { sd.SysInfo.Memory.Total = float64(m.total) * 1024 sd.SysInfo.Memory.Free = float64(m.free) * 1024 sd.SysInfo.Memory.Buffered = float64(m.buffered) * 1024 sd.SysInfo.Memory.Cached = float64(m.cached) * 1024 sd.SysInfo.Memory.Available = float64(m.avail) * 1024 any = true } } // #1500: zona horaria portable (ubus no la da nunca; la ficha pintaba // "—" incluso en equipos con ubus). if tz := readTimezone(); tz != "" { if sd.SysInfo == nil { sd.SysInfo = &SysInfo{} } if sd.SysInfo.Timezone == "" { sd.SysInfo.Timezone = tz } } if out := p.runBest(ctx, CmdUbusSystemBoard, 0); out != "" { var b BoardInfo if err := json.Unmarshal([]byte(out), &b); err == nil { sd.Board = &b any = true } } if out := p.runBest(ctx, CmdProcStat, 0); out != "" { if cur, err := ParseProcStat(out); err == nil { if p.lastStat != nil { sd.CPU = CPUPercent(*p.lastStat, cur) } c := cur p.lastStat = &c any = true } } if out := p.runBest(ctx, CmdTemp, 0); out != "" { sd.Temp = ParseTempC(out) any = true } if out := p.runBest(ctx, CmdNetDev, 0); out != "" { rx, tx := ParseNetDev(out) now := time.Now() if p.hasLastNet { sd.RxBps, sd.TxBps = NetDevBps(p.lastNetRx, p.lastNetTx, rx, tx, now.Sub(p.lastNetAt).Seconds()) // #2048: el agregado suma todas las bocas físicas y en un router // que enruta cuenta la bajada dos veces (entra por la WAN y sale // por la LAN). Si el equipo sabe cuál es su WAN, se publica la // tasa de ESA boca. Sin WAN identificable (AP) manda el agregado. if p.lastWan != nil && p.lastWan.Port != "" && p.lastNetIf != nil { rates := IfRates(p.lastNetIf, ParseNetDevIfaces(out), now.Sub(p.lastNetIfAt).Seconds()) if r, ok := rates[p.lastWan.Port]; ok && r.RxBps != nil && r.TxBps != nil { sd.RxBps, sd.TxBps = r.RxBps, r.TxBps } } } // Se guarda SIEMPRE, también en la primera muestra, que es la que abre // la ventana: si no, el ciclo siguiente no tiene con qué comparar. p.lastNetIf = ParseNetDevIfaces(out) p.lastNetIfAt = now p.lastNetRx, p.lastNetTx, p.lastNetAt, p.hasLastNet = rx, tx, now, true p.lastNetRaw = out p.netIfUpdated = true any = true } if p.opts.WanPingTarget != "" { out := p.runBest(ctx, fmt.Sprintf(CmdPingWan, p.opts.WanPingTarget), 10*time.Second) sd.LatencyMs, sd.LossPct = ParsePingSummary(out) any = true } else if p.opts.GwPingTarget != "" { out := p.runBest(ctx, fmt.Sprintf(CmdPingGateway, p.opts.GwPingTarget), 10*time.Second) sd.LatencyMs, _ = ParsePingSummary(out) any = true } if out := p.runBest(ctx, CmdUbusWireless, 0); out != "" { if wifi, err := ParseWirelessUplink([]byte(out)); err == nil { sd.Backhaul = "cable" if wifi { sd.Backhaul = "wifi" } any = true } } if out := p.runBest(ctx, CmdBridgeMAC, 0); out != "" { sd.BridgeMAC = strings.ToUpper(strings.TrimSpace(out)) any = true } if out := p.runBest(ctx, CmdIfaceMACs, 0); out != "" { if macs := ParseIfaceMACs(out); len(macs) > 0 { sd.IfaceMACs = macs any = true } } if !any { return nil } return sd } // probeWireless: clientes asociados + radios por banda (#368: ubus primero, // iwinfo combinado en UNA pasada como fallback, radios cacheadas radiosTTL). // full=false (path de eventos nl80211) evita iwinfo por completo: ubus para // clientes y radios de caché. nil si no hay fuente wireless. func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData { wd := &WirelessData{} any := false // Clientes: ubus hostapd get_clients (barato, sin ucode). if out := p.runBest(ctx, CmdHostapdClients, 5*time.Second); out != "" { wd.Clients = ParseHostapdClients(out) if len(wd.Clients) > 0 { any = true } } // Fallback (o APs sin ubus hostapd): iwinfo en UNA pasada por interfaz, // que además produce el resumen de radios. combined := "" if !any { combined = p.runBest(ctx, CmdWirelessCombined, 8*time.Second) if combined != "" { clients, radios := ParseWirelessCombined(combined) wd.Clients = clients if len(clients) > 0 { any = true } p.radiosMu.Lock() if len(radios) > 0 { p.radiosCache, p.radiosAt = radios, time.Now() } else if time.Since(p.radiosAt) < radiosTTL { radios = p.radiosCache } p.radiosMu.Unlock() wd.Radios = radios } } // Último recurso (#368): el par de comandos clásico (equipos donde el // combinado no produjo clientes p. ej. iwinfo sin ESSID en la interfaz). if !any { if out := p.runBest(ctx, CmdIwinfoAssoc, 8*time.Second); out != "" { wd.Clients = ParseWirelessClients(out) any = len(wd.Clients) > 0 } } // #1481: fallback nl80211 portable sin ubus hostapd ni iwinfo (Asuswrt // con iw, Linux genérico): station dump por interfaz + radios por phy // del mismo `iw dev`. if !any { if out := p.runBest(ctx, CmdIwStationDump, 8*time.Second); out != "" { clients, radios := ParseIwWireless(out) if len(clients) > 0 { wd.Clients = clients any = true } if len(radios) > 0 { p.radiosMu.Lock() p.radiosCache, p.radiosAt = radios, time.Now() p.radiosMu.Unlock() wd.Radios = radios } } } // Broadcom dhd (RT-AX92U con Merlin): nl80211 no expone NADA util — ni // estaciones ni canal — y la unidad parece vacía aunque tenga clientes // asociados (visibles en el panel del firmware). `wl` sí los sabe. Solo // corre cuando los tiers anteriores dejaron huérfanos los clientes o // ninguna radio trae banda. { needWl := !any || len(wd.Radios) == 0 if !needWl { banded := false for _, r := range wd.Radios { if r.Name != "" { banded = true break } } needWl = !banded } if needWl { if out := p.runBest(ctx, CmdWlWireless, 8*time.Second); out != "" { wclients, wradios := ParseWlWireless(out) if !any && len(wclients) > 0 { wd.Clients = wclients any = true } if len(wradios) > 0 { p.radiosMu.Lock() p.radiosCache, p.radiosAt = wradios, time.Now() p.radiosMu.Unlock() wd.Radios = wradios } } } } // Radios: solo en el sondeo completo (canal/htmode/txpower casi nunca // cambian); el path de eventos reutiliza la caché. if full { if combined != "" && wd.Radios == nil { wd.Radios = []Radio{} } if combined == "" { if out := p.runBest(ctx, CmdRadios, 8*time.Second); out != "" { radios := ParseRadios(out) // Sección UCI por banda (#500): habilita aplicar cambios de // canal desde el server. Best-effort: sin uci, sin sección. if secOut := p.runBest(ctx, CmdRadioSections, 5*time.Second); secOut != "" { sections := ParseRadioSections(secOut) for i := range radios { if sec, ok := sections[radios[i].Name]; ok { radios[i].Section = sec } } } p.radiosMu.Lock() p.radiosCache, p.radiosAt = radios, time.Now() wd.Radios = p.radiosCache p.radiosMu.Unlock() } } // `iw dev` a secas, barato y estable: alimenta con UN solo spawn los // BSSIDs propios (#1087) y la lista de interfaces a escanear (#1338). iwDev := p.runBest(ctx, CmdIwDev, 5*time.Second) // Scan pasivo de vecinos (#452): SOLO en sondeo completo y con // throttle (#591) para no sacar la radio del canal en cada push. // #1338: un comando POR INTERFAZ, cada una con su propio presupuesto // (8 s). Antes el bucle completo compartía un timeout de 10 s y, al // expirar, la salida parcial se descartaba entera: una radio lenta // (5 GHz en canal DFS, scan pasivo canal a canal) dejaba la unidad // sin NINGÚN vecino aunque las demás interfaces sí hubieran // escaneado con éxito. if p.scanDue() && iwDev != "" { scans, outcomes := p.scanNeighbours(ctx, iwDev) if len(scans) > 0 { wd.Scans = scans } if len(outcomes) > 0 { wd.ScanOutcomes = outcomes } } // BSSIDs propios (#1087), del mismo `iw dev` de arriba. if iwDev != "" { wd.OwnBssids = ParseIwDev(iwDev) } // Survey en vivo (#1214): ocupación por canal para la lente "Ahora" // del server en unidades agent-only (sin SSH). Texto crudo: el // parser vive en el server y así no se duplica. if p.surveyDue() { if out := p.runBest(ctx, CmdSurvey, 10*time.Second); out != "" { wd.SurveyRaw = out } } } else { p.radiosMu.Lock() cached := p.radiosCache p.radiosMu.Unlock() if len(cached) > 0 { wd.Radios = cached if len(wd.Clients) > 0 { any = true } } } // #1092: `any` lo marcaban solo los CLIENTES: una unidad sin clientes // asociados en ese momento descartaba TODA la sección wireless (radios, // scans, BSSIDs propios) y el server la veía como "sin WiFi". Que haya // radios o BSSIDs propios también prueba presencia wireless. if !any && (len(wd.Radios) > 0 || len(wd.OwnBssids) > 0) { any = true } // Config wireless cruda (#1450): alimenta la vista 802.11r del server en // flotas agent-only. Se refresca solo en el sondeo completo y se emite // SIEMPRE desde la caché (también en el path de eventos, para que el // último payload no pierda la sección). No cuenta para `any`: una unidad // con la config presente pero sin wifi operativa no debe aparecer como // wireless vivo. if full { p.refreshUciWireless(ctx) } wd.UciWirelessRaw = p.uciWirelessCached() if !any { return nil } if wd.Clients == nil { wd.Clients = map[string]WirelessClient{} } if wd.Radios == nil { wd.Radios = []Radio{} } return wd } // probeDHCP: ubus dhcp ipv4leases con fallback a /tmp/dhcp.leases, más // gl-clients (GL.iNet) como superset para resolver IPs sin lease // (issue #5 bug 1 — el gateway Flint2 llega por esta ruta de agente). func (p *Prober) probeDHCP(ctx context.Context) *DHCPData { var dd *DHCPData if out := p.runBest(ctx, CmdDhcpUbus, 0); out != "" { if leases, err := ParseDhcpUbus([]byte(out)); err == nil { dd = &DHCPData{Leases: leases} } } if dd == nil { out := p.runBest(ctx, CmdDhcpFile, 0) if out == "" { return nil } dd = &DHCPData{Leases: ParseDhcpLeasesFile(out)} } if out := p.runBest(ctx, CmdGlClients, 0); out != "" { if gl, err := ParseGlClients([]byte(out)); err == nil { dd.GlClients = gl } } // Names pinned in /etc/config/dhcp: the only ones a client with a fixed // address of its own ever gets. if out := p.runBest(ctx, CmdDhcpReservations, 0); out != "" { dd.Reservations = ParseDhcpReservations(out) } return dd } // probeWan: estado del uplink (proto, IP pública, gateway, DNS y la boca por // la que sale), eligiendo la interfaz por su ruta por defecto y no por // llamarse "wan". nil cuando no hay nada utilizable: un AP sin uplink, o un // equipo sin ubus. Guarda el resultado para probeFDB. func (p *Prober) probeWan(ctx context.Context) *WanInfo { p.lastWan = nil out := p.runBest(ctx, CmdNetworkDump, 0) if out == "" { return nil } info := ParseWanStatusPreferring([]byte(out), p.activeUplink()) if info.Proto == "" && info.IP == "" && info.Gateway == "" && info.Port == "" { return nil } p.lastWan = &info return &info } // probeFDB: MACs aprendidas (brctl) + puertos ethernet (layout + /sys). func (p *Prober) probeFDB(ctx context.Context, lldpPorts map[string]bool, radios []Radio) *FDBData { fd := &FDBData{} any := false if out := p.runBest(ctx, CmdBridgeFDB, 0); out != "" { fd.MACs, fd.WirelessSide, fd.VLANs = ParseBridgeFdbVlans(out) fd.WirelessSide = bandTagWirelessSide(fd.WirelessSide, radios) any = true } statesOut := p.runBest(ctx, CmdPortStates, 0) if statesOut != "" { states := ParsePortStates(statesOut) layout := []PortLayout{} if out := p.runBest(ctx, CmdBoardJSON, 0); out != "" { if lay, err := ParsePortLayout(out); err == nil { layout = lay } } members := map[string]bool{} if out := p.runBest(ctx, CmdBrifMembers, 0); out != "" { for _, l := range strings.Split(strings.TrimSpace(out), "\n") { if l != "" { members[l] = true } } } // Contadores por iface (#305): absolutos del MISMO /proc/net/dev de // probeSystem (si ya corrió este ciclo); los rates los computa el // server con el delta entre payloads. var ifaces map[string]IfRate if p.lastNetRaw != "" { ifaces = map[string]IfRate{} for name, c := range ParseNetDevIfaces(p.lastNetRaw) { ifaces[name] = IfRate{IfCounters: c} } } // Boca del uplink: la marca como WAN cuando el layout no trae // ninguna (PPPoE sobre una boca "lan" y demás). uplink := "" if p.lastWan != nil { uplink = p.lastWan.Port } // #1500: sin ubus no hay WanInfo: el uplink sale de la ruta default // de /proc/net/route. Si cae en un bridge (APs: la default vive en // br0), la boca física es el miembro con un vecino LLDP (la que // mira al core) o, en su defecto, el de más rx bytes. if uplink == "" { uplink = defaultRouteIface() } if uplink != "" && isBridgeIface(uplink) { if m := bridgeMemberUplink(members, lldpPorts, states, ifaces); m != "" { uplink = m } } fd.Ports = BuildEthPorts(layout, states, members, ifaces, uplink) any = true } if !any { return nil } if fd.MACs == nil { fd.MACs = map[string]string{} } if fd.Ports == nil { fd.Ports = []EthPort{} } return fd } // bandTagWirelessSide convierte el mapa MAC→puerto inalámbrico del FDB en // MAC→banda, casando la MAC de la interfaz del puerto (o la del padre para // subinterfaces VLAN como wl0.1) con el BSSID de una radio sondeada en el // mismo ciclo. Sin radio que casar, la MAC se descarta: mejor no decir nada // que inventarse una banda. Es el hint que evita que el server clasifique // como cableado un MAC que solo vive detrás de una radio propia. func bandTagWirelessSide(side map[string]string, radios []Radio) map[string]string { if len(side) == 0 { return nil } bandByBSSID := make(map[string]string, len(radios)) for _, r := range radios { if r.BSSID != "" { bandByBSSID[strings.ToUpper(r.BSSID)] = r.Name } } addrOf := func(iface string) string { raw, err := os.ReadFile("/sys/class/net/" + iface + "/address") if err != nil { return "" } return strings.ToUpper(strings.TrimSpace(string(raw))) } baseOf := func(port string) string { if i := strings.IndexAny(port, ".@"); i >= 0 { return port[:i] } return port } // Pasada 1: MACs propias del equipo (BSSID de cada radio + dirección de // cada interfaz de puerto inalámbrico, ambas con su variante de bit LAA // volteado: el bridge las aprende como si fueran estaciones externas). // Lo que cae en este conjunto es identidad, no cliente. self := map[string]bool{} addSelf := func(mac string) { if mac == "" { return } self[mac] = true if flipped, err := hexFlipLAA(mac); err == nil { self[flipped] = true } } for bssid := range bandByBSSID { addSelf(bssid) } addrs := map[string]string{} for _, port := range side { for _, iface := range []string{port, baseOf(port)} { if iface == "" { continue } if _, done := addrs[iface]; !done { addrs[iface] = addrOf(iface) } } } for _, addr := range addrs { addSelf(addr) } // Pasada 2: banda por MAC casando la dirección del puerto con un BSSID // sondeado; sin radio que casar (o MAC propia) la MAC se descarta: mejor // no decir nada que inventarse una banda. out := make(map[string]string, len(side)) for mac, port := range side { um := strings.ToUpper(mac) if self[um] { continue } band := "" for _, iface := range []string{port, baseOf(port)} { if a := addrs[iface]; a != "" { if b, ok := bandByBSSID[a]; ok { band = b break } } } if band != "" { out[um] = band } } if len(out) == 0 { return nil } return out } // hexFlipLAA devuelve la MAC con el bit localmente-administrada (0x02 del // primer octeto) volteado, en formato colon-upper como el resto del FDB. func hexFlipLAA(mac string) (string, error) { b, err := net.ParseMAC(mac) if err != nil || len(b) == 0 { return "", err } b[0] ^= 0x02 return strings.ToUpper(b.String()), nil } // probeLldp: vecinos LLDP de lldpd (#489). Contrato: Available=false cuando // lldpcli no existe (hint "instala lldpd"); Available=true con Neighbors // nil si la sonda falla esta ronda (lldpd parado, salida no JSON); [] vacío // honesto cuando no hay vecinos. Solo en el sondeo completo (Build): los // pushes event-driven no re-sondean y el server conserva el último bueno. func (p *Prober) probeLldp(ctx context.Context) *LldpData { if p.runBest(ctx, CmdLldpCheck, 0) == "" { return &LldpData{Available: false} } out := p.runBest(ctx, CmdLldpNeighbors, 5*time.Second) neighbors, err := ParseLldpNeighbors([]byte(out)) if out != "" && err != nil { // #1481: JSON no vacío pero inparseable (lldpd exótico): el mismo // vecino en texto plano antes de declarar la ronda fallida. Con // out=="" simplemente no hay vecinos: no se gasta un spawn en el // texto (review de #1491, es el caso común de unidad sin vecinos). if txt := p.runBest(ctx, CmdLldpNeighborsText, 5*time.Second); txt != "" { neighbors, err = ParseLldpNeighborsText(txt), nil } } if err != nil { // JSON y texto fallaron esta ronda: Available con Neighbors nil // (el server conserva el último dato bueno). return &LldpData{Available: true} } d := &LldpData{Available: true, Neighbors: neighbors} // #1369: 0 vecinos honestos + binding SOLO a bridge (br-lan) = el caso // silencioso de OpenWrt (los frames LLDP no suben al bridge master en // nss-dp/DSA). Solo entonces consultamos UCI (un fork extra por ronda // cuando sí hay vecinos sería desperdicio). if len(neighbors) == 0 && LldpdBridgeOnly(p.runBest(ctx, CmdLldpdIfaces, 0)) { d.Hint = HintLldpdBridgeOnly } return d } // probeClientBw: contadores por MAC de nlbwmon (#551). Contrato: Available= // false cuando nlbw no está instalado (el server usa hostapd bytes); true con // Hosts nil si la sonda falla esta ronda; {} vacío honesto si el daemon no // tiene datos aún. Solo en el sondeo completo (Build), como LLDP. func (p *Prober) probeClientBw(ctx context.Context) *ClientBwData { if p.runBest(ctx, CmdNlbwmonCheck, 0) == "" { return &ClientBwData{Available: false} } out := p.runBest(ctx, CmdNlbwmonJSON, 5*time.Second) if out == "" { return &ClientBwData{Available: true} } hosts, err := ParseNlbwJSON([]byte(out)) if err != nil { return &ClientBwData{Available: true} } return &ClientBwData{Available: true, Hosts: hosts} } // probeLuCI: etiquetas de puertos/VLANs de LuCI (issue #258), si el router // las define en /etc/config/luci. Best-effort: sin fichero/sección → nil. func (p *Prober) probeLuCI(ctx context.Context) *LuCILabels { out := p.runBest(ctx, CmdLuCILabels, 0) if out == "" { return nil } return ParseLuCILabels(out) } // probeDawn: lee el estado de DAWN (roaming/band-steering, Fase 14) vía // `ubus call dawn get_network`. Devuelve nil si DAWN no está instalado // (fail-soft silencioso — la sección queda ausente en el payload). // // El output de ubus mezcla campos del AP (channel, freq, etc.) con clientes // anidados (MAC → {signal, ht, ...}) en el mismo objeto por BSSID. Los // distinguimos por tipo: escalares = metadata del AP, objetos = clientes. func (p *Prober) probeDawn(ctx context.Context) *DawnData { out := p.runBest(ctx, "ubus call dawn get_network", 5*time.Second) if out == "" { return nil } // SSID → BSSID → {campos mixtos} var raw map[string]map[string]json.RawMessage if err := json.Unmarshal([]byte(out), &raw); err != nil { return nil } ssids := make(map[string]DawnSSID, len(raw)) for ssid, bssids := range raw { var aps []DawnAP clients := make(map[string]DawnClient) for bssidKey, bssidRaw := range bssids { // Parsear todos los campos del BSSID como mapa flexible. var fields map[string]json.RawMessage if err := json.Unmarshal(bssidRaw, &fields); err != nil { continue } // ¿Tiene "channel"? → es un AP. chRaw, hasChannel := fields["channel"] if !hasChannel { continue } var channel int json.Unmarshal(chRaw, &channel) if channel == 0 { continue } ap := DawnAP{BSSID: bssidKey, Channel: channel} json.Unmarshal(fields["freq"], &ap.Freq) json.Unmarshal(fields["channel_utilization"], &ap.Utilization) json.Unmarshal(fields["num_sta"], &ap.Clients) json.Unmarshal(fields["ht_support"], &ap.HT) json.Unmarshal(fields["vht_support"], &ap.VHT) json.Unmarshal(fields["local"], &ap.Local) json.Unmarshal(fields["hostname"], &ap.Hostname) aps = append(aps, ap) // Buscar clientes anidados: cualquier key cuyo valor sea un // objeto (empieza con '{') y tenga "signal". for mac, valRaw := range fields { if mac == "channel" || mac == "freq" || mac == "channel_utilization" || mac == "num_sta" || mac == "ht_support" || mac == "vht_support" || mac == "local" || mac == "hostname" || mac == "iface" || mac == "neighbor_report" || mac == "op_class" { continue } s := strings.TrimSpace(string(valRaw)) if !strings.HasPrefix(s, "{") { continue } var c struct { Signal int `json:"signal"` HT bool `json:"ht"` VHT bool `json:"vht"` } if json.Unmarshal(valRaw, &c) == nil && c.Signal < 0 { clients[strings.ToUpper(mac)] = DawnClient{ BSSID: bssidKey, Signal: c.Signal, HT: c.HT, VHT: c.VHT, } } } } if len(aps) > 0 { ssids[ssid] = DawnSSID{APs: aps, Clients: clients} } } if len(ssids) == 0 { return nil } return &DawnData{SSIDs: ssids} } // probeUsteer: lee el estado de usteer (roaming/steering) vía // `ubus call usteer local_info`, `remote_info` y `connected_clients`. Devuelve // nil si usteer no está instalado (fail-soft silencioso — la sección queda // ausente en el payload). func (p *Prober) probeUsteer(ctx context.Context) *UsteerData { localOut := p.runBest(ctx, "ubus call usteer local_info", 5*time.Second) remoteOut := p.runBest(ctx, "ubus call usteer remote_info", 5*time.Second) if localOut == "" && remoteOut == "" { return nil } clientsOut := p.runBest(ctx, "ubus call usteer connected_clients", 5*time.Second) return ParseUsteer(localOut, remoteOut, clientsOut) } // usteerAPRaw es la forma cruda de una entrada de `ubus call usteer // local_info` / `remote_info` (por BSSID/iface). type usteerAPRaw struct { BSSID string `json:"bssid"` SSID string `json:"ssid"` Freq int `json:"freq"` NAssoc int `json:"n_assoc"` Load int `json:"load"` } // usteerClientRaw es la forma cruda de una entrada de `ubus call usteer // connected_clients` (por MAC). type usteerClientRaw struct { Signal int `json:"signal"` } // ParseUsteer parsea las salidas de `ubus call usteer local_info`, // `remote_info` y `connected_clients` a un UsteerData (SSID → APs + clientes). // Función pura para testear sin ejecutar ubus. // // - local_info: {"": {bssid, ssid, freq, n_assoc, load, ...}} (este router) // - remote_info: {"#": {...}} (otros routers) // - connected_clients: {"": {"": {signal, ...}}} // // Nota: usteer usa el nombre ubus de hostapd (`hostapd.phy0-ap0`) en // local_info/remote_info y el ifname (`hostapd.wlan0`) en connected_clients; // cuando ambas convenciones no casan, el cliente se omite (no se le asigna un // SSID erróneo). func ParseUsteer(localOut, remoteOut, clientsOut string) *UsteerData { ssids := make(map[string]UsteerSSID) ifaceSSID := map[string]string{} addAP := func(ssid string, ap UsteerAP) { s := ssids[ssid] s.APs = append(s.APs, ap) if s.Clients == nil { s.Clients = map[string]UsteerClient{} } ssids[ssid] = s } if localOut != "" { var local map[string]usteerAPRaw if json.Unmarshal([]byte(localOut), &local) == nil { for iface, ap := range local { if ap.SSID == "" || ap.BSSID == "" { continue } ifaceSSID[iface] = ap.SSID addAP(ap.SSID, UsteerAP{ BSSID: strings.ToUpper(ap.BSSID), Freq: ap.Freq, Load: ap.Load, Clients: ap.NAssoc, Local: true, }) } } } if remoteOut != "" { var remote map[string]usteerAPRaw if json.Unmarshal([]byte(remoteOut), &remote) == nil { for key, ap := range remote { if ap.SSID == "" || ap.BSSID == "" { continue } host := key if i := strings.IndexByte(key, '#'); i >= 0 { host = key[:i] } addAP(ap.SSID, UsteerAP{ BSSID: strings.ToUpper(ap.BSSID), Hostname: host, Freq: ap.Freq, Load: ap.Load, Clients: ap.NAssoc, Local: false, }) } } } if clientsOut != "" { var clients map[string]map[string]usteerClientRaw if json.Unmarshal([]byte(clientsOut), &clients) == nil { for iface, macs := range clients { ssid := ifaceSSID[iface] if ssid == "" { continue } s := ssids[ssid] if s.Clients == nil { s.Clients = map[string]UsteerClient{} } for mac, c := range macs { if c.Signal >= 0 { continue // señal 0/positiva = sin datos } s.Clients[strings.ToUpper(mac)] = UsteerClient{Signal: c.Signal} } ssids[ssid] = s } } } if len(ssids) == 0 { return nil } return &UsteerData{SSIDs: ssids} } // probeDiscovery (#338): mDNS service discovery + randomized MAC detection. // Runs umdns browse; enriches with randomized MACs from wireless clients. func (p *Prober) probeDiscovery(ctx context.Context, wireless *WirelessData) *DiscoveryData { out, err := p.run.Run(ctx, CmdMdnsBrowse, 5*time.Second) var dd *DiscoveryData if err == nil && strings.TrimSpace(out) != "" && strings.TrimSpace(out) != "{}" { dd = ParseMdnsBrowse([]byte(out)) } if dd == nil { dd = &DiscoveryData{} } // Host records: a device that announces only its name (no service) shows // up here and nowhere else. These win over a service instance name, // which is the service's label rather than the device's own. if out := p.runBest(ctx, CmdMdnsHosts, 5*time.Second); strings.TrimSpace(out) != "" { if hosts := ParseMdnsHosts([]byte(out)); len(hosts) > 0 { if dd.HostByIP == nil { dd.HostByIP = map[string]string{} } for ip, name := range hosts { dd.HostByIP[ip] = name } } } // Detect randomized MACs from wireless clients. if wireless != nil { for mac := range wireless.Clients { if IsRandomizedMAC(mac) { dd.RandomMACs = append(dd.RandomMACs, mac) } } } if len(dd.Services) == 0 && len(dd.HostByIP) == 0 && len(dd.RandomMACs) == 0 { return nil } return dd } // probeArp: tabla ARP del kernel (#377). nil si no hay fichero (equipo sin // ARP, p. ej. contenedor); mapa vacío es resultado real. // // Reads `ip neigh` first, which carries the state of each entry, and only // falls back to /proc/net/arp where `ip` is missing -- there the states are // unknowable and the returned stale set is empty, the behaviour agents had // before. stale lists the MACs the kernel remembers without confirming. func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []string, devs map[string]string) { // #2110: despertar las subredes que la unidad enruta ANTES de leer la // tabla, para que el mismo `ip neigh` vea lo que el barrido confirmó. p.scanPresence(ctx) if out := p.runBest(ctx, CmdIpNeigh, 3*time.Second); out != "" { m, st := ParseIPNeigh(out) if len(m) > 0 { // #2073: un vecino STALE es una direccion que el kernel recuerda // sin confirmar. Antes de darlo por fantasma se comprueba con un // echo corto, que es lo unico que puede resolver el caso de un // host cableado con IP estatica que lleva rato en silencio. due := p.stalePingDue() var fresh string m, st, fresh = p.confirmStaleNeighbours(ctx, m, st, due) if fresh != "" { out = fresh } // #2109: el mismo recheck sobre la tabla NDP. Un host solo-IPv6 // (SLAAC, sin lease ni tráfico v4) no tiene entrada en `ip -4 // neigh`, así que esta pasada es la única que puede confirmarlo. for mac, ip := range p.confirmStaleNeighbours6(ctx, due) { if _, ok := m[mac]; !ok { m[mac] = ip } delete(st, mac) } for mac := range st { stale = append(stale, mac) } sort.Strings(stale) // stable payloads, so a diff means a change return m, stale, ParseIPNeighDevs(out) } } out := p.runBest(ctx, CmdProcArp, 3*time.Second) if out == "" { return nil, nil, nil } m := ParseArp(out) if m == nil { m = map[string]string{} } return m, nil, ParseArpDevs(out) } // Parametros del recheck activo de vecinos (#2073), compartidos por el agente // y por el sondeo SSH del servidor. El tope por ronda es deliberado: el caso // real son un punado de vecinos idle, no un barrido de subred. Un /24 completo // se deja para un arpscan, que necesita raw sockets. const ( StalePingInterval = 60 * time.Second StalePingMax = 16 StalePingTimeout = 1500 * time.Millisecond ) // StalePingTargets devuelve, en orden determinista y con tope, las IPs de los // vecinos STALE que merece la pena sondear. Compartida por el agente (ping // local, #2073) y el cliente SSH del servidor (ping desde la unidad), para que // los dos caminos sondeen lo mismo. func StalePingTargets(arp map[string]string, stale map[string]bool) []string { macs := make([]string, 0, len(stale)) for mac := range stale { macs = append(macs, mac) } sort.Strings(macs) ips := make([]string, 0, StalePingMax) for _, mac := range macs { if len(ips) >= StalePingMax { break } if ip := arp[mac]; net.ParseIP(ip) != nil { ips = append(ips, ip) } } return ips } // confirmStaleNeighbours (#2073): manda un echo corto a cada IP de vecino // STALE y relee la tabla. El kernel pasa a REACHABLE la entrada cuya respuesta // ARP llega, asi que lo que se confirma es la PAREJA IP-MAC: una IP // reutilizada por otro equipo no resucita la MAC vieja. Es justo el dato que // falta cuando un host cableado con IP estatica lleva rato en silencio, la FDB // ha caducado y el ARP solo esta STALE (#2063). // // Best effort: sin runner, sin vecinos o si la relectura falla, los datos // vuelven como estaban. Throttle propio (stalePingInterval) para no lanzar // pings en cada sondeo. // stalePingDue decide si toca ronda y, si toca, marca el sello. Es el mismo // sello para v4 y v6: una ronda de sondeo no debe pagar dos veces el throttle // ni dejar la pasada v6 sin turno por haber gastado la v4. func (p *Prober) stalePingDue() bool { p.stalePingMu.Lock() defer p.stalePingMu.Unlock() if !p.stalePingAt.IsZero() && time.Since(p.stalePingAt) < StalePingInterval { return false } p.stalePingAt = time.Now() return true } func (p *Prober) confirmStaleNeighbours(ctx context.Context, arp map[string]string, stale map[string]bool, due bool) (map[string]string, map[string]bool, string) { if p.run == nil || len(stale) == 0 || !due { return arp, stale, "" } ips := StalePingTargets(arp, stale) if len(ips) == 0 { return arp, stale, "" } var wg sync.WaitGroup for _, ip := range ips { wg.Add(1) go func(ip string) { defer wg.Done() _, _ = p.run.Run(ctx, "ping -c 1 -W 1 "+ip+" >/dev/null 2>&1", StalePingTimeout) }(ip) } wg.Wait() out := p.runBest(ctx, CmdIpNeigh, 3*time.Second) if out == "" { return arp, stale, "" } fresh, stillStale := ParseIPNeigh(out) for mac := range stale { if stillStale[mac] { continue } // Respondio: el kernel ya tiene la entrada confirmada. Se copia la IP // fresca (puede haber cambiado de direccion) y sale del set stale. if ip := fresh[mac]; ip != "" { arp[mac] = ip } delete(stale, mac) } return arp, stale, out } // confirmStaleNeighbours6 (#2109): lo mismo sobre `ip -6 neigh`. Mismo tope y // mismo throttle, un echo por vecino STALE. La diferencia es que una // direccion link-local solo se alcanza indicando la interfaz, que el propio // `ip -6 neigh` declara (`dev br-lan`). // // Devuelve MAC → dirección confirmada. Best effort: sin tabla, sin vecinos o // sin respuesta, nada. No toca `arp`: quien llama decide qué hacer con la // pareja confirmada. func (p *Prober) confirmStaleNeighbours6(ctx context.Context, due bool) map[string]string { if p.run == nil || !due { return nil } out := p.runBest(ctx, CmdIpNeigh6, 3*time.Second) if out == "" { return nil } arp, stale := ParseIPNeigh(out) if len(stale) == 0 { return nil } devs := ParseIPNeighDevsAll(out) macs := make([]string, 0, len(stale)) for mac := range stale { macs = append(macs, mac) } sort.Strings(macs) type target struct{ mac, ip, dev string } targets := make([]target, 0, StalePingMax) for _, mac := range macs { ip := arp[mac] if net.ParseIP(ip) == nil { continue } targets = append(targets, target{mac: mac, ip: ip, dev: devs[mac]}) if len(targets) >= StalePingMax { break } } if len(targets) == 0 { return nil } var wg sync.WaitGroup for _, t := range targets { wg.Add(1) go func(t target) { defer wg.Done() _, _ = p.run.Run(ctx, StalePing6Command(t.ip, t.dev), StalePingTimeout) }(t) } wg.Wait() fresh, stillStale := ParseIPNeigh(p.runBest(ctx, CmdIpNeigh6, 3*time.Second)) confirmed := map[string]string{} for _, t := range targets { if stillStale[t.mac] { continue } if ip := fresh[t.mac]; ip != "" { confirmed[t.mac] = ip } } return confirmed } // StalePing6Command: echo IPv6 con dos caminos porque no todas las unidades traen // el mismo binario (`ping -6` en busybox reciente, `ping6` en el resto). Para // link-local se añade `-I `: sin interfaz el kernel no sabe por dónde // mandarlo. func StalePing6Command(ip, dev string) string { iface := "" if strings.HasPrefix(strings.ToLower(ip), "fe80:") && dev != "" { iface = " -I " + dev } return fmt.Sprintf( "ping -6%s -c 1 -W 1 %s >/dev/null 2>&1 || ping6%s -c 1 -W 1 %s >/dev/null 2>&1", iface, ip, iface, ip, ) }