local.go 45 KB

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