probe.go 91 KB

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