probe.go 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481
  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. "net"
  14. "os"
  15. "regexp"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. // ---------------------------------------------------------------------------
  22. // Comandos (idénticos a los del sondeo SSH de openwrt.go)
  23. // ---------------------------------------------------------------------------
  24. const (
  25. CmdProcStat = "grep '^cpu ' /proc/stat"
  26. // CmdProcUptime (#1481): fallback portable de uptime cuando no hay ubus
  27. // (Asuswrt, Linux genérico). Primer campo = segundos desde boot.
  28. CmdProcUptime = "cat /proc/uptime 2>/dev/null"
  29. // CmdTemp (#1484): temperatura de la CPU. En x86 la thermal_zone0 suele ser
  30. // acpitz (ambiente ACPI), así que se elige por `type` con prioridad y la
  31. // primera zona legible queda solo como fallback (ARM/SBC: cpu-thermal).
  32. // Último recurso (#1500): hwmon para equipos SIN thermal zones (Synology
  33. // DSM: k10temp en /sys/class/hwmon, cero zones). Con zones presentes
  34. // mandan las zones: una sola fuente por equipo (#1484).
  35. CmdTemp = `o=""; for w in x86_pkg_temp cpu-thermal cpu_thermal soc-thermal; do for d in /sys/class/thermal/thermal_zone*; do [ "$(cat "$d/type" 2>/dev/null)" = "$w" ] && o=$(cat "$d/temp" 2>/dev/null) && break 2; done; done; [ -n "$o" ] || for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && o=$(cat "$f") && break; done; [ -n "$o" ] || for h in /sys/class/hwmon/hwmon*; do case "$(cat "$h/name" 2>/dev/null)" in k10temp|coretemp|k8temp|cpu_thermal|soc_thermal) [ -r "$h/temp1_input" ] && o=$(cat "$h/temp1_input") && break;; esac; done; printf '%s\n' "$o"`
  36. CmdNetDev = "cat /proc/net/dev | tail -n +3"
  37. // CmdPingWan: latencia + pérdida a internet (solo gateway). %s = target.
  38. CmdPingWan = "ping -c 3 -W 2 %s 2>/dev/null | tail -2"
  39. // CmdPingGateway: ping corto al gateway desde un AP. %s = host gateway.
  40. CmdPingGateway = "ping -c 2 -W 2 %s 2>/dev/null | tail -1"
  41. CmdDhcpUbus = "ubus call dhcp ipv4leases"
  42. // CmdDhcpReservations: the `config host` entries of /etc/config/dhcp. A
  43. // device with a fixed address set on the device itself never asks for a
  44. // lease, so the name the admin pinned here is the only one the router
  45. // has for it. Lines for other sections come through too; the parser
  46. // keeps only the ones it saw declared as host.
  47. CmdDhcpReservations = `uci -q show dhcp 2>/dev/null | grep -E "=host$|\.(mac|name|ip)=" || true`
  48. // CmdDhcpFile: cat del fichero de leases de dnsmasq. Resuelve la ubicación
  49. // real vía UCI (dhcp.@dnsmasq[0].leasefile), porque puede NO ser la
  50. // standard /tmp/dhcp.leases (p. ej. en un SSD montado, #568); si el valor
  51. // UCI no existe o está vacío, cae a /tmp/dhcp.leases. Busybox: test -n y
  52. // comillas simples para $f.
  53. CmdDhcpFile = `f=$(uci -q get dhcp.@dnsmasq[0].leasefile 2>/dev/null); [ -n "$f" ] || f=/tmp/dhcp.leases; cat "$f" 2>/dev/null || true`
  54. // CmdGlClients (GL.iNet): base de clientes completa del firmware. Es un
  55. // SUPERSET de dhcp.leases: incluye equipos con IP estática o sin lease
  56. // DHCP que el dnsmasq del Flint2 no lista (issue #5 bug 1).
  57. CmdGlClients = "ubus call gl-clients list 2>/dev/null || true"
  58. // CmdIwinfoAssoc: "<mac> <sig> <freq>" por cliente wifi asociado.
  59. CmdIwinfoAssoc = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
  60. `freq=$(iwinfo "$i" info 2>/dev/null | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
  61. `iwinfo "$i" assoclist 2>/dev/null | sed -n 's/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/\1 \2/p' | while read mac sig; do ` +
  62. `echo "$mac $sig $freq"; done; done`
  63. // CmdHostapdClients (#368): clientes por AP vía ubus (una llamada por AP,
  64. // binario pequeñísimo, sin ucode ni libiwinfo). Emite "==AP==<obj>" antes
  65. // del JSON multi-línea de cada get_clients; el parser de Go trocea por la
  66. // marca. Mucho más barato que iwinfo en CPUs justas (MT7621: el ucode de
  67. // iwinfo quemaba 25% de CPU con churn de roaming).
  68. CmdHostapdClients = `for o in $(ubus list 'hostapd.*' 2>/dev/null); do ` +
  69. `echo "==AP==$o"; ubus call "$o" get_clients 2>/dev/null; done`
  70. // CmdWirelessCombined (#368): iwinfo en UNA pasada por interfaz (info una
  71. // vez + assoclist una vez) emitiendo clientes y resumen de radio juntos.
  72. // Sustituye a CmdIwinfoAssoc+CmdRadios cuando ubus no está: la mitad de
  73. // spawns. Líneas "C|mac|sig|freq" (clientes) y
  74. // "R|freq|ch|ht|tx|bssid|noise|n" (radio; #1213).
  75. CmdWirelessCombined = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
  76. `info=$(iwinfo "$i" info 2>/dev/null) || continue; ` +
  77. `echo "$info" | grep -q ESSID || continue; ` +
  78. `freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
  79. `ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); ` +
  80. `ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); ` +
  81. `tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); ` +
  82. `bssid=$(echo "$info" | sed -n 's/.*Access Point: \([0-9A-Fa-f:]\{17\}\).*/\1/p' | head -1); ` +
  83. `noise=$(echo "$info" | sed -n 's/.*Noise: \(-\{0,1\}[0-9][0-9]*\).*/\1/p' | head -1); ` +
  84. `al=$(iwinfo "$i" assoclist 2>/dev/null); ` +
  85. `n=$(echo "$al" | grep -c '^[0-9A-Fa-f:]'); ` +
  86. `echo "R|$freq|$ch|$ht|$tx|$bssid|$noise|$n"; ` +
  87. `echo "$al" | sed -n "s/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/C|\1|\2|$freq/p"; done`
  88. // CmdRadios: "freq|ch|ht|tx|bssid|noise|n" por radio (se agrega por banda
  89. // al parsear). #1213: bssid + noise de iwinfo info.
  90. CmdRadios = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
  91. `info=$(iwinfo "$i" info 2>/dev/null) || continue; ` +
  92. `echo "$info" | grep -q ESSID || continue; ` +
  93. `freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
  94. `ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); ` +
  95. `ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); ` +
  96. `tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); ` +
  97. `bssid=$(echo "$info" | sed -n 's/.*Access Point: \([0-9A-Fa-f:]\{17\}\).*/\1/p' | head -1); ` +
  98. `noise=$(echo "$info" | sed -n 's/.*Noise: \(-\{0,1\}[0-9][0-9]*\).*/\1/p' | head -1); ` +
  99. `n=$(iwinfo "$i" assoclist 2>/dev/null | grep -c '^[0-9A-Fa-f:]'); ` +
  100. `echo "$freq|$ch|$ht|$tx|$bssid|$noise|$n"; done`
  101. // CmdScan (#452): scan pasivo de vecinos con `iw dev`. Lista interfaces,
  102. // emite "==IFACE==<iface>" antes de cada scan y parsea BSS/freq/signal/SSID.
  103. // Si `iw` no está disponible, la sección Scans queda vacía (best-effort).
  104. //
  105. // DEPRECATED (#1338): el bucle monolítico corría con UN solo timeout para
  106. // todas las interfaces y, al expirar, la salida parcial se descartaba
  107. // entera. Una radio lenta (5 GHz en canal DFS, scan pasivo canal a canal)
  108. // dejaba la unidad sin NINGÚN vecino, aunque las demás interfaces sí
  109. // hubieran escaneado. El agente escanea ahora por interfaz con
  110. // CmdScanIface, cada una con su propio presupuesto. Se conserva la
  111. // constante por compatibilidad del módulo (consumidores vendorizados).
  112. CmdScan = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" scan 2>/dev/null; done`
  113. // CmdSurvey (#1214): `iw dev <iface> survey dump` por interfaz, con el
  114. // mismo marcador "==IFACE==" que CmdScan. El server parsea el texto
  115. // crudo con su parser existente: alimenta la lente "Ahora" (ocupación
  116. // por canal en vivo) en unidades agent-only sin SSH. Barato: no saca
  117. // la radio del canal.
  118. CmdSurvey = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" survey dump 2>/dev/null; done`
  119. // CmdIwDev (#1087): `iw dev` a secas, sin scan. Lista las interfaces con
  120. // su MAC y SSID: fuente de los BSSIDs propios para el análisis de
  121. // canales. Barato (no saca la radio del canal).
  122. CmdIwDev = "iw dev 2>/dev/null"
  123. // scanIfaceTimeout (#1338): presupuesto POR INTERFAZ del scan de vecinos.
  124. // Una radio 5 GHz en canal DFS escanea en pasivo canal a canal y puede
  125. // tardar varios segundos; con el presupuesto único de 10 s para todas,
  126. // esa radio lenta mataba el bucle y se perdían también los scans ya
  127. // hechos. Cada interfaz tiene ahora su propio tiempo y un fallo o un
  128. // cuelgue solo vacía su propia sección.
  129. scanIfaceTimeout = 8 * time.Second
  130. // maxScanFallbacks (#1839): reintentos por radio cuando la interfaz
  131. // elegida rechaza el scan. Dos basta para cubrir AP + managed + una
  132. // tercera, y acota el peor caso (3 x 8 s por radio).
  133. maxScanFallbacks = 2
  134. // CmdRadioSections (#500): secciones wifi-device de UCI con su banda, para
  135. // resolver "2.4 GHz" → radio0 (la relación iface→sección no sale de iwinfo).
  136. CmdRadioSections = `uci -q show wireless 2>/dev/null | grep -E "=wifi-device$|\.band=|\.hwmode="`
  137. // CmdUciWireless (#1450): volcado crudo de la configuración wireless, tal
  138. // cual lo emite `uci show wireless`. El server lo parsea con su
  139. // parseUciWireless (vista 802.11r) en unidades agent-only sin SSH: el
  140. // parser NO se duplica en el agente, igual que con CmdSurvey (#1214).
  141. // Solo lectura de /etc/config/wireless, barato (unos pocos KB).
  142. //
  143. // Los campos de SECRETO se descartan antes de enviarlo: a diferencia del
  144. // camino SSH (que los lee y los tira en el server), este volcado viaja en
  145. // cada push y queda persistido en kv agent.state.<slug>. El parser 802.11r
  146. // no usa la PSK, así que filtrarla no quita información a la vista.
  147. CmdUciWireless = `uci -q show wireless 2>/dev/null | ` + uciWirelessSecretsFilter
  148. // uciWirelessSecretsFilter: líneas `option` con secretos fuera del push
  149. // (key/PSK/SAE/contraseñas/RADIUS). Se conserva el resto del volcado tal
  150. // cual. Busybox grep -E soporta la alternancia.
  151. uciWirelessSecretsFilter = `grep -v -E '\.(key|sae_key|wpa_psk|psk|password|secret|radius_secret)='`
  152. // CmdPortStates: "<name> <operstate> <speed> <dsa> <type> <conduit>" por
  153. // interfaz.
  154. // - dsa: "dsa" cuando la interfaz es un conduit DSA (tiene el directorio
  155. // /sys/class/net/<i>/dsa): el puerto CPU interno del switch, no una
  156. // boca usable (#847); "-" si no.
  157. // - type: el ARPHRD del kernel (1 = ethernet). FORK: para no tomar por
  158. // boca un uplink que no lo es (wwan0 de un módem celular).
  159. // - conduit: FORK. La interfaz inferior (lower_*) cuando la hay: en un
  160. // switch DSA las bocas cuelgan de la interfaz de CPU (lan1/lan2 →
  161. // lower_eth0). "-" cuando no hay ninguna.
  162. // Los campos a partir del tercero son opcionales para ParsePortStates.
  163. CmdPortStates = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
  164. `o=$(cat "$d/operstate" 2>/dev/null || echo unknown); ` +
  165. `s=$(cat "$d/speed" 2>/dev/null || echo -1); ` +
  166. `x=$([ -d "$d/dsa" ] && echo dsa || echo -); ` +
  167. `t=$(cat "$d/type" 2>/dev/null || echo -1); ` +
  168. `c=-; for l in "$d"/lower_*; do [ -e "$l" ] || continue; c=${l##*/lower_}; break; done; ` +
  169. `echo "$i $o $s $x $t $c"; done`
  170. // CmdProcArp (#377): tabla ARP del kernel, "IP dev mac ..." por línea.
  171. CmdProcArp = "cat /proc/net/arp 2>/dev/null"
  172. // CmdIpNeigh: the same neighbour table, but with the state of each entry,
  173. // which /proc/net/arp cannot express -- its flags say ATF_COM for
  174. // REACHABLE and for STALE alike. A STALE neighbour is one the kernel has
  175. // not confirmed since the device last spoke, and it survives long after
  176. // the device is gone, so treating it as presence draws hosts that are no
  177. // longer there. Falls back to /proc/net/arp when `ip` is missing.
  178. CmdIpNeigh = "ip -4 neigh show 2>/dev/null"
  179. CmdBoardJSON = "cat /etc/board.json 2>/dev/null"
  180. // bridgeDetect: resuelve el nombre del bridge LAN en el router: br-lan,
  181. // br0, o el primer bridge real presente en /sys/class/net (#1435: en
  182. // switches OpenWrt con el bridge renombrado, p.ej. "switch", los dos
  183. // candidatos clásicos no existen y la FDB salía vacía). Si no hay
  184. // bridge, BR queda vacío y los comandos fallan en suave (mismo
  185. // comportamiento que antes en equipos sin bridge).
  186. bridgeDetect = `BR=br-lan; [ -d /sys/class/net/$BR/bridge ] || BR=br0; [ -d /sys/class/net/$BR/bridge ] || { BR=; for d in /sys/class/net/*/bridge; do [ -d "$d" ] || continue; BR=${d%/bridge}; BR=${BR##*/}; break; done; }; `
  187. CmdBrifMembers = bridgeDetect + `ls /sys/class/net/$BR/brif/ 2>/dev/null`
  188. // CmdBridgeFDB: "==PORTS==" (port_no ifname) + "==MACS==" (port mac).
  189. // No asume `brctl`: prueba brctl y, si no existe o no aporta, `bridge fdb
  190. // show` (OpenWrt/GLuON modernos usan iproute2). Issue #253. El bridge lo
  191. // resuelve bridgeDetect (#1435).
  192. // SIN `command -v`: el ash de busybox en Merlin/Asuswrt NO tiene el builtin
  193. // `command` ("sh: command: not found"), así que la guarda antigua
  194. // `if command -v brctl` fallaba siempre y caía al branch de `bridge`, que
  195. // allí no existe: la sección MACS salía vacía y el server se quedaba sin
  196. // FDB del AP (todos sus clientes cableados se atribuían al gateway o al
  197. // switch de arriba). Ahora se intentan ambas vías en subshells con stderr
  198. // suprimido; si las dos existen las líneas duplicadas son inofensivas
  199. // (ambas resuelven al mismo ifname en ParseBridgeFdb). El `true` final
  200. // garantiza exit 0 para que el runner no descarte la salida.
  201. // La vía bridge excluye las entradas LOCALES (flag "permanent": la MAC del
  202. // propio bridge registrada en cada puerto) para paridad con brctl ($3=="no"
  203. // allí); sin esto el server ve la MAC propia aprendida en el puerto y lo
  204. // clasifica como uplink, descartando TODOS sus clientes cableados (#506).
  205. CmdBridgeFDB = bridgeDetect +
  206. `echo "==PORTS=="; for d in /sys/class/net/$BR/brif/*; do [ -r "$d/port_no" ] && echo "$(cat $d/port_no) $(basename $d)"; done; ` +
  207. `echo "==MACS=="; (brctl showmacs $BR 2>/dev/null | awk 'NR>1 && $3=="no" {print $1, $2}') 2>/dev/null; ` +
  208. `(bridge fdb show br $BR 2>/dev/null | awk 'NF>=3 && $1!="01:" && $1!="33:33:" && $1!="ff:ff:" && $1!="00:00:00:00:00:00" && $0 !~ /permanent/ {for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1), $1}}') 2>/dev/null; true`
  209. CmdBridgeMAC = bridgeDetect + "cat /sys/class/net/$BR/address 2>/dev/null"
  210. // CmdIfaceMACs (#1765): "iface mac" de TODAS las interfaces del kernel.
  211. // Un equipo responde por la MAC del bridge, la de cada VLAN, la del puerto
  212. // CPU de un switch DSA y la de cada radio. Las que no son la MAC del router
  213. // guardado en la flota se aprenden en la FDB de un vecino y salían como
  214. // clientes desconocidos sin nombre ni IP. El equipo es la única fuente
  215. // fiable de su propia lista.
  216. CmdIfaceMACs = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
  217. `[ -r "$d/address" ] && echo "$i $(cat "$d/address" 2>/dev/null)"; done`
  218. CmdUbusSystemBoard = "ubus call system board"
  219. CmdUbusSystemInfo = "ubus call system info"
  220. CmdUbusWireless = "ubus call network.wireless status"
  221. // CmdLuCILabels: etiquetas de puertos/VLANs de LuCI (issue #258). OpenWrt
  222. // snapshots añaden `config switchvlan 'port_labels'` y `'vlan_labels'` en
  223. // /etc/config/luci con nombres amigables para la topología. Se lee el
  224. // fichero crudo (uci show luci sería más ruidoso: todo el paquete).
  225. CmdLuCILabels = "cat /etc/config/luci 2>/dev/null"
  226. // CmdWanStatus: estado de la interfaz WAN (solo gateway) vía ubus.
  227. // Da proto ("pppoe"), IP, gateway (ptpaddress/nexthop) y DNS (issue #276).
  228. CmdWanStatus = "ubus call network.interface.wan status 2>/dev/null || true"
  229. // CmdNetworkDump: estado de TODAS las interfaces, para elegir el uplink
  230. // por la ruta por defecto en vez de por el nombre "wan" (ver pickUplink)
  231. // y saber por qué boca sale internet.
  232. CmdNetworkDump = "ubus call network.interface dump 2>/dev/null || true"
  233. CmdBridgeVlan = "bridge vlan show 2>/dev/null || true"
  234. // CmdUciBridgeVlan: the VLANs as configured, for the routers whose
  235. // firmware carries no `bridge` binary — an optional package, and
  236. // absent on plenty of boards that do use VLANs.
  237. CmdUciBridgeVlan = `uci -q show network 2>/dev/null | grep -E "=bridge-vlan$|\.(device|vlan|ports)=" || true`
  238. // CmdMdnsBrowse (#338): mDNS service discovery via umdns (OpenWrt's
  239. // lightweight mDNS daemon). Returns JSON with hostname -> services.
  240. // Falls back to empty if umdns is not installed.
  241. CmdMdnsBrowse = "ubus call umdns browse 2>/dev/null || echo '{}'"
  242. // CmdMdnsHosts (#338): the plain host records umdns has learned, as
  243. // "<name>.local" -> {ipv4, ipv6}. browse only lists hosts that advertise
  244. // a SERVICE; a device that just announces its name (most laptops and
  245. // phones) appears here and nowhere else, and this is the map that names
  246. // a client with no DHCP hostname.
  247. CmdMdnsHosts = "ubus call umdns hosts 2>/dev/null || echo '{}'"
  248. CmdEthtoolSFP = "ethtool -m %s 2>/dev/null || true"
  249. )
  250. // CmdScanIface (#1338): scan pasivo de UNA interfaz. El agente lo lanza una
  251. // vez por interfaz de `iw dev` (en vez del bucle monolítico de CmdScan) para
  252. // que cada radio tenga su propio presupuesto de tiempo y una interfaz lenta
  253. // o colgada no se lleve por delante los resultados de las demás.
  254. func CmdScanIface(iface string) string {
  255. return `iw dev "` + iface + `" scan 2>/dev/null`
  256. }
  257. // ---------------------------------------------------------------------------
  258. // Shapes parseados (salida de las sondas; contrato del payload del agente)
  259. // ---------------------------------------------------------------------------
  260. // SysInfo: ubus system info (uptime, memoria, load).
  261. type SysInfo struct {
  262. Uptime float64 `json:"uptime"`
  263. Load []float64 `json:"load"`
  264. // Timezone (#1500): nombre IANA ("Asia/Shanghai") que el agente lee de
  265. // /etc/localtime (o /etc/timezone, /etc/TZ). ubus nunca lo da, así que
  266. // sin este campo la ficha mostraba "—" incluso en equipos con ubus.
  267. Timezone string `json:"timezone,omitempty"`
  268. Memory struct {
  269. Total float64 `json:"total"`
  270. Free float64 `json:"free"`
  271. Buffered float64 `json:"buffered"`
  272. Available float64 `json:"available"`
  273. Cached float64 `json:"cached,omitempty"` // cache de ficheros, la rellena el agente (ubus no lo da)
  274. Used float64 `json:"used"` // suma de VmRSS de procesos (#513)
  275. } `json:"memory"`
  276. }
  277. // BoardInfo: ubus system board (metadatos estáticos).
  278. type BoardInfo struct {
  279. Model string `json:"model"`
  280. Hostname string `json:"hostname"`
  281. System string `json:"system"`
  282. // BoardName es el board_name de ubus ("redmi,ax6"): el identificador
  283. // que casa con los perfiles de ASU (#477).
  284. BoardName string `json:"board_name"`
  285. Release struct {
  286. Version string `json:"version"`
  287. Description string `json:"description"`
  288. // Target es el DISTRIB_TARGET ("qualcommax/ipq807x"), lo que ASU
  289. // necesita junto al board_name para localizar la imagen (#477).
  290. Target string `json:"target"`
  291. } `json:"release"`
  292. }
  293. // WanInfo: datos de la conexión WAN (issue #276). Solo el gateway lo rellena;
  294. // los campos vacíos significan "sin datos WAN" (APs/desconocido).
  295. type WanInfo struct {
  296. Proto string `json:"proto,omitempty"` // "pppoe"|"dhcp"|"static"...
  297. Device string `json:"device,omitempty"` // interfaz L3 (p.ej. "pppoe-wan")
  298. IP string `json:"ip,omitempty"` // dirección IPv4 pública
  299. Gateway string `json:"gateway,omitempty"` // puerta de enlace (nexthop/ptpaddress)
  300. DNS []string `json:"dns,omitempty"` // servidores DNS
  301. // Port es la interfaz por debajo del protocolo: la boca por la que sale
  302. // internet ("lan1" para un PPPoE sobre esa boca, "eth1.20" con VLAN).
  303. // Vacía cuando el uplink no pasa por ninguna (módem celular).
  304. Port string `json:"port,omitempty"`
  305. }
  306. // DhcpReservation is one `config host` of /etc/config/dhcp: the name and
  307. // address pinned to a MAC (both optional). MAC uppercase, like DhcpLease.
  308. type DhcpReservation struct {
  309. MAC string `json:"mac"`
  310. Name string `json:"name,omitempty"`
  311. IP string `json:"ip,omitempty"`
  312. }
  313. // DhcpLease es {mac, ip, hostname} (mac en mayúsculas) + señales de huella
  314. // DHCP (vendor class y client-id) y expiración del lease cuando se dispone.
  315. type DhcpLease struct {
  316. MAC string `json:"mac"`
  317. IP string `json:"ip"`
  318. Hostname string `json:"hostname"`
  319. VendorClass string `json:"vendorClass,omitempty"`
  320. ClientID string `json:"clientId,omitempty"`
  321. LeaseExpiresAt *int64 `json:"leaseExpiresAt,omitempty"` // Unix segundos; nil si no se conoce
  322. }
  323. // WirelessClient es {signalDbm, band} por MAC + contadores de tráfico de la
  324. // estación cuando el driver los expone (#551). RxBytes/TxBytes son contadores
  325. // ACUMULADOS desde que la estación se asoció (ubus hostapd get_clients →
  326. // hostapd_drv_read_sta_data); el server calcula el delta entre muestras para
  327. // obtener bytes del intervalo. omitempty: ausentes si la fuente no los da
  328. // (iwinfo, drivers sin read_sta_data).
  329. type WirelessClient struct {
  330. SignalDbm int `json:"signalDbm"`
  331. Band string `json:"band"`
  332. RxBytes uint64 `json:"rxBytes,omitempty"`
  333. TxBytes uint64 `json:"txBytes,omitempty"`
  334. // Iface/SSID (#1757): interfaz AP y SSID con la que la estacion esta
  335. // asociada. Permiten al servidor cruzar la estacion con el bridge VLAN
  336. // filtering y saber en que segmento vive. Omitidos cuando la fuente no
  337. // los expone (wl, iwinfo, drivers sin esa salida): el campo es opcional.
  338. Iface string `json:"iface,omitempty"`
  339. SSID string `json:"ssid,omitempty"`
  340. }
  341. // PortState es {name, up, speed} de una interfaz (/sys operstate+speed).
  342. type PortState struct {
  343. Name string `json:"name"`
  344. Up bool `json:"up"`
  345. // Oper is the raw sysfs operstate (up/down/dormant/unknown/...). Kept so
  346. // the panel can tell a real port (up, or down when unplugged) from a
  347. // Broadcom internal ghost interface that never carries user traffic
  348. // (dormant/unknown) and must not be shown as a usable port.
  349. Oper string `json:"oper,omitempty"`
  350. Speed string `json:"speed"` // "1 Gbps" | "2.5 Gbps" | "100 Mbps" | "—"
  351. // DSA: la interfaz es un conduit DSA (puerto CPU interno del switch,
  352. // /sys/class/net/<i>/dsa presente). No es una boca usable: se excluye
  353. // de los puertos del panel (#847).
  354. DSA bool `json:"dsa,omitempty"`
  355. // Type es el ARPHRD de /sys/class/net/<i>/type: 1 = ethernet. 0 o
  356. // negativo = desconocido (salida antigua), y entonces no se descarta
  357. // nada por el tipo. FORK.
  358. Type int `json:"type,omitempty"`
  359. // Conduit es la interfaz inferior (lower_*), vacío si no hay. En un
  360. // switch DSA es el puerto de CPU del que cuelga la boca. FORK.
  361. Conduit string `json:"conduit,omitempty"`
  362. }
  363. // fmtSpeedMbps (#847) formatea la velocidad de enlace: Gbps con decimales
  364. // cuando no es múltiplo de 1000 (2500 → "2.5 Gbps"; antes truncaba a
  365. // entero y mentía "2 Gbps") y Mbps en otro caso.
  366. func fmtSpeedMbps(mbps int) string {
  367. if mbps >= 1000 {
  368. if mbps%1000 == 0 {
  369. return strconv.Itoa(mbps/1000) + " Gbps"
  370. }
  371. return strconv.FormatFloat(float64(mbps)/1000, 'f', 1, 64) + " Gbps"
  372. }
  373. return strconv.Itoa(mbps) + " Mbps"
  374. }
  375. // ARPHRDEther es el /sys/class/net/<i>/type de una interfaz ethernet.
  376. const ARPHRDEther = 1
  377. // PortLayout es una boca del layout canónico (/etc/board.json).
  378. type PortLayout struct {
  379. ID string `json:"id"`
  380. Name string `json:"name"`
  381. Label string `json:"label"`
  382. Role string `json:"role"` // "lan" | "wan"
  383. }
  384. // EthPort es una boca ethernet lista para el detalle ({id, label, up, speed?}
  385. // + contadores por puerto #305: iface física, bytes/errores acumulados y
  386. // rates instantáneos; omitempty para no engordar el contrato viejo).
  387. type EthPort struct {
  388. ID string `json:"id"`
  389. Label string `json:"label"`
  390. Up bool `json:"up"`
  391. Speed string `json:"speed,omitempty"` // solo si up
  392. // Iface física de la boca (/proc/net/dev); puede diferir del id en
  393. // plataformas swconfig ("1" vs "eth0.1").
  394. Iface string `json:"iface,omitempty"`
  395. // Contadores acumulados de la iface (issue #305).
  396. RxBytes uint64 `json:"rxBytes,omitempty"`
  397. TxBytes uint64 `json:"txBytes,omitempty"`
  398. RxErrs uint64 `json:"rxErrors,omitempty"`
  399. TxErrs uint64 `json:"txErrors,omitempty"`
  400. RxBps *float64 `json:"rxBps,omitempty"`
  401. TxBps *float64 `json:"txBps,omitempty"`
  402. // Sfp: diagnóstico digital (DDM/DOM) si la boca tiene módulo óptico
  403. // (#313). nil = sin SFP o sin datos; el servidor lo conserva.
  404. Sfp *SfpInfo `json:"sfp,omitempty"`
  405. }
  406. // SfpInfo: diagnóstico digital (DDM/DOM) de un módulo SFP (#313). Present
  407. // indica si se leyeron datos (ethtool -m devolvió algo parseable).
  408. type SfpInfo struct {
  409. Temperature float64 `json:"temperature"` // grados Celsius
  410. Voltage float64 `json:"voltage,omitempty"` // voltios (3.3 V típico)
  411. TxPower float64 `json:"txPower"` // dBm
  412. RxPower float64 `json:"rxPower"` // dBm (negativo)
  413. Vendor string `json:"vendor,omitempty"` // "FS.COM", "Ubiquiti", ...
  414. PartNumber string `json:"partNumber,omitempty"`
  415. Present bool `json:"present"`
  416. }
  417. // IfCounters son los contadores acumulados de UNA interfaz de /proc/net/dev.
  418. type IfCounters struct {
  419. Rx uint64 // bytes
  420. Tx uint64 // bytes
  421. RxErr uint64
  422. TxErr uint64
  423. }
  424. // IfRate añade a los contadores los rates instantáneos (delta entre muestras;
  425. // punteros nil = primera muestra o iface nueva, sin rate todavía).
  426. type IfRate struct {
  427. IfCounters
  428. RxBps *float64
  429. TxBps *float64
  430. }
  431. // Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).
  432. type Radio struct {
  433. Name string `json:"name"` // "5 GHz"|"2.4 GHz"
  434. Channel int `json:"channel"`
  435. WidthMhz int `json:"widthMhz"`
  436. PowerDbm float64 `json:"powerDbm"`
  437. Clients int `json:"clients"`
  438. // Section es la sección UCI de la radio ("radio0"), para que el server
  439. // pueda construir cambios de canal (uci set wireless.<section>.channel).
  440. // Vacía si no se pudo resolver (#500).
  441. Section string `json:"section,omitempty"`
  442. // #1213/#1206: suelo de ruido (dBm, de iwinfo info "Noise") y BSSID de la
  443. // interfaz AP ("Access Point"). Opcionales: drivers que no los reportan →
  444. // nil/vacío y el front no dibuja esas filas. El BSSID es "el sitio donde
  445. // viven" las MACs de interfaz que antes asomaban como clientes.
  446. NoiseDbm *int `json:"noiseDbm,omitempty"`
  447. BSSID string `json:"bssid,omitempty"`
  448. }
  449. // ---------------------------------------------------------------------------
  450. // Sistema: /proc/stat, thermal, /proc/net/dev, ping
  451. // ---------------------------------------------------------------------------
  452. // CPUSample es la muestra agregada de "cpu " de /proc/stat.
  453. type CPUSample struct{ Total, IdleAll float64 }
  454. // ParseProcStat parsea "cpu user nice system idle iowait irq softirq ...".
  455. func ParseProcStat(out string) (CPUSample, error) {
  456. fields := strings.Fields(strings.TrimSpace(out))
  457. if len(fields) < 5 || fields[0] != "cpu" {
  458. return CPUSample{}, fmt.Errorf("/proc/stat inesperado: %q", out)
  459. }
  460. nums := make([]float64, 0, len(fields)-1)
  461. for _, f := range fields[1:] {
  462. n, err := strconv.ParseFloat(f, 64)
  463. if err != nil {
  464. n = 0
  465. }
  466. nums = append(nums, n)
  467. }
  468. get := func(i int) float64 {
  469. if i < len(nums) {
  470. return nums[i]
  471. }
  472. return 0
  473. }
  474. idleAll := get(3) + get(4) // idle + iowait
  475. nonIdle := get(0) + get(1) + get(2) + get(5) + get(6) // user+nice+system+irq+softirq
  476. return CPUSample{Total: idleAll + nonIdle, IdleAll: idleAll}, nil
  477. }
  478. // ParseUptimeSec (#1481): segundos desde boot del primer campo de
  479. // /proc/uptime ("70273.29 269277.55"). 0 si la salida no es parseable: el
  480. // caller lo trata como "sin dato" y conserva el camino ubus cuando existe.
  481. func ParseUptimeSec(out string) float64 {
  482. fields := strings.Fields(strings.TrimSpace(out))
  483. if len(fields) == 0 {
  484. return 0
  485. }
  486. sec, err := strconv.ParseFloat(fields[0], 64)
  487. if err != nil || sec < 0 {
  488. return 0
  489. }
  490. return sec
  491. }
  492. // CPUPercent: % de CPU por delta de muestras (nil si no hay delta válido:
  493. // primera muestra o contadores reseteados).
  494. func CPUPercent(prev, cur CPUSample) *int {
  495. dTotal := cur.Total - prev.Total
  496. dIdle := cur.IdleAll - prev.IdleAll
  497. if dTotal <= 0 {
  498. return nil
  499. }
  500. v := int(float64(dTotal-dIdle)/float64(dTotal)*100 + 0.5)
  501. return &v
  502. }
  503. // ParseTempC: °C del primer thermal zone (nil si la salida no es un entero).
  504. func ParseTempC(out string) *int {
  505. milli, err := strconv.Atoi(strings.TrimSpace(out))
  506. if err != nil {
  507. return nil
  508. }
  509. v := milli / 1000
  510. if milli%1000 >= 500 {
  511. v++
  512. }
  513. return &v
  514. }
  515. var netdevSkipRe = regexp.MustCompile(`^(lo|br-|ifb|wg|tun|tap)`)
  516. // ParseNetDev suma rx/tx de las interfaces físicas (excluye lo, bridges,
  517. // ifb, wg, tun/tap para no duplicar contadores).
  518. func ParseNetDev(out string) (rx, tx float64) {
  519. lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
  520. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  521. m := lineRe.FindStringSubmatch(line)
  522. if m == nil || netdevSkipRe.MatchString(m[1]) {
  523. continue
  524. }
  525. fields := strings.Fields(strings.TrimSpace(m[2]))
  526. num := func(i int) float64 {
  527. if i < len(fields) {
  528. n, _ := strconv.ParseFloat(fields[i], 64)
  529. return n
  530. }
  531. return 0
  532. }
  533. rx += num(0)
  534. tx += num(8)
  535. }
  536. return rx, tx
  537. }
  538. // ParseNetDevIfaces devuelve los contadores POR INTERFAZ de /proc/net/dev
  539. // (sin filtrar: el consumidor decide qué ifaces le interesan; las bocas
  540. // físicas se casan por nombre con el layout, issue #305).
  541. func ParseNetDevIfaces(out string) map[string]IfCounters {
  542. res := map[string]IfCounters{}
  543. lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
  544. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  545. m := lineRe.FindStringSubmatch(line)
  546. if m == nil {
  547. continue
  548. }
  549. fields := strings.Fields(strings.TrimSpace(m[2]))
  550. num := func(i int) uint64 {
  551. if i < len(fields) {
  552. n, _ := strconv.ParseUint(fields[i], 10, 64)
  553. return n
  554. }
  555. return 0
  556. }
  557. res[m[1]] = IfCounters{
  558. Rx: num(0), Tx: num(8), // bytes
  559. RxErr: num(2), TxErr: num(10),
  560. }
  561. }
  562. return res
  563. }
  564. // IfRates calcula los rates por interfaz con el delta de contadores entre
  565. // dos muestras separadas dt segundos. Ifaces nuevas o dt <= 0 → nil rates.
  566. // Contadores reseteados (reboot) → max0 dentro de NetDevBps da 0, no negativos.
  567. func IfRates(prev, cur map[string]IfCounters, dt float64) map[string]IfRate {
  568. res := make(map[string]IfRate, len(cur))
  569. for name, c := range cur {
  570. r := IfRate{IfCounters: c}
  571. if p, ok := prev[name]; ok && dt > 0 {
  572. r.RxBps, r.TxBps = NetDevBps(float64(p.Rx), float64(p.Tx), float64(c.Rx), float64(c.Tx), dt)
  573. }
  574. res[name] = r
  575. }
  576. return res
  577. }
  578. // NetDevBps: bps por delta de contadores en dt segundos (nil si dt <= 0 o
  579. // contadores reseteados).
  580. func NetDevBps(prevRx, prevTx, rx, tx, dt float64) (rxBps, txBps *float64) {
  581. if dt <= 0 {
  582. return nil, nil
  583. }
  584. rb := round0(max0((rx - prevRx) * 8 / dt))
  585. tb := round0(max0((tx - prevTx) * 8 / dt))
  586. return &rb, &tb
  587. }
  588. var pingLossRe = regexp.MustCompile(`(\d+(?:\.\d+)?)% packet loss`)
  589. // #1281: GNU iputils imprime min/avg/max/MDEV (4 numeros) pero busybox
  590. // (OpenWrt) imprime min/avg/max (3): la regex exigia los 4 y en OpenWrt
  591. // la latencia salia nil siempre ("—" en Overview y Flota). El avg es el
  592. // segundo numero en ambos formatos.
  593. var pingRTTRe = regexp.MustCompile(`= [\d.]+/([\d.]+)(?:/[\d.]+){1,2} ms`)
  594. // ParsePingSummary extrae (latencia avg redondeada, pérdida %) del resumen de
  595. // ping; cada una es nil si su línea no está.
  596. func ParsePingSummary(out string) (latency, loss *float64) {
  597. if m := pingRTTRe.FindStringSubmatch(out); m != nil {
  598. v, _ := strconv.ParseFloat(m[1], 64)
  599. // #1384: sin redondeo a entero - en LAN el ping es <1 ms y el
  600. // redondeo lo dejaba en 0 (ruido). El formateo es cosa de la UI.
  601. latency = &v
  602. }
  603. if m := pingLossRe.FindStringSubmatch(out); m != nil {
  604. v, _ := strconv.ParseFloat(m[1], 64)
  605. loss = &v
  606. }
  607. return latency, loss
  608. }
  609. // ---------------------------------------------------------------------------
  610. // Clientes (DHCP + wireless)
  611. // ---------------------------------------------------------------------------
  612. // ParseDhcpUbus parsea la respuesta de `ubus call dhcp ipv4leases`
  613. // ({lease: [...]} o {leases: [...]}). Error si no es JSON con esas claves.
  614. func ParseDhcpUbus(raw []byte) ([]DhcpLease, error) {
  615. type leaseJSON struct {
  616. MAC string `json:"mac"`
  617. IPAddr string `json:"ip-address"`
  618. IP string `json:"ip"`
  619. Hostname string `json:"hostname"`
  620. VendorID string `json:"vendorid"`
  621. ClientID string `json:"clientid"`
  622. Expires int64 `json:"expires"` // segundos restantes o absoluto según firmware
  623. }
  624. var data struct {
  625. Lease []leaseJSON `json:"lease"`
  626. Leases []leaseJSON `json:"leases"`
  627. }
  628. if err := json.Unmarshal(raw, &data); err != nil {
  629. return nil, err
  630. }
  631. leases := data.Lease
  632. if leases == nil {
  633. leases = data.Leases
  634. }
  635. if leases == nil {
  636. return nil, fmt.Errorf("ubus dhcp: sin clave lease/leases")
  637. }
  638. out := make([]DhcpLease, 0, len(leases))
  639. for _, l := range leases {
  640. ip := l.IPAddr
  641. if ip == "" {
  642. ip = l.IP
  643. }
  644. lease := DhcpLease{MAC: strings.ToUpper(l.MAC), IP: ip, Hostname: l.Hostname, VendorClass: l.VendorID, ClientID: l.ClientID}
  645. if l.Expires > 0 {
  646. lease.LeaseExpiresAt = &l.Expires
  647. }
  648. out = append(out, lease)
  649. }
  650. return out, nil
  651. }
  652. // ifaceStatus es una interfaz de `ubus call network.interface[.<x>] status`,
  653. // y cada entrada de `... dump`.
  654. type ifaceStatus struct {
  655. Interface string `json:"interface"`
  656. Up bool `json:"up"`
  657. Proto string `json:"proto"`
  658. L3Device string `json:"l3_device"`
  659. // Device es la interfaz de debajo: para un PPPoE, la boca física.
  660. Device string `json:"device"`
  661. // Dynamic marks an interface netifd created itself — the DHCP child of
  662. // a modem uplink, the DHCPv6 side of a PPPoE one. It holds the address
  663. // and the route its parent has none of, and cannot be configured or
  664. // named in a policy, so it is only ever read through its parent.
  665. Dynamic bool `json:"dynamic"`
  666. IPV4 []struct {
  667. Address string `json:"address"`
  668. PtpAddress string `json:"ptpaddress"`
  669. } `json:"ipv4-address"`
  670. Route []struct {
  671. Target string `json:"target"`
  672. Mask int `json:"mask"`
  673. Nexthop string `json:"nexthop"`
  674. } `json:"route"`
  675. DNS []string `json:"dns-server"`
  676. }
  677. func (s ifaceStatus) defaultNexthop() string {
  678. for _, r := range s.Route {
  679. if r.Target == "0.0.0.0" && r.Mask == 0 && r.Nexthop != "" {
  680. return r.Nexthop
  681. }
  682. }
  683. return ""
  684. }
  685. // pickUplink elige la interfaz que lleva internet. No vale fiarse del nombre
  686. // "wan": en un router multi-WAN el uplink vivo puede llamarse de cualquier
  687. // forma (un PPPoE llamado "isp" junto a un módem celular que sí se llama
  688. // "wan" y que además reporta up=true estando ocioso), así que manda la ruta
  689. // por defecto. Sin ninguna con ruta, cae a la llamada "wan" para que un
  690. // router normal con el enlace caído siga saliendo como WAN caída y no como
  691. // router sin WAN.
  692. func pickUplink(ifaces []ifaceStatus) (ifaceStatus, bool) {
  693. return pickUplinkPreferring(ifaces, "")
  694. }
  695. // pickUplinkPreferring is pickUplink with the answer supplied from outside.
  696. //
  697. // A policy manager (mwan3) steers with packet marks and leaves the routes
  698. // alone, so the default route still points at the standby link while every
  699. // packet leaves by another one. When something knows which uplink is really
  700. // carrying traffic, that wins; everything else falls through to the route.
  701. func pickUplinkPreferring(ifaces []ifaceStatus, preferred string) (ifaceStatus, bool) {
  702. if preferred != "" {
  703. for _, i := range ifaces {
  704. if i.Interface != preferred {
  705. continue
  706. }
  707. i = withChildFacts(i, ifaces)
  708. if len(i.IPV4) > 0 || i.defaultNexthop() != "" {
  709. return i, true
  710. }
  711. }
  712. }
  713. for _, i := range ifaces {
  714. if i.Up && i.defaultNexthop() != "" {
  715. return i, true
  716. }
  717. }
  718. for _, i := range ifaces {
  719. if i.Interface == "wan" {
  720. return i, true
  721. }
  722. }
  723. return ifaceStatus{}, false
  724. }
  725. // withChildFacts gives an interface whatever netifd spawned underneath it.
  726. // A modem uplink keeps neither address nor route of its own: the child
  727. // sharing its layer-3 device holds both, and reporting the parent without
  728. // them would describe a connection with nothing on it.
  729. func withChildFacts(parent ifaceStatus, ifaces []ifaceStatus) ifaceStatus {
  730. if parent.Dynamic || parent.L3Device == "" {
  731. return parent
  732. }
  733. for _, c := range ifaces {
  734. if !c.Dynamic || c.Interface == parent.Interface || c.L3Device != parent.L3Device {
  735. continue
  736. }
  737. if len(parent.IPV4) == 0 {
  738. parent.IPV4 = c.IPV4
  739. }
  740. if len(parent.Route) == 0 {
  741. parent.Route = c.Route
  742. }
  743. if len(parent.DNS) == 0 {
  744. parent.DNS = c.DNS
  745. }
  746. }
  747. return parent
  748. }
  749. func wanInfoFrom(s ifaceStatus) WanInfo {
  750. info := WanInfo{Proto: s.Proto, Device: s.L3Device, Port: s.Device, DNS: s.DNS}
  751. if len(s.IPV4) > 0 {
  752. info.IP = s.IPV4[0].Address
  753. if s.IPV4[0].PtpAddress != "" {
  754. info.Gateway = s.IPV4[0].PtpAddress
  755. }
  756. }
  757. // El gateway real es el nexthop de la ruta por defecto (0.0.0.0/0).
  758. if nh := s.defaultNexthop(); nh != "" {
  759. info.Gateway = nh
  760. }
  761. return info
  762. }
  763. // ParseWanStatus parsea el estado de la WAN (issue #276). Acepta las dos
  764. // formas: `ubus call network.interface dump` (y entonces elige el uplink
  765. // activo, ver pickUplink) y el status de una sola interfaz. Extrae proto,
  766. // interfaz L3, boca física, IP pública, gateway y DNS; campos vacíos si el
  767. // JSON no trae datos utilizables.
  768. func ParseWanStatus(raw []byte) WanInfo {
  769. return ParseWanStatusPreferring(raw, "")
  770. }
  771. // ParseWanStatusPreferring is ParseWanStatus told which uplink is carrying
  772. // traffic (see pickUplinkPreferring). An empty name behaves exactly as
  773. // before.
  774. func ParseWanStatusPreferring(raw []byte, preferred string) WanInfo {
  775. var dump struct {
  776. Interface []ifaceStatus `json:"interface"`
  777. }
  778. if err := json.Unmarshal(raw, &dump); err == nil && len(dump.Interface) > 0 {
  779. s, ok := pickUplinkPreferring(dump.Interface, preferred)
  780. if !ok {
  781. return WanInfo{}
  782. }
  783. return wanInfoFrom(s)
  784. }
  785. var one ifaceStatus
  786. if json.Unmarshal(raw, &one) != nil {
  787. return WanInfo{}
  788. }
  789. return wanInfoFrom(one)
  790. }
  791. // ParseDhcpReservations parses the host sections of `uci show dhcp`. A host
  792. // entry can carry several MACs (GL firmware stores mac as a list) and they
  793. // all share the entry's name and address. Sorted by MAC so the payload does
  794. // not churn between pushes.
  795. func ParseDhcpReservations(out string) []DhcpReservation {
  796. type entry struct {
  797. name, ip string
  798. macs []string
  799. }
  800. entries := map[string]*entry{}
  801. order := []string{}
  802. get := func(section string) *entry {
  803. e, ok := entries[section]
  804. if !ok {
  805. e = &entry{}
  806. entries[section] = e
  807. order = append(order, section)
  808. }
  809. return e
  810. }
  811. for _, line := range strings.Split(out, "\n") {
  812. line = strings.TrimSpace(line)
  813. key, val, ok := strings.Cut(line, "=")
  814. if !ok || !strings.HasPrefix(key, "dhcp.") {
  815. continue
  816. }
  817. key = strings.TrimPrefix(key, "dhcp.")
  818. val = strings.Trim(val, "'")
  819. section, attr, isAttr := strings.Cut(key, ".")
  820. if !isAttr {
  821. if val == "host" {
  822. get(section)
  823. }
  824. continue
  825. }
  826. e, declared := entries[section]
  827. if !declared {
  828. continue // an option of a section that is not a host entry
  829. }
  830. switch attr {
  831. case "name":
  832. e.name = val
  833. case "ip":
  834. e.ip = val
  835. case "mac":
  836. // A list comes back as 'aa:..' 'bb:..'; a single value plain.
  837. for _, mac := range strings.Fields(strings.ReplaceAll(val, "'", " ")) {
  838. e.macs = append(e.macs, strings.ToUpper(mac))
  839. }
  840. }
  841. }
  842. res := []DhcpReservation{}
  843. for _, section := range order {
  844. e := entries[section]
  845. for _, mac := range e.macs {
  846. res = append(res, DhcpReservation{MAC: mac, Name: e.name, IP: e.ip})
  847. }
  848. }
  849. sort.Slice(res, func(i, j int) bool { return res[i].MAC < res[j].MAC })
  850. return res
  851. }
  852. // ParseDhcpLeasesFile parsea /tmp/dhcp.leases:
  853. // <expiry> <mac> <ip> <hostname> <clientid>
  854. func ParseDhcpLeasesFile(out string) []DhcpLease {
  855. leases := []DhcpLease{}
  856. now := time.Now().Unix()
  857. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  858. if line == "" {
  859. continue
  860. }
  861. p := strings.Fields(line)
  862. if len(p) < 3 {
  863. continue
  864. }
  865. hostname := ""
  866. if len(p) > 3 && p[3] != "*" {
  867. hostname = p[3]
  868. }
  869. clientID := ""
  870. if len(p) > 4 && p[4] != "*" {
  871. clientID = p[4]
  872. }
  873. var exp *int64
  874. if secs, err := strconv.ParseInt(p[0], 10, 64); err == nil && secs > now {
  875. exp = &secs
  876. }
  877. leases = append(leases, DhcpLease{MAC: strings.ToUpper(p[1]), IP: p[2], Hostname: hostname, ClientID: clientID, LeaseExpiresAt: exp})
  878. }
  879. return leases
  880. }
  881. // ParseGlClients parsea la respuesta de `ubus call gl-clients list`
  882. // (GL.iNet Flint2 y similares): {"clients": {"MAC": {mac, ip, name, online, ...}}}.
  883. // Error si no es JSON con esa forma. Solo devuelve entradas ONLINE con IP:
  884. // la base del firmware acumula historial (cientos de entradas) y las offline
  885. // solo servirían para inflar la lista de dispositivos; los equipos que
  886. // necesitan resolución de IP son los que están en la red ahora (issue #5
  887. // bug 1).
  888. func ParseGlClients(raw []byte) ([]DhcpLease, error) {
  889. type clientJSON struct {
  890. MAC string `json:"mac"`
  891. IP string `json:"ip"`
  892. Name string `json:"name"`
  893. Hostname string `json:"hostname"`
  894. Online bool `json:"online"`
  895. }
  896. var data struct {
  897. Clients map[string]clientJSON `json:"clients"`
  898. }
  899. if err := json.Unmarshal(raw, &data); err != nil {
  900. return nil, err
  901. }
  902. if data.Clients == nil {
  903. return nil, fmt.Errorf("gl-clients: sin clave clients")
  904. }
  905. out := make([]DhcpLease, 0, len(data.Clients))
  906. for key, c := range data.Clients {
  907. mac := c.MAC
  908. if mac == "" {
  909. mac = key
  910. }
  911. if mac == "" || c.IP == "" || !c.Online {
  912. continue
  913. }
  914. hostname := c.Hostname
  915. if hostname == "" {
  916. hostname = c.Name
  917. }
  918. out = append(out, DhcpLease{MAC: strings.ToUpper(mac), IP: c.IP, Hostname: hostname})
  919. }
  920. sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC })
  921. return out, nil
  922. }
  923. // ParseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
  924. func ParseWirelessClients(out string) map[string]WirelessClient {
  925. m := map[string]WirelessClient{}
  926. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  927. if line == "" {
  928. continue
  929. }
  930. p := strings.Fields(line)
  931. if len(p) < 2 {
  932. continue
  933. }
  934. freq := 0.0
  935. if len(p) > 2 {
  936. freq, _ = strconv.ParseFloat(p[2], 64)
  937. }
  938. sig, _ := strconv.Atoi(p[1])
  939. band := "2.4 GHz"
  940. if freq >= 5 {
  941. band = "5 GHz"
  942. }
  943. m[strings.ToUpper(p[0])] = WirelessClient{SignalDbm: sig, Band: band}
  944. }
  945. return m
  946. }
  947. // ParseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio
  948. // up e ifname asignado = asociada) → uplink inalámbrico. Tolerante con
  949. // radios/entradas raras; error si la respuesta no es JSON.
  950. func ParseWirelessUplink(raw []byte) (bool, error) {
  951. var radios map[string]struct {
  952. Up bool `json:"up"`
  953. Interfaces []struct {
  954. Ifname string `json:"ifname"`
  955. Config struct {
  956. Mode string `json:"mode"`
  957. } `json:"config"`
  958. } `json:"interfaces"`
  959. }
  960. if err := json.Unmarshal(raw, &radios); err != nil {
  961. return false, err
  962. }
  963. for _, r := range radios {
  964. if !r.Up {
  965. continue
  966. }
  967. for _, itf := range r.Interfaces {
  968. if itf.Config.Mode == "sta" && itf.Ifname != "" {
  969. return true, nil
  970. }
  971. }
  972. }
  973. return false, nil
  974. }
  975. // ---------------------------------------------------------------------------
  976. // Puertos
  977. // ---------------------------------------------------------------------------
  978. // ParsePortStates parsea líneas "<name> <operstate> <speed> [dsa] [type]
  979. // [conduit]". Los campos opcionales que falten dejan su valor por defecto:
  980. // sin type no se descarta ninguna boca por él.
  981. func ParsePortStates(out string) []PortState {
  982. ports := []PortState{}
  983. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  984. if line == "" {
  985. continue
  986. }
  987. p := strings.Fields(line)
  988. if len(p) < 3 {
  989. continue
  990. }
  991. mbps, _ := strconv.Atoi(p[2])
  992. speed := "—"
  993. if mbps > 0 {
  994. speed = fmtSpeedMbps(mbps)
  995. }
  996. st := PortState{Name: p[0], Up: p[1] == "up", Oper: p[1], Speed: speed}
  997. if len(p) > 3 && p[3] == "dsa" {
  998. st.DSA = true
  999. }
  1000. if len(p) > 4 {
  1001. st.Type, _ = strconv.Atoi(p[4])
  1002. }
  1003. if len(p) > 5 && p[5] != "-" {
  1004. st.Conduit = p[5]
  1005. }
  1006. ports = append(ports, st)
  1007. }
  1008. return ports
  1009. }
  1010. // ParsePortLayout parsea board.json → [{id, name, label, role}] (WAN
  1011. // normalizado a id 'wan').
  1012. // portPrettyLabel (#1200): etiqueta humana para el panel de bocas. Los
  1013. // patrones clásicos conservan su formato (lan1→"LAN 1", wan→"WAN",
  1014. // eth0→"ETH 0", sfp0→"SFP 0"); cualquier otro nombre físico reconocido
  1015. // muestra su nombre real intacto: los netdev de OpenWrt 25.12+ (sfp-lan,
  1016. // sfp-wan en BPI-R4) y las bocas sin dígitos (lan en UniFi 6 Lite). Ni
  1017. // mayúsculas inyectadas en medio del nombre ni sufijos partidos.
  1018. func portPrettyLabel(name string) string {
  1019. switch {
  1020. case name == "lan":
  1021. return "LAN"
  1022. case name == "wan":
  1023. return "WAN"
  1024. case lanNumRe.MatchString(name):
  1025. return "LAN " + strings.TrimPrefix(name, "lan")
  1026. case ethNumRe.MatchString(name):
  1027. return "ETH " + strings.TrimPrefix(name, "eth")
  1028. case sfpNumRe.MatchString(name):
  1029. if name == "sfp" {
  1030. return "SFP"
  1031. }
  1032. return "SFP " + strings.TrimPrefix(name, "sfp")
  1033. default:
  1034. return name
  1035. }
  1036. }
  1037. var (
  1038. lanNumRe = regexp.MustCompile(`^lan\d+$`)
  1039. ethNumRe = regexp.MustCompile(`^eth\d+$`)
  1040. sfpNumRe = regexp.MustCompile(`^sfp\d*$`)
  1041. )
  1042. func ParsePortLayout(out string) ([]PortLayout, error) {
  1043. var board struct {
  1044. Network struct {
  1045. Lan struct {
  1046. Ports []string `json:"ports"`
  1047. } `json:"lan"`
  1048. Wan struct {
  1049. Device string `json:"device"`
  1050. } `json:"wan"`
  1051. } `json:"network"`
  1052. }
  1053. if err := json.Unmarshal([]byte(out), &board); err != nil {
  1054. return nil, err
  1055. }
  1056. ports := []PortLayout{}
  1057. for _, name := range board.Network.Lan.Ports {
  1058. ports = append(ports, PortLayout{ID: name, Name: name, Label: portPrettyLabel(name), Role: "lan"})
  1059. }
  1060. if wanDev := board.Network.Wan.Device; wanDev != "" {
  1061. ports = append([]PortLayout{{ID: "wan", Name: wanDev, Label: "WAN", Role: "wan"}}, ports...)
  1062. }
  1063. return ports, nil
  1064. }
  1065. // phyRe/skipRe: nombres que pueden ser una boca física y nombres que nunca lo
  1066. // son (bridges, VLANs, túneles, wireless, módems).
  1067. var (
  1068. phyRe = regexp.MustCompile(`^(eth|sfp|en|swp)[0-9a-zA-Z_\-]*$|^(lan|wan)[0-9]*$`)
  1069. skipRe = regexp.MustCompile(`^(lo|br[-_]?|br-lan|br0|docker|veth|wg|tun|tap|ifb|pppoe|wlan|wpan|phy|gre|gretap|erspan|ip6tnl|sit|teql|bond|dummy|nat64|rmnet|usb|wwan)`)
  1070. )
  1071. // switchConduits: puertos de CPU de un switch, deducidos de las propias
  1072. // bocas. En DSA cada boca cuelga de la interfaz de CPU (lan1 y lan2 tienen
  1073. // lower_eth0), que no es una boca física por mucho que se llame eth0.
  1074. //
  1075. // Solo se mira el lower_* de interfaces que parecen bocas: el de un bridge
  1076. // son sus miembros (br-lan → lower_lan2) y el de una VLAN su interfaz padre,
  1077. // relaciones que no señalan ningún puerto de CPU.
  1078. func switchConduits(states []PortState) map[string]bool {
  1079. conduits := map[string]bool{}
  1080. for _, st := range states {
  1081. if st.Conduit == "" || skipRe.MatchString(st.Name) || !phyRe.MatchString(st.Name) {
  1082. continue
  1083. }
  1084. conduits[st.Conduit] = true
  1085. }
  1086. return conduits
  1087. }
  1088. // isEthNetdev: el layout nombra una interfaz de red ethernet de verdad.
  1089. // board.json declara como WAN lo que el router use de uplink, y no siempre es
  1090. // una boca: en un router celular es "/dev/cdc-wdm0",
  1091. // que ni siquiera aparece en /sys/class/net. Un tipo desconocido (salida
  1092. // antigua, sin el campo) cuenta como ethernet: mejor enseñar una boca de más
  1093. // que esconder una real.
  1094. func isEthNetdev(st PortState, ok bool) bool {
  1095. return ok && (st.Type <= 0 || st.Type == ARPHRDEther)
  1096. }
  1097. // BuildEthPorts: layout + estado /sys → []EthPort listo para el detalle.
  1098. // brMembers = miembros del bridge br-lan (AP en bridge re-etiqueta wan→LAN
  1099. // N+1); sin layout, fallback heurístico. ifaces = contadores/rates por iface
  1100. // física (issue #305; nil = sin datos, las bocas salen sin stats). Literal de
  1101. // openwrt.go GetEthPorts.
  1102. //
  1103. // Descarta dos bocas que no existen: el uplink del layout cuando no es una
  1104. // interfaz ethernet (módem celular) y el puerto de CPU del switch. Sin ellos
  1105. // un router así pasa de enseñar cuatro bocas -- WAN (nunca conectada), LAN 1,
  1106. // LAN 2 y ETH 0 -- a las dos que tiene.
  1107. //
  1108. // uplink es la boca por la que sale internet (WanInfo.Port); cuando ninguna
  1109. // boca ha salido como WAN se promueve esa, ver promoteUplink. "" = sin dato,
  1110. // y entonces no se promueve nada.
  1111. func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool, ifaces map[string]IfRate, uplink string) []EthPort {
  1112. applyStats := func(ep *EthPort, iface string) {
  1113. st, ok := ifaces[iface]
  1114. if !ok {
  1115. return
  1116. }
  1117. ep.Iface = iface
  1118. ep.RxBytes, ep.TxBytes = st.Rx, st.Tx
  1119. ep.RxErrs, ep.TxErrs = st.RxErr, st.TxErr
  1120. ep.RxBps, ep.TxBps = st.RxBps, st.TxBps
  1121. }
  1122. byName := map[string]PortState{}
  1123. for _, p := range states {
  1124. byName[p.Name] = p
  1125. }
  1126. conduits := switchConduits(states)
  1127. used := map[string]bool{}
  1128. ports := make([]EthPort, 0, len(states))
  1129. // netdev de cada boca por id, para saber luego cuál lleva el uplink: el
  1130. // id no siempre es el nombre de la interfaz (en swconfig, "1" vs
  1131. // "eth0.1").
  1132. netdev := map[string]string{}
  1133. if len(layout) > 0 {
  1134. lanCount := 0
  1135. for _, p := range layout {
  1136. if p.Role == "lan" {
  1137. lanCount++
  1138. }
  1139. }
  1140. for _, p := range layout {
  1141. st, ok := byName[p.Name]
  1142. if p.Role == "wan" && !isEthNetdev(st, ok) {
  1143. continue
  1144. }
  1145. up := ok && st.Up
  1146. label := p.Label
  1147. if p.Role == "wan" && brMembers[p.Name] {
  1148. label = "LAN " + strconv.Itoa(lanCount+1)
  1149. }
  1150. ep := EthPort{ID: p.ID, Label: label, Up: up}
  1151. if up {
  1152. ep.Speed = st.Speed
  1153. }
  1154. applyStats(&ep, p.Name)
  1155. ports = append(ports, ep)
  1156. netdev[ep.ID] = p.Name
  1157. used[p.Name] = true
  1158. }
  1159. } else {
  1160. // Fallback sin config. #1200: también "lan"/"wan" a secas (UniFi
  1161. // 6 Lite: la boca no se llama lan1 sino lan, y antes el panel
  1162. // salía vacío - 0 de 0 - porque ningún patrón la reconocía).
  1163. lanRe := regexp.MustCompile(`^lan\d*$`)
  1164. lans := []PortState{}
  1165. for _, p := range states {
  1166. if lanRe.MatchString(p.Name) {
  1167. lans = append(lans, p)
  1168. }
  1169. }
  1170. sort.Slice(lans, func(i, j int) bool { return NaturalLess(lans[i].Name, lans[j].Name) })
  1171. for _, p := range lans {
  1172. ep := EthPort{ID: p.Name, Label: portPrettyLabel(p.Name), Up: p.Up}
  1173. if p.Up {
  1174. ep.Speed = p.Speed
  1175. }
  1176. applyStats(&ep, p.Name)
  1177. ports = append(ports, ep)
  1178. netdev[ep.ID] = p.Name
  1179. used[p.Name] = true
  1180. }
  1181. wanName := ""
  1182. if uplink != "" {
  1183. // #1500: con uplink runtime la WAN es esa boca, no la heurística
  1184. // ciega de abajo (un AP bridge sin layout marcaba WAN en eth1
  1185. // teniendo el uplink en eth0). El uplink puede llegar etiquetado
  1186. // ("br0.1"): la boca es la de debajo.
  1187. base := uplink
  1188. if i := strings.LastIndexByte(base, '.'); i > 0 {
  1189. base = base[:i]
  1190. }
  1191. if st, ok := byName[base]; ok && phyRe.MatchString(base) && isEthNetdev(st, ok) && !conduits[base] {
  1192. wanName = base
  1193. } else if len(brMembers) > 0 {
  1194. // Uplink sobre bridge (APs: la ruta default vive en br0): la
  1195. // boca WAN es el miembro con vecino LLDP (la que mira al
  1196. // core) o, en su defecto, el de más rx bytes. Iteración
  1197. // ordenada: empates no deben bailar entre sondeos (#1500).
  1198. names := make([]string, 0, len(brMembers))
  1199. for m := range brMembers {
  1200. names = append(names, m)
  1201. }
  1202. sort.Strings(names)
  1203. bestRx := uint64(0)
  1204. for _, m := range names {
  1205. st, ok := byName[m]
  1206. if !ok || !st.Up || !phyRe.MatchString(m) || !isEthNetdev(st, ok) || conduits[m] {
  1207. continue
  1208. }
  1209. if wanName == "" || ifaces[m].Rx > bestRx {
  1210. wanName, bestRx = m, ifaces[m].Rx
  1211. }
  1212. }
  1213. }
  1214. }
  1215. if wanName == "" {
  1216. if _, ok := byName["wan"]; ok {
  1217. wanName = "wan"
  1218. } else if _, ok := byName["pppoe-wan"]; ok {
  1219. wanName = "eth1"
  1220. } else if st, ok := byName["eth1"]; ok && !st.DSA {
  1221. // #847: un conduit DSA no es la WAN física aunque se llame eth1.
  1222. wanName = "eth1"
  1223. }
  1224. }
  1225. if wanName != "" {
  1226. st := byName[wanName]
  1227. ep := EthPort{ID: "wan", Label: "WAN", Up: st.Up}
  1228. if st.Up {
  1229. ep.Speed = st.Speed
  1230. }
  1231. applyStats(&ep, wanName)
  1232. ports = append([]EthPort{ep}, ports...)
  1233. netdev[ep.ID] = wanName
  1234. used[wanName] = true
  1235. }
  1236. }
  1237. // Mejora #413/#416: añadir interfaces físicas que no estén ya cubiertas
  1238. // por el layout/fallback (p. ej. eth0, sfp+ en BPI-R4/UniFi).
  1239. extras := make([]EthPort, 0)
  1240. for _, st := range states {
  1241. if used[st.Name] {
  1242. continue
  1243. }
  1244. // #847: el conduit DSA (puerto CPU interno del switch, /sys .../dsa)
  1245. // no es una boca usable: su velocidad es interna y sin sentido para
  1246. // el usuario (p. ej. 150 Mbps en BPI-R4). Se excluye del panel.
  1247. if st.DSA {
  1248. continue
  1249. }
  1250. if skipRe.MatchString(st.Name) {
  1251. continue
  1252. }
  1253. if !phyRe.MatchString(st.Name) {
  1254. continue
  1255. }
  1256. if conduits[st.Name] {
  1257. continue // puerto de CPU del switch, no una boca
  1258. }
  1259. // Broadcom/Asuswrt internal "ghost" interfaces (eth5/6/7 on an RT-AX92U)
  1260. // pass phyRe and carry no DSA/conduit marker, but their sysfs operstate
  1261. // is dormant/unknown and speed is unreadable: they are not front-panel
  1262. // ports and never carry user traffic. A real port is either "up" (kept
  1263. // here and everywhere) or "down" when unplugged. Oper=="" is legacy
  1264. // three-field output, so nothing is hidden for it.
  1265. if !st.Up && st.Oper != "" && st.Oper != "down" {
  1266. continue
  1267. }
  1268. // #1200: label centralizado en portPrettyLabel - sfp-lan/sfp-wan
  1269. // conservan su nombre (antes "SFP -lan"/"SFP -wan").
  1270. label := portPrettyLabel(st.Name)
  1271. ep := EthPort{ID: st.Name, Label: label, Up: st.Up}
  1272. if st.Up {
  1273. ep.Speed = st.Speed
  1274. }
  1275. applyStats(&ep, st.Name)
  1276. extras = append(extras, ep)
  1277. netdev[ep.ID] = st.Name
  1278. used[st.Name] = true
  1279. }
  1280. if len(extras) > 0 {
  1281. sort.Slice(extras, func(i, j int) bool { return NaturalLess(extras[i].ID, extras[j].ID) })
  1282. // Mantener WAN primero, luego LANs, luego extras.
  1283. ports = append(ports, extras...)
  1284. }
  1285. return promoteUplink(ports, netdev, uplink)
  1286. }
  1287. // promoteUplink marca como WAN la boca por la que sale internet cuando
  1288. // ninguna ha salido ya como tal. Hay routers cuyo uplink no entra por una
  1289. // boca WAN dedicada: el PPPoE puede ir sobre una boca llamada "lan1" y el
  1290. // board.json solo declara un módem como WAN, así que sin esto ninguna boca
  1291. // sale con id "wan" -- y la UI marca el uplink y cuelga los datos de la
  1292. // conexión (proto, IP pública, gateway, DNS) justo de esa.
  1293. //
  1294. // La boca conserva su sitio y su iface: las estadísticas y la MAC siguen
  1295. // siendo las suyas, solo cambia cómo se presenta.
  1296. //
  1297. // #1482: cuando el layout YA trae una boca WAN pero el uplink runtime cae
  1298. // en otra distinta, manda netifd: la boca del uplink se promueve y la del
  1299. // layout vuelve a su netdev (ETH n). El layout es una descripción estática
  1300. // del cableado de vendor; el uplink runtime es la verdad de terreno de por
  1301. // dónde sale internet (caso real: board.json con wan en eth0 porque ahí
  1302. // vive el management, y el PPPoE saliendo por eth2). Si la boca WAN del
  1303. // layout no tiene un netdev físico al que volver (no consta, o se llama
  1304. // literalmente "wan"), no se toca nada: antes mantener la presentación del
  1305. // layout que duplicar el id "wan".
  1306. func promoteUplink(ports []EthPort, netdev map[string]string, uplink string) []EthPort {
  1307. if uplink == "" {
  1308. return ports
  1309. }
  1310. // El uplink puede llegar etiquetado ("lan1.7"): la boca es la de debajo.
  1311. base := uplink
  1312. if i := strings.LastIndexByte(base, '.'); i > 0 {
  1313. base = base[:i]
  1314. }
  1315. wanIdx, upIdx := -1, -1
  1316. for i := range ports {
  1317. if ports[i].ID == "wan" {
  1318. wanIdx = i
  1319. }
  1320. if upIdx < 0 {
  1321. if n := netdev[ports[i].ID]; n == uplink || n == base {
  1322. upIdx = i
  1323. }
  1324. }
  1325. }
  1326. if wanIdx < 0 {
  1327. // Ninguna boca salió como WAN en el layout: promueve la del uplink.
  1328. if upIdx >= 0 {
  1329. ports[upIdx].ID, ports[upIdx].Label = "wan", "WAN"
  1330. }
  1331. return ports
  1332. }
  1333. if upIdx < 0 || upIdx == wanIdx {
  1334. return ports // sin uplink, o de acuerdo con el layout
  1335. }
  1336. nd := netdev[ports[wanIdx].ID]
  1337. if nd == "" || nd == "wan" {
  1338. return ports // sin netdev físico al que volver: no duplicar la WAN
  1339. }
  1340. ports[wanIdx].ID, ports[wanIdx].Label = nd, portPrettyLabel(nd)
  1341. ports[upIdx].ID, ports[upIdx].Label = "wan", "WAN"
  1342. return ports
  1343. }
  1344. // NaturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
  1345. func NaturalLess(a, b string) bool {
  1346. re := regexp.MustCompile(`^(.*?)(\d+)$`)
  1347. ma, mb := re.FindStringSubmatch(a), re.FindStringSubmatch(b)
  1348. if ma != nil && mb != nil && ma[1] == mb[1] {
  1349. na, _ := strconv.Atoi(ma[2])
  1350. nb, _ := strconv.Atoi(mb[2])
  1351. return na < nb
  1352. }
  1353. return a < b
  1354. }
  1355. // Filtro de puertos del FDB (#506): DENYLIST, no allowlist. El allowlist
  1356. // histórico (lan\d+|wan|eth\d+|swp\d+|en...) descartaba en silencio MACs
  1357. // aprendidas en puertos con nombres no enumerados: las jaulas SFP del BPI-R4
  1358. // se llaman "sfp-lan"/"sfp-wan" (openwrt,netdev-name, 25.12+) y sus
  1359. // dispositivos cableados jamás llegaban a descubrirse. Ahora vale cualquier
  1360. // puerto MIEMBRO del bridge (los no-miembros ya no resuelven en ==PORTS==)
  1361. // salvo los wireless (clientes que llegan por la sección wireless) y las
  1362. // interfaces virtuales.
  1363. var (
  1364. // wl\d+ cubre las radios Broadcom de Asuswrt/Merlin (wl0..wl3): el bridge
  1365. // aprende las MACs propias de cada radio (bit LAA volteado) como entradas
  1366. // externas en esos puertos, y sin excluirlas cada radio aparecía como un
  1367. // cliente "cableado" fantasma del AP. La alternativa wl va anclada (con su
  1368. // subinterfaz VLAN opcional): por prefijo casaría interfaces futuras que
  1369. // solo compartan las letras iniciales.
  1370. fdbWirelessRe = regexp.MustCompile(`^(phy\d+-ap\d*|wlan\d*|wl[0-9]+(\.[0-9]+)?)$`)
  1371. fdbVirtualRe = regexp.MustCompile(`^(br|lo|veth|wg|tun|tap|ppp|sit|ip6|gre|erspan|dummy|macv|ifb)`)
  1372. )
  1373. // fdbPortWired: ¿cuenta este puerto como cableado para el mapa MAC→puerto?
  1374. // Las subinterfaces VLAN (lan1.10, eth0.100) tampoco cuentan: el FDB de un
  1375. // bridge con VLAN filtering reporta el puerto físico.
  1376. func fdbPortWired(port string) bool {
  1377. if port == "" || strings.ContainsAny(port, ".@") {
  1378. return false
  1379. }
  1380. return !fdbWirelessRe.MatchString(port) && !fdbVirtualRe.MatchString(port)
  1381. }
  1382. // ParseBridgeFdb parsea la salida ==PORTS==/==MACS== → MAC aprendida → puerto.
  1383. // Acepta dos formatos en ==MACS==: brctl (`<port_no> <mac>`) y
  1384. // `bridge fdb show` (`<ifname> <mac>`, emitido por CmdBridgeFDB).
  1385. func ParseBridgeFdb(out string) map[string]string {
  1386. wired, _ := ParseBridgeFdbSplit(out)
  1387. return wired
  1388. }
  1389. // ParseBridgeFdbSplit es ParseBridgeFdb devolviendo además las MACs aprendidas
  1390. // en puertos del lado inalámbrico (wl0.1, wlan0, phy0-ap0…): no son clientes
  1391. // cableados, pero tampoco deben tirarse: son la única evidencia de que esa MAC
  1392. // vive detrás de esta radio (MACs rotadas que siguen emitiendo, clientes en
  1393. // backhaul 4-address). Sin este segundo mapa el server las vería únicamente en
  1394. // el FDB de tránsito del gateway y su fallback las dibujaría como cableadas.
  1395. func ParseBridgeFdbSplit(out string) (wired, wirelessSide map[string]string) {
  1396. wired = map[string]string{}
  1397. wirelessSide = map[string]string{}
  1398. portNames := map[string]string{} // port_no → ifname
  1399. section := byte(0)
  1400. for _, line := range strings.Split(out, "\n") {
  1401. t := strings.TrimSpace(line)
  1402. if strings.HasPrefix(t, "==PORTS==") {
  1403. section = 'p'
  1404. continue
  1405. }
  1406. if strings.HasPrefix(t, "==MACS==") {
  1407. section = 'm'
  1408. continue
  1409. }
  1410. p := strings.Fields(t)
  1411. if len(p) < 2 {
  1412. continue
  1413. }
  1414. switch section {
  1415. case 'p':
  1416. no, name := p[0], p[1]
  1417. if strings.HasPrefix(no, "0x") {
  1418. if n, err := strconv.ParseInt(no[2:], 16, 64); err == nil {
  1419. no = strconv.FormatInt(n, 10)
  1420. }
  1421. }
  1422. portNames[no] = name
  1423. portNames[name] = name // puerto también localizable por nombre (bridge fdb)
  1424. case 'm':
  1425. no, mac := p[0], p[1]
  1426. port, ok := portNames[no]
  1427. if !ok || mac == "" {
  1428. continue
  1429. }
  1430. mac = strings.ToUpper(mac)
  1431. switch {
  1432. case fdbPortWired(port):
  1433. wired[mac] = port
  1434. case fdbPortWirelessSide(port):
  1435. wirelessSide[mac] = port
  1436. }
  1437. }
  1438. }
  1439. return wired, wirelessSide
  1440. }
  1441. // fdbPortWirelessSide: puertos del bridge que son radios o subinterfaces de
  1442. // radio (wl0.1, wlan0, phy0-ap0). Las interfaces virtuales no inalámbricas
  1443. // (br*, veth*, tun*) NO cuentan: ahí la MAC no llegó por el aire.
  1444. func fdbPortWirelessSide(port string) bool {
  1445. base := port
  1446. if i := strings.IndexAny(base, ".@"); i >= 0 {
  1447. base = base[:i]
  1448. }
  1449. return fdbWirelessRe.MatchString(base)
  1450. }
  1451. // LuCILabels: etiquetas de puertos y VLANs de LuCI (issue #258). OpenWrt
  1452. // snapshots las definen en /etc/config/luci como secciones switchvlan:
  1453. //
  1454. // config switchvlan 'port_labels'
  1455. // option lan1 'Router/Fritzbox'
  1456. // config switchvlan 'vlan_labels'
  1457. // option 1 'LAN'
  1458. //
  1459. // PortLabels mapea interfaz (lan1…) → etiqueta; VlanLabels mapea id de
  1460. // VLAN → etiqueta.
  1461. type LuCILabels struct {
  1462. PortLabels map[string]string `json:"portLabels,omitempty"`
  1463. VlanLabels map[string]string `json:"vlanLabels,omitempty"`
  1464. }
  1465. var (
  1466. luciSectionRe = regexp.MustCompile(`^config\s+(\S+)\s+['"]?([A-Za-z0-9_]+)['"]?`)
  1467. luciOptionRe = regexp.MustCompile(`^option\s+(\S+)\s+['"]?([^'"]*)['"]?$`)
  1468. )
  1469. // ParseLuCILabels parsea /etc/config/luci y extrae las secciones
  1470. // port_labels/vlan_labels. Devuelve nil si no hay ninguna etiqueta.
  1471. func ParseLuCILabels(out string) *LuCILabels {
  1472. var labels LuCILabels
  1473. var section string
  1474. for _, raw := range strings.Split(out, "\n") {
  1475. line := strings.TrimSpace(raw)
  1476. if line == "" || strings.HasPrefix(line, "#") {
  1477. continue
  1478. }
  1479. if m := luciSectionRe.FindStringSubmatch(line); m != nil {
  1480. section = m[2]
  1481. continue
  1482. }
  1483. if section != "port_labels" && section != "vlan_labels" {
  1484. continue
  1485. }
  1486. if m := luciOptionRe.FindStringSubmatch(line); m != nil {
  1487. if m[2] == "" {
  1488. continue
  1489. }
  1490. if section == "port_labels" {
  1491. if labels.PortLabels == nil {
  1492. labels.PortLabels = map[string]string{}
  1493. }
  1494. labels.PortLabels[m[1]] = m[2]
  1495. } else {
  1496. if labels.VlanLabels == nil {
  1497. labels.VlanLabels = map[string]string{}
  1498. }
  1499. labels.VlanLabels[m[1]] = m[2]
  1500. }
  1501. }
  1502. }
  1503. if len(labels.PortLabels) == 0 && len(labels.VlanLabels) == 0 {
  1504. return nil
  1505. }
  1506. return &labels
  1507. }
  1508. // VlanEntry: una VLAN de un puerto del bridge (issue #315). ID es el número
  1509. // de VLAN (1-4094); Tagged=false + Untagged en el wire (Egress Untagged);
  1510. // PVID=true indica que este puerto es el puerto nativo de esta VLAN.
  1511. type VlanEntry struct {
  1512. ID int `json:"id"`
  1513. Tagged bool `json:"tagged"`
  1514. PVID bool `json:"pvid"`
  1515. // Name es la etiqueta que LuCI da a la VLAN (uci show network, #258),
  1516. // rellenada por el servidor al juntarla con VlanLabels (#1757).
  1517. Name string `json:"name,omitempty"`
  1518. }
  1519. // VlanPort: puerto del bridge con sus VLANs (issue #315).
  1520. type VlanPort struct {
  1521. Port string `json:"port"`
  1522. Vlans []VlanEntry `json:"vlans"`
  1523. }
  1524. var vlanIDRe = regexp.MustCompile(`^(\d+)(.*)$`)
  1525. // ParseBridgeVlan parsea la salida de `bridge vlan show` (issue #315).
  1526. // Formato: líneas "port vlan-id [flags]" o " vlan-id [flags]" (continuation).
  1527. // Flags: "PVID" = puerto nativo; "Egress Untagged" = untagged en salida.
  1528. func ParseBridgeVlan(out string) []VlanPort {
  1529. var ports []VlanPort
  1530. var cur *VlanPort
  1531. for _, raw := range strings.Split(out, "\n") {
  1532. line := strings.TrimRight(raw, "\r\n")
  1533. if line == "" || strings.HasPrefix(line, "port") {
  1534. continue
  1535. }
  1536. trimmed := strings.TrimSpace(line)
  1537. if trimmed == "" {
  1538. continue
  1539. }
  1540. isContinuation := len(line) > 0 && (line[0] == ' ' || line[0] == '\t')
  1541. fields := strings.Fields(trimmed)
  1542. if len(fields) == 0 {
  1543. continue
  1544. }
  1545. var portName string
  1546. var vlanField string
  1547. if isContinuation {
  1548. if cur == nil {
  1549. continue
  1550. }
  1551. vlanField = fields[0]
  1552. } else {
  1553. portName = fields[0]
  1554. if len(fields) < 2 {
  1555. continue
  1556. }
  1557. vlanField = fields[1]
  1558. }
  1559. m := vlanIDRe.FindStringSubmatch(vlanField)
  1560. if m == nil {
  1561. continue
  1562. }
  1563. id, err := strconv.Atoi(m[1])
  1564. if err != nil || id < 1 || id > 4094 {
  1565. continue
  1566. }
  1567. rest := strings.ToLower(m[2])
  1568. if len(fields) > 2 {
  1569. rest += " " + strings.ToLower(strings.Join(fields[2:], " "))
  1570. }
  1571. pvid := strings.Contains(rest, "pvid")
  1572. tagged := !strings.Contains(rest, "egress untagged")
  1573. entry := VlanEntry{ID: id, Tagged: tagged, PVID: pvid}
  1574. if isContinuation {
  1575. cur.Vlans = append(cur.Vlans, entry)
  1576. } else {
  1577. ports = append(ports, VlanPort{Port: portName, Vlans: []VlanEntry{entry}})
  1578. cur = &ports[len(ports)-1]
  1579. }
  1580. }
  1581. return ports
  1582. }
  1583. var nonDigitRe = regexp.MustCompile(`\D`)
  1584. // ParseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
  1585. // hostapdClientsJSON es el shape de `ubus call hostapd.<if> get_clients`.
  1586. // El objeto por estación incluye `bytes:{rx,tx}` (acumulados desde la
  1587. // asociación) y `packets` cuando el driver responde a read_sta_data (#551);
  1588. // si no los expone, quedan a cero.
  1589. type hostapdClientsJSON struct {
  1590. Freq float64 `json:"freq"`
  1591. Clients map[string]struct {
  1592. Auth bool `json:"auth"`
  1593. Assoc bool `json:"assoc"`
  1594. Authorized bool `json:"authorized"`
  1595. Signal int `json:"signal"`
  1596. Bytes struct {
  1597. Rx uint64 `json:"rx"`
  1598. Tx uint64 `json:"tx"`
  1599. } `json:"bytes"`
  1600. } `json:"clients"`
  1601. }
  1602. // ParseHostapdClients (#368) parsea el output de CmdHostapdClients: bloques
  1603. // "==AP==hostapd.phy0-ap0" seguidos del JSON de get_clients. Solo cuenta
  1604. // estaciones asociadas y autorizadas (equivalente a iwinfo assoclist); la
  1605. // banda sale del "freq" del bloque (>=5 GHz = "5 GHz"). Mismo shape que
  1606. // ParseWirelessClients. RxBytes/TxBytes son los contadores acumulados de la
  1607. // estación si el driver los reportó (issue #551).
  1608. func ParseHostapdClients(out string) map[string]WirelessClient {
  1609. m := map[string]WirelessClient{}
  1610. for _, chunk := range strings.Split(out, "==AP==") {
  1611. chunk = strings.TrimSpace(chunk)
  1612. if chunk == "" {
  1613. continue
  1614. }
  1615. // La marca lleva el objeto ubus delante; el JSON empieza en "{".
  1616. i := strings.Index(chunk, "{")
  1617. if i < 0 {
  1618. continue
  1619. }
  1620. var j hostapdClientsJSON
  1621. if err := json.Unmarshal([]byte(chunk[i:]), &j); err != nil || j.Freq == 0 {
  1622. continue
  1623. }
  1624. freq := j.Freq
  1625. if freq >= 1000 { // ubus get_clients da MHz; iwinfo da GHz
  1626. freq /= 1000
  1627. }
  1628. band := "2.4 GHz"
  1629. if freq >= 5 {
  1630. band = "5 GHz"
  1631. }
  1632. for mac, st := range j.Clients {
  1633. if !st.Assoc || !st.Authorized {
  1634. continue
  1635. }
  1636. m[strings.ToUpper(mac)] = WirelessClient{
  1637. SignalDbm: st.Signal, Band: band,
  1638. RxBytes: st.Bytes.Rx, TxBytes: st.Bytes.Tx,
  1639. }
  1640. }
  1641. }
  1642. return m
  1643. }
  1644. // ParseWirelessCombined (#368) parsea CmdWirelessCombined: líneas "C|mac|sig|
  1645. // freq" (clientes, mismo shape que ParseWirelessClients) y "R|freq|ch|ht|tx|n"
  1646. // (radios, mismo shape que ParseRadios, que se reutiliza).
  1647. func ParseWirelessCombined(out string) (map[string]WirelessClient, []Radio) {
  1648. clients := map[string]WirelessClient{}
  1649. var radioLines []string
  1650. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  1651. line = strings.TrimSpace(line)
  1652. switch {
  1653. case strings.HasPrefix(line, "C|"):
  1654. p := strings.Split(line, "|")
  1655. if len(p) < 4 {
  1656. continue
  1657. }
  1658. sig, _ := strconv.Atoi(p[2])
  1659. freq, _ := strconv.ParseFloat(p[3], 64)
  1660. band := "2.4 GHz"
  1661. if freq >= 5 {
  1662. band = "5 GHz"
  1663. }
  1664. clients[strings.ToUpper(p[1])] = WirelessClient{SignalDbm: sig, Band: band}
  1665. case strings.HasPrefix(line, "R|"):
  1666. radioLines = append(radioLines, strings.TrimPrefix(line, "R|"))
  1667. }
  1668. }
  1669. return clients, ParseRadios(strings.Join(radioLines, "\n"))
  1670. }
  1671. func ParseRadios(out string) []Radio {
  1672. byBand := map[string]*Radio{}
  1673. order := []string{}
  1674. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  1675. if line == "" {
  1676. continue
  1677. }
  1678. p := strings.Split(line, "|")
  1679. if len(p) < 5 {
  1680. continue
  1681. }
  1682. freq, _ := strconv.ParseFloat(p[0], 64)
  1683. if freq == 0 {
  1684. continue
  1685. }
  1686. band := "2.4 GHz"
  1687. if freq >= 5 {
  1688. band = "5 GHz"
  1689. }
  1690. width, _ := strconv.Atoi(nonDigitRe.ReplaceAllString(p[2], ""))
  1691. if width == 0 {
  1692. width = 20
  1693. }
  1694. ch, _ := strconv.Atoi(p[1])
  1695. tx, _ := strconv.Atoi(p[3])
  1696. // #1213: formato nuevo "freq|ch|ht|tx|bssid|noise|n" (7 campos);
  1697. // el histórico "freq|ch|ht|tx|n" (5) sigue parseando igual.
  1698. var noise *int
  1699. var bssid string
  1700. n := 0
  1701. if len(p) >= 7 {
  1702. bssid = strings.ToUpper(strings.TrimSpace(p[4]))
  1703. if v, err := strconv.Atoi(strings.TrimSpace(p[5])); err == nil && v != 0 {
  1704. noise = &v
  1705. }
  1706. n, _ = strconv.Atoi(p[6])
  1707. } else {
  1708. n, _ = strconv.Atoi(p[4])
  1709. }
  1710. if cur, ok := byBand[band]; ok {
  1711. cur.Clients += n
  1712. if cur.NoiseDbm == nil {
  1713. cur.NoiseDbm = noise
  1714. }
  1715. if cur.BSSID == "" {
  1716. cur.BSSID = bssid
  1717. }
  1718. } else {
  1719. byBand[band] = &Radio{Name: band, Channel: ch, WidthMhz: width, PowerDbm: float64(tx), Clients: n, NoiseDbm: noise, BSSID: bssid}
  1720. order = append(order, band)
  1721. }
  1722. }
  1723. radios := []Radio{}
  1724. for _, b := range order {
  1725. radios = append(radios, *byBand[b])
  1726. }
  1727. return radios
  1728. }
  1729. // ParseRadioSections parsea la salida de CmdRadioSections y devuelve
  1730. // banda ("2.4 GHz"|"5 GHz"|"6 GHz") → sección UCI ("radio0"). Solo se queda
  1731. // con la primera sección por banda (si hay varias, la primera gana; el
  1732. // channel plan trabaja por banda).
  1733. func ParseRadioSections(out string) map[string]string {
  1734. sections := map[string]string{}
  1735. secBand := map[string]string{}
  1736. for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
  1737. line = strings.TrimSpace(line)
  1738. if !strings.HasPrefix(line, "wireless.") {
  1739. continue
  1740. }
  1741. parts := strings.SplitN(line, "=", 2)
  1742. if len(parts) != 2 {
  1743. continue
  1744. }
  1745. key := strings.TrimPrefix(parts[0], "wireless.")
  1746. val := strings.Trim(parts[1], "'")
  1747. rel, opt, hasOpt := strings.Cut(key, ".")
  1748. if !hasOpt {
  1749. if val == "wifi-device" {
  1750. secBand[rel] = "" // sección conocida, banda pendiente
  1751. }
  1752. continue
  1753. }
  1754. band, ok := secBand[rel]
  1755. if !ok || band != "" {
  1756. continue
  1757. }
  1758. switch {
  1759. case opt == "band" || (opt == "hwmode" && (val == "11g" || val == "11a")):
  1760. switch {
  1761. case val == "2g" || val == "11g":
  1762. secBand[rel] = "2.4 GHz"
  1763. case val == "5g" || val == "11a":
  1764. secBand[rel] = "5 GHz"
  1765. case val == "6g":
  1766. secBand[rel] = "6 GHz"
  1767. }
  1768. }
  1769. }
  1770. for sec, band := range secBand {
  1771. if band != "" {
  1772. if _, exists := sections[band]; !exists {
  1773. sections[band] = sec
  1774. }
  1775. }
  1776. }
  1777. return sections
  1778. }
  1779. // ParseScan parsea la salida de CmdScan: bloques "==IFACE==<iface>" seguidos de
  1780. // la salida de `iw dev <iface> scan`. Extrae BSS, freq, signal y SSID.
  1781. func ParseScan(out string) []ScanResult {
  1782. var res []ScanResult
  1783. iface := ""
  1784. var current *ScanResult
  1785. // Estado del bloque HT/VHT en curso para el ancho de canal (#1087).
  1786. section := ""
  1787. ht40, vhtWidth := false, 0
  1788. flush := func() {
  1789. if current != nil && current.BSSID != "" && current.Freq > 0 {
  1790. current.Channel = FreqToChannel(current.Freq)
  1791. if current.Channel > 0 {
  1792. switch {
  1793. case vhtWidth > 0:
  1794. current.WidthMhz = vhtWidth
  1795. case ht40:
  1796. current.WidthMhz = 40
  1797. default:
  1798. current.WidthMhz = 20
  1799. }
  1800. res = append(res, *current)
  1801. }
  1802. }
  1803. current = nil
  1804. }
  1805. for _, raw := range strings.Split(out, "\n") {
  1806. line := strings.TrimSpace(raw)
  1807. if strings.HasPrefix(line, "==IFACE==") {
  1808. flush()
  1809. iface = strings.TrimPrefix(line, "==IFACE==")
  1810. continue
  1811. }
  1812. if strings.HasPrefix(line, "BSS ") {
  1813. flush()
  1814. fields := strings.Fields(line)
  1815. if len(fields) < 2 {
  1816. continue
  1817. }
  1818. bssid := strings.ToUpper(strings.Split(fields[1], "(")[0])
  1819. current = &ScanResult{Iface: iface, BSSID: bssid}
  1820. section, ht40, vhtWidth = "", false, 0
  1821. continue
  1822. }
  1823. if current == nil {
  1824. continue
  1825. }
  1826. // Ancho de canal anunciado por el vecino (#1087): HT operation da
  1827. // el salto de 40 MHz; VHT operation el de 80/160.
  1828. switch {
  1829. case strings.HasPrefix(line, "HT operation:"):
  1830. section = "ht"
  1831. continue
  1832. case strings.HasPrefix(line, "VHT operation:"):
  1833. section = "vht"
  1834. continue
  1835. case strings.HasPrefix(line, "HE operation:") || strings.HasPrefix(line, "EHT operation:"):
  1836. section = ""
  1837. continue
  1838. }
  1839. if section == "ht" && strings.Contains(line, "secondary channel offset:") {
  1840. ht40 = !strings.Contains(line, "no secondary")
  1841. continue
  1842. }
  1843. if section == "vht" && strings.Contains(line, "channel width:") {
  1844. // "* channel width: 1 (80 MHz)": 1 = 80 MHz, 2 = 160 MHz.
  1845. re := vhtWidthRe.FindStringSubmatch(line)
  1846. if re != nil {
  1847. n, _ := strconv.Atoi(re[1])
  1848. switch n {
  1849. case 1:
  1850. vhtWidth = 80
  1851. case 2:
  1852. vhtWidth = 160
  1853. }
  1854. }
  1855. continue
  1856. }
  1857. if strings.HasPrefix(line, "freq:") {
  1858. // iw imprime la frecuencia como float ("freq: 5260.0"): Atoi
  1859. // fallaba en silencio, Freq quedaba 0 y el flush descartaba TODOS
  1860. // los BSS (scans siempre vacíos, #475).
  1861. if f, err := strconv.ParseFloat(strings.TrimSpace(strings.TrimPrefix(line, "freq:")), 64); err == nil {
  1862. current.Freq = int(f)
  1863. }
  1864. continue
  1865. }
  1866. if strings.HasPrefix(line, "signal:") {
  1867. v, _ := strconv.ParseFloat(strings.Fields(strings.TrimPrefix(line, "signal:"))[0], 64)
  1868. current.Signal = int(v)
  1869. continue
  1870. }
  1871. if strings.HasPrefix(line, "SSID:") {
  1872. current.SSID = strings.TrimSpace(strings.TrimPrefix(line, "SSID:"))
  1873. continue
  1874. }
  1875. }
  1876. flush()
  1877. return res
  1878. }
  1879. var vhtWidthRe = regexp.MustCompile(`channel width:\s*(\d)\s*\(`)
  1880. // ParseIwDev parsea la salida de CmdIwDev (`iw dev`) y devuelve las
  1881. // interfaces AP de ESTE equipo con su BSSID y SSID (#1087). Los bloques
  1882. // "Interface <name>" traen addr, ssid y type; solo type AP interesa (los
  1883. // STA/clientes managed no son red propia).
  1884. func ParseIwDev(out string) []OwnBSSID {
  1885. var res []OwnBSSID
  1886. iface, addr, ssid, ifType := "", "", "", ""
  1887. flush := func() {
  1888. if iface != "" && addr != "" && ifType == "AP" {
  1889. res = append(res, OwnBSSID{Iface: iface, BSSID: strings.ToUpper(addr), SSID: ssid})
  1890. }
  1891. }
  1892. for _, raw := range strings.Split(out, "\n") {
  1893. line := strings.TrimSpace(raw)
  1894. fields := strings.Fields(line)
  1895. if len(fields) >= 2 && fields[0] == "Interface" {
  1896. flush()
  1897. iface, addr, ssid, ifType = fields[1], "", "", ""
  1898. continue
  1899. }
  1900. if len(fields) >= 2 && fields[0] == "addr" {
  1901. addr = fields[1]
  1902. continue
  1903. }
  1904. if len(fields) >= 2 && fields[0] == "ssid" {
  1905. ssid = strings.TrimSpace(strings.TrimPrefix(line, "ssid"))
  1906. continue
  1907. }
  1908. if len(fields) >= 2 && fields[0] == "type" {
  1909. ifType = fields[1]
  1910. continue
  1911. }
  1912. }
  1913. flush()
  1914. return res
  1915. }
  1916. // IwDevIfaces (#1338) lists EVERY interface of `iw dev` (any type, not only
  1917. // AP like ParseIwDev). Since #1560 the scan groups them by radio with
  1918. // ParseIwDevDetailed instead of scanning each one.
  1919. func IwDevIfaces(out string) []string {
  1920. var res []string
  1921. for _, i := range ParseIwDevDetailed(out) {
  1922. res = append(res, i.Iface)
  1923. }
  1924. return res
  1925. }
  1926. // FreqToChannel convierte frecuencia (MHz) a número de canal 802.11.
  1927. func FreqToChannel(freq int) int {
  1928. switch {
  1929. case freq >= 2412 && freq <= 2484:
  1930. if freq == 2484 {
  1931. return 14
  1932. }
  1933. return (freq-2412)/5 + 1
  1934. case freq >= 5180 && freq <= 5885:
  1935. // 5 GHz UNII-1/2/3: 36, 40, 44, ... 165
  1936. return (freq-5180)/5 + 36
  1937. case freq >= 5955 && freq <= 7115:
  1938. // 6 GHz: 1-229 (PSCO no se soporta en esta fase)
  1939. return (freq-5955)/5 + 1
  1940. }
  1941. return 0
  1942. }
  1943. var (
  1944. sfpTempRe = regexp.MustCompile(`(?i)Module temperature\s*:\s*(-?[\d.]+)`)
  1945. sfpVoltRe = regexp.MustCompile(`(?i)Module voltage\s*:\s*([\d.]+)`)
  1946. sfpTxPwrRe = regexp.MustCompile(`(?i)Laser output power\s*:.*?/\s*(-?[\d.]+)\s*dBm`)
  1947. sfpRxPwrRe = regexp.MustCompile(`(?i)Laser receiver power\s*:.*?/\s*(-?[\d.]+)\s*dBm`)
  1948. sfpVendorRe = regexp.MustCompile(`(?i)Vendor [Nn]ame\s*:\s*(.+)`)
  1949. sfpPNRe = regexp.MustCompile(`(?i)Vendor [Pp]art [Nn]umber\s*:\s*(.+)`)
  1950. )
  1951. // ParseEthtoolSFP parsea la salida de `ethtool -m <iface>` y extrae los
  1952. // valores DDM/DOM del módulo (#313). Devuelve nil si la salida está vacía o
  1953. // no contiene datos de SFP.
  1954. func ParseEthtoolSFP(out string) *SfpInfo {
  1955. if strings.TrimSpace(out) == "" {
  1956. return nil
  1957. }
  1958. info := &SfpInfo{}
  1959. if m := sfpTempRe.FindStringSubmatch(out); m != nil {
  1960. info.Temperature, _ = strconv.ParseFloat(m[1], 64)
  1961. info.Present = true
  1962. }
  1963. if m := sfpVoltRe.FindStringSubmatch(out); m != nil {
  1964. info.Voltage, _ = strconv.ParseFloat(m[1], 64)
  1965. }
  1966. if m := sfpTxPwrRe.FindStringSubmatch(out); m != nil {
  1967. info.TxPower, _ = strconv.ParseFloat(m[1], 64)
  1968. }
  1969. if m := sfpRxPwrRe.FindStringSubmatch(out); m != nil {
  1970. info.RxPower, _ = strconv.ParseFloat(m[1], 64)
  1971. }
  1972. if m := sfpVendorRe.FindStringSubmatch(out); m != nil {
  1973. info.Vendor = strings.TrimSpace(m[1])
  1974. }
  1975. if m := sfpPNRe.FindStringSubmatch(out); m != nil {
  1976. info.PartNumber = strings.TrimSpace(m[1])
  1977. }
  1978. if !info.Present {
  1979. return nil
  1980. }
  1981. return info
  1982. }
  1983. func round0(v float64) float64 { return float64(int64(v + 0.5)) }
  1984. func max0(v float64) float64 {
  1985. if v < 0 {
  1986. return 0
  1987. }
  1988. return v
  1989. }
  1990. // ParseMdnsHosts (#338): parses `ubus call umdns hosts` into IP -> hostname.
  1991. // The trailing ".local" is dropped: it is the mDNS suffix, not part of the
  1992. // name anyone recognises. Entries without an IPv4 are skipped.
  1993. func ParseMdnsHosts(raw []byte) map[string]string {
  1994. var hosts map[string]struct {
  1995. IPv4 string `json:"ipv4"`
  1996. }
  1997. out := map[string]string{}
  1998. if json.Unmarshal(raw, &hosts) != nil {
  1999. return out
  2000. }
  2001. for name, h := range hosts {
  2002. if h.IPv4 == "" {
  2003. continue
  2004. }
  2005. out[h.IPv4] = strings.TrimSuffix(name, ".local")
  2006. }
  2007. return out
  2008. }
  2009. // ParseMdnsBrowse (#338): parsea la salida de `ubus call umdns browse`.
  2010. // Formato típico (JSON):
  2011. //
  2012. // { "hostname._service._tcp.local": { "port": 1234, "txt": [...] }, ... }
  2013. //
  2014. // Extrae: hostname (de la clave, antes del primer punto) y tipos de servicio
  2015. // (el segmento _service._tcp). También recoge IPs si aparecen en registros A.
  2016. func ParseMdnsBrowse(raw []byte) *DiscoveryData {
  2017. if len(raw) == 0 {
  2018. return nil
  2019. }
  2020. // umdns browse devuelve un objeto JSON con claves "fqdn" y valores que
  2021. // contienen "port", "txt", "ipv4", etc. Parseamos como map genérico.
  2022. var browse map[string]json.RawMessage
  2023. if json.Unmarshal(raw, &browse) != nil {
  2024. return nil
  2025. }
  2026. if len(browse) == 0 {
  2027. return nil
  2028. }
  2029. dd := &DiscoveryData{
  2030. Services: map[string][]string{},
  2031. HostByIP: map[string]string{},
  2032. }
  2033. for fqdn, val := range browse {
  2034. // Extraer hostname: primera parte antes del "."
  2035. hostname := fqdn
  2036. if idx := strings.Index(fqdn, "."); idx > 0 {
  2037. hostname = fqdn[:idx]
  2038. }
  2039. // Extraer tipo de servicio: segundo segmento "_svc._tcp" o "_svc._udp"
  2040. parts := strings.SplitN(fqdn, ".", 3)
  2041. if len(parts) >= 2 && strings.HasPrefix(parts[1], "_") {
  2042. svcType := parts[1]
  2043. if len(parts) >= 3 {
  2044. svcType = parts[1] + "." + strings.SplitN(parts[2], ".", 2)[0]
  2045. }
  2046. dd.Services[hostname] = appendUnique(dd.Services[hostname], svcType)
  2047. }
  2048. // Extraer IP si disponible
  2049. var entry struct {
  2050. IPv4 string `json:"ipv4"`
  2051. }
  2052. if json.Unmarshal(val, &entry) == nil && entry.IPv4 != "" {
  2053. dd.HostByIP[entry.IPv4] = hostname
  2054. }
  2055. }
  2056. if len(dd.Services) == 0 && len(dd.HostByIP) == 0 {
  2057. return nil
  2058. }
  2059. return dd
  2060. }
  2061. func appendUnique(slice []string, s string) []string {
  2062. for _, x := range slice {
  2063. if x == s {
  2064. return slice
  2065. }
  2066. }
  2067. return append(slice, s)
  2068. }
  2069. // IsRandomizedMAC returns true if the MAC address has the locally-administered
  2070. // bit set (bit 1 of byte 0). Apple, Google, and Samsung use this for WiFi
  2071. // privacy features — the device appears as a new MAC periodically.
  2072. func IsRandomizedMAC(mac string) bool {
  2073. if len(mac) < 2 {
  2074. return false
  2075. }
  2076. // Byte 0: first two hex chars
  2077. b, err := parseHexByte(mac[0], mac[1])
  2078. if err != nil {
  2079. return false
  2080. }
  2081. return b&0x02 != 0
  2082. }
  2083. func parseHexByte(hi, lo byte) (byte, error) {
  2084. h, err := hexNibble(hi)
  2085. if err != nil {
  2086. return 0, err
  2087. }
  2088. l, err := hexNibble(lo)
  2089. if err != nil {
  2090. return 0, err
  2091. }
  2092. return h<<4 | l, nil
  2093. }
  2094. func hexNibble(c byte) (byte, error) {
  2095. switch {
  2096. case c >= '0' && c <= '9':
  2097. return c - '0', nil
  2098. case c >= 'a' && c <= 'f':
  2099. return c - 'a' + 10, nil
  2100. case c >= 'A' && c <= 'F':
  2101. return c - 'A' + 10, nil
  2102. default:
  2103. return 0, fmt.Errorf("invalid hex nibble: %c", c)
  2104. }
  2105. }
  2106. // ParseArp parsea /proc/net/arp (#377): cabecera + líneas
  2107. // "IP net/arp HW flags MAC mask device". Devuelve MAC (upper) → IP,
  2108. // ignorando entradas incompletas (flags 0x0) y MACs nulas.
  2109. func ParseArp(out string) map[string]string {
  2110. m := map[string]string{}
  2111. for _, line := range strings.Split(out, "\n") {
  2112. f := strings.Fields(line)
  2113. if len(f) < 4 || f[0] == "IP" {
  2114. continue
  2115. }
  2116. mac := strings.ToUpper(f[3])
  2117. if mac == "" || mac == "00:00:00:00:00:00" {
  2118. continue
  2119. }
  2120. // flags 0x0 = incomplete: el kernel retiene la IP sin vecino válido.
  2121. if f[2] == "0x0" {
  2122. continue
  2123. }
  2124. if net.ParseIP(f[0]) == nil {
  2125. continue
  2126. }
  2127. m[mac] = f[0]
  2128. }
  2129. return m
  2130. }
  2131. // neighConfirmed: the states in which the kernel vouches for the neighbour
  2132. // being there right now. REACHABLE was confirmed within the reachable time;
  2133. // DELAY and PROBE are on their way to being reconfirmed; PERMANENT and NOARP
  2134. // were put there by hand or by a link that needs no resolution.
  2135. //
  2136. // Everything else -- STALE, FAILED, INCOMPLETE, NONE -- is an address the
  2137. // kernel remembers without being able to say the host is still connected.
  2138. var neighConfirmed = map[string]bool{
  2139. "REACHABLE": true, "DELAY": true, "PROBE": true,
  2140. "PERMANENT": true, "NOARP": true,
  2141. }
  2142. // ParseIPNeigh parses `ip neigh show`, whose lines read
  2143. // "IP dev IFACE lladdr MAC STATE" (an entry being resolved has no lladdr).
  2144. // It returns the same MAC→IP map as ParseArp plus the set of MACs whose
  2145. // every entry is unconfirmed: remembered addresses, not present hosts.
  2146. //
  2147. // A MAC with several addresses counts as confirmed when any one of them is,
  2148. // since one confirmed neighbour is enough to prove the host is there.
  2149. func ParseIPNeigh(out string) (arp map[string]string, stale map[string]bool) {
  2150. arp, stale = map[string]string{}, map[string]bool{}
  2151. confirmed := map[string]bool{}
  2152. for _, line := range strings.Split(out, "\n") {
  2153. f := strings.Fields(line)
  2154. // "IP dev IFACE lladdr MAC STATE" is the shortest useful line.
  2155. if len(f) < 6 || net.ParseIP(f[0]) == nil {
  2156. continue
  2157. }
  2158. var mac string
  2159. for i := 1; i+1 < len(f); i++ {
  2160. if f[i] == "lladdr" {
  2161. mac = strings.ToUpper(f[i+1])
  2162. break
  2163. }
  2164. }
  2165. if mac == "" || mac == "00:00:00:00:00:00" {
  2166. continue
  2167. }
  2168. // The state is the last word of the line; an entry without one is
  2169. // not something to claim presence from.
  2170. if neighConfirmed[f[len(f)-1]] {
  2171. // Confirmed wins for good: a later unconfirmed address for the
  2172. // same host must not undo it.
  2173. arp[mac] = f[0]
  2174. confirmed[mac] = true
  2175. delete(stale, mac)
  2176. continue
  2177. }
  2178. if !confirmed[mac] {
  2179. if _, ok := arp[mac]; !ok {
  2180. arp[mac] = f[0]
  2181. }
  2182. stale[mac] = true
  2183. }
  2184. }
  2185. return arp, stale
  2186. }
  2187. // ParseIPNeighDevs devuelve MAC -> interfaz de `ip neigh show` (#1485). Solo
  2188. // entradas confirmadas, con la misma regla que ParseIPNeigh: una entrada STALE
  2189. // no prueba presencia y su interfaz tampoco sirve para atribuir el lado WAN.
  2190. func ParseIPNeighDevs(out string) map[string]string {
  2191. devs := map[string]string{}
  2192. for _, line := range strings.Split(out, "\n") {
  2193. f := strings.Fields(line)
  2194. if len(f) < 6 || net.ParseIP(f[0]) == nil {
  2195. continue
  2196. }
  2197. var mac, dev string
  2198. for i := 1; i+1 < len(f); i++ {
  2199. switch f[i] {
  2200. case "lladdr":
  2201. mac = strings.ToUpper(f[i+1])
  2202. case "dev":
  2203. dev = f[i+1]
  2204. }
  2205. }
  2206. if mac == "" || mac == "00:00:00:00:00:00" || dev == "" {
  2207. continue
  2208. }
  2209. if !neighConfirmed[f[len(f)-1]] {
  2210. continue
  2211. }
  2212. devs[mac] = dev
  2213. }
  2214. return devs
  2215. }
  2216. // ParseArpDevs devuelve MAC -> interfaz de /proc/net/arp (#1485), con el mismo
  2217. // filtro de entradas incompletas que ParseArp. Es el fallback cuando el equipo
  2218. // no tiene `ip`.
  2219. func ParseArpDevs(out string) map[string]string {
  2220. devs := map[string]string{}
  2221. for _, line := range strings.Split(out, "\n") {
  2222. f := strings.Fields(line)
  2223. if len(f) < 6 || f[0] == "IP" {
  2224. continue
  2225. }
  2226. mac := strings.ToUpper(f[3])
  2227. if mac == "" || mac == "00:00:00:00:00:00" || f[2] == "0x0" || net.ParseIP(f[0]) == nil {
  2228. continue
  2229. }
  2230. devs[mac] = f[5]
  2231. }
  2232. return devs
  2233. }
  2234. // sumProcRSS returns the total VmRSS (bytes) of every user-space process
  2235. // (/proc/<pid>/status): the memory actually held by processes, excluding the
  2236. // kernel page cache that inflates (total-available) on ubifs/overlay routers.
  2237. func sumProcRSS() float64 {
  2238. entries, err := os.ReadDir("/proc")
  2239. if err != nil {
  2240. return 0
  2241. }
  2242. var total float64
  2243. for _, e := range entries {
  2244. if !allDigits(e.Name()) {
  2245. continue
  2246. }
  2247. b, err := os.ReadFile("/proc/" + e.Name() + "/status")
  2248. if err != nil {
  2249. continue
  2250. }
  2251. for _, line := range strings.Split(string(b), "\n") {
  2252. if !strings.HasPrefix(line, "VmRSS:") {
  2253. continue
  2254. }
  2255. f := strings.Fields(line)
  2256. if len(f) >= 2 {
  2257. if v, err := strconv.ParseFloat(f[1], 64); err == nil {
  2258. total += v * 1024
  2259. }
  2260. }
  2261. break
  2262. }
  2263. }
  2264. return total
  2265. }
  2266. func allDigits(s string) bool {
  2267. for _, r := range s {
  2268. if r < '0' || r > '9' {
  2269. return false
  2270. }
  2271. }
  2272. return s != ""
  2273. }
  2274. // ParseUciBridgeVlans reads the bridge VLANs out of `uci show network`.
  2275. //
  2276. // `bridge vlan show` is the truth, but its binary is part of an optional
  2277. // package and plenty of routers do not carry it — including ones with VLANs
  2278. // configured, where the panel then shows nothing at all. The declared
  2279. // configuration is the next best answer: it is what the router was told to
  2280. // do, and on a healthy box it is what the kernel is doing.
  2281. //
  2282. // A bridge-vlan section names a device, a VLAN id and its ports, each port
  2283. // written "<port>[:u|:t][*]": ":t" tagged, ":u" untagged, a trailing "*"
  2284. // marking the port's own ingress VLAN.
  2285. func ParseUciBridgeVlans(out string) []VlanPort {
  2286. type section struct {
  2287. vlan int
  2288. ports []string
  2289. }
  2290. sections := map[string]*section{}
  2291. order := []string{}
  2292. for _, line := range strings.Split(out, "\n") {
  2293. line = strings.TrimSpace(line)
  2294. if !strings.HasPrefix(line, "network.") {
  2295. continue
  2296. }
  2297. key, val, ok := strings.Cut(strings.TrimPrefix(line, "network."), "=")
  2298. if !ok {
  2299. continue
  2300. }
  2301. val = strings.Trim(val, "'")
  2302. name, attr, isAttr := strings.Cut(key, ".")
  2303. if !isAttr {
  2304. if val == "bridge-vlan" {
  2305. if _, seen := sections[name]; !seen {
  2306. sections[name] = &section{}
  2307. order = append(order, name)
  2308. }
  2309. }
  2310. continue
  2311. }
  2312. sec, ok := sections[name]
  2313. if !ok {
  2314. continue
  2315. }
  2316. switch attr {
  2317. case "vlan":
  2318. if id, err := strconv.Atoi(val); err == nil {
  2319. sec.vlan = id
  2320. }
  2321. case "ports":
  2322. // A list option prints all its values on one line, each in
  2323. // its own quotes.
  2324. for _, part := range strings.Split(val, "' '") {
  2325. if p := strings.TrimSpace(strings.Trim(part, "'")); p != "" {
  2326. sec.ports = append(sec.ports, p)
  2327. }
  2328. }
  2329. }
  2330. }
  2331. // Group by port, the way `bridge vlan show` reports it: the panel is a
  2332. // list of ports, each with the VLANs it carries.
  2333. byPort := map[string][]VlanEntry{}
  2334. portOrder := []string{}
  2335. for _, name := range order {
  2336. sec := sections[name]
  2337. if sec.vlan < 1 || sec.vlan > 4094 {
  2338. continue
  2339. }
  2340. for _, raw := range sec.ports {
  2341. port, entry := parseUciVlanPort(raw, sec.vlan)
  2342. if port == "" {
  2343. continue
  2344. }
  2345. if _, seen := byPort[port]; !seen {
  2346. portOrder = append(portOrder, port)
  2347. }
  2348. byPort[port] = append(byPort[port], entry)
  2349. }
  2350. }
  2351. out2 := make([]VlanPort, 0, len(portOrder))
  2352. for _, port := range portOrder {
  2353. out2 = append(out2, VlanPort{Port: port, Vlans: byPort[port]})
  2354. }
  2355. return out2
  2356. }
  2357. // parseUciVlanPort splits one "<port>[:u|:t][*]" entry.
  2358. func parseUciVlanPort(raw string, vlan int) (string, VlanEntry) {
  2359. name := raw
  2360. entry := VlanEntry{ID: vlan}
  2361. if strings.HasSuffix(name, "*") {
  2362. entry.PVID = true
  2363. name = strings.TrimSuffix(name, "*")
  2364. }
  2365. switch {
  2366. case strings.HasSuffix(name, ":t"):
  2367. entry.Tagged = true
  2368. name = strings.TrimSuffix(name, ":t")
  2369. case strings.HasSuffix(name, ":u"):
  2370. name = strings.TrimSuffix(name, ":u")
  2371. }
  2372. return name, entry
  2373. }