local.go 48 KB

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