probe.go 85 KB

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