local.go 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. // local.go — prober local del agente: ejecuta EN EL ROUTER los mismos
  2. // comandos que el servidor lanza por SSH (constantes Cmd* de probe.go) y
  3. // construye el Payload con los shapes parseados. Cada sonda es best-effort:
  4. // si un comando no existe (ubus, iwinfo, brctl...) la sección queda ausente
  5. // y el servidor conserva el último dato bueno (anti-parpadeo).
  6. package probe
  7. import (
  8. "context"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "log/slog"
  13. "net"
  14. "os"
  15. "os/exec"
  16. "sort"
  17. "strings"
  18. "sync"
  19. "time"
  20. )
  21. // Runner ejecuta un comando de shell local y devuelve su stdout.
  22. // timeout 0 = default corto de sonda.
  23. type Runner interface {
  24. Run(ctx context.Context, cmd string, timeout time.Duration) (string, error)
  25. }
  26. // ShellRunner ejecuta con /bin/sh -c (BusyBox ash en OpenWrt).
  27. type ShellRunner struct {
  28. DefaultTimeout time.Duration
  29. }
  30. // Run implementa Runner.
  31. func (s ShellRunner) Run(ctx context.Context, cmd string, timeout time.Duration) (string, error) {
  32. if timeout <= 0 {
  33. timeout = s.DefaultTimeout
  34. if timeout <= 0 {
  35. timeout = 5 * time.Second
  36. }
  37. }
  38. cctx, cancel := context.WithTimeout(ctx, timeout)
  39. defer cancel()
  40. out, err := exec.CommandContext(cctx, "/bin/sh", "-c", cmd).Output()
  41. if err != nil {
  42. // #1839: iw escribe el motivo en stderr ("command failed: Operation
  43. // not supported (-95)") y Output() lo tira. Sin el, un scan rechazado
  44. // y un scan vacio llegan al servidor exactamente igual.
  45. var ee *exec.ExitError
  46. if errors.As(err, &ee) {
  47. if msg := lastLine(ee.Stderr); msg != "" {
  48. return "", fmt.Errorf("%w: %s", err, msg)
  49. }
  50. }
  51. return "", err
  52. }
  53. return string(out), nil
  54. }
  55. // lastLine devuelve la ultima linea no vacia de b.
  56. func lastLine(b []byte) string {
  57. lines := strings.Split(strings.TrimSpace(string(b)), "\n")
  58. for i := len(lines) - 1; i >= 0; i-- {
  59. if line := strings.TrimSpace(lines[i]); line != "" {
  60. return line
  61. }
  62. }
  63. return ""
  64. }
  65. // Options configura las sondas opcionales del prober.
  66. type Options struct {
  67. // WanPingTarget: si no está vacío, ping WAN (latencia + pérdida) — gateway.
  68. WanPingTarget string
  69. // GwPingTarget: si no está vacío, ping corto al gateway (latencia) — AP.
  70. GwPingTarget string
  71. // ScanInterval: mínimo entre scans de vecinos (#591/#699). 0 = usar
  72. // DefaultScanInterval; negativo (ScanDisabled) = sin scans periódicos,
  73. // solo on-demand vía ForceScan (env NETPULSE_SCAN_INTERVAL).
  74. ScanInterval time.Duration
  75. // ActiveUplink names the uplink a policy manager is steering traffic
  76. // through, when the embedder knows. nil or "" = decide from the routes,
  77. // as before.
  78. ActiveUplink func() string
  79. }
  80. // Prober sondea el equipo local y construye payloads. Mantiene el estado de
  81. // deltas (/proc/stat y /proc/net/dev) entre muestras — es el único estado
  82. // del agente y vive solo en RAM.
  83. type Prober struct {
  84. run Runner
  85. opts Options
  86. lastStat *CPUSample
  87. lastNetRx float64
  88. lastNetTx float64
  89. lastNetAt time.Time
  90. hasLastNet bool
  91. // lastNetRaw conserva el último output de /proc/net/dev de probeSystem
  92. // para derivar la sección NetIf (contadores por iface, #305) sin un
  93. // segundo cat.
  94. lastNetRaw string
  95. // lastNetIf/lastNetIfAt: contadores por interfaz del ciclo anterior, para
  96. // publicar la tasa de la WAN y no la suma de todas las bocas (#2048).
  97. lastNetIf map[string]IfCounters
  98. lastNetIfAt time.Time
  99. // lastWan: uplink del último Build, para que probeFDB marque la boca por
  100. // la que sale internet sin repetir la llamada a ubus.
  101. lastWan *WanInfo
  102. // netIfUpdated indica si el último ciclo de probeSystem consiguió
  103. // refrescar /proc/net/dev. Build solo incluye NetIf cuando es true,
  104. // evitando enviar contadores repetidos si CmdNetDev falla o tarda.
  105. netIfUpdated bool
  106. // radiosCache (#368): el resumen de radios (canal/htmode/txpower) cambia
  107. // tan poco que no merece iwinfo en cada ciclo NI en el path de eventos:
  108. // se refresca cada radiosTTL en el sondeo completo y el resto de las
  109. // llamadas reutilizan la última.
  110. radiosMu sync.Mutex
  111. radiosCache []Radio
  112. radiosAt time.Time
  113. // scanMu protege el throttle del scan pasivo de vecinos (#591): el scan
  114. // activo (`iw dev scan`) saca la radio del canal y degrada a los clientes
  115. // si se repite en cada sondeo (cada ~30 s). Se ejecuta como mucho cada
  116. // scanInterval, o antes si el server pide un refresh explícito.
  117. scanMu sync.Mutex
  118. lastScanAt time.Time
  119. scanForced bool
  120. scanInterval time.Duration
  121. // Survey en vivo (#1214): throttle propio de 5 min. No saca la radio
  122. // del canal, pero el texto crudo engorda el push: no va en cada ciclo.
  123. surveyMu sync.Mutex
  124. surveyForced bool
  125. surveyAt time.Time
  126. // Config wireless cruda (#1450): `uci show wireless` para que el server
  127. // pinte 802.11r en flotas agent-only. Se refresca cada uciWirelessTTL
  128. // (la config cambia a mano, no sola) y el valor cacheado se emite en
  129. // TODOS los pushes: un push de evento (BuildWireless) no debe dejar al
  130. // server sin la sección mientras llega el siguiente sondeo completo.
  131. uciWirelessMu sync.Mutex
  132. uciWirelessRaw string
  133. uciWirelessAt time.Time
  134. // stalePing (#2073): recheck activo de vecinos ARP en STALE. El ping a
  135. // cada IP sale del throttle como mucho cada stalePingInterval; el sondeo
  136. // del agente es cada ~30 s y una entrada STALE cambia despacio.
  137. stalePingMu sync.Mutex
  138. stalePingAt time.Time
  139. // presenceAt (#2110): última ronda del barrido de subredes enrutadas.
  140. presenceMu sync.Mutex
  141. presenceAt time.Time
  142. }
  143. // surveyInterval: mínimo entre `iw survey dump` si no hay force (#1214).
  144. const surveyInterval = 5 * time.Minute
  145. // uciWirelessTTL: mínimo entre lecturas de `uci show wireless` (#1450).
  146. // Leer /etc/config/wireless es barato, pero la configuración solo cambia
  147. // cuando alguien la edita: con 5 min el panel sigue fresco y el push no
  148. // engorda en cada ciclo.
  149. const uciWirelessTTL = 5 * time.Minute
  150. const radiosTTL = 5 * time.Minute
  151. const (
  152. // ScanDisabled: sin scans periódicos (solo on-demand vía ForceScan).
  153. // Lo selecciona NETPULSE_SCAN_INTERVAL=0; en un AP con clientes Intel
  154. // cada off-channel gap puede costar un deauth por beacon-loss (#699).
  155. ScanDisabled = -1 * time.Second
  156. // DefaultScanInterval: mínimo entre scans de vecinos si no se configura
  157. // NETPULSE_SCAN_INTERVAL. Los datos de "Análisis de canales" apenas
  158. // cambian; 30 minutos mantienen el mapa razonablemente fresco sin
  159. // martillear el aire con off-channel scans (#591/#699).
  160. DefaultScanInterval = 30 * time.Minute
  161. )
  162. // NewProber crea el prober con el runner dado.
  163. func NewProber(run Runner, opts Options) *Prober {
  164. si := opts.ScanInterval
  165. if si == 0 {
  166. si = DefaultScanInterval
  167. }
  168. return &Prober{run: run, opts: opts, scanInterval: si}
  169. }
  170. // activeUplink asks the embedder which uplink is carrying traffic. Never
  171. // panics on a callback that does: the WAN section is not worth an agent.
  172. func (p *Prober) activeUplink() string {
  173. if p.opts.ActiveUplink == nil {
  174. return ""
  175. }
  176. defer func() { _ = recover() }()
  177. return p.opts.ActiveUplink()
  178. }
  179. // ForceScan pide un scan en el próximo Build (lo usa el runtime cuando el
  180. // server envía "refresh" por SSE): no espera al intervalo del throttle.
  181. func (p *Prober) ForceScan() {
  182. p.scanMu.Lock()
  183. p.scanForced = true
  184. p.scanMu.Unlock()
  185. }
  186. // ForceSurvey pide un survey en el próximo Build (#1214): el runtime lo
  187. // llama cuando el server envía "refresh" por SSE.
  188. func (p *Prober) ForceSurvey() {
  189. p.surveyMu.Lock()
  190. p.surveyForced = true
  191. p.surveyMu.Unlock()
  192. }
  193. // surveyDue decide si toca lanzar CmdSurvey en este sondeo completo: true si
  194. // hay force pendiente o si pasó surveyInterval desde el último intento. Al
  195. // devolver true registra el intento para no repetirlo.
  196. func (p *Prober) surveyDue() bool {
  197. p.surveyMu.Lock()
  198. defer p.surveyMu.Unlock()
  199. if p.surveyForced {
  200. p.surveyForced = false
  201. p.surveyAt = time.Now()
  202. return true
  203. }
  204. if p.surveyAt.IsZero() || time.Since(p.surveyAt) >= surveyInterval {
  205. p.surveyAt = time.Now()
  206. return true
  207. }
  208. return false
  209. }
  210. // refreshUciWireless lee `uci show wireless` si toca (#1450) y lo deja en
  211. // caché para el resto de pushes. Marca el intento aunque falle: un equipo sin
  212. // uci (o un switch sin sección wireless) no reintenta en cada sondeo.
  213. func (p *Prober) refreshUciWireless(ctx context.Context) {
  214. p.uciWirelessMu.Lock()
  215. due := p.uciWirelessAt.IsZero() || time.Since(p.uciWirelessAt) >= uciWirelessTTL
  216. p.uciWirelessMu.Unlock()
  217. if !due {
  218. return
  219. }
  220. out := p.runBest(ctx, CmdUciWireless, 3*time.Second)
  221. p.uciWirelessMu.Lock()
  222. p.uciWirelessAt = time.Now()
  223. if out != "" {
  224. p.uciWirelessRaw = out
  225. }
  226. p.uciWirelessMu.Unlock()
  227. }
  228. // uciWirelessCached devuelve el último volcado bueno de la config wireless
  229. // ("" si nunca se pudo leer).
  230. func (p *Prober) uciWirelessCached() string {
  231. p.uciWirelessMu.Lock()
  232. defer p.uciWirelessMu.Unlock()
  233. return p.uciWirelessRaw
  234. }
  235. // scanDue decide si toca lanzar CmdScan en este sondeo completo: true si hay
  236. // un force pendiente (refresh del server) o si pasó scanInterval desde el
  237. // último intento. Con ScanDisabled los periódicos no corren nunca (solo
  238. // force). La primera Build tras arrancar también escanea (lastScanAt cero),
  239. // salvo desactivado. Al devolver true registra el intento para no repetirlo.
  240. func (p *Prober) scanDue() bool {
  241. p.scanMu.Lock()
  242. defer p.scanMu.Unlock()
  243. if p.scanForced {
  244. p.scanForced = false
  245. p.lastScanAt = time.Now()
  246. return true
  247. }
  248. if p.scanInterval < 0 {
  249. return false
  250. }
  251. if p.lastScanAt.IsZero() || time.Since(p.lastScanAt) >= p.scanInterval {
  252. p.lastScanAt = time.Now()
  253. return true
  254. }
  255. return false
  256. }
  257. // scanNeighbours runs one `iw dev <iface> scan` per physical radio (#1560)
  258. // and logs every cycle (#1559).
  259. //
  260. // The scan is the only probe that takes a radio off-channel, so it is also
  261. // the only one that can drop clients (#1557). Until now it left no trace in
  262. // the log, which made that correlation impossible from a router: the log line
  263. // carries the interfaces, per-radio duration and BSS count to line a drop up
  264. // against the scan that caused it.
  265. func (p *Prober) scanNeighbours(ctx context.Context, iwDev string) ([]ScanResult, []ScanOutcome) {
  266. ifaces := ParseIwDevDetailed(iwDev)
  267. targets := IwDevScanTargets(ifaces)
  268. if len(targets) == 0 {
  269. return nil, nil
  270. }
  271. names := make([]string, len(targets))
  272. for i, t := range targets {
  273. names[i] = t.Iface
  274. }
  275. start := time.Now()
  276. slog.Info("neighbor scan start", "radios", len(targets), "ifaces", strings.Join(names, ","))
  277. var scans []ScanResult
  278. outcomes := make([]ScanOutcome, 0, len(targets))
  279. for _, t := range targets {
  280. at := time.Now()
  281. used, out, err := p.scanWithFallback(ctx, ifaces, t)
  282. got := ParseScan("==IFACE==" + used.Iface + "\n" + out)
  283. scans = append(scans, got...)
  284. oc := ScanOutcome{Iface: used.Iface, Phy: used.Phy, BSS: len(got)}
  285. if err != nil {
  286. oc.Error = err.Error()
  287. }
  288. outcomes = append(outcomes, oc)
  289. slog.Info("neighbor scan radio", "iface", used.Iface, "phy", used.Phy,
  290. "bss", len(got), "duration_ms", time.Since(at).Milliseconds(), "error", oc.Error)
  291. }
  292. slog.Info("neighbor scan done", "bss", len(scans),
  293. "duration_ms", time.Since(start).Milliseconds(), "empty", len(scans) == 0)
  294. return scans, outcomes
  295. }
  296. // scanWithFallback scans the interface chosen for the radio and, when it
  297. // refuses (#1839: on Asuswrt/dhd the AP VAP answers NL80211_CMD_TRIGGER_SCAN
  298. // with "Operation not supported"), tries the other interfaces of the same phy
  299. // in the same cycle. Nothing is remembered between cycles: caching a failure
  300. // would turn one bad scan into a permanent choice.
  301. func (p *Prober) scanWithFallback(ctx context.Context, ifaces []IwDevIface, chosen IwDevIface) (IwDevIface, string, error) {
  302. out, err := p.run.Run(ctx, CmdScanIface(chosen.Iface), scanIfaceTimeout)
  303. if err == nil {
  304. return chosen, out, nil
  305. }
  306. used, lastErr := chosen, err
  307. for i, alt := range IwDevScanAlternates(ifaces, chosen) {
  308. if i >= maxScanFallbacks {
  309. break
  310. }
  311. out, err = p.run.Run(ctx, CmdScanIface(alt.Iface), scanIfaceTimeout)
  312. if err == nil {
  313. slog.Info("neighbor scan fallback", "from", chosen.Iface, "to", alt.Iface,
  314. "phy", alt.Phy, "reason", lastErr.Error())
  315. return alt, out, nil
  316. }
  317. used, lastErr = alt, err
  318. }
  319. return used, "", lastErr
  320. }
  321. // probeVlans reports the bridge VLANs, merging what the kernel says with what
  322. // the configuration declares.
  323. //
  324. // The section has existed in the payload since VLANs were added, but
  325. // nothing ever filled it: only the server's own SSH probe did, and a router
  326. // reached through its agent never takes that path, so its VLAN panel has
  327. // always been empty.
  328. //
  329. // Neither source is enough on its own. `bridge` lives in an optional package,
  330. // so plenty of routers have VLANs only the configuration knows about. And a
  331. // box that segments with 802.1Q subinterfaces (eth0.999 into br-iot) answers
  332. // with every port on VLAN 1, a valid-looking answer that says nothing about
  333. // the real layout. The two views are therefore merged always, the kernel
  334. // owning the flags and the configuration the names, subnets and the VLANs
  335. // that only exist as subinterfaces (#1757).
  336. func (p *Prober) probeVlans(ctx context.Context) ([]VlanPort, []UciNetwork) {
  337. var kernel []VlanPort
  338. if out := p.runBest(ctx, CmdBridgeVlan, 0); out != "" {
  339. kernel = ParseBridgeVlan(out)
  340. }
  341. var declared []VlanPort
  342. var networks []UciNetwork
  343. if out := p.runBest(ctx, CmdUciBridgeVlan, 0); out != "" {
  344. // La misma configuracion alimenta las dos vistas (#1889): una sola
  345. // lectura de `uci show network` por ronda.
  346. // A router uses one model or the other, so the two UCI parsers
  347. // never describe the same port: bridge-vlan sections name bridge
  348. // ports, the subinterface model names bridges and their parents.
  349. declared = MergeVlanPorts(ParseUciBridgeVlans(out), ParseUciNetworkVlans(out))
  350. networks = ParseUciNetworks(out)
  351. }
  352. return MergeVlanPorts(kernel, declared), networks
  353. }
  354. // runBest es best-effort: error → "" (la sección queda ausente).
  355. func (p *Prober) runBest(ctx context.Context, cmd string, timeout time.Duration) string {
  356. out, err := p.run.Run(ctx, cmd, timeout)
  357. if err != nil {
  358. return ""
  359. }
  360. return out
  361. }
  362. // Build ejecuta una ronda de sondas y devuelve el payload listo para empujar.
  363. // router/version los rellena el caller (main) o van aquí por comodidad.
  364. func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
  365. pl := &Payload{
  366. Router: router,
  367. Ts: time.Now().Unix(),
  368. Version: version,
  369. }
  370. // Wan antes que FDB: probeFDB usa la boca del uplink para marcarla.
  371. pl.Data.Wan, pl.Data.NetIfaces = p.probeWan(ctx)
  372. pl.Data.Vlans, pl.Data.Networks = p.probeVlans(ctx)
  373. pl.Data.System = p.probeSystem(ctx)
  374. pl.Data.Wireless = p.probeWireless(ctx, true)
  375. pl.Data.DHCP = p.probeDHCP(ctx)
  376. // LLDP antes que FDB (#1500): los puertos con vecino LLDP deciden qué
  377. // miembro de un bridge es el uplink del AP. Una sola sonda por push:
  378. // el resultado se reusa para el payload.
  379. lldpData := p.probeLldp(ctx)
  380. pl.Data.Lldp = lldpData
  381. lldpPorts := map[string]bool{}
  382. if lldpData != nil {
  383. for _, nb := range lldpData.Neighbors {
  384. if nb.Port != "" {
  385. lldpPorts[nb.Port] = true
  386. }
  387. }
  388. }
  389. pl.Data.FDB = p.probeFDB(ctx, lldpPorts, pl.Data.Wireless.GetRadios())
  390. pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx)
  391. pl.Data.Dawn = p.probeDawn(ctx)
  392. pl.Data.Usteer = p.probeUsteer(ctx)
  393. pl.Data.LuCI = p.probeLuCI(ctx)
  394. // ClientBw (#551): tráfico por cliente desde nlbwmon (solo si instalado).
  395. pl.Data.ClientBw = p.probeClientBw(ctx)
  396. // Discovery (#338): mDNS services + randomized MAC detection.
  397. pl.Data.Discovery = p.probeDiscovery(ctx, pl.Data.Wireless)
  398. // NetIf (#305): contadores por iface desde el MISMO /proc/net/dev que
  399. // leyó probeSystem (sin segundo cat). Solo se incluyen si el ciclo actual
  400. // refrescó la muestra; si no, el payload se envía sin NetIf para que el
  401. // servidor no inserte deltas 0 con contadores repetidos (#408).
  402. if p.netIfUpdated {
  403. pl.Data.NetIf = ParseNetDevIfaces(p.lastNetRaw)
  404. p.netIfUpdated = false
  405. }
  406. return pl
  407. }
  408. // BuildWireless es un sondeo rápido de solo wireless + DHCP (Fase 7.1:
  409. // disparado por eventos ubus assoc/disassoc). El servidor conserva el último
  410. // dato bueno de system y FDB (parpadeo suprimido por secciones nil).
  411. func (p *Prober) BuildWireless(ctx context.Context, router, version string) *Payload {
  412. pl := &Payload{
  413. Router: router,
  414. Ts: time.Now().Unix(),
  415. Version: version,
  416. }
  417. pl.Data.Wireless = p.probeWireless(ctx, false)
  418. pl.Data.DHCP = p.probeDHCP(ctx)
  419. pl.Data.Arp, pl.Data.ArpStale, pl.Data.ArpDevs = p.probeArp(ctx)
  420. return pl
  421. }
  422. // probeSystem: sysinfo + board + cpu/temp + netdev + pings + backhaul + MAC
  423. // del bridge. Devuelve nil solo si TODAS las sondas fallaron (equipo sin
  424. // ubus y sin /proc — no pasa en OpenWrt; cubre al fake runner de tests).
  425. func (p *Prober) probeSystem(ctx context.Context) *SystemData {
  426. sd := &SystemData{}
  427. any := false
  428. if out := p.runBest(ctx, CmdUbusSystemInfo, 0); out != "" {
  429. var si SysInfo
  430. if err := json.Unmarshal([]byte(out), &si); err == nil {
  431. if si.Memory.Total > 0 {
  432. // ubus system info no expone la caché de ficheros, la lee el
  433. // agente de /proc/meminfo (fallback silencioso si no existe).
  434. if cached := readMeminfoCachedKB(); cached > 0 {
  435. si.Memory.Cached = float64(cached) * 1024
  436. }
  437. // Y el uso real (lo que el usuario percibe) es la memoria de
  438. // los procesos; así el server no sobreestima en ubifs (#513).
  439. if rss := sumProcRSS(); rss > 0 && rss < si.Memory.Total {
  440. si.Memory.Used = rss
  441. }
  442. }
  443. sd.SysInfo = &si
  444. any = true
  445. }
  446. }
  447. // #1481: fallback portable de uptime sin ubus (Asuswrt, Linux genérico):
  448. // el primer campo de /proc/uptime. Solo rellena el uptime; el resto de
  449. // SysInfo sigue viniendo de ubus cuando existe.
  450. if sd.SysInfo == nil || sd.SysInfo.Uptime == 0 {
  451. if out := p.runBest(ctx, CmdProcUptime, 0); out != "" {
  452. if sec := ParseUptimeSec(out); sec > 0 {
  453. if sd.SysInfo == nil {
  454. sd.SysInfo = &SysInfo{}
  455. }
  456. sd.SysInfo.Uptime = sec
  457. any = true
  458. }
  459. }
  460. }
  461. // #1500: memoria portable de /proc/meminfo cuando ubus no la dio (sin
  462. // esto la ficha pinta RAM 0% en todo target sin ubus). Se rellenan los
  463. // campos crudos y NUNCA Used: el server aplica su fórmula clásica
  464. // (total-free-buffered-cached), la misma semántica que en unidades con
  465. // ubus donde Used es la suma de RSS (#513).
  466. if m := readMeminfoFieldsKB(); m.total > 0 {
  467. if sd.SysInfo == nil {
  468. sd.SysInfo = &SysInfo{}
  469. }
  470. if sd.SysInfo.Memory.Total == 0 {
  471. sd.SysInfo.Memory.Total = float64(m.total) * 1024
  472. sd.SysInfo.Memory.Free = float64(m.free) * 1024
  473. sd.SysInfo.Memory.Buffered = float64(m.buffered) * 1024
  474. sd.SysInfo.Memory.Cached = float64(m.cached) * 1024
  475. sd.SysInfo.Memory.Available = float64(m.avail) * 1024
  476. any = true
  477. }
  478. }
  479. // #1500: zona horaria portable (ubus no la da nunca; la ficha pintaba
  480. // "—" incluso en equipos con ubus).
  481. if tz := readTimezone(); tz != "" {
  482. if sd.SysInfo == nil {
  483. sd.SysInfo = &SysInfo{}
  484. }
  485. if sd.SysInfo.Timezone == "" {
  486. sd.SysInfo.Timezone = tz
  487. }
  488. }
  489. if out := p.runBest(ctx, CmdUbusSystemBoard, 0); out != "" {
  490. var b BoardInfo
  491. if err := json.Unmarshal([]byte(out), &b); err == nil {
  492. sd.Board = &b
  493. any = true
  494. }
  495. }
  496. if out := p.runBest(ctx, CmdProcStat, 0); out != "" {
  497. if cur, err := ParseProcStat(out); err == nil {
  498. if p.lastStat != nil {
  499. sd.CPU = CPUPercent(*p.lastStat, cur)
  500. }
  501. c := cur
  502. p.lastStat = &c
  503. any = true
  504. }
  505. }
  506. if out := p.runBest(ctx, CmdTemp, 0); out != "" {
  507. sd.Temp = ParseTempC(out)
  508. any = true
  509. }
  510. if out := p.runBest(ctx, CmdNetDev, 0); out != "" {
  511. rx, tx := ParseNetDev(out)
  512. now := time.Now()
  513. if p.hasLastNet {
  514. sd.RxBps, sd.TxBps = NetDevBps(p.lastNetRx, p.lastNetTx, rx, tx, now.Sub(p.lastNetAt).Seconds())
  515. // #2048: el agregado suma todas las bocas físicas y en un router
  516. // que enruta cuenta la bajada dos veces (entra por la WAN y sale
  517. // por la LAN). Si el equipo sabe cuál es su WAN, se publica la
  518. // tasa de ESA boca. Sin WAN identificable (AP) manda el agregado.
  519. if p.lastWan != nil && p.lastWan.Port != "" && p.lastNetIf != nil {
  520. rates := IfRates(p.lastNetIf, ParseNetDevIfaces(out), now.Sub(p.lastNetIfAt).Seconds())
  521. if r, ok := rates[p.lastWan.Port]; ok && r.RxBps != nil && r.TxBps != nil {
  522. sd.RxBps, sd.TxBps = r.RxBps, r.TxBps
  523. }
  524. }
  525. }
  526. // Se guarda SIEMPRE, también en la primera muestra, que es la que abre
  527. // la ventana: si no, el ciclo siguiente no tiene con qué comparar.
  528. p.lastNetIf = ParseNetDevIfaces(out)
  529. p.lastNetIfAt = now
  530. p.lastNetRx, p.lastNetTx, p.lastNetAt, p.hasLastNet = rx, tx, now, true
  531. p.lastNetRaw = out
  532. p.netIfUpdated = true
  533. any = true
  534. }
  535. if p.opts.WanPingTarget != "" {
  536. out := p.runBest(ctx, fmt.Sprintf(CmdPingWan, p.opts.WanPingTarget), 10*time.Second)
  537. sd.LatencyMs, sd.LossPct = ParsePingSummary(out)
  538. any = true
  539. } else if p.opts.GwPingTarget != "" {
  540. out := p.runBest(ctx, fmt.Sprintf(CmdPingGateway, p.opts.GwPingTarget), 10*time.Second)
  541. sd.LatencyMs, _ = ParsePingSummary(out)
  542. any = true
  543. }
  544. if out := p.runBest(ctx, CmdUbusWireless, 0); out != "" {
  545. if wifi, err := ParseWirelessUplink([]byte(out)); err == nil {
  546. sd.Backhaul = "cable"
  547. if wifi {
  548. sd.Backhaul = "wifi"
  549. }
  550. any = true
  551. }
  552. }
  553. if out := p.runBest(ctx, CmdBridgeMAC, 0); out != "" {
  554. sd.BridgeMAC = strings.ToUpper(strings.TrimSpace(out))
  555. any = true
  556. }
  557. if out := p.runBest(ctx, CmdIfaceMACs, 0); out != "" {
  558. if macs := ParseIfaceMACs(out); len(macs) > 0 {
  559. sd.IfaceMACs = macs
  560. any = true
  561. }
  562. }
  563. if !any {
  564. return nil
  565. }
  566. return sd
  567. }
  568. // probeWireless: clientes asociados + radios por banda (#368: ubus primero,
  569. // iwinfo combinado en UNA pasada como fallback, radios cacheadas radiosTTL).
  570. // full=false (path de eventos nl80211) evita iwinfo por completo: ubus para
  571. // clientes y radios de caché. nil si no hay fuente wireless.
  572. func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
  573. wd := &WirelessData{}
  574. any := false
  575. // Clientes: ubus hostapd get_clients (barato, sin ucode).
  576. if out := p.runBest(ctx, CmdHostapdClients, 5*time.Second); out != "" {
  577. wd.Clients = ParseHostapdClients(out)
  578. if len(wd.Clients) > 0 {
  579. any = true
  580. }
  581. }
  582. // Fallback (o APs sin ubus hostapd): iwinfo en UNA pasada por interfaz,
  583. // que además produce el resumen de radios.
  584. combined := ""
  585. combinedRan := false
  586. if !any {
  587. combined = p.runBest(ctx, CmdWirelessCombined, 8*time.Second)
  588. if combined != "" {
  589. clients, radios := ParseWirelessCombined(combined)
  590. // #2176: si el combinado devolvió algo (clientes o resumen de
  591. // radios), la pasada se hizo y repetir iwinfo con el par clásico
  592. // solo duplica los ioctl. En mt_wifi cada ioctl contra una
  593. // interfaz caída escribe una línea KERN_ERR en el log del router.
  594. combinedRan = len(clients) > 0 || len(radios) > 0
  595. wd.Clients = clients
  596. if len(clients) > 0 {
  597. any = true
  598. }
  599. p.radiosMu.Lock()
  600. if len(radios) > 0 {
  601. p.radiosCache, p.radiosAt = radios, time.Now()
  602. } else if time.Since(p.radiosAt) < radiosTTL {
  603. radios = p.radiosCache
  604. }
  605. p.radiosMu.Unlock()
  606. wd.Radios = radios
  607. }
  608. }
  609. // Último recurso (#368): el par de comandos clásico (equipos donde el
  610. // combinado no produjo clientes p. ej. iwinfo sin ESSID en la interfaz).
  611. if !any && !combinedRan {
  612. if out := p.runBest(ctx, CmdIwinfoAssoc, 8*time.Second); out != "" {
  613. wd.Clients = ParseWirelessClients(out)
  614. any = len(wd.Clients) > 0
  615. }
  616. }
  617. // #1481: fallback nl80211 portable sin ubus hostapd ni iwinfo (Asuswrt
  618. // con iw, Linux genérico): station dump por interfaz + radios por phy
  619. // del mismo `iw dev`.
  620. if !any {
  621. if out := p.runBest(ctx, CmdIwStationDump, 8*time.Second); out != "" {
  622. clients, radios := ParseIwWireless(out)
  623. if len(clients) > 0 {
  624. wd.Clients = clients
  625. any = true
  626. }
  627. if len(radios) > 0 {
  628. p.radiosMu.Lock()
  629. p.radiosCache, p.radiosAt = radios, time.Now()
  630. p.radiosMu.Unlock()
  631. wd.Radios = radios
  632. }
  633. }
  634. }
  635. // Broadcom dhd (RT-AX92U con Merlin): nl80211 no expone NADA util — ni
  636. // estaciones ni canal — y la unidad parece vacía aunque tenga clientes
  637. // asociados (visibles en el panel del firmware). `wl` sí los sabe. Solo
  638. // corre cuando los tiers anteriores dejaron huérfanos los clientes o
  639. // ninguna radio trae banda.
  640. {
  641. needWl := !any || len(wd.Radios) == 0
  642. if !needWl {
  643. banded := false
  644. for _, r := range wd.Radios {
  645. if r.Name != "" {
  646. banded = true
  647. break
  648. }
  649. }
  650. needWl = !banded
  651. }
  652. if needWl {
  653. if out := p.runBest(ctx, CmdWlWireless, 8*time.Second); out != "" {
  654. wclients, wradios := ParseWlWireless(out)
  655. if !any && len(wclients) > 0 {
  656. wd.Clients = wclients
  657. any = true
  658. }
  659. if len(wradios) > 0 {
  660. p.radiosMu.Lock()
  661. p.radiosCache, p.radiosAt = wradios, time.Now()
  662. p.radiosMu.Unlock()
  663. wd.Radios = wradios
  664. }
  665. }
  666. }
  667. }
  668. // Radios: solo en el sondeo completo (canal/htmode/txpower casi nunca
  669. // cambian); el path de eventos reutiliza la caché.
  670. if full {
  671. if combined != "" && wd.Radios == nil {
  672. wd.Radios = []Radio{}
  673. }
  674. if combined == "" {
  675. if out := p.runBest(ctx, CmdRadios, 8*time.Second); out != "" {
  676. radios := ParseRadios(out)
  677. // Sección UCI por banda (#500): habilita aplicar cambios de
  678. // canal desde el server. Best-effort: sin uci, sin sección.
  679. if secOut := p.runBest(ctx, CmdRadioSections, 5*time.Second); secOut != "" {
  680. sections := ParseRadioSections(secOut)
  681. for i := range radios {
  682. if sec, ok := sections[radios[i].Name]; ok {
  683. radios[i].Section = sec
  684. }
  685. }
  686. }
  687. p.radiosMu.Lock()
  688. p.radiosCache, p.radiosAt = radios, time.Now()
  689. wd.Radios = p.radiosCache
  690. p.radiosMu.Unlock()
  691. }
  692. }
  693. // `iw dev` a secas, barato y estable: alimenta con UN solo spawn los
  694. // BSSIDs propios (#1087) y la lista de interfaces a escanear (#1338).
  695. iwDev := p.runBest(ctx, CmdIwDev, 5*time.Second)
  696. // Scan pasivo de vecinos (#452): SOLO en sondeo completo y con
  697. // throttle (#591) para no sacar la radio del canal en cada push.
  698. // #1338: un comando POR INTERFAZ, cada una con su propio presupuesto
  699. // (8 s). Antes el bucle completo compartía un timeout de 10 s y, al
  700. // expirar, la salida parcial se descartaba entera: una radio lenta
  701. // (5 GHz en canal DFS, scan pasivo canal a canal) dejaba la unidad
  702. // sin NINGÚN vecino aunque las demás interfaces sí hubieran
  703. // escaneado con éxito.
  704. if p.scanDue() && iwDev != "" {
  705. scans, outcomes := p.scanNeighbours(ctx, iwDev)
  706. if len(scans) > 0 {
  707. wd.Scans = scans
  708. }
  709. if len(outcomes) > 0 {
  710. wd.ScanOutcomes = outcomes
  711. }
  712. }
  713. // BSSIDs propios (#1087), del mismo `iw dev` de arriba.
  714. if iwDev != "" {
  715. wd.OwnBssids = ParseIwDev(iwDev)
  716. }
  717. // Survey en vivo (#1214): ocupación por canal para la lente "Ahora"
  718. // del server en unidades agent-only (sin SSH). Texto crudo: el
  719. // parser vive en el server y así no se duplica.
  720. if p.surveyDue() {
  721. if out := p.runBest(ctx, CmdSurvey, 10*time.Second); out != "" {
  722. wd.SurveyRaw = out
  723. }
  724. }
  725. } else {
  726. p.radiosMu.Lock()
  727. cached := p.radiosCache
  728. p.radiosMu.Unlock()
  729. if len(cached) > 0 {
  730. wd.Radios = cached
  731. if len(wd.Clients) > 0 {
  732. any = true
  733. }
  734. }
  735. }
  736. // #1092: `any` lo marcaban solo los CLIENTES: una unidad sin clientes
  737. // asociados en ese momento descartaba TODA la sección wireless (radios,
  738. // scans, BSSIDs propios) y el server la veía como "sin WiFi". Que haya
  739. // radios o BSSIDs propios también prueba presencia wireless.
  740. if !any && (len(wd.Radios) > 0 || len(wd.OwnBssids) > 0) {
  741. any = true
  742. }
  743. // Config wireless cruda (#1450): alimenta la vista 802.11r del server en
  744. // flotas agent-only. Se refresca solo en el sondeo completo y se emite
  745. // SIEMPRE desde la caché (también en el path de eventos, para que el
  746. // último payload no pierda la sección). No cuenta para `any`: una unidad
  747. // con la config presente pero sin wifi operativa no debe aparecer como
  748. // wireless vivo.
  749. if full {
  750. p.refreshUciWireless(ctx)
  751. }
  752. wd.UciWirelessRaw = p.uciWirelessCached()
  753. if !any {
  754. return nil
  755. }
  756. if wd.Clients == nil {
  757. wd.Clients = map[string]WirelessClient{}
  758. }
  759. if wd.Radios == nil {
  760. wd.Radios = []Radio{}
  761. }
  762. return wd
  763. }
  764. // probeDHCP: ubus dhcp ipv4leases con fallback a /tmp/dhcp.leases, más
  765. // gl-clients (GL.iNet) como superset para resolver IPs sin lease
  766. // (issue #5 bug 1 — el gateway Flint2 llega por esta ruta de agente).
  767. func (p *Prober) probeDHCP(ctx context.Context) *DHCPData {
  768. var dd *DHCPData
  769. if out := p.runBest(ctx, CmdDhcpUbus, 0); out != "" {
  770. if leases, err := ParseDhcpUbus([]byte(out)); err == nil {
  771. dd = &DHCPData{Leases: leases}
  772. }
  773. }
  774. if dd == nil {
  775. out := p.runBest(ctx, CmdDhcpFile, 0)
  776. if out == "" {
  777. return nil
  778. }
  779. dd = &DHCPData{Leases: ParseDhcpLeasesFile(out)}
  780. }
  781. if out := p.runBest(ctx, CmdGlClients, 0); out != "" {
  782. if gl, err := ParseGlClients([]byte(out)); err == nil {
  783. dd.GlClients = gl
  784. }
  785. }
  786. // Names pinned in /etc/config/dhcp: the only ones a client with a fixed
  787. // address of its own ever gets.
  788. if out := p.runBest(ctx, CmdDhcpReservations, 0); out != "" {
  789. dd.Reservations = ParseDhcpReservations(out)
  790. }
  791. return dd
  792. }
  793. // probeWan: estado del uplink (proto, IP pública, gateway, DNS y la boca por
  794. // la que sale) e interfaces lógicas de `ubus call network.interface dump`,
  795. // eligiendo el uplink por su ruta por defecto y no por llamarse "wan". WanInfo
  796. // es nil cuando no hay uplink utilizable (un AP o un equipo sin ubus), pero
  797. // conserva las interfaces lógicas. Guarda el uplink para probeFDB.
  798. func (p *Prober) probeWan(ctx context.Context) (*WanInfo, []NetIface) {
  799. p.lastWan = nil
  800. out := p.runBest(ctx, CmdNetworkDump, 0)
  801. if out == "" {
  802. return nil, nil
  803. }
  804. dump := ParseInterfaceDump([]byte(out), p.activeUplink())
  805. info := dump.Wan
  806. if info.Proto == "" && info.IP == "" && info.Gateway == "" && info.Port == "" {
  807. return nil, dump.Ifaces
  808. }
  809. p.lastWan = &info
  810. return &info, dump.Ifaces
  811. }
  812. // probeFDB: MACs aprendidas (brctl) + puertos ethernet (layout + /sys).
  813. func (p *Prober) probeFDB(ctx context.Context, lldpPorts map[string]bool, radios []Radio) *FDBData {
  814. fd := &FDBData{}
  815. any := false
  816. if out := p.runBest(ctx, CmdBridgeFDB, 0); out != "" {
  817. fd.MACs, fd.WirelessSide, fd.VLANs = ParseBridgeFdbVlans(out)
  818. fd.WirelessSide = bandTagWirelessSide(fd.WirelessSide, radios)
  819. any = true
  820. }
  821. statesOut := p.runBest(ctx, CmdPortStates, 0)
  822. if statesOut != "" {
  823. states := ParsePortStates(statesOut)
  824. layout := []PortLayout{}
  825. if out := p.runBest(ctx, CmdBoardJSON, 0); out != "" {
  826. if lay, err := ParsePortLayout(out); err == nil {
  827. layout = lay
  828. }
  829. }
  830. members := map[string]bool{}
  831. if out := p.runBest(ctx, CmdBrifMembers, 0); out != "" {
  832. for _, l := range strings.Split(strings.TrimSpace(out), "\n") {
  833. if l != "" {
  834. members[l] = true
  835. }
  836. }
  837. }
  838. // Contadores por iface (#305): absolutos del MISMO /proc/net/dev de
  839. // probeSystem (si ya corrió este ciclo); los rates los computa el
  840. // server con el delta entre payloads.
  841. var ifaces map[string]IfRate
  842. if p.lastNetRaw != "" {
  843. ifaces = map[string]IfRate{}
  844. for name, c := range ParseNetDevIfaces(p.lastNetRaw) {
  845. ifaces[name] = IfRate{IfCounters: c}
  846. }
  847. }
  848. // Boca del uplink: la marca como WAN cuando el layout no trae
  849. // ninguna (PPPoE sobre una boca "lan" y demás).
  850. uplink := ""
  851. if p.lastWan != nil {
  852. uplink = p.lastWan.Port
  853. }
  854. // #1500: sin ubus no hay WanInfo: el uplink sale de la ruta default
  855. // de /proc/net/route. Si cae en un bridge (APs: la default vive en
  856. // br0), la boca física es el miembro con un vecino LLDP (la que
  857. // mira al core) o, en su defecto, el de más rx bytes.
  858. if uplink == "" {
  859. uplink = defaultRouteIface()
  860. }
  861. if uplink != "" && isBridgeIface(uplink) {
  862. if m := bridgeMemberUplink(members, lldpPorts, states, ifaces); m != "" {
  863. uplink = m
  864. }
  865. }
  866. fd.Ports = BuildEthPorts(layout, states, members, ifaces, uplink)
  867. any = true
  868. }
  869. if !any {
  870. return nil
  871. }
  872. if fd.MACs == nil {
  873. fd.MACs = map[string]string{}
  874. }
  875. if fd.Ports == nil {
  876. fd.Ports = []EthPort{}
  877. }
  878. return fd
  879. }
  880. // bandTagWirelessSide convierte el mapa MAC→puerto inalámbrico del FDB en
  881. // MAC→banda, casando la MAC de la interfaz del puerto (o la del padre para
  882. // subinterfaces VLAN como wl0.1) con el BSSID de una radio sondeada en el
  883. // mismo ciclo. Sin radio que casar, la MAC se descarta: mejor no decir nada
  884. // que inventarse una banda. Es el hint que evita que el server clasifique
  885. // como cableado un MAC que solo vive detrás de una radio propia.
  886. func bandTagWirelessSide(side map[string]string, radios []Radio) map[string]string {
  887. if len(side) == 0 {
  888. return nil
  889. }
  890. bandByBSSID := make(map[string]string, len(radios))
  891. for _, r := range radios {
  892. if r.BSSID != "" {
  893. bandByBSSID[strings.ToUpper(r.BSSID)] = r.Name
  894. }
  895. }
  896. addrOf := func(iface string) string {
  897. raw, err := os.ReadFile("/sys/class/net/" + iface + "/address")
  898. if err != nil {
  899. return ""
  900. }
  901. return strings.ToUpper(strings.TrimSpace(string(raw)))
  902. }
  903. baseOf := func(port string) string {
  904. if i := strings.IndexAny(port, ".@"); i >= 0 {
  905. return port[:i]
  906. }
  907. return port
  908. }
  909. // Pasada 1: MACs propias del equipo (BSSID de cada radio + dirección de
  910. // cada interfaz de puerto inalámbrico, ambas con su variante de bit LAA
  911. // volteado: el bridge las aprende como si fueran estaciones externas).
  912. // Lo que cae en este conjunto es identidad, no cliente.
  913. self := map[string]bool{}
  914. addSelf := func(mac string) {
  915. if mac == "" {
  916. return
  917. }
  918. self[mac] = true
  919. if flipped, err := hexFlipLAA(mac); err == nil {
  920. self[flipped] = true
  921. }
  922. }
  923. for bssid := range bandByBSSID {
  924. addSelf(bssid)
  925. }
  926. addrs := map[string]string{}
  927. for _, port := range side {
  928. for _, iface := range []string{port, baseOf(port)} {
  929. if iface == "" {
  930. continue
  931. }
  932. if _, done := addrs[iface]; !done {
  933. addrs[iface] = addrOf(iface)
  934. }
  935. }
  936. }
  937. for _, addr := range addrs {
  938. addSelf(addr)
  939. }
  940. // Pasada 2: banda por MAC casando la dirección del puerto con un BSSID
  941. // sondeado; sin radio que casar (o MAC propia) la MAC se descarta: mejor
  942. // no decir nada que inventarse una banda.
  943. out := make(map[string]string, len(side))
  944. for mac, port := range side {
  945. um := strings.ToUpper(mac)
  946. if self[um] {
  947. continue
  948. }
  949. band := ""
  950. for _, iface := range []string{port, baseOf(port)} {
  951. if a := addrs[iface]; a != "" {
  952. if b, ok := bandByBSSID[a]; ok {
  953. band = b
  954. break
  955. }
  956. }
  957. }
  958. if band != "" {
  959. out[um] = band
  960. }
  961. }
  962. if len(out) == 0 {
  963. return nil
  964. }
  965. return out
  966. }
  967. // hexFlipLAA devuelve la MAC con el bit localmente-administrada (0x02 del
  968. // primer octeto) volteado, en formato colon-upper como el resto del FDB.
  969. func hexFlipLAA(mac string) (string, error) {
  970. b, err := net.ParseMAC(mac)
  971. if err != nil || len(b) == 0 {
  972. return "", err
  973. }
  974. b[0] ^= 0x02
  975. return strings.ToUpper(b.String()), nil
  976. }
  977. // probeLldp: vecinos LLDP de lldpd (#489). Contrato: Available=false cuando
  978. // lldpcli no existe (hint "instala lldpd"); Available=true con Neighbors
  979. // nil si la sonda falla esta ronda (lldpd parado, salida no JSON); [] vacío
  980. // honesto cuando no hay vecinos. Solo en el sondeo completo (Build): los
  981. // pushes event-driven no re-sondean y el server conserva el último bueno.
  982. func (p *Prober) probeLldp(ctx context.Context) *LldpData {
  983. if p.runBest(ctx, CmdLldpCheck, 0) == "" {
  984. return &LldpData{Available: false}
  985. }
  986. out := p.runBest(ctx, CmdLldpNeighbors, 5*time.Second)
  987. neighbors, err := ParseLldpNeighbors([]byte(out))
  988. if out != "" && err != nil {
  989. // #1481: JSON no vacío pero inparseable (lldpd exótico): el mismo
  990. // vecino en texto plano antes de declarar la ronda fallida. Con
  991. // out=="" simplemente no hay vecinos: no se gasta un spawn en el
  992. // texto (review de #1491, es el caso común de unidad sin vecinos).
  993. if txt := p.runBest(ctx, CmdLldpNeighborsText, 5*time.Second); txt != "" {
  994. neighbors, err = ParseLldpNeighborsText(txt), nil
  995. }
  996. }
  997. if err != nil {
  998. // JSON y texto fallaron esta ronda: Available con Neighbors nil
  999. // (el server conserva el último dato bueno).
  1000. return &LldpData{Available: true}
  1001. }
  1002. d := &LldpData{Available: true, Neighbors: neighbors}
  1003. // #1369: 0 vecinos honestos + binding SOLO a bridge (br-lan) = el caso
  1004. // silencioso de OpenWrt (los frames LLDP no suben al bridge master en
  1005. // nss-dp/DSA). Solo entonces consultamos UCI (un fork extra por ronda
  1006. // cuando sí hay vecinos sería desperdicio).
  1007. if len(neighbors) == 0 && LldpdBridgeOnly(p.runBest(ctx, CmdLldpdIfaces, 0)) {
  1008. d.Hint = HintLldpdBridgeOnly
  1009. }
  1010. return d
  1011. }
  1012. // probeClientBw: contadores por MAC de nlbwmon (#551). Contrato: Available=
  1013. // false cuando nlbw no está instalado (el server usa hostapd bytes); true con
  1014. // Hosts nil si la sonda falla esta ronda; {} vacío honesto si el daemon no
  1015. // tiene datos aún. Solo en el sondeo completo (Build), como LLDP.
  1016. func (p *Prober) probeClientBw(ctx context.Context) *ClientBwData {
  1017. if p.runBest(ctx, CmdNlbwmonCheck, 0) == "" {
  1018. return &ClientBwData{Available: false}
  1019. }
  1020. out := p.runBest(ctx, CmdNlbwmonJSON, 5*time.Second)
  1021. if out == "" {
  1022. return &ClientBwData{Available: true}
  1023. }
  1024. hosts, err := ParseNlbwJSON([]byte(out))
  1025. if err != nil {
  1026. return &ClientBwData{Available: true}
  1027. }
  1028. return &ClientBwData{Available: true, Hosts: hosts}
  1029. }
  1030. // probeLuCI: etiquetas de puertos/VLANs de LuCI (issue #258), si el router
  1031. // las define en /etc/config/luci. Best-effort: sin fichero/sección → nil.
  1032. func (p *Prober) probeLuCI(ctx context.Context) *LuCILabels {
  1033. out := p.runBest(ctx, CmdLuCILabels, 0)
  1034. if out == "" {
  1035. return nil
  1036. }
  1037. return ParseLuCILabels(out)
  1038. }
  1039. // probeDawn: lee el estado de DAWN (roaming/band-steering, Fase 14) vía
  1040. // `ubus call dawn get_network`. Devuelve nil si DAWN no está instalado
  1041. // (fail-soft silencioso — la sección queda ausente en el payload).
  1042. //
  1043. // El output de ubus mezcla campos del AP (channel, freq, etc.) con clientes
  1044. // anidados (MAC → {signal, ht, ...}) en el mismo objeto por BSSID. Los
  1045. // distinguimos por tipo: escalares = metadata del AP, objetos = clientes.
  1046. func (p *Prober) probeDawn(ctx context.Context) *DawnData {
  1047. out := p.runBest(ctx, "ubus call dawn get_network", 5*time.Second)
  1048. if out == "" {
  1049. return nil
  1050. }
  1051. // SSID → BSSID → {campos mixtos}
  1052. var raw map[string]map[string]json.RawMessage
  1053. if err := json.Unmarshal([]byte(out), &raw); err != nil {
  1054. return nil
  1055. }
  1056. ssids := make(map[string]DawnSSID, len(raw))
  1057. for ssid, bssids := range raw {
  1058. var aps []DawnAP
  1059. clients := make(map[string]DawnClient)
  1060. for bssidKey, bssidRaw := range bssids {
  1061. // Parsear todos los campos del BSSID como mapa flexible.
  1062. var fields map[string]json.RawMessage
  1063. if err := json.Unmarshal(bssidRaw, &fields); err != nil {
  1064. continue
  1065. }
  1066. // ¿Tiene "channel"? → es un AP.
  1067. chRaw, hasChannel := fields["channel"]
  1068. if !hasChannel {
  1069. continue
  1070. }
  1071. var channel int
  1072. json.Unmarshal(chRaw, &channel)
  1073. if channel == 0 {
  1074. continue
  1075. }
  1076. ap := DawnAP{BSSID: bssidKey, Channel: channel}
  1077. json.Unmarshal(fields["freq"], &ap.Freq)
  1078. json.Unmarshal(fields["channel_utilization"], &ap.Utilization)
  1079. json.Unmarshal(fields["num_sta"], &ap.Clients)
  1080. json.Unmarshal(fields["ht_support"], &ap.HT)
  1081. json.Unmarshal(fields["vht_support"], &ap.VHT)
  1082. json.Unmarshal(fields["local"], &ap.Local)
  1083. json.Unmarshal(fields["hostname"], &ap.Hostname)
  1084. aps = append(aps, ap)
  1085. // Buscar clientes anidados: cualquier key cuyo valor sea un
  1086. // objeto (empieza con '{') y tenga "signal".
  1087. for mac, valRaw := range fields {
  1088. if mac == "channel" || mac == "freq" || mac == "channel_utilization" ||
  1089. mac == "num_sta" || mac == "ht_support" || mac == "vht_support" ||
  1090. mac == "local" || mac == "hostname" || mac == "iface" ||
  1091. mac == "neighbor_report" || mac == "op_class" {
  1092. continue
  1093. }
  1094. s := strings.TrimSpace(string(valRaw))
  1095. if !strings.HasPrefix(s, "{") {
  1096. continue
  1097. }
  1098. var c struct {
  1099. Signal int `json:"signal"`
  1100. HT bool `json:"ht"`
  1101. VHT bool `json:"vht"`
  1102. }
  1103. if json.Unmarshal(valRaw, &c) == nil && c.Signal < 0 {
  1104. clients[strings.ToUpper(mac)] = DawnClient{
  1105. BSSID: bssidKey, Signal: c.Signal, HT: c.HT, VHT: c.VHT,
  1106. }
  1107. }
  1108. }
  1109. }
  1110. if len(aps) > 0 {
  1111. ssids[ssid] = DawnSSID{APs: aps, Clients: clients}
  1112. }
  1113. }
  1114. if len(ssids) == 0 {
  1115. return nil
  1116. }
  1117. return &DawnData{SSIDs: ssids}
  1118. }
  1119. // probeUsteer: lee el estado de usteer (roaming/steering) vía
  1120. // `ubus call usteer local_info`, `remote_info` y `connected_clients`. Devuelve
  1121. // nil si usteer no está instalado (fail-soft silencioso — la sección queda
  1122. // ausente en el payload).
  1123. func (p *Prober) probeUsteer(ctx context.Context) *UsteerData {
  1124. localOut := p.runBest(ctx, "ubus call usteer local_info", 5*time.Second)
  1125. remoteOut := p.runBest(ctx, "ubus call usteer remote_info", 5*time.Second)
  1126. if localOut == "" && remoteOut == "" {
  1127. return nil
  1128. }
  1129. clientsOut := p.runBest(ctx, "ubus call usteer connected_clients", 5*time.Second)
  1130. return ParseUsteer(localOut, remoteOut, clientsOut)
  1131. }
  1132. // usteerAPRaw es la forma cruda de una entrada de `ubus call usteer
  1133. // local_info` / `remote_info` (por BSSID/iface).
  1134. type usteerAPRaw struct {
  1135. BSSID string `json:"bssid"`
  1136. SSID string `json:"ssid"`
  1137. Freq int `json:"freq"`
  1138. NAssoc int `json:"n_assoc"`
  1139. Load int `json:"load"`
  1140. }
  1141. // usteerClientRaw es la forma cruda de una entrada de `ubus call usteer
  1142. // connected_clients` (por MAC).
  1143. type usteerClientRaw struct {
  1144. Signal int `json:"signal"`
  1145. }
  1146. // ParseUsteer parsea las salidas de `ubus call usteer local_info`,
  1147. // `remote_info` y `connected_clients` a un UsteerData (SSID → APs + clientes).
  1148. // Función pura para testear sin ejecutar ubus.
  1149. //
  1150. // - local_info: {"<iface>": {bssid, ssid, freq, n_assoc, load, ...}} (este router)
  1151. // - remote_info: {"<ip>#<iface>": {...}} (otros routers)
  1152. // - connected_clients: {"<iface>": {"<mac>": {signal, ...}}}
  1153. //
  1154. // Nota: usteer usa el nombre ubus de hostapd (`hostapd.phy0-ap0`) en
  1155. // local_info/remote_info y el ifname (`hostapd.wlan0`) en connected_clients;
  1156. // cuando ambas convenciones no casan, el cliente se omite (no se le asigna un
  1157. // SSID erróneo).
  1158. func ParseUsteer(localOut, remoteOut, clientsOut string) *UsteerData {
  1159. ssids := make(map[string]UsteerSSID)
  1160. ifaceSSID := map[string]string{}
  1161. addAP := func(ssid string, ap UsteerAP) {
  1162. s := ssids[ssid]
  1163. s.APs = append(s.APs, ap)
  1164. if s.Clients == nil {
  1165. s.Clients = map[string]UsteerClient{}
  1166. }
  1167. ssids[ssid] = s
  1168. }
  1169. if localOut != "" {
  1170. var local map[string]usteerAPRaw
  1171. if json.Unmarshal([]byte(localOut), &local) == nil {
  1172. for iface, ap := range local {
  1173. if ap.SSID == "" || ap.BSSID == "" {
  1174. continue
  1175. }
  1176. ifaceSSID[iface] = ap.SSID
  1177. addAP(ap.SSID, UsteerAP{
  1178. BSSID: strings.ToUpper(ap.BSSID), Freq: ap.Freq,
  1179. Load: ap.Load, Clients: ap.NAssoc, Local: true,
  1180. })
  1181. }
  1182. }
  1183. }
  1184. if remoteOut != "" {
  1185. var remote map[string]usteerAPRaw
  1186. if json.Unmarshal([]byte(remoteOut), &remote) == nil {
  1187. for key, ap := range remote {
  1188. if ap.SSID == "" || ap.BSSID == "" {
  1189. continue
  1190. }
  1191. host := key
  1192. if i := strings.IndexByte(key, '#'); i >= 0 {
  1193. host = key[:i]
  1194. }
  1195. addAP(ap.SSID, UsteerAP{
  1196. BSSID: strings.ToUpper(ap.BSSID), Hostname: host, Freq: ap.Freq,
  1197. Load: ap.Load, Clients: ap.NAssoc, Local: false,
  1198. })
  1199. }
  1200. }
  1201. }
  1202. if clientsOut != "" {
  1203. var clients map[string]map[string]usteerClientRaw
  1204. if json.Unmarshal([]byte(clientsOut), &clients) == nil {
  1205. for iface, macs := range clients {
  1206. ssid := ifaceSSID[iface]
  1207. if ssid == "" {
  1208. continue
  1209. }
  1210. s := ssids[ssid]
  1211. if s.Clients == nil {
  1212. s.Clients = map[string]UsteerClient{}
  1213. }
  1214. for mac, c := range macs {
  1215. if c.Signal >= 0 {
  1216. continue // señal 0/positiva = sin datos
  1217. }
  1218. s.Clients[strings.ToUpper(mac)] = UsteerClient{Signal: c.Signal}
  1219. }
  1220. ssids[ssid] = s
  1221. }
  1222. }
  1223. }
  1224. if len(ssids) == 0 {
  1225. return nil
  1226. }
  1227. return &UsteerData{SSIDs: ssids}
  1228. }
  1229. // probeDiscovery (#338): mDNS service discovery + randomized MAC detection.
  1230. // Runs umdns browse; enriches with randomized MACs from wireless clients.
  1231. func (p *Prober) probeDiscovery(ctx context.Context, wireless *WirelessData) *DiscoveryData {
  1232. out, err := p.run.Run(ctx, CmdMdnsBrowse, 5*time.Second)
  1233. var dd *DiscoveryData
  1234. if err == nil && strings.TrimSpace(out) != "" && strings.TrimSpace(out) != "{}" {
  1235. dd = ParseMdnsBrowse([]byte(out))
  1236. }
  1237. if dd == nil {
  1238. dd = &DiscoveryData{}
  1239. }
  1240. // Host records: a device that announces only its name (no service) shows
  1241. // up here and nowhere else. These win over a service instance name,
  1242. // which is the service's label rather than the device's own.
  1243. if out := p.runBest(ctx, CmdMdnsHosts, 5*time.Second); strings.TrimSpace(out) != "" {
  1244. if hosts := ParseMdnsHosts([]byte(out)); len(hosts) > 0 {
  1245. dd.MergeMdnsHosts(hosts)
  1246. }
  1247. }
  1248. // Detect randomized MACs from wireless clients.
  1249. if wireless != nil {
  1250. for mac := range wireless.Clients {
  1251. if IsRandomizedMAC(mac) {
  1252. dd.RandomMACs = append(dd.RandomMACs, mac)
  1253. }
  1254. }
  1255. }
  1256. if len(dd.Services) == 0 && len(dd.HostByIP) == 0 && len(dd.Models) == 0 && len(dd.Manufacturers) == 0 && len(dd.RandomMACs) == 0 {
  1257. return nil
  1258. }
  1259. return dd
  1260. }
  1261. // probeArp: tabla ARP del kernel (#377). nil si no hay fichero (equipo sin
  1262. // ARP, p. ej. contenedor); mapa vacío es resultado real.
  1263. //
  1264. // Reads `ip neigh` first, which carries the state of each entry, and only
  1265. // falls back to /proc/net/arp where `ip` is missing -- there the states are
  1266. // unknowable and the returned stale set is empty, the behaviour agents had
  1267. // before. stale lists the MACs the kernel remembers without confirming.
  1268. func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []string, devs map[string]string) {
  1269. // #2110: despertar las subredes que la unidad enruta ANTES de leer la
  1270. // tabla, para que el mismo `ip neigh` vea lo que el barrido confirmó.
  1271. p.scanPresence(ctx)
  1272. if out := p.runBest(ctx, CmdIpNeigh, 3*time.Second); out != "" {
  1273. m, st := ParseIPNeigh(out)
  1274. if len(m) > 0 {
  1275. // #2073: un vecino STALE es una direccion que el kernel recuerda
  1276. // sin confirmar. Antes de darlo por fantasma se comprueba con un
  1277. // echo corto, que es lo unico que puede resolver el caso de un
  1278. // host cableado con IP estatica que lleva rato en silencio.
  1279. due := p.stalePingDue()
  1280. var fresh string
  1281. m, st, fresh = p.confirmStaleNeighbours(ctx, m, st, due)
  1282. if fresh != "" {
  1283. out = fresh
  1284. }
  1285. // #2109: el mismo recheck sobre la tabla NDP. Un host solo-IPv6
  1286. // (SLAAC, sin lease ni tráfico v4) no tiene entrada en `ip -4
  1287. // neigh`, así que esta pasada es la única que puede confirmarlo.
  1288. // #2200: la interfaz viaja con la pareja confirmada, o el servidor
  1289. // no puede marcar como lado WAN un vecino IPv6 de la boca WAN.
  1290. devs := ParseIPNeighDevs(out)
  1291. v6arp, v6devs := p.confirmStaleNeighbours6(ctx, due)
  1292. for mac, ip := range v6arp {
  1293. if _, ok := m[mac]; !ok {
  1294. m[mac] = ip
  1295. }
  1296. delete(st, mac)
  1297. if _, ok := devs[mac]; !ok {
  1298. if d := v6devs[mac]; d != "" {
  1299. devs[mac] = d
  1300. }
  1301. }
  1302. }
  1303. for mac := range st {
  1304. stale = append(stale, mac)
  1305. }
  1306. sort.Strings(stale) // stable payloads, so a diff means a change
  1307. return m, stale, devs
  1308. }
  1309. }
  1310. out := p.runBest(ctx, CmdProcArp, 3*time.Second)
  1311. if out == "" {
  1312. return nil, nil, nil
  1313. }
  1314. m := ParseArp(out)
  1315. if m == nil {
  1316. m = map[string]string{}
  1317. }
  1318. return m, nil, ParseArpDevs(out)
  1319. }
  1320. // Parametros del recheck activo de vecinos (#2073), compartidos por el agente
  1321. // y por el sondeo SSH del servidor. El tope por ronda es deliberado: el caso
  1322. // real son un punado de vecinos idle, no un barrido de subred. Un /24 completo
  1323. // se deja para un arpscan, que necesita raw sockets.
  1324. const (
  1325. StalePingInterval = 60 * time.Second
  1326. StalePingMax = 16
  1327. StalePingTimeout = 1500 * time.Millisecond
  1328. )
  1329. // StalePingTargets devuelve, en orden determinista y con tope, las IPs de los
  1330. // vecinos STALE que merece la pena sondear. Compartida por el agente (ping
  1331. // local, #2073) y el cliente SSH del servidor (ping desde la unidad), para que
  1332. // los dos caminos sondeen lo mismo.
  1333. func StalePingTargets(arp map[string]string, stale map[string]bool) []string {
  1334. macs := make([]string, 0, len(stale))
  1335. for mac := range stale {
  1336. macs = append(macs, mac)
  1337. }
  1338. sort.Strings(macs)
  1339. ips := make([]string, 0, StalePingMax)
  1340. for _, mac := range macs {
  1341. if len(ips) >= StalePingMax {
  1342. break
  1343. }
  1344. if ip := arp[mac]; net.ParseIP(ip) != nil {
  1345. ips = append(ips, ip)
  1346. }
  1347. }
  1348. return ips
  1349. }
  1350. // confirmStaleNeighbours (#2073): manda un echo corto a cada IP de vecino
  1351. // STALE y relee la tabla. El kernel pasa a REACHABLE la entrada cuya respuesta
  1352. // ARP llega, asi que lo que se confirma es la PAREJA IP-MAC: una IP
  1353. // reutilizada por otro equipo no resucita la MAC vieja. Es justo el dato que
  1354. // falta cuando un host cableado con IP estatica lleva rato en silencio, la FDB
  1355. // ha caducado y el ARP solo esta STALE (#2063).
  1356. //
  1357. // Best effort: sin runner, sin vecinos o si la relectura falla, los datos
  1358. // vuelven como estaban. Throttle propio (stalePingInterval) para no lanzar
  1359. // pings en cada sondeo.
  1360. // stalePingDue decide si toca ronda y, si toca, marca el sello. Es el mismo
  1361. // sello para v4 y v6: una ronda de sondeo no debe pagar dos veces el throttle
  1362. // ni dejar la pasada v6 sin turno por haber gastado la v4.
  1363. func (p *Prober) stalePingDue() bool {
  1364. p.stalePingMu.Lock()
  1365. defer p.stalePingMu.Unlock()
  1366. if !p.stalePingAt.IsZero() && time.Since(p.stalePingAt) < StalePingInterval {
  1367. return false
  1368. }
  1369. p.stalePingAt = time.Now()
  1370. return true
  1371. }
  1372. func (p *Prober) confirmStaleNeighbours(ctx context.Context, arp map[string]string, stale map[string]bool, due bool) (map[string]string, map[string]bool, string) {
  1373. if p.run == nil || len(stale) == 0 || !due {
  1374. return arp, stale, ""
  1375. }
  1376. ips := StalePingTargets(arp, stale)
  1377. if len(ips) == 0 {
  1378. return arp, stale, ""
  1379. }
  1380. var wg sync.WaitGroup
  1381. for _, ip := range ips {
  1382. wg.Add(1)
  1383. go func(ip string) {
  1384. defer wg.Done()
  1385. _, _ = p.run.Run(ctx, "ping -c 1 -W 1 "+ip+" >/dev/null 2>&1", StalePingTimeout)
  1386. }(ip)
  1387. }
  1388. wg.Wait()
  1389. out := p.runBest(ctx, CmdIpNeigh, 3*time.Second)
  1390. if out == "" {
  1391. return arp, stale, ""
  1392. }
  1393. fresh, stillStale := ParseIPNeigh(out)
  1394. for mac := range stale {
  1395. if stillStale[mac] {
  1396. continue
  1397. }
  1398. // Respondio: el kernel ya tiene la entrada confirmada. Se copia la IP
  1399. // fresca (puede haber cambiado de direccion) y sale del set stale.
  1400. if ip := fresh[mac]; ip != "" {
  1401. arp[mac] = ip
  1402. }
  1403. delete(stale, mac)
  1404. }
  1405. return arp, stale, out
  1406. }
  1407. // confirmStaleNeighbours6 (#2109): lo mismo sobre `ip -6 neigh`. Mismo tope y
  1408. // mismo throttle, un echo por vecino STALE. La diferencia es que una
  1409. // direccion link-local solo se alcanza indicando la interfaz, que el propio
  1410. // `ip -6 neigh` declara (`dev br-lan`).
  1411. //
  1412. // Devuelve MAC → dirección confirmada y MAC → interfaz de esa confirmación
  1413. // (#2200): el servidor atribuye el lado WAN con el mapa de interfaces, así que
  1414. // sin él un vecino IPv6 de la boca WAN se publica como cliente LAN.
  1415. // Best effort: sin tabla, sin vecinos o sin respuesta, nada. No toca `arp`:
  1416. // quien llama decide qué hacer con la pareja confirmada.
  1417. func (p *Prober) confirmStaleNeighbours6(ctx context.Context, due bool) (map[string]string, map[string]string) {
  1418. if p.run == nil || !due {
  1419. return nil, nil
  1420. }
  1421. out := p.runBest(ctx, CmdIpNeigh6, 3*time.Second)
  1422. if out == "" {
  1423. return nil, nil
  1424. }
  1425. arp, stale := ParseIPNeigh(out)
  1426. if len(stale) == 0 {
  1427. return nil, nil
  1428. }
  1429. devs := ParseIPNeighDevsAll(out)
  1430. macs := make([]string, 0, len(stale))
  1431. for mac := range stale {
  1432. macs = append(macs, mac)
  1433. }
  1434. sort.Strings(macs)
  1435. type target struct{ mac, ip, dev string }
  1436. targets := make([]target, 0, StalePingMax)
  1437. for _, mac := range macs {
  1438. ip := arp[mac]
  1439. if net.ParseIP(ip) == nil {
  1440. continue
  1441. }
  1442. targets = append(targets, target{mac: mac, ip: ip, dev: devs[mac]})
  1443. if len(targets) >= StalePingMax {
  1444. break
  1445. }
  1446. }
  1447. if len(targets) == 0 {
  1448. return nil, nil
  1449. }
  1450. var wg sync.WaitGroup
  1451. for _, t := range targets {
  1452. wg.Add(1)
  1453. go func(t target) {
  1454. defer wg.Done()
  1455. _, _ = p.run.Run(ctx, StalePing6Command(t.ip, t.dev), StalePingTimeout)
  1456. }(t)
  1457. }
  1458. wg.Wait()
  1459. out = p.runBest(ctx, CmdIpNeigh6, 3*time.Second)
  1460. fresh, stillStale := ParseIPNeigh(out)
  1461. freshDevs := ParseIPNeighDevs(out)
  1462. confirmed := map[string]string{}
  1463. confirmedDevs := map[string]string{}
  1464. for _, t := range targets {
  1465. if stillStale[t.mac] {
  1466. continue
  1467. }
  1468. if ip := fresh[t.mac]; ip != "" {
  1469. confirmed[t.mac] = ip
  1470. if d := freshDevs[t.mac]; d != "" {
  1471. confirmedDevs[t.mac] = d
  1472. }
  1473. }
  1474. }
  1475. return confirmed, confirmedDevs
  1476. }
  1477. // StalePing6Command: echo IPv6 con dos caminos porque no todas las unidades traen
  1478. // el mismo binario (`ping -6` en busybox reciente, `ping6` en el resto). Para
  1479. // link-local se añade `-I <iface>`: sin interfaz el kernel no sabe por dónde
  1480. // mandarlo.
  1481. func StalePing6Command(ip, dev string) string {
  1482. iface := ""
  1483. if strings.HasPrefix(strings.ToLower(ip), "fe80:") && dev != "" {
  1484. iface = " -I " + dev
  1485. }
  1486. return fmt.Sprintf(
  1487. "ping -6%s -c 1 -W 1 %s >/dev/null 2>&1 || ping6%s -c 1 -W 1 %s >/dev/null 2>&1",
  1488. iface, ip, iface, ip,
  1489. )
  1490. }