openwrt.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  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/http"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/gnacho/netpulse/agent/probe"
  23. )
  24. const (
  25. ubusHTTPTimeout = 4 * time.Second
  26. iwinfoTimeout = 8 * time.Second
  27. // radiosTTL (#368/#373, paridad con el agente): el resumen de radios
  28. // (canal/htmode/txpower) apenas cambia; cachearlo evita correr iwinfo en
  29. // cada poll de 5 s del server contra APs de bajas prestaciones (p.ej.
  30. // Archer A7 v5). El agente usa el mismo TTL desde el PR #373.
  31. radiosTTL = 5 * time.Minute
  32. )
  33. // poolRunner es el subconjunto de *SSHPool que usa OpenWrtClient (Run para
  34. // los comandos y RunCtx para LLDP). Permite inyectar un runner falso en
  35. // tests, igual que sshRunner para las funciones live sueltas.
  36. type poolRunner interface {
  37. Run(host, cmd string, timeout time.Duration) (string, error)
  38. RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error)
  39. }
  40. // OpenWrtClient es el cliente de un router (uno por router del config).
  41. type OpenWrtClient struct {
  42. Host string
  43. User string // para ubus HTTP (default root)
  44. Password string
  45. pool poolRunner
  46. // mu protege el estado mutable del cliente (sid, lastStat, lastNetDev,
  47. // lldpDownUntil): los handlers HTTP pueden sondear (p.ej. GetSurvey) en
  48. // paralelo con el poller.
  49. mu sync.Mutex
  50. sid string // sesión ubus HTTP cacheada
  51. lastStat *cpuSample // /proc/stat previo
  52. lastNetDev *netSample // /proc/net/dev previo
  53. // lastNetIf: /proc/net/dev previo POR INTERFAZ (contadores por boca,
  54. // issue #305). Acceso serializado por mu.
  55. lastNetIf *netIfSample
  56. // lldpDownUntil: indisponibilidad de lldpd cacheada (≥5 min) para no
  57. // martillear con un comando que no existe. Acceso serializado por mu.
  58. lldpDownUntil time.Time
  59. // radiosMu serializa la caché de radios (radiosCache/radiosAt): el
  60. // poller y los handlers HTTP pueden sondear el mismo cliente en paralelo.
  61. radiosMu sync.Mutex
  62. radiosCache []Radio // resumen por banda, refrescado cada radiosTTL
  63. radiosAt time.Time
  64. }
  65. type cpuSample struct{ total, idleAll float64 }
  66. type netSample struct {
  67. rx, tx float64
  68. at time.Time
  69. }
  70. type netIfSample struct {
  71. at time.Time
  72. ifaces map[string]probe.IfCounters
  73. }
  74. // Aliases a los shapes compartidos de agent/probe: el agente nativo parsea
  75. // LOCALMENTE con el mismo package (misma fuente de verdad) y empuja esos
  76. // shapes al endpoint de ingesta (SPEC-AGENTE-PILOTO §1-2).
  77. type (
  78. SysInfo = probe.SysInfo
  79. BoardInfo = probe.BoardInfo
  80. DhcpLease = probe.DhcpLease
  81. WirelessClient = probe.WirelessClient
  82. PortState = probe.PortState
  83. PortLayout = probe.PortLayout
  84. VlanPort = probe.VlanPort
  85. MultiWanInfo = probe.MultiWanInfo
  86. WanUplink = probe.WanUplink
  87. VlanEntry = probe.VlanEntry
  88. DhcpReservation = probe.DhcpReservation
  89. )
  90. // NewOpenWrtClient crea el cliente de un router.
  91. func NewOpenWrtClient(cfg RouterConfig, pool poolRunner, user, password string) *OpenWrtClient {
  92. if user == "" {
  93. user = "root"
  94. }
  95. // Host aquí es el destino `host:port` (#605) para el pool SSH.
  96. return &OpenWrtClient{Host: cfg.SSHAddr(), User: user, Password: password, pool: pool}
  97. }
  98. // ---------------------------------------------------------------------------
  99. // Transporte ubus HTTP (JSON-RPC)
  100. // ---------------------------------------------------------------------------
  101. type ubusRPCError struct{ msg string }
  102. func (e *ubusRPCError) Error() string { return e.msg }
  103. // ubusHTTPRpc: POST /ubus; devuelve result[1] si result[0] == 0.
  104. func (c *OpenWrtClient) ubusHTTPRpc(sid, object, method string, params any) (json.RawMessage, error) {
  105. if params == nil {
  106. params = map[string]any{}
  107. }
  108. body, _ := json.Marshal(map[string]any{
  109. "jsonrpc": "2.0", "id": 1, "method": "call",
  110. "params": []any{sid, object, method, params},
  111. })
  112. ctx, cancel := context.WithTimeout(context.Background(), ubusHTTPTimeout)
  113. defer cancel()
  114. req, err := http.NewRequestWithContext(ctx, "POST", "http://"+c.Host+"/ubus", bytes.NewReader(body))
  115. if err != nil {
  116. return nil, err
  117. }
  118. req.Header.Set("Content-Type", "application/json")
  119. res, err := http.DefaultClient.Do(req)
  120. if err != nil {
  121. return nil, err
  122. }
  123. defer res.Body.Close()
  124. data, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
  125. if err != nil {
  126. return nil, err
  127. }
  128. if res.StatusCode != 200 {
  129. return nil, &ubusRPCError{fmt.Sprintf("ubus HTTP %d", res.StatusCode)}
  130. }
  131. var rpc struct {
  132. Error json.RawMessage `json:"error"`
  133. Result json.RawMessage `json:"result"`
  134. }
  135. if err := json.Unmarshal(data, &rpc); err != nil {
  136. return nil, &ubusRPCError{"ubus: respuesta no JSON"}
  137. }
  138. if len(rpc.Error) > 0 && string(rpc.Error) != "null" {
  139. return nil, &ubusRPCError{"ubus RPC error: " + string(rpc.Error)}
  140. }
  141. // ubus devuelve [exitCode, payload]
  142. var result []json.RawMessage
  143. if err := json.Unmarshal(rpc.Result, &result); err != nil || len(result) != 2 {
  144. return nil, &ubusRPCError{"ubus call falló: " + string(rpc.Result)}
  145. }
  146. var code int
  147. if err := json.Unmarshal(result[0], &code); err != nil || code != 0 {
  148. return nil, &ubusRPCError{"ubus call falló: " + string(rpc.Result)}
  149. }
  150. return result[1], nil
  151. }
  152. // ubusLogin: session login con sid '0'×32 → ubus_rpc_session.
  153. func (c *OpenWrtClient) ubusLogin() error {
  154. payload, err := c.ubusHTTPRpc("00000000000000000000000000000000", "session", "login",
  155. map[string]any{"username": c.User, "password": c.Password})
  156. if err != nil {
  157. return err
  158. }
  159. var res struct {
  160. Session string `json:"ubus_rpc_session"`
  161. }
  162. if err := json.Unmarshal(payload, &res); err != nil || res.Session == "" {
  163. return &ubusRPCError{"ubus login: sin ubus_rpc_session"}
  164. }
  165. c.sid = res.Session
  166. return nil
  167. }
  168. // UbusCall: ubus call con HTTP + login cacheado; un solo re-login si la
  169. // sesión caducó; fallback a SSH si HTTP no está disponible.
  170. func (c *OpenWrtClient) UbusCall(object, method string, params any) (json.RawMessage, error) {
  171. if params == nil {
  172. params = map[string]any{}
  173. }
  174. payload, err := func() (json.RawMessage, error) {
  175. if c.sid == "" {
  176. if err := c.ubusLogin(); err != nil {
  177. return nil, err
  178. }
  179. }
  180. payload, err := c.ubusHTTPRpc(c.sid, object, method, params)
  181. if err != nil {
  182. // Sesión caducada → un solo re-login
  183. c.sid = ""
  184. if lerr := c.ubusLogin(); lerr != nil {
  185. return nil, lerr
  186. }
  187. return c.ubusHTTPRpc(c.sid, object, method, params)
  188. }
  189. return payload, nil
  190. }()
  191. if err == nil {
  192. return payload, nil
  193. }
  194. // Fallback SSH: ubus call <object> <method> '<json>'
  195. paramsJSON, _ := json.Marshal(params)
  196. esc := strings.ReplaceAll(string(paramsJSON), `'`, `'\''`)
  197. out, serr := c.pool.Run(c.Host, fmt.Sprintf("ubus call %s %s '%s'", object, method, esc), 0)
  198. if serr != nil {
  199. return nil, serr
  200. }
  201. if !json.Valid([]byte(out)) {
  202. return nil, &ubusRPCError{"ubus ssh: respuesta no JSON"}
  203. }
  204. return json.RawMessage(out), nil
  205. }
  206. // ---------------------------------------------------------------------------
  207. // Sonda de sistema
  208. // ---------------------------------------------------------------------------
  209. // GetBoard: modelo, release, kernel → metadatos estáticos del router.
  210. func (c *OpenWrtClient) GetBoard() (*BoardInfo, error) {
  211. raw, err := c.UbusCall("system", "board", nil)
  212. if err != nil {
  213. return nil, err
  214. }
  215. var b BoardInfo
  216. if err := json.Unmarshal(raw, &b); err != nil {
  217. return nil, err
  218. }
  219. return &b, nil
  220. }
  221. // GetSysInfo: uptime, memoria, load.
  222. func (c *OpenWrtClient) GetSysInfo() (*SysInfo, error) {
  223. raw, err := c.UbusCall("system", "info", nil)
  224. if err != nil {
  225. return nil, err
  226. }
  227. var s SysInfo
  228. if err := json.Unmarshal(raw, &s); err != nil {
  229. return nil, err
  230. }
  231. return &s, nil
  232. }
  233. // ---------------------------------------------------------------------------
  234. // CPU / temperatura / netdev / ping (SSH; parseo literal del JS)
  235. // ---------------------------------------------------------------------------
  236. // GetCPUPercent: CPU % por delta de /proc/stat. Primera muestra: nil.
  237. func (c *OpenWrtClient) GetCPUPercent() (*int, error) {
  238. out, err := c.pool.Run(c.Host, probe.CmdProcStat, 0)
  239. if err != nil {
  240. return nil, err
  241. }
  242. cur, err := parseProcStat(out)
  243. if err != nil {
  244. return nil, err
  245. }
  246. prev := c.lastStat
  247. c.lastStat = &cur
  248. if prev == nil {
  249. return nil, nil
  250. }
  251. return probe.CPUPercent(probe.CPUSample{Total: prev.total, IdleAll: prev.idleAll},
  252. probe.CPUSample{Total: cur.total, IdleAll: cur.idleAll}), nil
  253. }
  254. // parseProcStat parsea "cpu user nice system idle iowait irq softirq ..."
  255. // (delega en el parseo compartido con el agente nativo).
  256. func parseProcStat(out string) (cpuSample, error) {
  257. s, err := probe.ParseProcStat(out)
  258. return cpuSample{total: s.Total, idleAll: s.IdleAll}, err
  259. }
  260. // GetTempC: °C del primer thermal zone disponible (nil si no hay).
  261. func (c *OpenWrtClient) GetTempC() (*int, error) {
  262. out, err := c.pool.Run(c.Host, probe.CmdTemp, 0)
  263. if err != nil {
  264. return nil, err
  265. }
  266. return probe.ParseTempC(out), nil
  267. }
  268. // NetDevBps es el resultado del delta de /proc/net/dev.
  269. type NetDevBps struct {
  270. RxBps *float64
  271. TxBps *float64
  272. }
  273. // GetNetDev: tráfico agregado por delta de /proc/net/dev (excluye lo,
  274. // bridges, ifb, wg, tun/tap para no duplicar contadores) + rates POR INTERFAZ
  275. // (issue #305, para las bocas del chasis). Una sola lectura de /proc/net/dev;
  276. // primera muestra: rates null.
  277. func (c *OpenWrtClient) GetNetDev() (*NetDevBps, map[string]probe.IfRate) {
  278. out, err := c.pool.Run(c.Host, probe.CmdNetDev, 0)
  279. if err != nil {
  280. return nil, nil
  281. }
  282. rx, tx := parseNetDev(out)
  283. curIf := probe.ParseNetDevIfaces(out)
  284. now := time.Now()
  285. c.mu.Lock()
  286. defer c.mu.Unlock()
  287. prev := c.lastNetDev
  288. c.lastNetDev = &netSample{rx: rx, tx: tx, at: now}
  289. prevIf := c.lastNetIf
  290. c.lastNetIf = &netIfSample{at: now, ifaces: curIf}
  291. res := &NetDevBps{}
  292. if prev != nil {
  293. res.RxBps, res.TxBps = probe.NetDevBps(prev.rx, prev.tx, rx, tx, now.Sub(prev.at).Seconds())
  294. }
  295. var rates map[string]probe.IfRate
  296. if prevIf != nil {
  297. rates = probe.IfRates(prevIf.ifaces, curIf, now.Sub(prevIf.at).Seconds())
  298. }
  299. return res, rates
  300. }
  301. // parseNetDev suma rx/tx de las interfaces físicas (compartido con el agente).
  302. func parseNetDev(out string) (rx, tx float64) {
  303. return probe.ParseNetDev(out)
  304. }
  305. // GetWanLatency: ping a internet (solo gateway) → latencia avg + pérdida.
  306. func (c *OpenWrtClient) GetWanLatency(target string) (latency *float64, loss *float64, err error) {
  307. if target == "" {
  308. target = "1.1.1.1"
  309. }
  310. out, err := c.pool.Run(c.Host, fmt.Sprintf(probe.CmdPingWan, target), 0)
  311. if err != nil {
  312. return nil, nil, err
  313. }
  314. latency, loss = probe.ParsePingSummary(out)
  315. return latency, loss, nil
  316. }
  317. // GetGatewayLatency: ping corto al gateway desde un AP (avg, redondeado).
  318. func (c *OpenWrtClient) GetGatewayLatency(gatewayHost string) (*float64, error) {
  319. out, err := c.pool.Run(c.Host, fmt.Sprintf(probe.CmdPingGateway, gatewayHost), 0)
  320. if err != nil {
  321. return nil, err
  322. }
  323. latency, _ := probe.ParsePingSummary(out)
  324. return latency, nil
  325. }
  326. // ---------------------------------------------------------------------------
  327. // Clientes (DHCP + wireless)
  328. // ---------------------------------------------------------------------------
  329. // GetDhcpLeases: ubus dhcp ipv4leases; fallback /tmp/dhcp.leases.
  330. func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
  331. raw, err := c.UbusCall("dhcp", "ipv4leases", nil)
  332. if err == nil {
  333. if leases, perr := probe.ParseDhcpUbus(raw); perr == nil {
  334. return leases
  335. }
  336. }
  337. out, serr := c.pool.Run(c.Host, probe.CmdDhcpFile, 0)
  338. if serr != nil {
  339. return []DhcpLease{}
  340. }
  341. return parseDhcpLeasesFile(out)
  342. }
  343. // GetWanInfo: estado del uplink (issue #276). Via ubus network.interface
  344. // dump, que trae todas las interfaces y deja elegir la que lleva internet
  345. // por su ruta por defecto en vez de por llamarse "wan" (un PPPoE puede
  346. // llamarse de cualquier forma, y el nombre "wan" puede ser un módem ocioso).
  347. // Cae al status de la interfaz "wan" con los ubus antiguos; si el router no
  348. // tiene ninguna (AP), devuelve WanInfo vacío.
  349. func (c *OpenWrtClient) GetWanInfo() probe.WanInfo {
  350. if raw, err := c.UbusCall("network.interface", "dump", nil); err == nil {
  351. if info := probe.ParseWanStatus(raw); info.Proto != "" || info.IP != "" || info.Gateway != "" {
  352. return info
  353. }
  354. }
  355. raw, err := c.UbusCall("network.interface.wan", "status", nil)
  356. if err == nil {
  357. return probe.ParseWanStatus(raw)
  358. }
  359. return probe.WanInfo{}
  360. }
  361. // GetDhcpReservations: the `config host` entries of /etc/config/dhcp, for
  362. // the routers polled over SSH (the agent sends them in its payload). Error
  363. // or no entries → empty, and clients keep falling back to their MAC.
  364. func (c *OpenWrtClient) GetDhcpReservations() []DhcpReservation {
  365. out, err := c.pool.Run(c.Host, probe.CmdDhcpReservations, 0)
  366. if err != nil {
  367. return nil
  368. }
  369. return probe.ParseDhcpReservations(out)
  370. }
  371. // GetGlClients: base de clientes del firmware GL.iNet (`ubus call gl-clients
  372. // list`). SUPERSET de dhcp.leases: incluye equipos con IP estática o sin
  373. // lease que el dnsmasq del Flint2 no lista. En routers sin el objeto ubus
  374. // gl-clients devuelve vacío (la salida del comando es vacía) — el caller lo
  375. // usa solo para enriquecer IPs de dispositivos ya conocidos, nunca para
  376. // crearlos (issue #5 bug 1).
  377. func (c *OpenWrtClient) GetGlClients() []DhcpLease {
  378. out, err := c.pool.Run(c.Host, probe.CmdGlClients, 0)
  379. if err != nil || strings.TrimSpace(out) == "" {
  380. return []DhcpLease{}
  381. }
  382. leases, perr := probe.ParseGlClients([]byte(out))
  383. if perr != nil {
  384. return []DhcpLease{}
  385. }
  386. return leases
  387. }
  388. // parseDhcpLeasesFile parsea /tmp/dhcp.leases:
  389. // <expiry> <mac> <ip> <hostname> <clientid>
  390. func parseDhcpLeasesFile(out string) []DhcpLease {
  391. return probe.ParseDhcpLeasesFile(out)
  392. }
  393. // GetWirelessClients: clientes wifi asociados (MAC → señal/banda). Port del
  394. // fix #373 (#368) al sondeo SSH: ubus hostapd get_clients primero (una
  395. // llamada ubus barata por AP, sin ucode/iwinfo), fallback de iwinfo combinado
  396. // en UNA pasada por interfaz, y como último recurso el par legacy. Vacío si
  397. // el router no expone ninguna fuente wireless.
  398. func (c *OpenWrtClient) GetWirelessClients() map[string]WirelessClient {
  399. // 1. ubus hostapd get_clients (barato; APs con hostapd ubus moderno).
  400. // Autoritativo cuando hay objetos hostapd.* (incluso con 0 clientes: un
  401. // AP vacío no debe caer al fallback iwinfo en cada poll de 5 s del
  402. // server). Solo si ubus no expone objetos se baja al fallback.
  403. if out, err := c.pool.Run(c.Host, probe.CmdHostapdClients, iwinfoTimeout); err == nil && strings.Contains(out, "==AP==") {
  404. return probe.ParseHostapdClients(out)
  405. }
  406. // 2. iwinfo combinado en UNA pasada (info + assoclist juntos por interfaz;
  407. // emite clientes y radios). Mitad de spawns que el par legacy de abajo.
  408. // Las radios se cachean aunque no haya clientes (GetRadios no re-sondea).
  409. if out, err := c.pool.Run(c.Host, probe.CmdWirelessCombined, iwinfoTimeout); err == nil {
  410. clients, radios := probe.ParseWirelessCombined(out)
  411. if len(radios) > 0 {
  412. c.setRadiosCache(radiosToAdapter(radios))
  413. }
  414. if len(clients) > 0 {
  415. return clients
  416. }
  417. }
  418. // 3. Último recurso: par legacy (equipos donde el combinado no aplica).
  419. out, err := c.pool.Run(c.Host, probe.CmdIwinfoAssoc, iwinfoTimeout)
  420. if err != nil {
  421. return map[string]WirelessClient{}
  422. }
  423. return parseWirelessClients(out)
  424. }
  425. // parseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
  426. func parseWirelessClients(out string) map[string]WirelessClient {
  427. return probe.ParseWirelessClients(out)
  428. }
  429. // GetRadios: radios activas por banda (canal/htmode/txpower + nº clientes).
  430. // Cacheadas radiosTTL (5 min): el resumen de radios apenas cambia y correr
  431. // CmdRadios (iwinfo) en CADA poll de 5 s del server quemaba CPU en APs de
  432. // bajas prestaciones (port #373 al sondeo SSH). Si la caché está fresca se
  433. // devuelve sin tocar el router; si caducó (o está vacía) se refresca.
  434. func (c *OpenWrtClient) GetRadios() []Radio {
  435. c.radiosMu.Lock()
  436. cached := c.radiosCache
  437. if len(cached) > 0 && time.Since(c.radiosAt) < radiosTTL {
  438. c.radiosMu.Unlock()
  439. return cached
  440. }
  441. c.radiosMu.Unlock()
  442. // Refresco. Prioridad al combinado (una pasada por interfaz) cuando ubus
  443. // no estuvo disponible para clientes: el propio comando emite las radios.
  444. out, err := c.pool.Run(c.Host, probe.CmdWirelessCombined, iwinfoTimeout)
  445. if err == nil {
  446. if _, radios := probe.ParseWirelessCombined(out); len(radios) > 0 {
  447. rs := radiosToAdapter(radios)
  448. c.setRadiosCache(rs)
  449. return rs
  450. }
  451. }
  452. out, err = c.pool.Run(c.Host, probe.CmdRadios, iwinfoTimeout)
  453. if err != nil {
  454. return []Radio{}
  455. }
  456. rs := parseRadios(out)
  457. if len(rs) > 0 {
  458. c.setRadiosCache(rs)
  459. }
  460. return rs
  461. }
  462. // setRadiosCache guarda el resumen de radios con su timestamp (best-effort:
  463. // no falla si la caché está vacía; el poller reintenta en el próximo ciclo).
  464. func (c *OpenWrtClient) setRadiosCache(rs []Radio) {
  465. if len(rs) == 0 {
  466. return
  467. }
  468. c.radiosMu.Lock()
  469. c.radiosCache = rs
  470. c.radiosAt = time.Now()
  471. c.radiosMu.Unlock()
  472. }
  473. // GetWirelessUplink: true si el router tiene uplink inalámbrico (alguna
  474. // interfaz STA activa/asociada en `ubus call network.wireless status`).
  475. // Error si el router no soporta la llamada (sin wifi → el caller omite el
  476. // campo backhaul, nunca rompe el sondeo).
  477. func (c *OpenWrtClient) GetWirelessUplink() (bool, error) {
  478. raw, err := c.UbusCall("network.wireless", "status", nil)
  479. if err != nil {
  480. return false, err
  481. }
  482. return parseWirelessUplink(raw)
  483. }
  484. // parseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio
  485. // up e ifname asignado = asociada). Tolerante con radios/entradas raras.
  486. func parseWirelessUplink(raw json.RawMessage) (bool, error) {
  487. return probe.ParseWirelessUplink(raw)
  488. }
  489. // ---------------------------------------------------------------------------
  490. // Puertos
  491. // ---------------------------------------------------------------------------
  492. // GetPortStates: estado de interfaces desde /sys (SSH).
  493. func (c *OpenWrtClient) GetPortStates() []PortState {
  494. out, err := c.pool.Run(c.Host, probe.CmdPortStates, 0)
  495. if err != nil {
  496. return []PortState{}
  497. }
  498. return parsePortStates(out)
  499. }
  500. // parsePortStates parsea líneas "<name> <operstate> <speed>".
  501. func parsePortStates(out string) []PortState {
  502. return probe.ParsePortStates(out)
  503. }
  504. // GetPortLayout: layout canónico desde /etc/board.json (estático; lo cachea
  505. // el live). WAN normalizado a id 'wan'.
  506. func (c *OpenWrtClient) GetPortLayout() ([]PortLayout, error) {
  507. out, err := c.pool.Run(c.Host, probe.CmdBoardJSON, 0)
  508. if err != nil {
  509. return nil, err
  510. }
  511. return parsePortLayout(out)
  512. }
  513. // parsePortLayout parsea board.json → [{id, name, label, role}].
  514. func parsePortLayout(out string) ([]PortLayout, error) {
  515. return probe.ParsePortLayout(out)
  516. }
  517. // GetEthPorts: layout + estado /sys; AP en bridge re-etiqueta wan→LAN N+1;
  518. // fallback heurístico sin config. rates = contadores por iface (#305, de
  519. // GetNetDev; nil = sin stats). Devuelve []EthPort listo para el detalle.
  520. func (c *OpenWrtClient) GetEthPorts(layout []PortLayout, rates map[string]probe.IfRate, uplink string) []EthPort {
  521. states := c.GetPortStates()
  522. members := map[string]bool{}
  523. if len(layout) > 0 {
  524. // Miembros del bridge: si "wan" está en br-lan, este router es un AP
  525. brif, _ := c.pool.Run(c.Host, probe.CmdBrifMembers, 0)
  526. for _, l := range strings.Split(strings.TrimSpace(brif), "\n") {
  527. if l != "" {
  528. members[l] = true
  529. }
  530. }
  531. }
  532. return ethPortsToAdapter(probe.BuildEthPorts(layout, states, members, rates, uplink))
  533. }
  534. // ethPortsToAdapter convierte el shape compartido al EthPort del contrato.
  535. func ethPortsToAdapter(in []probe.EthPort) []EthPort {
  536. f := func(v *float64) float64 {
  537. if v == nil {
  538. return 0
  539. }
  540. return *v
  541. }
  542. out := make([]EthPort, 0, len(in))
  543. for _, p := range in {
  544. ep := EthPort{ID: p.ID, Label: p.Label, Up: p.Up, Iface: p.Iface,
  545. RxBytes: p.RxBytes, TxBytes: p.TxBytes, RxErrs: p.RxErrs, TxErrs: p.TxErrs,
  546. RxBps: f(p.RxBps), TxBps: f(p.TxBps)}
  547. if p.Up {
  548. ep.Speed = p.Speed
  549. }
  550. if p.Sfp != nil {
  551. ep.Sfp = &SfpInfo{
  552. Temperature: p.Sfp.Temperature, Voltage: p.Sfp.Voltage,
  553. TxPower: p.Sfp.TxPower, RxPower: p.Sfp.RxPower,
  554. Vendor: p.Sfp.Vendor, PartNumber: p.Sfp.PartNumber,
  555. Present: p.Sfp.Present,
  556. }
  557. }
  558. out = append(out, ep)
  559. }
  560. return out
  561. }
  562. // naturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
  563. func naturalLess(a, b string) bool {
  564. return probe.NaturalLess(a, b)
  565. }
  566. // GetBridgeFdb: MAC aprendida → puerto (brctl showmacs + port_no).
  567. // Devuelve nil en error para que el anti-parpadeo de pollRouter conserve la
  568. // última lista buena en vez de sustituirla por un FDB vacío (#694).
  569. func (c *OpenWrtClient) GetBridgeFdb() map[string]string {
  570. out, err := c.pool.Run(c.Host, probe.CmdBridgeFDB, 0)
  571. if err != nil {
  572. return nil
  573. }
  574. return parseBridgeFdb(out)
  575. }
  576. // parseBridgeFdb parsea la salida ==PORTS==/==MACS== del JS.
  577. func parseBridgeFdb(out string) map[string]string {
  578. return probe.ParseBridgeFdb(out)
  579. }
  580. // GetBridgeMac: MAC del bridge br-lan (para reconocer uplinks).
  581. func (c *OpenWrtClient) GetBridgeMac() string {
  582. out, err := c.pool.Run(c.Host, probe.CmdBridgeMAC, 0)
  583. if err != nil {
  584. return ""
  585. }
  586. return strings.ToUpper(strings.TrimSpace(out))
  587. }
  588. // GetLuCILabels: etiquetas de puertos/VLANs de LuCI (issue #258), si el
  589. // router las define en /etc/config/luci. Best-effort: fichero sin secciones
  590. // → nil.
  591. func (c *OpenWrtClient) GetLuCILabels() *probe.LuCILabels {
  592. out, err := c.pool.Run(c.Host, probe.CmdLuCILabels, 0)
  593. if err != nil {
  594. return nil
  595. }
  596. return probe.ParseLuCILabels(out)
  597. }
  598. // GetBridgeVlans: VLANs del bridge (issue #315). La salida del kernel se
  599. // fusiona con la configuración (#1757): un router que segmenta con
  600. // subinterfaces 802.1Q contesta con todos los puertos en la VLAN 1 y las
  601. // VLANs reales solo están en `uci show network`. nil si ninguna de las dos
  602. // fuentes dice nada.
  603. func (c *OpenWrtClient) GetBridgeVlans() []probe.VlanPort {
  604. var kernel []probe.VlanPort
  605. if out, err := c.pool.Run(c.Host, probe.CmdBridgeVlan, 0); err == nil {
  606. kernel = probe.ParseBridgeVlan(out)
  607. }
  608. var declared []probe.VlanPort
  609. if out, err := c.pool.Run(c.Host, probe.CmdUciBridgeVlan, 0); err == nil {
  610. declared = probe.MergeVlanPorts(probe.ParseUciBridgeVlans(out), probe.ParseUciNetworkVlans(out))
  611. }
  612. ports := probe.MergeVlanPorts(kernel, declared)
  613. if len(ports) == 0 {
  614. return nil
  615. }
  616. return ports
  617. }
  618. // ---------------------------------------------------------------------------
  619. // Radios WiFi
  620. // ---------------------------------------------------------------------------
  621. // parseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
  622. func parseRadios(out string) []Radio {
  623. return radiosToAdapter(probe.ParseRadios(out))
  624. }
  625. // radiosToAdapter convierte el shape compartido al Radio del contrato.
  626. func radiosToAdapter(in []probe.Radio) []Radio {
  627. out := make([]Radio, 0, len(in))
  628. for _, r := range in {
  629. out = append(out, Radio{Name: r.Name, Channel: r.Channel,
  630. WidthMhz: r.WidthMhz, PowerDbm: r.PowerDbm, Clients: r.Clients,
  631. NoiseDbm: r.NoiseDbm, BSSID: r.BSSID})
  632. }
  633. return out
  634. }
  635. // GetArp devuelve la tabla ARP del equipo (MAC→IP, #377). Fuente barata
  636. // para resolver IPs cuando el DHCP no es local.
  637. //
  638. // Reads `ip neigh` so the state of each entry comes with it, and returns the
  639. // MACs the kernel remembers without confirming (stale): their address is
  640. // still usable, but they are not evidence that the host is connected. Falls
  641. // back to /proc/net/arp, where no state is available and nothing is stale.
  642. // GetArp devuelve además MAC -> interfaz (#1485): con esa columna el poller
  643. // distingue el ARP del puerto WAN (primer salto del enlace) del de la LAN.
  644. func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool, devs map[string]string) {
  645. if out, err := c.pool.Run(c.Host, probe.CmdIpNeigh, 0); err == nil {
  646. if m, st := probe.ParseIPNeigh(out); len(m) > 0 {
  647. return m, st, probe.ParseIPNeighDevs(out)
  648. }
  649. }
  650. out, err := c.pool.Run(c.Host, probe.CmdProcArp, 0)
  651. if err != nil {
  652. return nil, nil, nil
  653. }
  654. return probe.ParseArp(out), nil, probe.ParseArpDevs(out)
  655. }
  656. // GetNetworks: redes logicas que la unidad declara en UCI (#1889). Es la
  657. // misma lectura que alimenta las VLANs, asi que una unidad por SSH tambien
  658. // tiene la vista de redes; lo que no tiene son los contadores por interfaz.
  659. // nil si no hay datos, para que el anti-parpadeo conserve la ultima lista.
  660. func (c *OpenWrtClient) GetNetworks() []probe.UciNetwork {
  661. out, err := c.pool.Run(c.Host, probe.CmdUciBridgeVlan, 0)
  662. if err != nil {
  663. return nil
  664. }
  665. nets := probe.ParseUciNetworks(out)
  666. if len(nets) == 0 {
  667. return nil
  668. }
  669. return nets
  670. }