local.go 44 KB

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