openwrt.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. // openwrt.go — Cliente live para routers OpenWrt / GL.iNet (port de
  2. // src/adapters/openwrt.js, SPEC §7.2):
  3. //
  4. // 1. ubus JSON-RPC sobre HTTP (POST http://<host>/ubus, session login con
  5. // token cacheado y un solo re-login ante sesión caducada).
  6. // 2. Fallback SSH con pool persistente (sshpool.go; equivalente al
  7. // ControlMaster del JS).
  8. //
  9. // Comandos y parseo literales del JS; timeouts cortos y errores controlados:
  10. // el caller (live) marca el router offline y sigue con el resto.
  11. package adapters
  12. import (
  13. "bytes"
  14. "context"
  15. "encoding/json"
  16. "fmt"
  17. "io"
  18. "net"
  19. "net/http"
  20. "sort"
  21. "strings"
  22. "sync"
  23. "time"
  24. "github.com/gnacho/netpulse/agent/probe"
  25. )
  26. const (
  27. ubusHTTPTimeout = 4 * time.Second
  28. iwinfoTimeout = 8 * time.Second
  29. // radiosTTL (#368/#373, paridad con el agente): el resumen de radios
  30. // (canal/htmode/txpower) apenas cambia; cachearlo evita correr iwinfo en
  31. // cada poll de 5 s del server contra APs de bajas prestaciones (p.ej.
  32. // Archer A7 v5). El agente usa el mismo TTL desde el PR #373.
  33. radiosTTL = 5 * time.Minute
  34. )
  35. // poolRunner es el subconjunto de *SSHPool que usa OpenWrtClient (Run para
  36. // los comandos y RunCtx para LLDP). Permite inyectar un runner falso en
  37. // tests, igual que sshRunner para las funciones live sueltas.
  38. type poolRunner interface {
  39. Run(host, cmd string, timeout time.Duration) (string, error)
  40. RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error)
  41. }
  42. // OpenWrtClient es el cliente de un router (uno por router del config).
  43. type OpenWrtClient struct {
  44. Host string
  45. User string // para ubus HTTP (default root)
  46. Password string
  47. pool poolRunner
  48. // mu protege el estado mutable del cliente (sid, lastStat, lastNetDev,
  49. // lldpDownUntil): los handlers HTTP pueden sondear (p.ej. GetSurvey) en
  50. // paralelo con el poller.
  51. mu sync.Mutex
  52. sid string // sesión ubus HTTP cacheada
  53. lastStat *cpuSample // /proc/stat previo
  54. lastNetDev *netSample // /proc/net/dev previo
  55. // lastNetIf: /proc/net/dev previo POR INTERFAZ (contadores por boca,
  56. // issue #305). Acceso serializado por mu.
  57. lastNetIf *netIfSample
  58. // lldpDownUntil: indisponibilidad de lldpd cacheada (≥5 min) para no
  59. // martillear con un comando que no existe. Acceso serializado por mu.
  60. lldpDownUntil time.Time
  61. // radiosMu serializa la caché de radios (radiosCache/radiosAt): el
  62. // poller y los handlers HTTP pueden sondear el mismo cliente en paralelo.
  63. radiosMu sync.Mutex
  64. radiosCache []Radio // resumen por banda, refrescado cada radiosTTL
  65. radiosAt time.Time
  66. // stalePing (#2073): recheck activo de vecinos ARP en STALE. El ping sale
  67. // de la propia unidad (esta en la subred), no del servidor, y va con
  68. // throttle para no lanzarlo en cada poll.
  69. stalePingMu sync.Mutex
  70. stalePingAt time.Time
  71. // presenceAt (#2110): última ronda del barrido de subredes enrutadas.
  72. presenceMu sync.Mutex
  73. presenceAt time.Time
  74. }
  75. type cpuSample struct{ total, idleAll float64 }
  76. type netSample struct {
  77. rx, tx float64
  78. at time.Time
  79. }
  80. type netIfSample struct {
  81. at time.Time
  82. ifaces map[string]probe.IfCounters
  83. }
  84. // Aliases a los shapes compartidos de agent/probe: el agente nativo parsea
  85. // LOCALMENTE con el mismo package (misma fuente de verdad) y empuja esos
  86. // shapes al endpoint de ingesta (SPEC-AGENTE-PILOTO §1-2).
  87. type (
  88. SysInfo = probe.SysInfo
  89. BoardInfo = probe.BoardInfo
  90. DhcpLease = probe.DhcpLease
  91. WirelessClient = probe.WirelessClient
  92. PortState = probe.PortState
  93. PortLayout = probe.PortLayout
  94. VlanPort = probe.VlanPort
  95. MultiWanInfo = probe.MultiWanInfo
  96. WanUplink = probe.WanUplink
  97. VlanEntry = probe.VlanEntry
  98. DhcpReservation = probe.DhcpReservation
  99. )
  100. // NewOpenWrtClient crea el cliente de un router.
  101. func NewOpenWrtClient(cfg RouterConfig, pool poolRunner, user, password string) *OpenWrtClient {
  102. if user == "" {
  103. user = "root"
  104. }
  105. // Host aquí es el destino `host:port` (#605) para el pool SSH.
  106. return &OpenWrtClient{Host: cfg.SSHAddr(), User: user, Password: password, pool: pool}
  107. }
  108. // ---------------------------------------------------------------------------
  109. // Transporte ubus HTTP (JSON-RPC)
  110. // ---------------------------------------------------------------------------
  111. type ubusRPCError struct{ msg string }
  112. func (e *ubusRPCError) Error() string { return e.msg }
  113. // ubusHTTPRpc: POST /ubus; devuelve result[1] si result[0] == 0.
  114. func (c *OpenWrtClient) ubusHTTPRpc(sid, object, method string, params any) (json.RawMessage, error) {
  115. if params == nil {
  116. params = map[string]any{}
  117. }
  118. body, _ := json.Marshal(map[string]any{
  119. "jsonrpc": "2.0", "id": 1, "method": "call",
  120. "params": []any{sid, object, method, params},
  121. })
  122. ctx, cancel := context.WithTimeout(context.Background(), ubusHTTPTimeout)
  123. defer cancel()
  124. req, err := http.NewRequestWithContext(ctx, "POST", "http://"+c.Host+"/ubus", bytes.NewReader(body))
  125. if err != nil {
  126. return nil, err
  127. }
  128. req.Header.Set("Content-Type", "application/json")
  129. res, err := http.DefaultClient.Do(req)
  130. if err != nil {
  131. return nil, err
  132. }
  133. defer res.Body.Close()
  134. data, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
  135. if err != nil {
  136. return nil, err
  137. }
  138. if res.StatusCode != 200 {
  139. return nil, &ubusRPCError{fmt.Sprintf("ubus HTTP %d", res.StatusCode)}
  140. }
  141. var rpc struct {
  142. Error json.RawMessage `json:"error"`
  143. Result json.RawMessage `json:"result"`
  144. }
  145. if err := json.Unmarshal(data, &rpc); err != nil {
  146. return nil, &ubusRPCError{"ubus: respuesta no JSON"}
  147. }
  148. if len(rpc.Error) > 0 && string(rpc.Error) != "null" {
  149. return nil, &ubusRPCError{"ubus RPC error: " + string(rpc.Error)}
  150. }
  151. // ubus devuelve [exitCode, payload]
  152. var result []json.RawMessage
  153. if err := json.Unmarshal(rpc.Result, &result); err != nil || len(result) != 2 {
  154. return nil, &ubusRPCError{"ubus call falló: " + string(rpc.Result)}
  155. }
  156. var code int
  157. if err := json.Unmarshal(result[0], &code); err != nil || code != 0 {
  158. return nil, &ubusRPCError{"ubus call falló: " + string(rpc.Result)}
  159. }
  160. return result[1], nil
  161. }
  162. // ubusLogin: session login con sid '0'×32 → ubus_rpc_session.
  163. func (c *OpenWrtClient) ubusLogin() error {
  164. payload, err := c.ubusHTTPRpc("00000000000000000000000000000000", "session", "login",
  165. map[string]any{"username": c.User, "password": c.Password})
  166. if err != nil {
  167. return err
  168. }
  169. var res struct {
  170. Session string `json:"ubus_rpc_session"`
  171. }
  172. if err := json.Unmarshal(payload, &res); err != nil || res.Session == "" {
  173. return &ubusRPCError{"ubus login: sin ubus_rpc_session"}
  174. }
  175. c.sid = res.Session
  176. return nil
  177. }
  178. // UbusCall: ubus call con HTTP + login cacheado; un solo re-login si la
  179. // sesión caducó; fallback a SSH si HTTP no está disponible.
  180. func (c *OpenWrtClient) UbusCall(object, method string, params any) (json.RawMessage, error) {
  181. if params == nil {
  182. params = map[string]any{}
  183. }
  184. payload, err := func() (json.RawMessage, error) {
  185. if c.sid == "" {
  186. if err := c.ubusLogin(); err != nil {
  187. return nil, err
  188. }
  189. }
  190. payload, err := c.ubusHTTPRpc(c.sid, object, method, params)
  191. if err != nil {
  192. // Sesión caducada → un solo re-login
  193. c.sid = ""
  194. if lerr := c.ubusLogin(); lerr != nil {
  195. return nil, lerr
  196. }
  197. return c.ubusHTTPRpc(c.sid, object, method, params)
  198. }
  199. return payload, nil
  200. }()
  201. if err == nil {
  202. return payload, nil
  203. }
  204. // Fallback SSH: ubus call <object> <method> '<json>'
  205. paramsJSON, _ := json.Marshal(params)
  206. esc := strings.ReplaceAll(string(paramsJSON), `'`, `'\''`)
  207. out, serr := c.pool.Run(c.Host, fmt.Sprintf("ubus call %s %s '%s'", object, method, esc), 0)
  208. if serr != nil {
  209. return nil, serr
  210. }
  211. if !json.Valid([]byte(out)) {
  212. return nil, &ubusRPCError{"ubus ssh: respuesta no JSON"}
  213. }
  214. return json.RawMessage(out), nil
  215. }
  216. // ---------------------------------------------------------------------------
  217. // Sonda de sistema
  218. // ---------------------------------------------------------------------------
  219. // GetBoard: modelo, release, kernel → metadatos estáticos del router.
  220. func (c *OpenWrtClient) GetBoard() (*BoardInfo, error) {
  221. raw, err := c.UbusCall("system", "board", nil)
  222. if err != nil {
  223. return nil, err
  224. }
  225. var b BoardInfo
  226. if err := json.Unmarshal(raw, &b); err != nil {
  227. return nil, err
  228. }
  229. return &b, nil
  230. }
  231. // GetSysInfo: uptime, memoria, load.
  232. func (c *OpenWrtClient) GetSysInfo() (*SysInfo, error) {
  233. raw, err := c.UbusCall("system", "info", nil)
  234. if err != nil {
  235. return nil, err
  236. }
  237. var s SysInfo
  238. if err := json.Unmarshal(raw, &s); err != nil {
  239. return nil, err
  240. }
  241. return &s, nil
  242. }
  243. // ---------------------------------------------------------------------------
  244. // CPU / temperatura / netdev / ping (SSH; parseo literal del JS)
  245. // ---------------------------------------------------------------------------
  246. // GetCPUPercent: CPU % por delta de /proc/stat. Primera muestra: nil.
  247. func (c *OpenWrtClient) GetCPUPercent() (*int, error) {
  248. out, err := c.pool.Run(c.Host, probe.CmdProcStat, 0)
  249. if err != nil {
  250. return nil, err
  251. }
  252. cur, err := parseProcStat(out)
  253. if err != nil {
  254. return nil, err
  255. }
  256. prev := c.lastStat
  257. c.lastStat = &cur
  258. if prev == nil {
  259. return nil, nil
  260. }
  261. return probe.CPUPercent(probe.CPUSample{Total: prev.total, IdleAll: prev.idleAll},
  262. probe.CPUSample{Total: cur.total, IdleAll: cur.idleAll}), nil
  263. }
  264. // parseProcStat parsea "cpu user nice system idle iowait irq softirq ..."
  265. // (delega en el parseo compartido con el agente nativo).
  266. func parseProcStat(out string) (cpuSample, error) {
  267. s, err := probe.ParseProcStat(out)
  268. return cpuSample{total: s.Total, idleAll: s.IdleAll}, err
  269. }
  270. // GetTempC: °C del primer thermal zone disponible (nil si no hay).
  271. func (c *OpenWrtClient) GetTempC() (*int, error) {
  272. out, err := c.pool.Run(c.Host, probe.CmdTemp, 0)
  273. if err != nil {
  274. return nil, err
  275. }
  276. return probe.ParseTempC(out), nil
  277. }
  278. // NetDevBps es el resultado del delta de /proc/net/dev.
  279. type NetDevBps struct {
  280. RxBps *float64
  281. TxBps *float64
  282. }
  283. // GetNetDev: tráfico agregado por delta de /proc/net/dev (excluye lo,
  284. // bridges, ifb, wg, tun/tap para no duplicar contadores) + rates POR INTERFAZ
  285. // (issue #305, para las bocas del chasis). Una sola lectura de /proc/net/dev;
  286. // primera muestra: rates null.
  287. func (c *OpenWrtClient) GetNetDev() (*NetDevBps, map[string]probe.IfRate) {
  288. out, err := c.pool.Run(c.Host, probe.CmdNetDev, 0)
  289. if err != nil {
  290. return nil, nil
  291. }
  292. rx, tx := parseNetDev(out)
  293. curIf := probe.ParseNetDevIfaces(out)
  294. now := time.Now()
  295. c.mu.Lock()
  296. defer c.mu.Unlock()
  297. prev := c.lastNetDev
  298. c.lastNetDev = &netSample{rx: rx, tx: tx, at: now}
  299. prevIf := c.lastNetIf
  300. c.lastNetIf = &netIfSample{at: now, ifaces: curIf}
  301. res := &NetDevBps{}
  302. if prev != nil {
  303. res.RxBps, res.TxBps = probe.NetDevBps(prev.rx, prev.tx, rx, tx, now.Sub(prev.at).Seconds())
  304. }
  305. var rates map[string]probe.IfRate
  306. if prevIf != nil {
  307. rates = probe.IfRates(prevIf.ifaces, curIf, now.Sub(prevIf.at).Seconds())
  308. }
  309. return res, rates
  310. }
  311. // parseNetDev suma rx/tx de las interfaces físicas (compartido con el agente).
  312. func parseNetDev(out string) (rx, tx float64) {
  313. return probe.ParseNetDev(out)
  314. }
  315. // GetWanLatency: ping a internet (solo gateway) → latencia avg + pérdida.
  316. func (c *OpenWrtClient) GetWanLatency(target string) (latency *float64, loss *float64, err error) {
  317. if target == "" {
  318. target = "1.1.1.1"
  319. }
  320. out, err := c.pool.Run(c.Host, fmt.Sprintf(probe.CmdPingWan, target), 0)
  321. if err != nil {
  322. return nil, nil, err
  323. }
  324. latency, loss = probe.ParsePingSummary(out)
  325. return latency, loss, nil
  326. }
  327. // GetGatewayLatency: ping corto al gateway desde un AP (avg, redondeado).
  328. func (c *OpenWrtClient) GetGatewayLatency(gatewayHost string) (*float64, error) {
  329. out, err := c.pool.Run(c.Host, fmt.Sprintf(probe.CmdPingGateway, gatewayHost), 0)
  330. if err != nil {
  331. return nil, err
  332. }
  333. latency, _ := probe.ParsePingSummary(out)
  334. return latency, nil
  335. }
  336. // ---------------------------------------------------------------------------
  337. // Clientes (DHCP + wireless)
  338. // ---------------------------------------------------------------------------
  339. // GetDhcpLeases: ubus dhcp ipv4leases; fallback /tmp/dhcp.leases.
  340. func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
  341. raw, err := c.UbusCall("dhcp", "ipv4leases", nil)
  342. if err == nil {
  343. if leases, perr := probe.ParseDhcpUbus(raw); perr == nil {
  344. return leases
  345. }
  346. }
  347. out, serr := c.pool.Run(c.Host, probe.CmdDhcpFile, 0)
  348. if serr != nil {
  349. return []DhcpLease{}
  350. }
  351. return parseDhcpLeasesFile(out)
  352. }
  353. // GetWanInfo: estado del uplink (issue #276). Via ubus network.interface
  354. // dump, que trae todas las interfaces y deja elegir la que lleva internet
  355. // por su ruta por defecto en vez de por llamarse "wan" (un PPPoE puede
  356. // llamarse de cualquier forma, y el nombre "wan" puede ser un módem ocioso).
  357. // Cae al status de la interfaz "wan" con los ubus antiguos; si el router no
  358. // tiene ninguna (AP), devuelve WanInfo vacío.
  359. func (c *OpenWrtClient) GetWanInfo() probe.WanInfo {
  360. if raw, err := c.UbusCall("network.interface", "dump", nil); err == nil {
  361. if info := probe.ParseWanStatus(raw); info.Proto != "" || info.IP != "" || info.Gateway != "" {
  362. return info
  363. }
  364. }
  365. raw, err := c.UbusCall("network.interface.wan", "status", nil)
  366. if err == nil {
  367. return probe.ParseWanStatus(raw)
  368. }
  369. return probe.WanInfo{}
  370. }
  371. // GetDhcpReservations: the `config host` entries of /etc/config/dhcp, for
  372. // the routers polled over SSH (the agent sends them in its payload). Error
  373. // or no entries → empty, and clients keep falling back to their MAC.
  374. func (c *OpenWrtClient) GetDhcpReservations() []DhcpReservation {
  375. out, err := c.pool.Run(c.Host, probe.CmdDhcpReservations, 0)
  376. if err != nil {
  377. return nil
  378. }
  379. return probe.ParseDhcpReservations(out)
  380. }
  381. // GetGlClients: base de clientes del firmware GL.iNet (`ubus call gl-clients
  382. // list`). SUPERSET de dhcp.leases: incluye equipos con IP estática o sin
  383. // lease que el dnsmasq del Flint2 no lista. En routers sin el objeto ubus
  384. // gl-clients devuelve vacío (la salida del comando es vacía) — el caller lo
  385. // usa solo para enriquecer IPs de dispositivos ya conocidos, nunca para
  386. // crearlos (issue #5 bug 1).
  387. func (c *OpenWrtClient) GetGlClients() []DhcpLease {
  388. out, err := c.pool.Run(c.Host, probe.CmdGlClients, 0)
  389. if err != nil || strings.TrimSpace(out) == "" {
  390. return []DhcpLease{}
  391. }
  392. leases, perr := probe.ParseGlClients([]byte(out))
  393. if perr != nil {
  394. return []DhcpLease{}
  395. }
  396. return leases
  397. }
  398. // parseDhcpLeasesFile parsea /tmp/dhcp.leases:
  399. // <expiry> <mac> <ip> <hostname> <clientid>
  400. func parseDhcpLeasesFile(out string) []DhcpLease {
  401. return probe.ParseDhcpLeasesFile(out)
  402. }
  403. // GetWirelessClients: clientes wifi asociados (MAC → señal/banda). Port del
  404. // fix #373 (#368) al sondeo SSH: ubus hostapd get_clients primero (una
  405. // llamada ubus barata por AP, sin ucode/iwinfo), fallback de iwinfo combinado
  406. // en UNA pasada por interfaz, y como último recurso el par legacy. Vacío si
  407. // el router no expone ninguna fuente wireless.
  408. func (c *OpenWrtClient) GetWirelessClients() map[string]WirelessClient {
  409. // 1. ubus hostapd get_clients (barato; APs con hostapd ubus moderno).
  410. // Autoritativo cuando hay objetos hostapd.* (incluso con 0 clientes: un
  411. // AP vacío no debe caer al fallback iwinfo en cada poll de 5 s del
  412. // server). Solo si ubus no expone objetos se baja al fallback.
  413. if out, err := c.pool.Run(c.Host, probe.CmdHostapdClients, iwinfoTimeout); err == nil && strings.Contains(out, "==AP==") {
  414. return probe.ParseHostapdClients(out)
  415. }
  416. // 2. iwinfo combinado en UNA pasada (info + assoclist juntos por interfaz;
  417. // emite clientes y radios). Mitad de spawns que el par legacy de abajo.
  418. // Las radios se cachean aunque no haya clientes (GetRadios no re-sondea).
  419. if out, err := c.pool.Run(c.Host, probe.CmdWirelessCombined, iwinfoTimeout); err == nil {
  420. clients, radios := probe.ParseWirelessCombined(out)
  421. if len(radios) > 0 {
  422. c.setRadiosCache(radiosToAdapter(radios))
  423. }
  424. if len(clients) > 0 {
  425. return clients
  426. }
  427. }
  428. // 3. Último recurso: par legacy (equipos donde el combinado no aplica).
  429. out, err := c.pool.Run(c.Host, probe.CmdIwinfoAssoc, iwinfoTimeout)
  430. if err != nil {
  431. return map[string]WirelessClient{}
  432. }
  433. return parseWirelessClients(out)
  434. }
  435. // parseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
  436. func parseWirelessClients(out string) map[string]WirelessClient {
  437. return probe.ParseWirelessClients(out)
  438. }
  439. // GetRadios: radios activas por banda (canal/htmode/txpower + nº clientes).
  440. // Cacheadas radiosTTL (5 min): el resumen de radios apenas cambia y correr
  441. // CmdRadios (iwinfo) en CADA poll de 5 s del server quemaba CPU en APs de
  442. // bajas prestaciones (port #373 al sondeo SSH). Si la caché está fresca se
  443. // devuelve sin tocar el router; si caducó (o está vacía) se refresca.
  444. func (c *OpenWrtClient) GetRadios() []Radio {
  445. c.radiosMu.Lock()
  446. cached := c.radiosCache
  447. if len(cached) > 0 && time.Since(c.radiosAt) < radiosTTL {
  448. c.radiosMu.Unlock()
  449. return cached
  450. }
  451. c.radiosMu.Unlock()
  452. // Refresco. Prioridad al combinado (una pasada por interfaz) cuando ubus
  453. // no estuvo disponible para clientes: el propio comando emite las radios.
  454. out, err := c.pool.Run(c.Host, probe.CmdWirelessCombined, iwinfoTimeout)
  455. if err == nil {
  456. if _, radios := probe.ParseWirelessCombined(out); len(radios) > 0 {
  457. rs := radiosToAdapter(radios)
  458. c.setRadiosCache(rs)
  459. return rs
  460. }
  461. }
  462. out, err = c.pool.Run(c.Host, probe.CmdRadios, iwinfoTimeout)
  463. if err != nil {
  464. return []Radio{}
  465. }
  466. rs := parseRadios(out)
  467. if len(rs) > 0 {
  468. c.setRadiosCache(rs)
  469. }
  470. return rs
  471. }
  472. // setRadiosCache guarda el resumen de radios con su timestamp (best-effort:
  473. // no falla si la caché está vacía; el poller reintenta en el próximo ciclo).
  474. func (c *OpenWrtClient) setRadiosCache(rs []Radio) {
  475. if len(rs) == 0 {
  476. return
  477. }
  478. c.radiosMu.Lock()
  479. c.radiosCache = rs
  480. c.radiosAt = time.Now()
  481. c.radiosMu.Unlock()
  482. }
  483. // GetWirelessUplink: true si el router tiene uplink inalámbrico (alguna
  484. // interfaz STA activa/asociada en `ubus call network.wireless status`).
  485. // Error si el router no soporta la llamada (sin wifi → el caller omite el
  486. // campo backhaul, nunca rompe el sondeo).
  487. func (c *OpenWrtClient) GetWirelessUplink() (bool, error) {
  488. raw, err := c.UbusCall("network.wireless", "status", nil)
  489. if err != nil {
  490. return false, err
  491. }
  492. return parseWirelessUplink(raw)
  493. }
  494. // parseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio
  495. // up e ifname asignado = asociada). Tolerante con radios/entradas raras.
  496. func parseWirelessUplink(raw json.RawMessage) (bool, error) {
  497. return probe.ParseWirelessUplink(raw)
  498. }
  499. // ---------------------------------------------------------------------------
  500. // Puertos
  501. // ---------------------------------------------------------------------------
  502. // GetPortStates: estado de interfaces desde /sys (SSH).
  503. func (c *OpenWrtClient) GetPortStates() []PortState {
  504. out, err := c.pool.Run(c.Host, probe.CmdPortStates, 0)
  505. if err != nil {
  506. return []PortState{}
  507. }
  508. return parsePortStates(out)
  509. }
  510. // parsePortStates parsea líneas "<name> <operstate> <speed>".
  511. func parsePortStates(out string) []PortState {
  512. return probe.ParsePortStates(out)
  513. }
  514. // GetPortLayout: layout canónico desde /etc/board.json (estático; lo cachea
  515. // el live). WAN normalizado a id 'wan'.
  516. func (c *OpenWrtClient) GetPortLayout() ([]PortLayout, error) {
  517. out, err := c.pool.Run(c.Host, probe.CmdBoardJSON, 0)
  518. if err != nil {
  519. return nil, err
  520. }
  521. return parsePortLayout(out)
  522. }
  523. // parsePortLayout parsea board.json → [{id, name, label, role}].
  524. func parsePortLayout(out string) ([]PortLayout, error) {
  525. return probe.ParsePortLayout(out)
  526. }
  527. // GetEthPorts: layout + estado /sys; AP en bridge re-etiqueta wan→LAN N+1;
  528. // fallback heurístico sin config. rates = contadores por iface (#305, de
  529. // GetNetDev; nil = sin stats). Devuelve []EthPort listo para el detalle.
  530. func (c *OpenWrtClient) GetEthPorts(layout []PortLayout, rates map[string]probe.IfRate, uplink string) []EthPort {
  531. states := c.GetPortStates()
  532. members := map[string]bool{}
  533. if len(layout) > 0 {
  534. // Miembros del bridge: si "wan" está en br-lan, este router es un AP
  535. brif, _ := c.pool.Run(c.Host, probe.CmdBrifMembers, 0)
  536. for _, l := range strings.Split(strings.TrimSpace(brif), "\n") {
  537. if l != "" {
  538. members[l] = true
  539. }
  540. }
  541. }
  542. return ethPortsToAdapter(probe.BuildEthPorts(layout, states, members, rates, uplink))
  543. }
  544. // ethPortsToAdapter convierte el shape compartido al EthPort del contrato.
  545. func ethPortsToAdapter(in []probe.EthPort) []EthPort {
  546. f := func(v *float64) float64 {
  547. if v == nil {
  548. return 0
  549. }
  550. return *v
  551. }
  552. out := make([]EthPort, 0, len(in))
  553. for _, p := range in {
  554. ep := EthPort{ID: p.ID, Label: p.Label, Up: p.Up, Iface: p.Iface,
  555. RxBytes: p.RxBytes, TxBytes: p.TxBytes, RxErrs: p.RxErrs, TxErrs: p.TxErrs,
  556. RxBps: f(p.RxBps), TxBps: f(p.TxBps)}
  557. if p.Up {
  558. ep.Speed = p.Speed
  559. }
  560. if p.Sfp != nil {
  561. ep.Sfp = &SfpInfo{
  562. Temperature: p.Sfp.Temperature, Voltage: p.Sfp.Voltage,
  563. TxPower: p.Sfp.TxPower, RxPower: p.Sfp.RxPower,
  564. Vendor: p.Sfp.Vendor, PartNumber: p.Sfp.PartNumber,
  565. Present: p.Sfp.Present,
  566. }
  567. }
  568. out = append(out, ep)
  569. }
  570. return out
  571. }
  572. // naturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
  573. func naturalLess(a, b string) bool {
  574. return probe.NaturalLess(a, b)
  575. }
  576. // GetBridgeFdb: MAC aprendida → puerto (brctl showmacs + port_no).
  577. // Devuelve nil en error para que el anti-parpadeo de pollRouter conserve la
  578. // última lista buena en vez de sustituirla por un FDB vacío (#694).
  579. func (c *OpenWrtClient) GetBridgeFdb() map[string]string {
  580. out, err := c.pool.Run(c.Host, probe.CmdBridgeFDB, 0)
  581. if err != nil {
  582. return nil
  583. }
  584. return parseBridgeFdb(out)
  585. }
  586. // parseBridgeFdb parsea la salida ==PORTS==/==MACS== del JS.
  587. func parseBridgeFdb(out string) map[string]string {
  588. return probe.ParseBridgeFdb(out)
  589. }
  590. // GetBridgeMac: MAC del bridge br-lan (para reconocer uplinks).
  591. func (c *OpenWrtClient) GetBridgeMac() string {
  592. out, err := c.pool.Run(c.Host, probe.CmdBridgeMAC, 0)
  593. if err != nil {
  594. return ""
  595. }
  596. return strings.ToUpper(strings.TrimSpace(out))
  597. }
  598. // GetLuCILabels: etiquetas de puertos/VLANs de LuCI (issue #258), si el
  599. // router las define en /etc/config/luci. Best-effort: fichero sin secciones
  600. // → nil.
  601. func (c *OpenWrtClient) GetLuCILabels() *probe.LuCILabels {
  602. out, err := c.pool.Run(c.Host, probe.CmdLuCILabels, 0)
  603. if err != nil {
  604. return nil
  605. }
  606. return probe.ParseLuCILabels(out)
  607. }
  608. // GetBridgeVlans: VLANs del bridge (issue #315). La salida del kernel se
  609. // fusiona con la configuración (#1757): un router que segmenta con
  610. // subinterfaces 802.1Q contesta con todos los puertos en la VLAN 1 y las
  611. // VLANs reales solo están en `uci show network`. nil si ninguna de las dos
  612. // fuentes dice nada.
  613. func (c *OpenWrtClient) GetBridgeVlans() []probe.VlanPort {
  614. var kernel []probe.VlanPort
  615. if out, err := c.pool.Run(c.Host, probe.CmdBridgeVlan, 0); err == nil {
  616. kernel = probe.ParseBridgeVlan(out)
  617. }
  618. var declared []probe.VlanPort
  619. if out, err := c.pool.Run(c.Host, probe.CmdUciBridgeVlan, 0); err == nil {
  620. declared = probe.MergeVlanPorts(probe.ParseUciBridgeVlans(out), probe.ParseUciNetworkVlans(out))
  621. }
  622. ports := probe.MergeVlanPorts(kernel, declared)
  623. if len(ports) == 0 {
  624. return nil
  625. }
  626. return ports
  627. }
  628. // ---------------------------------------------------------------------------
  629. // Radios WiFi
  630. // ---------------------------------------------------------------------------
  631. // parseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
  632. func parseRadios(out string) []Radio {
  633. return radiosToAdapter(probe.ParseRadios(out))
  634. }
  635. // radiosToAdapter convierte el shape compartido al Radio del contrato.
  636. func radiosToAdapter(in []probe.Radio) []Radio {
  637. out := make([]Radio, 0, len(in))
  638. for _, r := range in {
  639. out = append(out, Radio{Name: r.Name, Channel: r.Channel,
  640. WidthMhz: r.WidthMhz, PowerDbm: r.PowerDbm, Clients: r.Clients,
  641. NoiseDbm: r.NoiseDbm, BSSID: r.BSSID})
  642. }
  643. return out
  644. }
  645. // GetArp devuelve la tabla ARP del equipo (MAC→IP, #377). Fuente barata
  646. // para resolver IPs cuando el DHCP no es local.
  647. //
  648. // Reads `ip neigh` so the state of each entry comes with it, and returns the
  649. // MACs the kernel remembers without confirming (stale): their address is
  650. // still usable, but they are not evidence that the host is connected. Falls
  651. // back to /proc/net/arp, where no state is available and nothing is stale.
  652. // GetArp devuelve además MAC -> interfaz (#1485): con esa columna el poller
  653. // distingue el ARP del puerto WAN (primer salto del enlace) del de la LAN.
  654. func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool, devs map[string]string) {
  655. // #2110: despertar las subredes que la unidad enruta antes de leer la
  656. // tabla, para que la misma lectura vea lo que el barrido confirmó.
  657. c.scanPresence()
  658. if out, err := c.pool.Run(c.Host, probe.CmdIpNeigh, 0); err == nil {
  659. if m, st := probe.ParseIPNeigh(out); len(m) > 0 {
  660. // #2073: la misma comprobacion activa que hace el agente, pero
  661. // lanzada desde la unidad (esta en la subred; el servidor puede
  662. // no estarlo). Un host cableado con IP estatica que lleva rato en
  663. // silencio deja el ARP en STALE sin estar apagado.
  664. due := c.stalePingDue()
  665. freshSrc := out
  666. if fresh, ok := c.recheckStaleNeighbours(m, st, due); ok {
  667. freshSrc = fresh
  668. }
  669. // #2109: el mismo recheck sobre NDP. Un host solo-IPv6 no tiene
  670. // entrada en `ip -4 neigh`, así que solo esta pasada lo confirma.
  671. if v6, ok := c.recheckStaleNeighbours6(due); ok {
  672. for mac, ip := range v6 {
  673. if _, has := m[mac]; !has {
  674. m[mac] = ip
  675. }
  676. delete(st, mac)
  677. }
  678. }
  679. return m, st, probe.ParseIPNeighDevs(freshSrc)
  680. }
  681. }
  682. out, err := c.pool.Run(c.Host, probe.CmdProcArp, 0)
  683. if err != nil {
  684. return nil, nil, nil
  685. }
  686. return probe.ParseArp(out), nil, probe.ParseArpDevs(out)
  687. }
  688. // recheckStaleNeighbours (#2073): un ping corto por cada vecino STALE, en
  689. // paralelo y desde la unidad, y una relectura de `ip neigh`. El kernel pasa a
  690. // REACHABLE la entrada cuya respuesta ARP llega, asi que lo confirmado es la
  691. // pareja IP-MAC. Devuelve la relectura y si se llego a hacer. Best effort.
  692. // stalePingDue decide si toca ronda y marca el sello. Un sello para v4 y v6:
  693. // la ronda no debe pagar dos veces el throttle ni dejar la pasada v6 sin turno
  694. // por haberlo gastado la v4.
  695. func (c *OpenWrtClient) stalePingDue() bool {
  696. c.stalePingMu.Lock()
  697. defer c.stalePingMu.Unlock()
  698. if !c.stalePingAt.IsZero() && time.Since(c.stalePingAt) < probe.StalePingInterval {
  699. return false
  700. }
  701. c.stalePingAt = time.Now()
  702. return true
  703. }
  704. func (c *OpenWrtClient) recheckStaleNeighbours(arp map[string]string, stale map[string]bool, due bool) (string, bool) {
  705. if c.pool == nil || len(stale) == 0 || !due {
  706. return "", false
  707. }
  708. ips := probe.StalePingTargets(arp, stale)
  709. if len(ips) == 0 {
  710. return "", false
  711. }
  712. var cmd strings.Builder
  713. for _, ip := range ips {
  714. cmd.WriteString("ping -c 1 -W 1 ")
  715. cmd.WriteString(ip)
  716. cmd.WriteString(" >/dev/null 2>&1 & ")
  717. }
  718. cmd.WriteString("wait")
  719. if _, err := c.pool.Run(c.Host, cmd.String(), probe.StalePingTimeout+2*time.Second); err != nil {
  720. return "", false
  721. }
  722. out, err := c.pool.Run(c.Host, probe.CmdIpNeigh, 0)
  723. if err != nil || out == "" {
  724. return "", false
  725. }
  726. fresh, stillStale := probe.ParseIPNeigh(out)
  727. for mac := range stale {
  728. if stillStale[mac] {
  729. continue
  730. }
  731. if ip := fresh[mac]; ip != "" {
  732. arp[mac] = ip
  733. }
  734. delete(stale, mac)
  735. }
  736. return out, true
  737. }
  738. // presenceScanDue: una ronda cada 5 minutos por unidad, compartida por todas
  739. // las subredes.
  740. func (c *OpenWrtClient) presenceScanDue() bool {
  741. c.presenceMu.Lock()
  742. defer c.presenceMu.Unlock()
  743. if !c.presenceAt.IsZero() && time.Since(c.presenceAt) < probe.PresenceScanInterval {
  744. return false
  745. }
  746. c.presenceAt = time.Now()
  747. return true
  748. }
  749. // scanPresence (#2110) por SSH: en una unidad sin agente no hay forma de
  750. // mandar un datagrama que fuerce el ARP, así que el barrido va con `ping`, que
  751. // en busybox está siempre. Cubre lo mismo salvo hosts que filtren ICMP; el
  752. // agente, cuando está, usa UDP y sí despierta el ARP.
  753. //
  754. // Mismas reglas: solo unidades que enrutan (forwarding y más de una subred),
  755. // o `NETPULSE_PRESENCE_SCAN=on`, como mucho una /24 por subred y en tandas de
  756. // 32 para no lanzar 254 procesos a la vez en un router.
  757. func (c *OpenWrtClient) scanPresence() {
  758. if c.pool == nil || !c.presenceScanDue() {
  759. return
  760. }
  761. if _, off := probe.PresenceScanEnabled(); off {
  762. return
  763. }
  764. forced, _ := probe.PresenceScanEnabled()
  765. out, err := c.pool.Run(c.Host, "ip -4 -o addr show scope global 2>/dev/null", 0)
  766. if err != nil || out == "" {
  767. return
  768. }
  769. subnets := probe.ParseGlobalIPv4Prefixes(out)
  770. if !forced {
  771. if len(subnets) < 2 {
  772. return
  773. }
  774. fwd, err := c.pool.Run(c.Host, "cat /proc/sys/net/ipv4/ip_forward 2>/dev/null", 0)
  775. if err != nil || strings.TrimSpace(fwd) != "1" {
  776. return
  777. }
  778. }
  779. if len(subnets) > 8 {
  780. subnets = subnets[:8]
  781. }
  782. var script strings.Builder
  783. for _, pf := range subnets {
  784. hosts := probe.HostAddrs(pf, probe.PresenceScanMaxHosts)
  785. for i := 0; i < len(hosts); i += 32 {
  786. end := i + 32
  787. if end > len(hosts) {
  788. end = len(hosts)
  789. }
  790. script.WriteString("for ip in ")
  791. script.WriteString(strings.Join(hosts[i:end], " "))
  792. script.WriteString("; do ping -c 1 -W 1 \"$ip\" >/dev/null 2>&1 & done; wait; ")
  793. }
  794. }
  795. if script.Len() == 0 {
  796. return
  797. }
  798. _, _ = c.pool.Run(c.Host, script.String(), 90*time.Second)
  799. }
  800. // recheckStaleNeighbours6 (#2109): la pasada NDP por SSH, desde la unidad.
  801. // Mismo tope y mismo throttle que la v4. `ip -6 neigh` declara la interfaz de
  802. // cada entrada, y una link-local necesita `-I` para alcanzarse. Devuelve
  803. // MAC → dirección confirmada; best effort.
  804. func (c *OpenWrtClient) recheckStaleNeighbours6(due bool) (map[string]string, bool) {
  805. if c.pool == nil || !due {
  806. return nil, false
  807. }
  808. out, err := c.pool.Run(c.Host, probe.CmdIpNeigh6, 0)
  809. if err != nil || out == "" {
  810. return nil, false
  811. }
  812. arp, stale := probe.ParseIPNeigh(out)
  813. if len(stale) == 0 {
  814. return nil, false
  815. }
  816. devs := probe.ParseIPNeighDevsAll(out)
  817. macs := make([]string, 0, len(stale))
  818. for mac := range stale {
  819. macs = append(macs, mac)
  820. }
  821. sort.Strings(macs)
  822. var cmd strings.Builder
  823. n := 0
  824. for _, mac := range macs {
  825. ip := arp[mac]
  826. if net.ParseIP(ip) == nil {
  827. continue
  828. }
  829. cmd.WriteString(probe.StalePing6Command(ip, devs[mac]))
  830. cmd.WriteString(" & ")
  831. n++
  832. if n >= probe.StalePingMax {
  833. break
  834. }
  835. }
  836. if n == 0 {
  837. return nil, false
  838. }
  839. cmd.WriteString("wait")
  840. if _, err := c.pool.Run(c.Host, cmd.String(), probe.StalePingTimeout+2*time.Second); err != nil {
  841. return nil, false
  842. }
  843. freshOut, err := c.pool.Run(c.Host, probe.CmdIpNeigh6, 0)
  844. if err != nil || freshOut == "" {
  845. return nil, false
  846. }
  847. fresh, stillStale := probe.ParseIPNeigh(freshOut)
  848. confirmed := map[string]string{}
  849. for _, mac := range macs {
  850. if stillStale[mac] {
  851. continue
  852. }
  853. if ip := fresh[mac]; ip != "" {
  854. confirmed[mac] = ip
  855. }
  856. }
  857. return confirmed, len(confirmed) > 0
  858. }
  859. // GetNetworks: redes logicas que la unidad declara en UCI (#1889). Es la
  860. // misma lectura que alimenta las VLANs, asi que una unidad por SSH tambien
  861. // tiene la vista de redes; lo que no tiene son los contadores por interfaz.
  862. // nil si no hay datos, para que el anti-parpadeo conserve la ultima lista.
  863. func (c *OpenWrtClient) GetNetworks() []probe.UciNetwork {
  864. out, err := c.pool.Run(c.Host, probe.CmdUciBridgeVlan, 0)
  865. if err != nil {
  866. return nil
  867. }
  868. nets := probe.ParseUciNetworks(out)
  869. if len(nets) == 0 {
  870. return nil
  871. }
  872. return nets
  873. }