probe.go 93 KB

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