local.go 41 KB

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