probe.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. // Package probe — sondas del tier rápido OpenWrt: comandos (los LITERALES que
  2. // internal/adapters/openwrt.go lanza por SSH) + parseo de sus salidas +
  3. // shapes JSON del payload que el agente empuja a POST /api/ingest/agent.
  4. //
  5. // Es la ÚNICA fuente de verdad del parseo: server-go (internal/adapters) lo
  6. // importa con un replace ../agent, y el binario netpulse-agent ejecuta los
  7. // mismos comandos localmente. Solo stdlib (el binario del agente tiene
  8. // objetivo ≤ 3 MB y CGO_ENABLED=0).
  9. package probe
  10. import (
  11. "encoding/json"
  12. "fmt"
  13. "regexp"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. )
  18. // ---------------------------------------------------------------------------
  19. // Comandos (idénticos a los del sondeo SSH de openwrt.go)
  20. // ---------------------------------------------------------------------------
  21. const (
  22. CmdProcStat = "grep '^cpu ' /proc/stat"
  23. CmdTemp = `for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && cat "$f" && break; done`
  24. CmdNetDev = "cat /proc/net/dev | tail -n +3"
  25. // CmdPingWan: latencia + pérdida a internet (solo gateway). %s = target.
  26. CmdPingWan = "ping -c 3 -W 2 %s 2>/dev/null | tail -2"
  27. // CmdPingGateway: ping corto al gateway desde un AP. %s = host gateway.
  28. CmdPingGateway = "ping -c 2 -W 2 %s 2>/dev/null | tail -1"
  29. CmdDhcpUbus = "ubus call dhcp ipv4leases"
  30. CmdDhcpFile = "cat /tmp/dhcp.leases 2>/dev/null || true"
  31. // CmdGlClients (GL.iNet): base de clientes completa del firmware. Es un
  32. // SUPERSET de dhcp.leases: incluye equipos con IP estática o sin lease
  33. // DHCP que el dnsmasq del Flint2 no lista (issue #5 bug 1).
  34. CmdGlClients = "ubus call gl-clients list 2>/dev/null || true"
  35. // CmdIwinfoAssoc: "<mac> <sig> <freq>" por cliente wifi asociado.
  36. CmdIwinfoAssoc = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
  37. `freq=$(iwinfo "$i" info 2>/dev/null | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
  38. `iwinfo "$i" assoclist 2>/dev/null | sed -n 's/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/\1 \2/p' | while read mac sig; do ` +
  39. `echo "$mac $sig $freq"; done; done`
  40. // CmdRadios: "freq|ch|ht|tx|n" por radio (se agrega por banda al parsear).
  41. CmdRadios = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
  42. `info=$(iwinfo "$i" info 2>/dev/null) || continue; ` +
  43. `echo "$info" | grep -q ESSID || continue; ` +
  44. `freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
  45. `ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); ` +
  46. `ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); ` +
  47. `tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); ` +
  48. `n=$(iwinfo "$i" assoclist 2>/dev/null | grep -c '^[0-9A-Fa-f:]'); ` +
  49. `echo "$freq|$ch|$ht|$tx|$n"; done`
  50. // CmdPortStates: "<name> <operstate> <speed>" por interfaz.
  51. CmdPortStates = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
  52. `echo "$i $(cat $d/operstate 2>/dev/null) $(cat $d/speed 2>/dev/null || echo -1)"; done`
  53. CmdBoardJSON = "cat /etc/board.json 2>/dev/null"
  54. CmdBrifMembers = "ls /sys/class/net/br-lan/brif/ 2>/dev/null"
  55. // CmdBridgeFDB: "==PORTS==" (port_no ifname) + "==MACS==" (port mac).
  56. CmdBridgeFDB = `echo "==PORTS=="; for d in /sys/class/net/br-lan/brif/*; do [ -r "$d/port_no" ] && echo "$(cat $d/port_no) $(basename $d)"; done; ` +
  57. `echo "==MACS=="; brctl showmacs br-lan 2>/dev/null | awk 'NR>1 && $3=="no" {print $1, $2}'`
  58. CmdBridgeMAC = "cat /sys/class/net/br-lan/address 2>/dev/null"
  59. CmdUbusSystemBoard = "ubus call system board"
  60. CmdUbusSystemInfo = "ubus call system info"
  61. CmdUbusWireless = "ubus call network.wireless status"
  62. )
  63. // ---------------------------------------------------------------------------
  64. // Shapes parseados (salida de las sondas; contrato del payload del agente)
  65. // ---------------------------------------------------------------------------
  66. // SysInfo: ubus system info (uptime, memoria, load).
  67. type SysInfo struct {
  68. Uptime float64 `json:"uptime"`
  69. Load []float64 `json:"load"`
  70. Memory struct {
  71. Total float64 `json:"total"`
  72. Free float64 `json:"free"`
  73. Buffered float64 `json:"buffered"`
  74. Available float64 `json:"available"`
  75. } `json:"memory"`
  76. }
  77. // BoardInfo: ubus system board (metadatos estáticos).
  78. type BoardInfo struct {
  79. Model string `json:"model"`
  80. Hostname string `json:"hostname"`
  81. System string `json:"system"`
  82. Release struct {
  83. Version string `json:"version"`
  84. Description string `json:"description"`
  85. } `json:"release"`
  86. }
  87. // DhcpLease es {mac, ip, hostname} (mac en mayúsculas).
  88. type DhcpLease struct {
  89. MAC string `json:"mac"`
  90. IP string `json:"ip"`
  91. Hostname string `json:"hostname"`
  92. }
  93. // WirelessClient es {signalDbm, band} por MAC.
  94. type WirelessClient struct {
  95. SignalDbm int `json:"signalDbm"`
  96. Band string `json:"band"`
  97. }
  98. // PortState es {name, up, speed} de una interfaz (/sys operstate+speed).
  99. type PortState struct {
  100. Name string `json:"name"`
  101. Up bool `json:"up"`
  102. Speed string `json:"speed"` // "1 Gbps" | "100 Mbps" | "—"
  103. }
  104. // PortLayout es una boca del layout canónico (/etc/board.json).
  105. type PortLayout struct {
  106. ID string `json:"id"`
  107. Name string `json:"name"`
  108. Label string `json:"label"`
  109. Role string `json:"role"` // "lan" | "wan"
  110. }
  111. // EthPort es una boca ethernet lista para el detalle ({id, label, up, speed?}).
  112. type EthPort struct {
  113. ID string `json:"id"`
  114. Label string `json:"label"`
  115. Up bool `json:"up"`
  116. Speed string `json:"speed,omitempty"` // solo si up
  117. }
  118. // Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).
  119. type Radio struct {
  120. Name string `json:"name"` // "5 GHz"|"2.4 GHz"
  121. Channel int `json:"channel"`
  122. WidthMhz int `json:"widthMhz"`
  123. PowerDbm float64 `json:"powerDbm"`
  124. Clients int `json:"clients"`
  125. }
  126. // ---------------------------------------------------------------------------
  127. // Sistema: /proc/stat, thermal, /proc/net/dev, ping
  128. // ---------------------------------------------------------------------------
  129. // CPUSample es la muestra agregada de "cpu " de /proc/stat.
  130. type CPUSample struct{ Total, IdleAll float64 }
  131. // ParseProcStat parsea "cpu user nice system idle iowait irq softirq ...".
  132. func ParseProcStat(out string) (CPUSample, error) {
  133. fields := strings.Fields(strings.TrimSpace(out))
  134. if len(fields) < 5 || fields[0] != "cpu" {
  135. return CPUSample{}, fmt.Errorf("/proc/stat inesperado: %q", out)
  136. }
  137. nums := make([]float64, 0, len(fields)-1)
  138. for _, f := range fields[1:] {
  139. n, err := strconv.ParseFloat(f, 64)
  140. if err != nil {
  141. n = 0
  142. }
  143. nums = append(nums, n)
  144. }
  145. get := func(i int) float64 {
  146. if i < len(nums) {
  147. return nums[i]
  148. }
  149. return 0
  150. }
  151. idleAll := get(3) + get(4) // idle + iowait
  152. nonIdle := get(0) + get(1) + get(2) + get(5) + get(6) // user+nice+system+irq+softirq
  153. return CPUSample{Total: idleAll + nonIdle, IdleAll: idleAll}, nil
  154. }
  155. // CPUPercent: % de CPU por delta de muestras (nil si no hay delta válido:
  156. // primera muestra o contadores reseteados).
  157. func CPUPercent(prev, cur CPUSample) *int {
  158. dTotal := cur.Total - prev.Total
  159. dIdle := cur.IdleAll - prev.IdleAll
  160. if dTotal <= 0 {
  161. return nil
  162. }
  163. v := int(float64(dTotal-dIdle)/float64(dTotal)*100 + 0.5)
  164. return &v
  165. }
  166. // ParseTempC: °C del primer thermal zone (nil si la salida no es un entero).
  167. func ParseTempC(out string) *int {
  168. milli, err := strconv.Atoi(strings.TrimSpace(out))
  169. if err != nil {
  170. return nil
  171. }
  172. v := milli / 1000
  173. if milli%1000 >= 500 {
  174. v++
  175. }
  176. return &v
  177. }
  178. var netdevSkipRe = regexp.MustCompile(`^(lo|br-|ifb|wg|tun|tap)`)
  179. // ParseNetDev suma rx/tx de las interfaces físicas (excluye lo, bridges,
  180. // ifb, wg, tun/tap para no duplicar contadores).
  181. func ParseNetDev(out string) (rx, tx float64) {
  182. lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
  183. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  184. m := lineRe.FindStringSubmatch(line)
  185. if m == nil || netdevSkipRe.MatchString(m[1]) {
  186. continue
  187. }
  188. fields := strings.Fields(strings.TrimSpace(m[2]))
  189. num := func(i int) float64 {
  190. if i < len(fields) {
  191. n, _ := strconv.ParseFloat(fields[i], 64)
  192. return n
  193. }
  194. return 0
  195. }
  196. rx += num(0)
  197. tx += num(8)
  198. }
  199. return rx, tx
  200. }
  201. // NetDevBps: bps por delta de contadores en dt segundos (nil si dt <= 0 o
  202. // contadores reseteados).
  203. func NetDevBps(prevRx, prevTx, rx, tx, dt float64) (rxBps, txBps *float64) {
  204. if dt <= 0 {
  205. return nil, nil
  206. }
  207. rb := round0(max0((rx - prevRx) * 8 / dt))
  208. tb := round0(max0((tx - prevTx) * 8 / dt))
  209. return &rb, &tb
  210. }
  211. var pingLossRe = regexp.MustCompile(`(\d+(?:\.\d+)?)% packet loss`)
  212. var pingRTTRe = regexp.MustCompile(`= [\d.]+/([\d.]+)/[\d.]+/[\d.]+ ms`)
  213. // ParsePingSummary extrae (latencia avg redondeada, pérdida %) del resumen de
  214. // ping; cada una es nil si su línea no está.
  215. func ParsePingSummary(out string) (latency, loss *float64) {
  216. if m := pingRTTRe.FindStringSubmatch(out); m != nil {
  217. v, _ := strconv.ParseFloat(m[1], 64)
  218. v = float64(int(v + 0.5))
  219. latency = &v
  220. }
  221. if m := pingLossRe.FindStringSubmatch(out); m != nil {
  222. v, _ := strconv.ParseFloat(m[1], 64)
  223. loss = &v
  224. }
  225. return latency, loss
  226. }
  227. // ---------------------------------------------------------------------------
  228. // Clientes (DHCP + wireless)
  229. // ---------------------------------------------------------------------------
  230. // ParseDhcpUbus parsea la respuesta de `ubus call dhcp ipv4leases`
  231. // ({lease: [...]} o {leases: [...]}). Error si no es JSON con esas claves.
  232. func ParseDhcpUbus(raw []byte) ([]DhcpLease, error) {
  233. type leaseJSON struct {
  234. MAC string `json:"mac"`
  235. IPAddr string `json:"ip-address"`
  236. IP string `json:"ip"`
  237. Hostname string `json:"hostname"`
  238. }
  239. var data struct {
  240. Lease []leaseJSON `json:"lease"`
  241. Leases []leaseJSON `json:"leases"`
  242. }
  243. if err := json.Unmarshal(raw, &data); err != nil {
  244. return nil, err
  245. }
  246. leases := data.Lease
  247. if leases == nil {
  248. leases = data.Leases
  249. }
  250. if leases == nil {
  251. return nil, fmt.Errorf("ubus dhcp: sin clave lease/leases")
  252. }
  253. out := make([]DhcpLease, 0, len(leases))
  254. for _, l := range leases {
  255. ip := l.IPAddr
  256. if ip == "" {
  257. ip = l.IP
  258. }
  259. out = append(out, DhcpLease{MAC: strings.ToUpper(l.MAC), IP: ip, Hostname: l.Hostname})
  260. }
  261. return out, nil
  262. }
  263. // ParseDhcpLeasesFile parsea /tmp/dhcp.leases:
  264. // <expiry> <mac> <ip> <hostname> <clientid>
  265. func ParseDhcpLeasesFile(out string) []DhcpLease {
  266. leases := []DhcpLease{}
  267. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  268. if line == "" {
  269. continue
  270. }
  271. p := strings.Fields(line)
  272. if len(p) < 3 {
  273. continue
  274. }
  275. hostname := ""
  276. if len(p) > 3 && p[3] != "*" {
  277. hostname = p[3]
  278. }
  279. leases = append(leases, DhcpLease{MAC: strings.ToUpper(p[1]), IP: p[2], Hostname: hostname})
  280. }
  281. return leases
  282. }
  283. // ParseGlClients parsea la respuesta de `ubus call gl-clients list`
  284. // (GL.iNet Flint2 y similares): {"clients": {"MAC": {mac, ip, name, online, ...}}}.
  285. // Error si no es JSON con esa forma. Solo devuelve entradas ONLINE con IP:
  286. // la base del firmware acumula historial (cientos de entradas) y las offline
  287. // solo servirían para inflar la lista de dispositivos; los equipos que
  288. // necesitan resolución de IP son los que están en la red ahora (issue #5
  289. // bug 1).
  290. func ParseGlClients(raw []byte) ([]DhcpLease, error) {
  291. type clientJSON struct {
  292. MAC string `json:"mac"`
  293. IP string `json:"ip"`
  294. Name string `json:"name"`
  295. Hostname string `json:"hostname"`
  296. Online bool `json:"online"`
  297. }
  298. var data struct {
  299. Clients map[string]clientJSON `json:"clients"`
  300. }
  301. if err := json.Unmarshal(raw, &data); err != nil {
  302. return nil, err
  303. }
  304. if data.Clients == nil {
  305. return nil, fmt.Errorf("gl-clients: sin clave clients")
  306. }
  307. out := make([]DhcpLease, 0, len(data.Clients))
  308. for key, c := range data.Clients {
  309. mac := c.MAC
  310. if mac == "" {
  311. mac = key
  312. }
  313. if mac == "" || c.IP == "" || !c.Online {
  314. continue
  315. }
  316. hostname := c.Hostname
  317. if hostname == "" {
  318. hostname = c.Name
  319. }
  320. out = append(out, DhcpLease{MAC: strings.ToUpper(mac), IP: c.IP, Hostname: hostname})
  321. }
  322. sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC })
  323. return out, nil
  324. }
  325. // ParseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
  326. func ParseWirelessClients(out string) map[string]WirelessClient {
  327. m := map[string]WirelessClient{}
  328. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  329. if line == "" {
  330. continue
  331. }
  332. p := strings.Fields(line)
  333. if len(p) < 2 {
  334. continue
  335. }
  336. freq := 0.0
  337. if len(p) > 2 {
  338. freq, _ = strconv.ParseFloat(p[2], 64)
  339. }
  340. sig, _ := strconv.Atoi(p[1])
  341. band := "2.4 GHz"
  342. if freq >= 5 {
  343. band = "5 GHz"
  344. }
  345. m[strings.ToUpper(p[0])] = WirelessClient{SignalDbm: sig, Band: band}
  346. }
  347. return m
  348. }
  349. // ParseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio
  350. // up e ifname asignado = asociada) → uplink inalámbrico. Tolerante con
  351. // radios/entradas raras; error si la respuesta no es JSON.
  352. func ParseWirelessUplink(raw []byte) (bool, error) {
  353. var radios map[string]struct {
  354. Up bool `json:"up"`
  355. Interfaces []struct {
  356. Ifname string `json:"ifname"`
  357. Config struct {
  358. Mode string `json:"mode"`
  359. } `json:"config"`
  360. } `json:"interfaces"`
  361. }
  362. if err := json.Unmarshal(raw, &radios); err != nil {
  363. return false, err
  364. }
  365. for _, r := range radios {
  366. if !r.Up {
  367. continue
  368. }
  369. for _, itf := range r.Interfaces {
  370. if itf.Config.Mode == "sta" && itf.Ifname != "" {
  371. return true, nil
  372. }
  373. }
  374. }
  375. return false, nil
  376. }
  377. // ---------------------------------------------------------------------------
  378. // Puertos
  379. // ---------------------------------------------------------------------------
  380. // ParsePortStates parsea líneas "<name> <operstate> <speed>".
  381. func ParsePortStates(out string) []PortState {
  382. ports := []PortState{}
  383. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  384. if line == "" {
  385. continue
  386. }
  387. p := strings.Fields(line)
  388. if len(p) < 3 {
  389. continue
  390. }
  391. mbps, _ := strconv.Atoi(p[2])
  392. speed := "—"
  393. if mbps > 0 {
  394. if mbps >= 1000 {
  395. speed = strconv.Itoa(mbps/1000) + " Gbps"
  396. } else {
  397. speed = strconv.Itoa(mbps) + " Mbps"
  398. }
  399. }
  400. ports = append(ports, PortState{Name: p[0], Up: p[1] == "up", Speed: speed})
  401. }
  402. return ports
  403. }
  404. // ParsePortLayout parsea board.json → [{id, name, label, role}] (WAN
  405. // normalizado a id 'wan').
  406. func ParsePortLayout(out string) ([]PortLayout, error) {
  407. var board struct {
  408. Network struct {
  409. Lan struct {
  410. Ports []string `json:"ports"`
  411. } `json:"lan"`
  412. Wan struct {
  413. Device string `json:"device"`
  414. } `json:"wan"`
  415. } `json:"network"`
  416. }
  417. if err := json.Unmarshal([]byte(out), &board); err != nil {
  418. return nil, err
  419. }
  420. ports := []PortLayout{}
  421. for _, name := range board.Network.Lan.Ports {
  422. ports = append(ports, PortLayout{ID: name, Name: name, Label: strings.Replace(name, "lan", "LAN ", 1), Role: "lan"})
  423. }
  424. if wanDev := board.Network.Wan.Device; wanDev != "" {
  425. ports = append([]PortLayout{{ID: "wan", Name: wanDev, Label: "WAN", Role: "wan"}}, ports...)
  426. }
  427. return ports, nil
  428. }
  429. // BuildEthPorts: layout + estado /sys → []EthPort listo para el detalle.
  430. // brMembers = miembros del bridge br-lan (AP en bridge re-etiqueta wan→LAN
  431. // N+1); sin layout, fallback heurístico. Literal de openwrt.go GetEthPorts.
  432. func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool) []EthPort {
  433. byName := map[string]PortState{}
  434. for _, p := range states {
  435. byName[p.Name] = p
  436. }
  437. if len(layout) > 0 {
  438. lanCount := 0
  439. for _, p := range layout {
  440. if p.Role == "lan" {
  441. lanCount++
  442. }
  443. }
  444. ports := make([]EthPort, 0, len(layout))
  445. for _, p := range layout {
  446. st, ok := byName[p.Name]
  447. up := ok && st.Up
  448. label := p.Label
  449. if p.Role == "wan" && brMembers[p.Name] {
  450. label = "LAN " + strconv.Itoa(lanCount+1)
  451. }
  452. ep := EthPort{ID: p.ID, Label: label, Up: up}
  453. if up {
  454. ep.Speed = st.Speed
  455. }
  456. ports = append(ports, ep)
  457. }
  458. return ports
  459. }
  460. // Fallback sin config
  461. lanRe := regexp.MustCompile(`^lan\d+$`)
  462. lans := []PortState{}
  463. for _, p := range states {
  464. if lanRe.MatchString(p.Name) {
  465. lans = append(lans, p)
  466. }
  467. }
  468. sort.Slice(lans, func(i, j int) bool { return NaturalLess(lans[i].Name, lans[j].Name) })
  469. ports := make([]EthPort, 0, len(lans)+1)
  470. for _, p := range lans {
  471. ep := EthPort{ID: p.Name, Label: strings.Replace(p.Name, "lan", "LAN ", 1), Up: p.Up}
  472. if p.Up {
  473. ep.Speed = p.Speed
  474. }
  475. ports = append(ports, ep)
  476. }
  477. wanName := ""
  478. if _, ok := byName["wan"]; ok {
  479. wanName = "wan"
  480. } else if _, ok := byName["pppoe-wan"]; ok {
  481. wanName = "eth1"
  482. } else if _, ok := byName["eth1"]; ok {
  483. wanName = "eth1"
  484. }
  485. if wanName != "" {
  486. st := byName[wanName]
  487. ep := EthPort{ID: "wan", Label: "WAN", Up: st.Up}
  488. if st.Up {
  489. ep.Speed = st.Speed
  490. }
  491. ports = append([]EthPort{ep}, ports...)
  492. }
  493. return ports
  494. }
  495. // NaturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
  496. func NaturalLess(a, b string) bool {
  497. re := regexp.MustCompile(`^(.*?)(\d+)$`)
  498. ma, mb := re.FindStringSubmatch(a), re.FindStringSubmatch(b)
  499. if ma != nil && mb != nil && ma[1] == mb[1] {
  500. na, _ := strconv.Atoi(ma[2])
  501. nb, _ := strconv.Atoi(mb[2])
  502. return na < nb
  503. }
  504. return a < b
  505. }
  506. var fdbPortRe = regexp.MustCompile(`^(lan\d+|wan)$`)
  507. // ParseBridgeFdb parsea la salida ==PORTS==/==MACS== → MAC aprendida → puerto.
  508. func ParseBridgeFdb(out string) map[string]string {
  509. m := map[string]string{}
  510. portNames := map[string]string{}
  511. section := byte(0)
  512. for _, line := range strings.Split(out, "\n") {
  513. t := strings.TrimSpace(line)
  514. if strings.HasPrefix(t, "==PORTS==") {
  515. section = 'p'
  516. continue
  517. }
  518. if strings.HasPrefix(t, "==MACS==") {
  519. section = 'm'
  520. continue
  521. }
  522. p := strings.Fields(t)
  523. if len(p) < 2 {
  524. continue
  525. }
  526. switch section {
  527. case 'p':
  528. no, name := p[0], p[1]
  529. if strings.HasPrefix(no, "0x") {
  530. if n, err := strconv.ParseInt(no[2:], 16, 64); err == nil {
  531. no = strconv.FormatInt(n, 10)
  532. }
  533. }
  534. portNames[no] = name
  535. case 'm':
  536. no, mac := p[0], p[1]
  537. if port, ok := portNames[no]; ok && mac != "" && fdbPortRe.MatchString(port) {
  538. m[strings.ToUpper(mac)] = port
  539. }
  540. }
  541. }
  542. return m
  543. }
  544. var nonDigitRe = regexp.MustCompile(`\D`)
  545. // ParseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
  546. func ParseRadios(out string) []Radio {
  547. byBand := map[string]*Radio{}
  548. order := []string{}
  549. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  550. if line == "" {
  551. continue
  552. }
  553. p := strings.Split(line, "|")
  554. if len(p) < 5 {
  555. continue
  556. }
  557. freq, _ := strconv.ParseFloat(p[0], 64)
  558. if freq == 0 {
  559. continue
  560. }
  561. band := "2.4 GHz"
  562. if freq >= 5 {
  563. band = "5 GHz"
  564. }
  565. width, _ := strconv.Atoi(nonDigitRe.ReplaceAllString(p[2], ""))
  566. if width == 0 {
  567. width = 20
  568. }
  569. ch, _ := strconv.Atoi(p[1])
  570. tx, _ := strconv.Atoi(p[3])
  571. n, _ := strconv.Atoi(p[4])
  572. if cur, ok := byBand[band]; ok {
  573. cur.Clients += n
  574. } else {
  575. byBand[band] = &Radio{Name: band, Channel: ch, WidthMhz: width, PowerDbm: float64(tx), Clients: n}
  576. order = append(order, band)
  577. }
  578. }
  579. radios := []Radio{}
  580. for _, b := range order {
  581. radios = append(radios, *byBand[b])
  582. }
  583. return radios
  584. }
  585. func round0(v float64) float64 { return float64(int64(v + 0.5)) }
  586. func max0(v float64) float64 {
  587. if v < 0 {
  588. return 0
  589. }
  590. return v
  591. }