local.go 51 KB

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