// Package probe — sondas del tier rápido OpenWrt: comandos (los LITERALES que // internal/adapters/openwrt.go lanza por SSH) + parseo de sus salidas + // shapes JSON del payload que el agente empuja a POST /api/ingest/agent. // // Es la ÚNICA fuente de verdad del parseo: server-go (internal/adapters) lo // importa con un replace ../agent, y el binario netpulse-agent ejecuta los // mismos comandos localmente. Solo stdlib (el binario del agente tiene // objetivo ≤ 3 MB y CGO_ENABLED=0). package probe import ( "encoding/json" "fmt" "net" "os" "regexp" "sort" "strconv" "strings" "time" "github.com/gnacho/netpulse/agent/macaddr" ) // --------------------------------------------------------------------------- // Comandos (idénticos a los del sondeo SSH de openwrt.go) // --------------------------------------------------------------------------- const ( CmdProcStat = "grep '^cpu ' /proc/stat" // CmdProcUptime (#1481): fallback portable de uptime cuando no hay ubus // (Asuswrt, Linux genérico). Primer campo = segundos desde boot. CmdProcUptime = "cat /proc/uptime 2>/dev/null" // CmdTemp (#1484): temperatura de la CPU. En x86 la thermal_zone0 suele ser // acpitz (ambiente ACPI), así que se elige por `type` con prioridad y la // primera zona legible queda solo como fallback (ARM/SBC: cpu-thermal). // Último recurso (#1500): hwmon para equipos SIN thermal zones (Synology // DSM: k10temp en /sys/class/hwmon, cero zones). Con zones presentes // mandan las zones: una sola fuente por equipo (#1484). 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"` CmdNetDev = "cat /proc/net/dev | tail -n +3" // CmdPingWan: latencia + pérdida a internet (solo gateway). %s = target. CmdPingWan = "ping -c 3 -W 2 %s 2>/dev/null | tail -2" // CmdPingGateway: ping corto al gateway desde un AP. %s = host gateway. CmdPingGateway = "ping -c 2 -W 2 %s 2>/dev/null | tail -1" CmdDhcpUbus = "ubus call dhcp ipv4leases" // CmdDhcpReservations: the `config host` entries of /etc/config/dhcp. A // device with a fixed address set on the device itself never asks for a // lease, so the name the admin pinned here is the only one the router // has for it. Lines for other sections come through too; the parser // keeps only the ones it saw declared as host. CmdDhcpReservations = `uci -q show dhcp 2>/dev/null | grep -E "=host$|\.(mac|name|ip)=" || true` // CmdDhcpFile: cat del fichero de leases de dnsmasq. Resuelve la ubicación // real vía UCI (dhcp.@dnsmasq[0].leasefile), porque puede NO ser la // standard /tmp/dhcp.leases (p. ej. en un SSD montado, #568); si el valor // UCI no existe o está vacío, cae a /tmp/dhcp.leases. Busybox: test -n y // comillas simples para $f. CmdDhcpFile = `f=$(uci -q get dhcp.@dnsmasq[0].leasefile 2>/dev/null); [ -n "$f" ] || f=/tmp/dhcp.leases; cat "$f" 2>/dev/null || true` // CmdGlClients (GL.iNet): base de clientes completa del firmware. Es un // SUPERSET de dhcp.leases: incluye equipos con IP estática o sin lease // DHCP que el dnsmasq del Flint2 no lista (issue #5 bug 1). CmdGlClients = "ubus call gl-clients list 2>/dev/null || true" // CmdIwinfoAssoc: " " por cliente wifi asociado. CmdIwinfoAssoc = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` + `freq=$(iwinfo "$i" info 2>/dev/null | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` + `iwinfo "$i" assoclist 2>/dev/null | sed -n 's/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/\1 \2/p' | while read mac sig; do ` + `echo "$mac $sig $freq"; done; done` // CmdHostapdClients (#368): clientes por AP vía ubus (una llamada por AP, // binario pequeñísimo, sin ucode ni libiwinfo). Emite "==AP==" antes // del JSON multi-línea de cada get_clients; el parser de Go trocea por la // marca. Mucho más barato que iwinfo en CPUs justas (MT7621: el ucode de // iwinfo quemaba 25% de CPU con churn de roaming). CmdHostapdClients = `for o in $(ubus list 'hostapd.*' 2>/dev/null); do ` + `echo "==AP==$o"; ubus call "$o" get_clients 2>/dev/null; done; ` + // #1757: SSID por interfaz AP. `ubus call get_clients` no lo trae y el // objeto ubus solo da el nombre de la interfaz (phy1-ap2), que es lo // que necesita la VLAN; el SSID lo pone la ficha del cliente. `echo "==SSID=="; iw dev 2>/dev/null | awk '/^[ \t]*Interface /{i=$2} /^[ \t]*ssid /{print i, $2}'` // CmdWirelessCombined (#368): iwinfo en UNA pasada por interfaz (info una // vez + assoclist una vez) emitiendo clientes y resumen de radio juntos. // Sustituye a CmdIwinfoAssoc+CmdRadios cuando ubus no está: la mitad de // spawns. Líneas "C|mac|sig|freq" (clientes) y // "R|freq|ch|ht|tx|bssid|noise|n" (radio; #1213). CmdWirelessCombined = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` + `info=$(iwinfo "$i" info 2>/dev/null) || continue; ` + `echo "$info" | grep -q ESSID || continue; ` + `freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` + `ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); ` + `ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); ` + `tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); ` + `bssid=$(echo "$info" | sed -n 's/.*Access Point: \([0-9A-Fa-f:]\{17\}\).*/\1/p' | head -1); ` + `noise=$(echo "$info" | sed -n 's/.*Noise: \(-\{0,1\}[0-9][0-9]*\).*/\1/p' | head -1); ` + `al=$(iwinfo "$i" assoclist 2>/dev/null); ` + `n=$(echo "$al" | grep -c '^[0-9A-Fa-f:]'); ` + `echo "R|$freq|$ch|$ht|$tx|$bssid|$noise|$n"; ` + `echo "$al" | sed -n "s/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/C|\1|\2|$freq/p"; done` // CmdRadios: "freq|ch|ht|tx|bssid|noise|n" por radio (se agrega por banda // al parsear). #1213: bssid + noise de iwinfo info. CmdRadios = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` + `info=$(iwinfo "$i" info 2>/dev/null) || continue; ` + `echo "$info" | grep -q ESSID || continue; ` + `freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` + `ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); ` + `ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); ` + `tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); ` + `bssid=$(echo "$info" | sed -n 's/.*Access Point: \([0-9A-Fa-f:]\{17\}\).*/\1/p' | head -1); ` + `noise=$(echo "$info" | sed -n 's/.*Noise: \(-\{0,1\}[0-9][0-9]*\).*/\1/p' | head -1); ` + `n=$(iwinfo "$i" assoclist 2>/dev/null | grep -c '^[0-9A-Fa-f:]'); ` + `echo "$freq|$ch|$ht|$tx|$bssid|$noise|$n"; done` // CmdScan (#452): scan pasivo de vecinos con `iw dev`. Lista interfaces, // emite "==IFACE==" antes de cada scan y parsea BSS/freq/signal/SSID. // Si `iw` no está disponible, la sección Scans queda vacía (best-effort). // // DEPRECATED (#1338): el bucle monolítico corría con UN solo timeout para // todas las interfaces y, al expirar, la salida parcial se descartaba // entera. Una radio lenta (5 GHz en canal DFS, scan pasivo canal a canal) // dejaba la unidad sin NINGÚN vecino, aunque las demás interfaces sí // hubieran escaneado. El agente escanea ahora por interfaz con // CmdScanIface, cada una con su propio presupuesto. Se conserva la // constante por compatibilidad del módulo (consumidores vendorizados). 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` // CmdSurvey (#1214): `iw dev survey dump` por interfaz, con el // mismo marcador "==IFACE==" que CmdScan. El server parsea el texto // crudo con su parser existente: alimenta la lente "Ahora" (ocupación // por canal en vivo) en unidades agent-only sin SSH. Barato: no saca // la radio del canal. 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` // CmdIwDev (#1087): `iw dev` a secas, sin scan. Lista las interfaces con // su MAC y SSID: fuente de los BSSIDs propios para el análisis de // canales. Barato (no saca la radio del canal). CmdIwDev = "iw dev 2>/dev/null" // scanIfaceTimeout (#1338): presupuesto POR INTERFAZ del scan de vecinos. // Una radio 5 GHz en canal DFS escanea en pasivo canal a canal y puede // tardar varios segundos; con el presupuesto único de 10 s para todas, // esa radio lenta mataba el bucle y se perdían también los scans ya // hechos. Cada interfaz tiene ahora su propio tiempo y un fallo o un // cuelgue solo vacía su propia sección. scanIfaceTimeout = 8 * time.Second // maxScanFallbacks (#1839): reintentos por radio cuando la interfaz // elegida rechaza el scan. Dos basta para cubrir AP + managed + una // tercera, y acota el peor caso (3 x 8 s por radio). maxScanFallbacks = 2 // CmdRadioSections (#500): secciones wifi-device de UCI con su banda, para // resolver "2.4 GHz" → radio0 (la relación iface→sección no sale de iwinfo). CmdRadioSections = `uci -q show wireless 2>/dev/null | grep -E "=wifi-device$|\.band=|\.hwmode="` // CmdUciWireless (#1450): volcado crudo de la configuración wireless, tal // cual lo emite `uci show wireless`. El server lo parsea con su // parseUciWireless (vista 802.11r) en unidades agent-only sin SSH: el // parser NO se duplica en el agente, igual que con CmdSurvey (#1214). // Solo lectura de /etc/config/wireless, barato (unos pocos KB). // // Los campos de SECRETO se descartan antes de enviarlo: a diferencia del // camino SSH (que los lee y los tira en el server), este volcado viaja en // cada push y queda persistido en kv agent.state.. El parser 802.11r // no usa la PSK, así que filtrarla no quita información a la vista. CmdUciWireless = `uci -q show wireless 2>/dev/null | ` + uciWirelessSecretsFilter // uciWirelessSecretsFilter: líneas `option` con secretos fuera del push // (key/PSK/SAE/contraseñas/RADIUS). Se conserva el resto del volcado tal // cual. Busybox grep -E soporta la alternancia. uciWirelessSecretsFilter = `grep -v -E '\.(key|sae_key|wpa_psk|psk|password|secret|radius_secret)='` // CmdPortStates: " " por // interfaz. // - dsa: "dsa" cuando la interfaz es un conduit DSA (tiene el directorio // /sys/class/net//dsa): el puerto CPU interno del switch, no una // boca usable (#847); "-" si no. // - type: el ARPHRD del kernel (1 = ethernet). FORK: para no tomar por // boca un uplink que no lo es (wwan0 de un módem celular). // - conduit: FORK. La interfaz inferior (lower_*) cuando la hay: en un // switch DSA las bocas cuelgan de la interfaz de CPU (lan1/lan2 → // lower_eth0). "-" cuando no hay ninguna. // Los campos a partir del tercero son opcionales para ParsePortStates. CmdPortStates = `for d in /sys/class/net/*; do i=$(basename "$d"); ` + `o=$(cat "$d/operstate" 2>/dev/null || echo unknown); ` + `s=$(cat "$d/speed" 2>/dev/null || echo -1); ` + `x=$([ -d "$d/dsa" ] && echo dsa || echo -); ` + `t=$(cat "$d/type" 2>/dev/null || echo -1); ` + `c=-; for l in "$d"/lower_*; do [ -e "$l" ] || continue; c=${l##*/lower_}; break; done; ` + `echo "$i $o $s $x $t $c"; done` // CmdProcArp (#377): tabla ARP del kernel, "IP dev mac ..." por línea. CmdProcArp = "cat /proc/net/arp 2>/dev/null" // CmdIpNeigh: the same neighbour table, but with the state of each entry, // which /proc/net/arp cannot express -- its flags say ATF_COM for // REACHABLE and for STALE alike. A STALE neighbour is one the kernel has // not confirmed since the device last spoke, and it survives long after // the device is gone, so treating it as presence draws hosts that are no // longer there. Falls back to /proc/net/arp when `ip` is missing. CmdIpNeigh = "ip -4 neigh show 2>/dev/null" // CmdIpNeigh6: la tabla de vecinos IPv6 (NDP). Misma forma que la v4, con // direcciones fe80:: scoped a la interfaz (#2109). CmdIpNeigh6 = "ip -6 neigh show 2>/dev/null" CmdBoardJSON = "cat /etc/board.json 2>/dev/null" // bridgeDetect: resuelve el nombre del bridge LAN en el router: br-lan, // br0, o el primer bridge real presente en /sys/class/net (#1435: en // switches OpenWrt con el bridge renombrado, p.ej. "switch", los dos // candidatos clásicos no existen y la FDB salía vacía). Si no hay // bridge, BR queda vacío y los comandos fallan en suave (mismo // comportamiento que antes en equipos sin bridge). 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; }; ` CmdBrifMembers = bridgeDetect + `ls /sys/class/net/$BR/brif/ 2>/dev/null` // CmdBridgeFDB: no asume `brctl`: prueba brctl y, si no existe o no aporta, // `bridge fdb show` (OpenWrt/GLuON modernos usan iproute2). Issue #253. // SIN `command -v`: el ash de busybox en Merlin/Asuswrt NO tiene el builtin // `command` ("sh: command: not found"), así que la guarda antigua // `if command -v brctl` fallaba siempre y caía al branch de `bridge`, que // allí no existe: la sección MACS salía vacía y el server se quedaba sin // FDB del AP (todos sus clientes cableados se atribuían al gateway o al // switch de arriba). Ahora se intentan ambas vías en subshells con stderr // suprimido; si las dos existen las líneas duplicadas son inofensivas // (ambas resuelven al mismo ifname en ParseBridgeFdb). El `true` final // garantiza exit 0 para que el runner no descarte la salida. // La vía bridge excluye las entradas LOCALES (flag "permanent": la MAC del // propio bridge registrada en cada puerto) para paridad con brctl ($3=="no" // allí); sin esto el server ve la MAC propia aprendida en el puerto y lo // clasifica como uplink, descartando TODOS sus clientes cableados (#506). // // CmdBridgeFDB: "==PORTS==" (port_no ifname) + "==MACS==" // (port mac [vlan]). El sufijo con el nombre del bridge es el que permite // leer TODOS los bridges sin mezclar sus tablas de puertos (cada bridge // numera sus puertos desde 1) y es opcional al parsear, así que la salida // antigua de un agente viejo sigue valiendo (#1757). // // Antes se leía UN solo bridge (br-lan, br0 o el primero). Un router que // segmenta con subinterfaces 802.1Q tiene un bridge POR segmento: los // clientes de br-iot/br-guest no aparecían en ninguna tabla y el mapa los // pintaba sin puerto y sin VLAN. // // El tercer campo de MACS es el `vlan ` que `bridge fdb show` imprime // en bridges con VLAN filtering: es la VLAN REAL del cliente, no el PVID // del puerto por el que entró. CmdBridgeFDB = `echo "==PORTS=="; for d in /sys/class/net/*; do [ -d "$d/bridge" ] || continue; ` + `br=$(basename "$d"); echo "==PORTS==$br"; ` + `for b in "$d"/brif/*; do [ -r "$b/port_no" ] && echo "$(cat $b/port_no) $(basename $b)"; done; done; ` + `echo "==MACS=="; for d in /sys/class/net/*; do [ -d "$d/bridge" ] || continue; ` + `br=$(basename "$d"); echo "==MACS==$br"; ` + `(brctl showmacs "$br" 2>/dev/null | awk 'NR>1 && $3=="no" {print $1, $2}') 2>/dev/null; ` + `(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` CmdBridgeMAC = bridgeDetect + "cat /sys/class/net/$BR/address 2>/dev/null" // CmdIfaceMACs (#1765): "iface mac" de TODAS las interfaces del kernel. // Un equipo responde por la MAC del bridge, la de cada VLAN, la del puerto // CPU de un switch DSA y la de cada radio. Las que no son la MAC del router // guardado en la flota se aprenden en la FDB de un vecino y salían como // clientes desconocidos sin nombre ni IP. El equipo es la única fuente // fiable de su propia lista. CmdIfaceMACs = `for d in /sys/class/net/*; do i=$(basename "$d"); ` + `[ -r "$d/address" ] && echo "$i $(cat "$d/address" 2>/dev/null)"; done` CmdUbusSystemBoard = "ubus call system board" CmdUbusSystemInfo = "ubus call system info" CmdUbusWireless = "ubus call network.wireless status" // CmdLuCILabels: etiquetas de puertos/VLANs de LuCI (issue #258). OpenWrt // snapshots añaden `config switchvlan 'port_labels'` y `'vlan_labels'` en // /etc/config/luci con nombres amigables para la topología. Se lee el // fichero crudo (uci show luci sería más ruidoso: todo el paquete). CmdLuCILabels = "cat /etc/config/luci 2>/dev/null" // CmdWanStatus: estado de la interfaz WAN (solo gateway) vía ubus. // Da proto ("pppoe"), IP, gateway (ptpaddress/nexthop) y DNS (issue #276). CmdWanStatus = "ubus call network.interface.wan status 2>/dev/null || true" // CmdNetworkDump: estado de TODAS las interfaces, para elegir el uplink // por la ruta por defecto en vez de por el nombre "wan" (ver pickUplink) // y saber por qué boca sale internet. CmdNetworkDump = "ubus call network.interface dump 2>/dev/null || true" CmdBridgeVlan = "bridge vlan show 2>/dev/null || true" // CmdUciBridgeVlan: the VLANs as configured, for the routers whose // firmware carries no `bridge` binary (an optional package, absent on // plenty of boards that do use VLANs) and for the ones that segment // with 802.1Q subinterfaces, which the kernel reports all on VLAN 1 // (#1757). Both models are read from `uci show network`. // // The section type lines must survive the filter (#1936): `uci show` // prints `network.lan=interface`, and that is the only place a named // section says what it is. Without it ParseUciNetworks sees no // interface at all and the networks view stays empty on every unit. CmdUciBridgeVlan = `uci -q show network 2>/dev/null | grep -E "=bridge-vlan$|=device$|=interface$|\.(device|vlan|ports|type|name|proto|ipaddr|netmask)=" || true` // CmdMdnsBrowse (#338): mDNS service discovery via umdns (OpenWrt's // lightweight mDNS daemon). Returns JSON with hostname -> services. // Falls back to empty if umdns is not installed. CmdMdnsBrowse = "ubus call umdns browse 2>/dev/null || echo '{}'" // CmdMdnsHosts (#338): the plain host records umdns has learned, as // ".local" -> {ipv4, ipv6}. browse only lists hosts that advertise // a SERVICE; a device that just announces its name (most laptops and // phones) appears here and nowhere else, and this is the map that names // a client with no DHCP hostname. CmdMdnsHosts = "ubus call umdns hosts 2>/dev/null || echo '{}'" CmdEthtoolSFP = "ethtool -m %s 2>/dev/null || true" ) // CmdScanIface (#1338): scan pasivo de UNA interfaz. El agente lo lanza una // vez por interfaz de `iw dev` (en vez del bucle monolítico de CmdScan) para // que cada radio tenga su propio presupuesto de tiempo y una interfaz lenta // o colgada no se lleve por delante los resultados de las demás. func CmdScanIface(iface string) string { return `iw dev "` + iface + `" scan 2>/dev/null` } // --------------------------------------------------------------------------- // Shapes parseados (salida de las sondas; contrato del payload del agente) // --------------------------------------------------------------------------- // SysInfo: ubus system info (uptime, memoria, load). type SysInfo struct { Uptime float64 `json:"uptime"` Load []float64 `json:"load"` // Timezone (#1500): nombre IANA ("Asia/Shanghai") que el agente lee de // /etc/localtime (o /etc/timezone, /etc/TZ). ubus nunca lo da, así que // sin este campo la ficha mostraba "—" incluso en equipos con ubus. Timezone string `json:"timezone,omitempty"` Memory struct { Total float64 `json:"total"` Free float64 `json:"free"` Buffered float64 `json:"buffered"` Available float64 `json:"available"` Cached float64 `json:"cached,omitempty"` // cache de ficheros, la rellena el agente (ubus no lo da) Used float64 `json:"used"` // suma de VmRSS de procesos (#513) } `json:"memory"` } // BoardInfo: ubus system board (metadatos estáticos). type BoardInfo struct { Model string `json:"model"` Hostname string `json:"hostname"` System string `json:"system"` // BoardName es el board_name de ubus ("redmi,ax6"): el identificador // que casa con los perfiles de ASU (#477). BoardName string `json:"board_name"` Release struct { Version string `json:"version"` Description string `json:"description"` // Target es el DISTRIB_TARGET ("qualcommax/ipq807x"), lo que ASU // necesita junto al board_name para localizar la imagen (#477). Target string `json:"target"` } `json:"release"` } // WanInfo: datos de la conexión WAN (issue #276). Solo el gateway lo rellena; // los campos vacíos significan "sin datos WAN" (APs/desconocido). type WanInfo struct { Proto string `json:"proto,omitempty"` // "pppoe"|"dhcp"|"static"... Device string `json:"device,omitempty"` // interfaz L3 (p.ej. "pppoe-wan") IP string `json:"ip,omitempty"` // dirección IPv4 pública Gateway string `json:"gateway,omitempty"` // puerta de enlace (nexthop/ptpaddress) DNS []string `json:"dns,omitempty"` // servidores DNS // Port es la interfaz por debajo del protocolo: la boca por la que sale // internet ("lan1" para un PPPoE sobre esa boca, "eth1.20" con VLAN). // Vacía cuando el uplink no pasa por ninguna (módem celular). Port string `json:"port,omitempty"` } // DhcpReservation is one `config host` of /etc/config/dhcp: the name and // address pinned to a MAC (both optional). MAC uppercase, like DhcpLease. type DhcpReservation struct { MAC string `json:"mac"` Name string `json:"name,omitempty"` IP string `json:"ip,omitempty"` } // DhcpLease es {mac, ip, hostname} (mac en mayúsculas) + señales de huella // DHCP (vendor class y client-id) y expiración del lease cuando se dispone. type DhcpLease struct { MAC string `json:"mac"` IP string `json:"ip"` Hostname string `json:"hostname"` VendorClass string `json:"vendorClass,omitempty"` ClientID string `json:"clientId,omitempty"` LeaseExpiresAt *int64 `json:"leaseExpiresAt,omitempty"` // Unix segundos; nil si no se conoce } // WirelessClient es {signalDbm, band} por MAC + contadores de tráfico de la // estación cuando el driver los expone (#551). RxBytes/TxBytes son contadores // ACUMULADOS desde que la estación se asoció (ubus hostapd get_clients → // hostapd_drv_read_sta_data); el server calcula el delta entre muestras para // obtener bytes del intervalo. omitempty: ausentes si la fuente no los da // (iwinfo, drivers sin read_sta_data). type WirelessClient struct { SignalDbm int `json:"signalDbm"` Band string `json:"band"` RxBytes uint64 `json:"rxBytes,omitempty"` TxBytes uint64 `json:"txBytes,omitempty"` // Iface/SSID (#1757): interfaz AP y SSID con la que la estacion esta // asociada. Permiten al servidor cruzar la estacion con el bridge VLAN // filtering y saber en que segmento vive. Omitidos cuando la fuente no // los expone (wl, iwinfo, drivers sin esa salida): el campo es opcional. Iface string `json:"iface,omitempty"` SSID string `json:"ssid,omitempty"` } // PortState es {name, up, speed} de una interfaz (/sys operstate+speed). type PortState struct { Name string `json:"name"` Up bool `json:"up"` // Oper is the raw sysfs operstate (up/down/dormant/unknown/...). Kept so // the panel can tell a real port (up, or down when unplugged) from a // Broadcom internal ghost interface that never carries user traffic // (dormant/unknown) and must not be shown as a usable port. Oper string `json:"oper,omitempty"` Speed string `json:"speed"` // "1 Gbps" | "2.5 Gbps" | "100 Mbps" | "—" // DSA: la interfaz es un conduit DSA (puerto CPU interno del switch, // /sys/class/net//dsa presente). No es una boca usable: se excluye // de los puertos del panel (#847). DSA bool `json:"dsa,omitempty"` // Type es el ARPHRD de /sys/class/net//type: 1 = ethernet. 0 o // negativo = desconocido (salida antigua), y entonces no se descarta // nada por el tipo. FORK. Type int `json:"type,omitempty"` // Conduit es la interfaz inferior (lower_*), vacío si no hay. En un // switch DSA es el puerto de CPU del que cuelga la boca. FORK. Conduit string `json:"conduit,omitempty"` } // fmtSpeedMbps (#847) formatea la velocidad de enlace: Gbps con decimales // cuando no es múltiplo de 1000 (2500 → "2.5 Gbps"; antes truncaba a // entero y mentía "2 Gbps") y Mbps en otro caso. func fmtSpeedMbps(mbps int) string { if mbps >= 1000 { if mbps%1000 == 0 { return strconv.Itoa(mbps/1000) + " Gbps" } return strconv.FormatFloat(float64(mbps)/1000, 'f', 1, 64) + " Gbps" } return strconv.Itoa(mbps) + " Mbps" } // ARPHRDEther es el /sys/class/net//type de una interfaz ethernet. const ARPHRDEther = 1 // PortLayout es una boca del layout canónico (/etc/board.json). type PortLayout struct { ID string `json:"id"` Name string `json:"name"` Label string `json:"label"` Role string `json:"role"` // "lan" | "wan" } // EthPort es una boca ethernet lista para el detalle ({id, label, up, speed?} // + contadores por puerto #305: iface física, bytes/errores acumulados y // rates instantáneos; omitempty para no engordar el contrato viejo). type EthPort struct { ID string `json:"id"` Label string `json:"label"` Up bool `json:"up"` Speed string `json:"speed,omitempty"` // solo si up // Iface física de la boca (/proc/net/dev); puede diferir del id en // plataformas swconfig ("1" vs "eth0.1"). Iface string `json:"iface,omitempty"` // Contadores acumulados de la iface (issue #305). RxBytes uint64 `json:"rxBytes,omitempty"` TxBytes uint64 `json:"txBytes,omitempty"` RxErrs uint64 `json:"rxErrors,omitempty"` TxErrs uint64 `json:"txErrors,omitempty"` RxBps *float64 `json:"rxBps,omitempty"` TxBps *float64 `json:"txBps,omitempty"` // Sfp: diagnóstico digital (DDM/DOM) si la boca tiene módulo óptico // (#313). nil = sin SFP o sin datos; el servidor lo conserva. Sfp *SfpInfo `json:"sfp,omitempty"` } // SfpInfo: diagnóstico digital (DDM/DOM) de un módulo SFP (#313). Present // indica si se leyeron datos (ethtool -m devolvió algo parseable). type SfpInfo struct { Temperature float64 `json:"temperature"` // grados Celsius Voltage float64 `json:"voltage,omitempty"` // voltios (3.3 V típico) TxPower float64 `json:"txPower"` // dBm RxPower float64 `json:"rxPower"` // dBm (negativo) Vendor string `json:"vendor,omitempty"` // "FS.COM", "Ubiquiti", ... PartNumber string `json:"partNumber,omitempty"` Present bool `json:"present"` } // IfCounters son los contadores acumulados de UNA interfaz de /proc/net/dev. type IfCounters struct { Rx uint64 // bytes Tx uint64 // bytes RxErr uint64 TxErr uint64 } // IfRate añade a los contadores los rates instantáneos (delta entre muestras; // punteros nil = primera muestra o iface nueva, sin rate todavía). type IfRate struct { IfCounters RxBps *float64 TxBps *float64 } // Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}). type Radio struct { Name string `json:"name"` // "5 GHz"|"2.4 GHz" Channel int `json:"channel"` WidthMhz int `json:"widthMhz"` PowerDbm float64 `json:"powerDbm"` Clients int `json:"clients"` // Section es la sección UCI de la radio ("radio0"), para que el server // pueda construir cambios de canal (uci set wireless.
.channel). // Vacía si no se pudo resolver (#500). Section string `json:"section,omitempty"` // #1213/#1206: suelo de ruido (dBm, de iwinfo info "Noise") y BSSID de la // interfaz AP ("Access Point"). Opcionales: drivers que no los reportan → // nil/vacío y el front no dibuja esas filas. El BSSID es "el sitio donde // viven" las MACs de interfaz que antes asomaban como clientes. NoiseDbm *int `json:"noiseDbm,omitempty"` BSSID string `json:"bssid,omitempty"` } // --------------------------------------------------------------------------- // Sistema: /proc/stat, thermal, /proc/net/dev, ping // --------------------------------------------------------------------------- // CPUSample es la muestra agregada de "cpu " de /proc/stat. type CPUSample struct{ Total, IdleAll float64 } // ParseProcStat parsea "cpu user nice system idle iowait irq softirq ...". func ParseProcStat(out string) (CPUSample, error) { fields := strings.Fields(strings.TrimSpace(out)) if len(fields) < 5 || fields[0] != "cpu" { return CPUSample{}, fmt.Errorf("/proc/stat inesperado: %q", out) } nums := make([]float64, 0, len(fields)-1) for _, f := range fields[1:] { n, err := strconv.ParseFloat(f, 64) if err != nil { n = 0 } nums = append(nums, n) } get := func(i int) float64 { if i < len(nums) { return nums[i] } return 0 } idleAll := get(3) + get(4) // idle + iowait nonIdle := get(0) + get(1) + get(2) + get(5) + get(6) // user+nice+system+irq+softirq return CPUSample{Total: idleAll + nonIdle, IdleAll: idleAll}, nil } // ParseUptimeSec (#1481): segundos desde boot del primer campo de // /proc/uptime ("70273.29 269277.55"). 0 si la salida no es parseable: el // caller lo trata como "sin dato" y conserva el camino ubus cuando existe. func ParseUptimeSec(out string) float64 { fields := strings.Fields(strings.TrimSpace(out)) if len(fields) == 0 { return 0 } sec, err := strconv.ParseFloat(fields[0], 64) if err != nil || sec < 0 { return 0 } return sec } // CPUPercent: % de CPU por delta de muestras (nil si no hay delta válido: // primera muestra o contadores reseteados). func CPUPercent(prev, cur CPUSample) *int { dTotal := cur.Total - prev.Total dIdle := cur.IdleAll - prev.IdleAll if dTotal <= 0 { return nil } v := int(float64(dTotal-dIdle)/float64(dTotal)*100 + 0.5) return &v } // ParseTempC: °C del primer thermal zone (nil si la salida no es un entero o // si el sensor no da una lectura creíble). Un 0 no es una temperatura de CPU: // las unidades sin sensor (WNDR3700v2, #1947) exponen la zona a 0 y pintarlo // como dato válido hace creer que la lectura funciona. func ParseTempC(out string) *int { milli, err := strconv.Atoi(strings.TrimSpace(out)) if err != nil || milli == 0 { return nil } v := milli / 1000 if milli%1000 >= 500 { v++ } if v == 0 { return nil } return &v } var netdevSkipRe = regexp.MustCompile(`^(lo|br-|ifb|wg|tun|tap)`) // ParseNetDev suma rx/tx de las interfaces físicas (excluye lo, bridges, // ifb, wg, tun/tap para no duplicar contadores). func ParseNetDev(out string) (rx, tx float64) { lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`) for _, line := range strings.Split(strings.TrimSpace(out), "\n") { m := lineRe.FindStringSubmatch(line) if m == nil || netdevSkipRe.MatchString(m[1]) { continue } fields := strings.Fields(strings.TrimSpace(m[2])) num := func(i int) float64 { if i < len(fields) { n, _ := strconv.ParseFloat(fields[i], 64) return n } return 0 } rx += num(0) tx += num(8) } return rx, tx } // ParseNetDevIfaces devuelve los contadores POR INTERFAZ de /proc/net/dev // (sin filtrar: el consumidor decide qué ifaces le interesan; las bocas // físicas se casan por nombre con el layout, issue #305). func ParseNetDevIfaces(out string) map[string]IfCounters { res := map[string]IfCounters{} lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`) for _, line := range strings.Split(strings.TrimSpace(out), "\n") { m := lineRe.FindStringSubmatch(line) if m == nil { continue } fields := strings.Fields(strings.TrimSpace(m[2])) num := func(i int) uint64 { if i < len(fields) { n, _ := strconv.ParseUint(fields[i], 10, 64) return n } return 0 } res[m[1]] = IfCounters{ Rx: num(0), Tx: num(8), // bytes RxErr: num(2), TxErr: num(10), } } return res } // IfRates calcula los rates por interfaz con el delta de contadores entre // dos muestras separadas dt segundos. Ifaces nuevas o dt <= 0 → nil rates. // Contadores reseteados (reboot) → max0 dentro de NetDevBps da 0, no negativos. func IfRates(prev, cur map[string]IfCounters, dt float64) map[string]IfRate { res := make(map[string]IfRate, len(cur)) for name, c := range cur { r := IfRate{IfCounters: c} if p, ok := prev[name]; ok && dt > 0 { r.RxBps, r.TxBps = NetDevBps(float64(p.Rx), float64(p.Tx), float64(c.Rx), float64(c.Tx), dt) } res[name] = r } return res } // NetDevBps: bps por delta de contadores en dt segundos (nil si dt <= 0 o // contadores reseteados). func NetDevBps(prevRx, prevTx, rx, tx, dt float64) (rxBps, txBps *float64) { if dt <= 0 { return nil, nil } rb := round0(max0((rx - prevRx) * 8 / dt)) tb := round0(max0((tx - prevTx) * 8 / dt)) return &rb, &tb } var pingLossRe = regexp.MustCompile(`(\d+(?:\.\d+)?)% packet loss`) // #1281: GNU iputils imprime min/avg/max/MDEV (4 numeros) pero busybox // (OpenWrt) imprime min/avg/max (3): la regex exigia los 4 y en OpenWrt // la latencia salia nil siempre ("—" en Overview y Flota). El avg es el // segundo numero en ambos formatos. var pingRTTRe = regexp.MustCompile(`= [\d.]+/([\d.]+)(?:/[\d.]+){1,2} ms`) // ParsePingSummary extrae (latencia avg redondeada, pérdida %) del resumen de // ping; cada una es nil si su línea no está. func ParsePingSummary(out string) (latency, loss *float64) { if m := pingRTTRe.FindStringSubmatch(out); m != nil { v, _ := strconv.ParseFloat(m[1], 64) // #1384: sin redondeo a entero - en LAN el ping es <1 ms y el // redondeo lo dejaba en 0 (ruido). El formateo es cosa de la UI. latency = &v } if m := pingLossRe.FindStringSubmatch(out); m != nil { v, _ := strconv.ParseFloat(m[1], 64) loss = &v } return latency, loss } // --------------------------------------------------------------------------- // Clientes (DHCP + wireless) // --------------------------------------------------------------------------- // ParseDhcpUbus parsea la respuesta de `ubus call dhcp ipv4leases` // ({lease: [...]} o {leases: [...]}). Error si no es JSON con esas claves. func ParseDhcpUbus(raw []byte) ([]DhcpLease, error) { type leaseJSON struct { MAC string `json:"mac"` IPAddr string `json:"ip-address"` IP string `json:"ip"` Hostname string `json:"hostname"` VendorID string `json:"vendorid"` ClientID string `json:"clientid"` Expires int64 `json:"expires"` // segundos restantes o absoluto según firmware } var data struct { Lease []leaseJSON `json:"lease"` Leases []leaseJSON `json:"leases"` } if err := json.Unmarshal(raw, &data); err != nil { return nil, err } leases := data.Lease if leases == nil { leases = data.Leases } if leases == nil { return nil, fmt.Errorf("ubus dhcp: no lease/leases key") } out := make([]DhcpLease, 0, len(leases)) for _, l := range leases { ip := l.IPAddr if ip == "" { ip = l.IP } lease := DhcpLease{MAC: strings.ToUpper(l.MAC), IP: ip, Hostname: l.Hostname, VendorClass: l.VendorID, ClientID: l.ClientID} if l.Expires > 0 { lease.LeaseExpiresAt = &l.Expires } out = append(out, lease) } return out, nil } // ifaceStatus es una interfaz de `ubus call network.interface[.] status`, // y cada entrada de `... dump`. type ifaceStatus struct { Interface string `json:"interface"` Up bool `json:"up"` Proto string `json:"proto"` L3Device string `json:"l3_device"` // Device es la interfaz de debajo: para un PPPoE, la boca física. Device string `json:"device"` // Dynamic marks an interface netifd created itself — the DHCP child of // a modem uplink, the DHCPv6 side of a PPPoE one. It holds the address // and the route its parent has none of, and cannot be configured or // named in a policy, so it is only ever read through its parent. Dynamic bool `json:"dynamic"` IPV4 []struct { Address string `json:"address"` PtpAddress string `json:"ptpaddress"` } `json:"ipv4-address"` Route []struct { Target string `json:"target"` Mask int `json:"mask"` Nexthop string `json:"nexthop"` } `json:"route"` DNS []string `json:"dns-server"` } func (s ifaceStatus) defaultNexthop() string { for _, r := range s.Route { if r.Target == "0.0.0.0" && r.Mask == 0 && r.Nexthop != "" { return r.Nexthop } } return "" } // pickUplink elige la interfaz que lleva internet. No vale fiarse del nombre // "wan": en un router multi-WAN el uplink vivo puede llamarse de cualquier // forma (un PPPoE llamado "isp" junto a un módem celular que sí se llama // "wan" y que además reporta up=true estando ocioso), así que manda la ruta // por defecto. Sin ninguna con ruta, cae a la llamada "wan" para que un // router normal con el enlace caído siga saliendo como WAN caída y no como // router sin WAN. func pickUplink(ifaces []ifaceStatus) (ifaceStatus, bool) { return pickUplinkPreferring(ifaces, "") } // pickUplinkPreferring is pickUplink with the answer supplied from outside. // // A policy manager (mwan3) steers with packet marks and leaves the routes // alone, so the default route still points at the standby link while every // packet leaves by another one. When something knows which uplink is really // carrying traffic, that wins; everything else falls through to the route. func pickUplinkPreferring(ifaces []ifaceStatus, preferred string) (ifaceStatus, bool) { if preferred != "" { for _, i := range ifaces { if i.Interface != preferred { continue } i = withChildFacts(i, ifaces) if len(i.IPV4) > 0 || i.defaultNexthop() != "" { return i, true } } } for _, i := range ifaces { if i.Up && i.defaultNexthop() != "" { return i, true } } for _, i := range ifaces { if i.Interface == "wan" { return i, true } } return ifaceStatus{}, false } // withChildFacts gives an interface whatever netifd spawned underneath it. // A modem uplink keeps neither address nor route of its own: the child // sharing its layer-3 device holds both, and reporting the parent without // them would describe a connection with nothing on it. func withChildFacts(parent ifaceStatus, ifaces []ifaceStatus) ifaceStatus { if parent.Dynamic || parent.L3Device == "" { return parent } for _, c := range ifaces { if !c.Dynamic || c.Interface == parent.Interface || c.L3Device != parent.L3Device { continue } if len(parent.IPV4) == 0 { parent.IPV4 = c.IPV4 } if len(parent.Route) == 0 { parent.Route = c.Route } if len(parent.DNS) == 0 { parent.DNS = c.DNS } } return parent } func wanInfoFrom(s ifaceStatus) WanInfo { info := WanInfo{Proto: s.Proto, Device: s.L3Device, Port: s.Device, DNS: s.DNS} if len(s.IPV4) > 0 { info.IP = s.IPV4[0].Address if s.IPV4[0].PtpAddress != "" { info.Gateway = s.IPV4[0].PtpAddress } } // El gateway real es el nexthop de la ruta por defecto (0.0.0.0/0). if nh := s.defaultNexthop(); nh != "" { info.Gateway = nh } return info } // ParseWanStatus parsea el estado de la WAN (issue #276). Acepta las dos // formas: `ubus call network.interface dump` (y entonces elige el uplink // activo, ver pickUplink) y el status de una sola interfaz. Extrae proto, // interfaz L3, boca física, IP pública, gateway y DNS; campos vacíos si el // JSON no trae datos utilizables. func ParseWanStatus(raw []byte) WanInfo { return ParseWanStatusPreferring(raw, "") } // ParseWanStatusPreferring is ParseWanStatus told which uplink is carrying // traffic (see pickUplinkPreferring). An empty name behaves exactly as // before. func ParseWanStatusPreferring(raw []byte, preferred string) WanInfo { var dump struct { Interface []ifaceStatus `json:"interface"` } if err := json.Unmarshal(raw, &dump); err == nil && len(dump.Interface) > 0 { s, ok := pickUplinkPreferring(dump.Interface, preferred) if !ok { return WanInfo{} } return wanInfoFrom(s) } var one ifaceStatus if json.Unmarshal(raw, &one) != nil { return WanInfo{} } return wanInfoFrom(one) } // ParseDhcpReservations parses the host sections of `uci show dhcp`. A host // entry can carry several MACs (GL firmware stores mac as a list) and they // all share the entry's name and address. Sorted by MAC so the payload does // not churn between pushes. func ParseDhcpReservations(out string) []DhcpReservation { type entry struct { name, ip string macs []string } entries := map[string]*entry{} order := []string{} get := func(section string) *entry { e, ok := entries[section] if !ok { e = &entry{} entries[section] = e order = append(order, section) } return e } for _, line := range strings.Split(out, "\n") { line = strings.TrimSpace(line) key, val, ok := strings.Cut(line, "=") if !ok || !strings.HasPrefix(key, "dhcp.") { continue } key = strings.TrimPrefix(key, "dhcp.") val = strings.Trim(val, "'") section, attr, isAttr := strings.Cut(key, ".") if !isAttr { if val == "host" { get(section) } continue } e, declared := entries[section] if !declared { continue // an option of a section that is not a host entry } switch attr { case "name": e.name = val case "ip": e.ip = val case "mac": // A list comes back as 'aa:..' 'bb:..'; a single value plain. for _, mac := range strings.Fields(strings.ReplaceAll(val, "'", " ")) { e.macs = append(e.macs, strings.ToUpper(mac)) } } } res := []DhcpReservation{} for _, section := range order { e := entries[section] for _, mac := range e.macs { res = append(res, DhcpReservation{MAC: mac, Name: e.name, IP: e.ip}) } } sort.Slice(res, func(i, j int) bool { return res[i].MAC < res[j].MAC }) return res } // ParseDhcpLeasesFile parsea /tmp/dhcp.leases: // func ParseDhcpLeasesFile(out string) []DhcpLease { leases := []DhcpLease{} now := time.Now().Unix() for _, line := range strings.Split(strings.TrimSpace(out), "\n") { if line == "" { continue } p := strings.Fields(line) if len(p) < 3 { continue } hostname := "" if len(p) > 3 && p[3] != "*" { hostname = p[3] } clientID := "" if len(p) > 4 && p[4] != "*" { clientID = p[4] } var exp *int64 if secs, err := strconv.ParseInt(p[0], 10, 64); err == nil && secs > now { exp = &secs } leases = append(leases, DhcpLease{MAC: strings.ToUpper(p[1]), IP: p[2], Hostname: hostname, ClientID: clientID, LeaseExpiresAt: exp}) } return leases } // ParseGlClients parsea la respuesta de `ubus call gl-clients list` // (GL.iNet Flint2 y similares): {"clients": {"MAC": {mac, ip, name, online, ...}}}. // Error si no es JSON con esa forma. Solo devuelve entradas ONLINE con IP: // la base del firmware acumula historial (cientos de entradas) y las offline // solo servirían para inflar la lista de dispositivos; los equipos que // necesitan resolución de IP son los que están en la red ahora (issue #5 // bug 1). func ParseGlClients(raw []byte) ([]DhcpLease, error) { type clientJSON struct { MAC string `json:"mac"` IP string `json:"ip"` Name string `json:"name"` Hostname string `json:"hostname"` Online bool `json:"online"` } var data struct { Clients map[string]clientJSON `json:"clients"` } if err := json.Unmarshal(raw, &data); err != nil { return nil, err } if data.Clients == nil { return nil, fmt.Errorf("gl-clients: no clients key") } out := make([]DhcpLease, 0, len(data.Clients)) for key, c := range data.Clients { // El firmware puede emitir MAC con guiones ("AA-BB-...", #1145): se // guarda siempre la forma canónica para que el servidor la encuentre. mac := macaddr.Normalize(c.MAC) if mac == "" { mac = macaddr.Normalize(key) } if mac == "" || c.IP == "" || !c.Online { continue } hostname := c.Hostname if hostname == "" { hostname = c.Name } out = append(out, DhcpLease{MAC: mac, IP: c.IP, Hostname: hostname}) } sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC }) return out, nil } // ParseWirelessClients parsea líneas " " del bucle iwinfo. func ParseWirelessClients(out string) map[string]WirelessClient { m := map[string]WirelessClient{} for _, line := range strings.Split(strings.TrimSpace(out), "\n") { if line == "" { continue } p := strings.Fields(line) if len(p) < 2 { continue } freq := 0.0 if len(p) > 2 { freq, _ = strconv.ParseFloat(p[2], 64) } sig, _ := strconv.Atoi(p[1]) band := "2.4 GHz" if freq >= 5 { band = "5 GHz" } m[strings.ToUpper(p[0])] = WirelessClient{SignalDbm: sig, Band: band} } return m } // ParseWirelessUplink: alguna interfaz con config.mode "sta" activa (radio // up e ifname asignado = asociada) → uplink inalámbrico. Tolerante con // radios/entradas raras; error si la respuesta no es JSON. func ParseWirelessUplink(raw []byte) (bool, error) { var radios map[string]struct { Up bool `json:"up"` Interfaces []struct { Ifname string `json:"ifname"` Config struct { Mode string `json:"mode"` } `json:"config"` } `json:"interfaces"` } if err := json.Unmarshal(raw, &radios); err != nil { return false, err } for _, r := range radios { if !r.Up { continue } for _, itf := range r.Interfaces { if itf.Config.Mode == "sta" && itf.Ifname != "" { return true, nil } } } return false, nil } // --------------------------------------------------------------------------- // Puertos // --------------------------------------------------------------------------- // ParsePortStates parsea líneas " [dsa] [type] // [conduit]". Los campos opcionales que falten dejan su valor por defecto: // sin type no se descarta ninguna boca por él. func ParsePortStates(out string) []PortState { ports := []PortState{} for _, line := range strings.Split(strings.TrimSpace(out), "\n") { if line == "" { continue } p := strings.Fields(line) if len(p) < 3 { continue } mbps, _ := strconv.Atoi(p[2]) speed := "—" if mbps > 0 { speed = fmtSpeedMbps(mbps) } st := PortState{Name: p[0], Up: p[1] == "up", Oper: p[1], Speed: speed} if len(p) > 3 && p[3] == "dsa" { st.DSA = true } if len(p) > 4 { st.Type, _ = strconv.Atoi(p[4]) } if len(p) > 5 && p[5] != "-" { st.Conduit = p[5] } ports = append(ports, st) } return ports } // ParsePortLayout parsea board.json → [{id, name, label, role}] (WAN // normalizado a id 'wan'). // portPrettyLabel (#1200): etiqueta humana para el panel de bocas. Los // patrones clásicos conservan su formato (lan1→"LAN 1", wan→"WAN", // eth0→"ETH 0", sfp0→"SFP 0"); cualquier otro nombre físico reconocido // muestra su nombre real intacto: los netdev de OpenWrt 25.12+ (sfp-lan, // sfp-wan en BPI-R4) y las bocas sin dígitos (lan en UniFi 6 Lite). Ni // mayúsculas inyectadas en medio del nombre ni sufijos partidos. func portPrettyLabel(name string) string { switch { case name == "lan": return "LAN" case name == "wan": return "WAN" case lanNumRe.MatchString(name): return "LAN " + strings.TrimPrefix(name, "lan") case ethNumRe.MatchString(name): return "ETH " + strings.TrimPrefix(name, "eth") case sfpNumRe.MatchString(name): if name == "sfp" { return "SFP" } return "SFP " + strings.TrimPrefix(name, "sfp") default: return name } } var ( lanNumRe = regexp.MustCompile(`^lan\d+$`) ethNumRe = regexp.MustCompile(`^eth\d+$`) sfpNumRe = regexp.MustCompile(`^sfp\d*$`) ) func ParsePortLayout(out string) ([]PortLayout, error) { var board struct { Network struct { Lan struct { Ports []string `json:"ports"` } `json:"lan"` Wan struct { Device string `json:"device"` } `json:"wan"` } `json:"network"` } if err := json.Unmarshal([]byte(out), &board); err != nil { return nil, err } ports := []PortLayout{} for _, name := range board.Network.Lan.Ports { ports = append(ports, PortLayout{ID: name, Name: name, Label: portPrettyLabel(name), Role: "lan"}) } if wanDev := board.Network.Wan.Device; wanDev != "" { ports = append([]PortLayout{{ID: "wan", Name: wanDev, Label: "WAN", Role: "wan"}}, ports...) } return ports, nil } // phyRe/skipRe: nombres que pueden ser una boca física y nombres que nunca lo // son (bridges, VLANs, túneles, wireless, módems). var ( phyRe = regexp.MustCompile(`^(eth|sfp|en|swp)[0-9a-zA-Z_\-]*$|^(lan|wan)[0-9]*$`) 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)`) ) // switchConduits: puertos de CPU de un switch, deducidos de las propias // bocas. En DSA cada boca cuelga de la interfaz de CPU (lan1 y lan2 tienen // lower_eth0), que no es una boca física por mucho que se llame eth0. // // Solo se mira el lower_* de interfaces que parecen bocas: el de un bridge // son sus miembros (br-lan → lower_lan2) y el de una VLAN su interfaz padre, // relaciones que no señalan ningún puerto de CPU. func switchConduits(states []PortState) map[string]bool { conduits := map[string]bool{} for _, st := range states { if st.Conduit == "" || skipRe.MatchString(st.Name) || !phyRe.MatchString(st.Name) { continue } conduits[st.Conduit] = true } return conduits } // isEthNetdev: el layout nombra una interfaz de red ethernet de verdad. // board.json declara como WAN lo que el router use de uplink, y no siempre es // una boca: en un router celular es "/dev/cdc-wdm0", // que ni siquiera aparece en /sys/class/net. Un tipo desconocido (salida // antigua, sin el campo) cuenta como ethernet: mejor enseñar una boca de más // que esconder una real. func isEthNetdev(st PortState, ok bool) bool { return ok && (st.Type <= 0 || st.Type == ARPHRDEther) } // BuildEthPorts: layout + estado /sys → []EthPort listo para el detalle. // brMembers = miembros del bridge br-lan (AP en bridge re-etiqueta wan→LAN // N+1); sin layout, fallback heurístico. ifaces = contadores/rates por iface // física (issue #305; nil = sin datos, las bocas salen sin stats). Literal de // openwrt.go GetEthPorts. // // Descarta dos bocas que no existen: el uplink del layout cuando no es una // interfaz ethernet (módem celular) y el puerto de CPU del switch. Sin ellos // un router así pasa de enseñar cuatro bocas -- WAN (nunca conectada), LAN 1, // LAN 2 y ETH 0 -- a las dos que tiene. // // uplink es la boca por la que sale internet (WanInfo.Port); cuando ninguna // boca ha salido como WAN se promueve esa, ver promoteUplink. "" = sin dato, // y entonces no se promueve nada. func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool, ifaces map[string]IfRate, uplink string) []EthPort { applyStats := func(ep *EthPort, iface string) { st, ok := ifaces[iface] if !ok { return } ep.Iface = iface ep.RxBytes, ep.TxBytes = st.Rx, st.Tx ep.RxErrs, ep.TxErrs = st.RxErr, st.TxErr ep.RxBps, ep.TxBps = st.RxBps, st.TxBps } byName := map[string]PortState{} for _, p := range states { byName[p.Name] = p } conduits := switchConduits(states) used := map[string]bool{} ports := make([]EthPort, 0, len(states)) // netdev de cada boca por id, para saber luego cuál lleva el uplink: el // id no siempre es el nombre de la interfaz (en swconfig, "1" vs // "eth0.1"). netdev := map[string]string{} wanDeclared := false if len(layout) > 0 { lanCount := 0 lanNames := map[string]bool{} for _, p := range layout { if p.Role == "lan" { lanCount++ lanNames[p.Name] = true } if p.Role == "wan" { wanDeclared = true } } for _, p := range layout { st, ok := byName[p.Name] if p.Role == "wan" && !isEthNetdev(st, ok) { continue } up := ok && st.Up label := p.Label id := p.ID if p.Role == "wan" && brMembers[p.Name] { // #1949: la "wan" del board.json de un AP de un solo puerto // es un miembro del bridge LAN, no una boca WAN. La boca se // queda como LAN y con su propio id: con id "wan" la UI la // pintaba como enlace a internet aunque el texto dijera LAN. if lanNames[p.Name] { continue // ya declarada como LAN: no duplicar la boca } id = p.Name label = "LAN " + strconv.Itoa(lanCount+1) } ep := EthPort{ID: id, Label: label, Up: up} if up { ep.Speed = st.Speed } applyStats(&ep, p.Name) ports = append(ports, ep) netdev[ep.ID] = p.Name used[p.Name] = true } } else { // Fallback sin config. #1200: también "lan"/"wan" a secas (UniFi // 6 Lite: la boca no se llama lan1 sino lan, y antes el panel // salía vacío - 0 de 0 - porque ningún patrón la reconocía). lanRe := regexp.MustCompile(`^lan\d*$`) lans := []PortState{} for _, p := range states { if lanRe.MatchString(p.Name) { lans = append(lans, p) } } sort.Slice(lans, func(i, j int) bool { return NaturalLess(lans[i].Name, lans[j].Name) }) for _, p := range lans { ep := EthPort{ID: p.Name, Label: portPrettyLabel(p.Name), Up: p.Up} if p.Up { ep.Speed = p.Speed } applyStats(&ep, p.Name) ports = append(ports, ep) netdev[ep.ID] = p.Name used[p.Name] = true } wanName := "" if uplink != "" { // #1500: con uplink runtime la WAN es esa boca, no la heurística // ciega de abajo (un AP bridge sin layout marcaba WAN en eth1 // teniendo el uplink en eth0). El uplink puede llegar etiquetado // ("br0.1"): la boca es la de debajo. base := uplink if i := strings.LastIndexByte(base, '.'); i > 0 { base = base[:i] } if st, ok := byName[base]; ok && phyRe.MatchString(base) && isEthNetdev(st, ok) && !conduits[base] { wanName = base } else if len(brMembers) > 0 { // Uplink sobre bridge (APs: la ruta default vive en br0): la // boca WAN es el miembro con vecino LLDP (la que mira al // core) o, en su defecto, el de más rx bytes. Iteración // ordenada: empates no deben bailar entre sondeos (#1500). names := make([]string, 0, len(brMembers)) for m := range brMembers { names = append(names, m) } sort.Strings(names) bestRx := uint64(0) for _, m := range names { st, ok := byName[m] if !ok || !st.Up || !phyRe.MatchString(m) || !isEthNetdev(st, ok) || conduits[m] { continue } if wanName == "" || ifaces[m].Rx > bestRx { wanName, bestRx = m, ifaces[m].Rx } } } } if wanName == "" { if _, ok := byName["wan"]; ok { wanName = "wan" } else if _, ok := byName["pppoe-wan"]; ok { wanName = "eth1" } else if st, ok := byName["eth1"]; ok && !st.DSA { // #847: un conduit DSA no es la WAN física aunque se llame eth1. wanName = "eth1" } } // #1949: un AP con una sola boca fisica no tiene puerto WAN que // ensenar. Su uplink es la propia LAN (eth0 dentro de br-lan), asi que // etiquetarlo WAN lo pinta como enlace a internet y le cuelga los // datos de la conexion (WAX220). Con dos o mas bocas el miembro del // bridge que mira al core si distingue y se conserva (#1500: GT-BE98 // Pro, eth0 con vecino LLDP frente a eth1 y eth3). if wanName != "" && brMembers[wanName] && physicalPortCount(states, conduits) < 2 { wanName = "" } if wanName != "" { st := byName[wanName] ep := EthPort{ID: "wan", Label: "WAN", Up: st.Up} if st.Up { ep.Speed = st.Speed } applyStats(&ep, wanName) ports = append([]EthPort{ep}, ports...) netdev[ep.ID] = wanName used[wanName] = true } } // Mejora #413/#416: añadir interfaces físicas que no estén ya cubiertas // por el layout/fallback (p. ej. eth0, sfp+ en BPI-R4/UniFi). extras := make([]EthPort, 0) for _, st := range states { if used[st.Name] { continue } // #847: el conduit DSA (puerto CPU interno del switch, /sys .../dsa) // no es una boca usable: su velocidad es interna y sin sentido para // el usuario (p. ej. 150 Mbps en BPI-R4). Se excluye del panel. if st.DSA { continue } if skipRe.MatchString(st.Name) { continue } if !phyRe.MatchString(st.Name) { continue } if conduits[st.Name] { continue // puerto de CPU del switch, no una boca } // Broadcom/Asuswrt internal "ghost" interfaces (eth5/6/7 on an RT-AX92U) // pass phyRe and carry no DSA/conduit marker, but their sysfs operstate // is dormant/unknown and speed is unreadable: they are not front-panel // ports and never carry user traffic. A real port is either "up" (kept // here and everywhere) or "down" when unplugged. Oper=="" is legacy // three-field output, so nothing is hidden for it. if !st.Up && st.Oper != "" && st.Oper != "down" { continue } // #1200: label centralizado en portPrettyLabel - sfp-lan/sfp-wan // conservan su nombre (antes "SFP -lan"/"SFP -wan"). label := portPrettyLabel(st.Name) ep := EthPort{ID: st.Name, Label: label, Up: st.Up} if st.Up { ep.Speed = st.Speed } applyStats(&ep, st.Name) extras = append(extras, ep) netdev[ep.ID] = st.Name used[st.Name] = true } if len(extras) > 0 { sort.Slice(extras, func(i, j int) bool { return NaturalLess(extras[i].ID, extras[j].ID) }) // Mantener WAN primero, luego LANs, luego extras. ports = append(ports, extras...) } return promoteUplink(ports, netdev, uplink, brMembers, wanDeclared, physicalPortCount(states, conduits)) } // physicalPortCount cuenta las bocas fisicas del payload: ni bridges, ni VLAN, // ni tuneles, ni el puerto de CPU de un switch DSA (#1949). func physicalPortCount(states []PortState, conduits map[string]bool) int { n := 0 for _, st := range states { if st.DSA || skipRe.MatchString(st.Name) || !phyRe.MatchString(st.Name) || conduits[st.Name] { continue } n++ } return n } // promoteUplink marca como WAN la boca por la que sale internet cuando // ninguna ha salido ya como tal. Hay routers cuyo uplink no entra por una // boca WAN dedicada: el PPPoE puede ir sobre una boca llamada "lan1" y el // board.json solo declara un módem como WAN, así que sin esto ninguna boca // sale con id "wan" -- y la UI marca el uplink y cuelga los datos de la // conexión (proto, IP pública, gateway, DNS) justo de esa. // // La boca conserva su sitio y su iface: las estadísticas y la MAC siguen // siendo las suyas, solo cambia cómo se presenta. // // #1482: cuando el layout YA trae una boca WAN pero el uplink runtime cae // en otra distinta, manda netifd: la boca del uplink se promueve y la del // layout vuelve a su netdev (ETH n). El layout es una descripción estática // del cableado de vendor; el uplink runtime es la verdad de terreno de por // dónde sale internet (caso real: board.json con wan en eth0 porque ahí // vive el management, y el PPPoE saliendo por eth2). Si la boca WAN del // layout no tiene un netdev físico al que volver (no consta, o se llama // literalmente "wan"), no se toca nada: antes mantener la presentación del // layout que duplicar el id "wan". func promoteUplink(ports []EthPort, netdev map[string]string, uplink string, brMembers map[string]bool, wanDeclared bool, physical int) []EthPort { if uplink == "" { return ports } // El uplink puede llegar etiquetado ("lan1.7"): la boca es la de debajo. base := uplink if i := strings.LastIndexByte(base, '.'); i > 0 { base = base[:i] } // #1976: si el layout ya declara una boca WAN y el uplink runtime cae en un // miembro del bridge LAN, la unidad está haciendo de puente o de AP y el // internet le llega por la LAN. Promover esa boca la pintaba como WAN con // el tráfico de la LAN y devolvía la WAN del layout a "ETH n" (WNDR3700v2: // la WAN declarada en eth1 se quedaba abajo como "ETH 1" y el puerto del // switch eth0 aparecía como WAN y activo). Sin WAN declarada manda el // uplink, que es lo que necesitan los AP sin layout (#1500). // wanDeclared: la unidad declara WAN y el uplink le llega por el bridge // (#1976). physical < 2: un AP de una sola boca no tiene puerto WAN que // enseñar (#1949), aunque no haya layout que lo diga. if brMembers[base] && (wanDeclared || physical < 2) { return ports } wanIdx, upIdx := -1, -1 for i := range ports { if ports[i].ID == "wan" { wanIdx = i } if upIdx < 0 { if n := netdev[ports[i].ID]; n == uplink || n == base { upIdx = i } } } if wanIdx < 0 { // Ninguna boca salió como WAN en el layout: promueve la del uplink. if upIdx >= 0 { ports[upIdx].ID, ports[upIdx].Label = "wan", "WAN" } return ports } if upIdx < 0 || upIdx == wanIdx { return ports // sin uplink, o de acuerdo con el layout } nd := netdev[ports[wanIdx].ID] if nd == "" || nd == "wan" { return ports // sin netdev físico al que volver: no duplicar la WAN } ports[wanIdx].ID, ports[wanIdx].Label = nd, portPrettyLabel(nd) ports[upIdx].ID, ports[upIdx].Label = "wan", "WAN" return ports } // NaturalLess ordena lan2 < lan10 (localeCompare numeric del JS). func NaturalLess(a, b string) bool { re := regexp.MustCompile(`^(.*?)(\d+)$`) ma, mb := re.FindStringSubmatch(a), re.FindStringSubmatch(b) if ma != nil && mb != nil && ma[1] == mb[1] { na, _ := strconv.Atoi(ma[2]) nb, _ := strconv.Atoi(mb[2]) return na < nb } return a < b } // Filtro de puertos del FDB (#506): DENYLIST, no allowlist. El allowlist // histórico (lan\d+|wan|eth\d+|swp\d+|en...) descartaba en silencio MACs // aprendidas en puertos con nombres no enumerados: las jaulas SFP del BPI-R4 // se llaman "sfp-lan"/"sfp-wan" (openwrt,netdev-name, 25.12+) y sus // dispositivos cableados jamás llegaban a descubrirse. Ahora vale cualquier // puerto MIEMBRO del bridge (los no-miembros ya no resuelven en ==PORTS==) // salvo los wireless (clientes que llegan por la sección wireless) y las // interfaces virtuales. var ( // wl\d+ cubre las radios Broadcom de Asuswrt/Merlin (wl0..wl3): el bridge // aprende las MACs propias de cada radio (bit LAA volteado) como entradas // externas en esos puertos, y sin excluirlas cada radio aparecía como un // cliente "cableado" fantasma del AP. La alternativa wl va anclada (con su // subinterfaz VLAN opcional): por prefijo casaría interfaces futuras que // solo compartan las letras iniciales. fdbWirelessRe = regexp.MustCompile(`^(phy\d+-ap\d*|wlan\d*|wl[0-9]+(\.[0-9]+)?)$`) fdbVirtualRe = regexp.MustCompile(`^(br|lo|veth|wg|tun|tap|ppp|sit|ip6|gre|erspan|dummy|macv|ifb)`) ) // fdbPortWired: ¿cuenta este puerto como cableado para el mapa MAC→puerto? // La subinterfaz VLAN (eth0.999, lan1.10) SÍ cuenta: es el puerto real del // bridge en un router que segmenta con 802.1Q y el FDB lo nombra así (antes se // descartaba por llevar punto, y todos los clientes cableados de sus bridges // se quedaban sin puerto y sin VLAN, #1757). Lo que no cuenta es una // subinterfaz de radio (wl0.1, wlan0.1) ni una interfaz virtual (br*, veth*). func fdbPortWired(port string) bool { if port == "" || strings.Contains(port, "@") { return false } base := port if i := strings.IndexByte(base, '.'); i > 0 { base = base[:i] } return !fdbWirelessRe.MatchString(base) && !fdbVirtualRe.MatchString(base) } // ParseBridgeFdb parsea la salida ==PORTS==/==MACS== → MAC aprendida → puerto. // Acepta dos formatos en ==MACS==: brctl (` `) y // `bridge fdb show` (` [vlan ]`). func ParseBridgeFdb(out string) map[string]string { wired, _, _ := ParseBridgeFdbVlans(out) return wired } // ParseBridgeFdbSplit es ParseBridgeFdb devolviendo además las MACs aprendidas // en puertos del lado inalámbrico (wl0.1, wlan0, phy0-ap0…): no son clientes // cableados, pero tampoco deben tirarse: son la única evidencia de que esa MAC // vive detrás de esta radio (MACs rotadas que siguen emitiendo, clientes en // backhaul 4-address). Sin este segundo mapa el server las vería únicamente en // el FDB de tránsito del gateway y su fallback las dibujaría como cableadas. func ParseBridgeFdbSplit(out string) (wired, wirelessSide map[string]string) { wired, wirelessSide, _ = ParseBridgeFdbVlans(out) return wired, wirelessSide } // ParseBridgeFdbVlans: lo anterior más la VLAN con la que el bridge aprendió // cada MAC (el `vlan ` de `bridge fdb show`, solo en bridges con VLAN // filtering). Es el dato exacto del segmento de un cliente cableado: el PVID // del puerto dice dónde entra la trama sin etiquetar, no en qué VLAN vive el // cliente. // // Las secciones pueden venir con el nombre del bridge detrás de la marca // ("==PORTS==br_switch", un bridge por segmento). Sin sufijo se asume una sola // tabla, que es lo que emite un agente viejo. func ParseBridgeFdbVlans(out string) (wired, wirelessSide map[string]string, vlans map[string]int) { wired = map[string]string{} wirelessSide = map[string]string{} vlans = map[string]int{} // bridge → port_no → ifname. La clave "" cubre la salida sin sufijo. portNames := map[string]map[string]string{} bridge := "" section := byte(0) ports := func(br string) map[string]string { m, ok := portNames[br] if !ok { m = map[string]string{} portNames[br] = m } return m } for _, line := range strings.Split(out, "\n") { t := strings.TrimSpace(line) if strings.HasPrefix(t, "==PORTS==") { section = 'p' bridge = strings.TrimSpace(strings.TrimPrefix(t, "==PORTS==")) continue } if strings.HasPrefix(t, "==MACS==") { section = 'm' bridge = strings.TrimSpace(strings.TrimPrefix(t, "==MACS==")) continue } p := strings.Fields(t) if len(p) < 2 { continue } switch section { case 'p': no, name := p[0], p[1] if strings.HasPrefix(no, "0x") { if n, err := strconv.ParseInt(no[2:], 16, 64); err == nil { no = strconv.FormatInt(n, 10) } } m := ports(bridge) m[no] = name m[name] = name // puerto también localizable por nombre (bridge fdb) case 'm': no, mac := p[0], p[1] m := ports(bridge) port, ok := m[no] if !ok || mac == "" { continue } mac = strings.ToUpper(mac) if len(p) >= 3 { if vid, err := strconv.Atoi(p[2]); err == nil && vid > 0 { vlans[mac] = vid } } switch { case fdbPortWired(port): wired[mac] = port case fdbPortWirelessSide(port): wirelessSide[mac] = port } } } return wired, wirelessSide, vlans } // fdbPortWirelessSide: puertos del bridge que son radios o subinterfaces de // radio (wl0.1, wlan0, phy0-ap0). Las interfaces virtuales no inalámbricas // (br*, veth*, tun*) NO cuentan: ahí la MAC no llegó por el aire. func fdbPortWirelessSide(port string) bool { base := port if i := strings.IndexAny(base, ".@"); i >= 0 { base = base[:i] } return fdbWirelessRe.MatchString(base) } // LuCILabels: etiquetas de puertos y VLANs de LuCI (issue #258). OpenWrt // snapshots las definen en /etc/config/luci como secciones switchvlan: // // config switchvlan 'port_labels' // option lan1 'Router/Fritzbox' // config switchvlan 'vlan_labels' // option 1 'LAN' // // PortLabels mapea interfaz (lan1…) → etiqueta; VlanLabels mapea id de // VLAN → etiqueta. type LuCILabels struct { PortLabels map[string]string `json:"portLabels,omitempty"` VlanLabels map[string]string `json:"vlanLabels,omitempty"` } var ( luciSectionRe = regexp.MustCompile(`^config\s+(\S+)\s+['"]?([A-Za-z0-9_]+)['"]?`) luciOptionRe = regexp.MustCompile(`^option\s+(\S+)\s+['"]?([^'"]*)['"]?$`) ) // ParseLuCILabels parsea /etc/config/luci y extrae las secciones // port_labels/vlan_labels. Devuelve nil si no hay ninguna etiqueta. func ParseLuCILabels(out string) *LuCILabels { var labels LuCILabels var section string for _, raw := range strings.Split(out, "\n") { line := strings.TrimSpace(raw) if line == "" || strings.HasPrefix(line, "#") { continue } if m := luciSectionRe.FindStringSubmatch(line); m != nil { section = m[2] continue } if section != "port_labels" && section != "vlan_labels" { continue } if m := luciOptionRe.FindStringSubmatch(line); m != nil { if m[2] == "" { continue } if section == "port_labels" { if labels.PortLabels == nil { labels.PortLabels = map[string]string{} } labels.PortLabels[m[1]] = m[2] } else { if labels.VlanLabels == nil { labels.VlanLabels = map[string]string{} } labels.VlanLabels[m[1]] = m[2] } } } if len(labels.PortLabels) == 0 && len(labels.VlanLabels) == 0 { return nil } return &labels } // VlanEntry: una VLAN de un puerto del bridge (issue #315). ID es el número // de VLAN (1-4094); Tagged=false + Untagged en el wire (Egress Untagged); // PVID=true indica que este puerto es el puerto nativo de esta VLAN. type VlanEntry struct { ID int `json:"id"` Tagged bool `json:"tagged"` PVID bool `json:"pvid"` // Name es la etiqueta que LuCI da a la VLAN (uci show network, #258), // rellenada por el servidor al juntarla con VlanLabels (#1757). Name string `json:"name,omitempty"` // Subnet es la red que sirve la VLAN (192.168.111.1/24), sacada de la // interfaz que vive en el bridge (#1757). Subnet string `json:"subnet,omitempty"` } // VlanPort: puerto del bridge con sus VLANs (issue #315). type VlanPort struct { Port string `json:"port"` Vlans []VlanEntry `json:"vlans"` } var vlanIDRe = regexp.MustCompile(`^(\d+)(.*)$`) // ParseBridgeVlan parsea la salida de `bridge vlan show` (issue #315). // Formato: líneas "port vlan-id [flags]" o " vlan-id [flags]" (continuation). // Flags: "PVID" = puerto nativo; "Egress Untagged" = untagged en salida. func ParseBridgeVlan(out string) []VlanPort { var ports []VlanPort var cur *VlanPort for _, raw := range strings.Split(out, "\n") { line := strings.TrimRight(raw, "\r\n") if line == "" || strings.HasPrefix(line, "port") { continue } trimmed := strings.TrimSpace(line) if trimmed == "" { continue } isContinuation := len(line) > 0 && (line[0] == ' ' || line[0] == '\t') fields := strings.Fields(trimmed) if len(fields) == 0 { continue } var portName string var vlanField string if isContinuation { if cur == nil { continue } vlanField = fields[0] } else { portName = fields[0] if len(fields) < 2 { continue } vlanField = fields[1] } m := vlanIDRe.FindStringSubmatch(vlanField) if m == nil { continue } id, err := strconv.Atoi(m[1]) if err != nil || id < 1 || id > 4094 { continue } rest := strings.ToLower(m[2]) if len(fields) > 2 { rest += " " + strings.ToLower(strings.Join(fields[2:], " ")) } pvid := strings.Contains(rest, "pvid") tagged := !strings.Contains(rest, "egress untagged") entry := VlanEntry{ID: id, Tagged: tagged, PVID: pvid} if isContinuation { cur.Vlans = append(cur.Vlans, entry) } else { ports = append(ports, VlanPort{Port: portName, Vlans: []VlanEntry{entry}}) cur = &ports[len(ports)-1] } } return ports } var nonDigitRe = regexp.MustCompile(`\D`) // ParseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes). // hostapdClientsJSON es el shape de `ubus call hostapd. get_clients`. // El objeto por estación incluye `bytes:{rx,tx}` (acumulados desde la // asociación) y `packets` cuando el driver responde a read_sta_data (#551); // si no los expone, quedan a cero. type hostapdClientsJSON struct { Freq float64 `json:"freq"` Clients map[string]struct { Auth bool `json:"auth"` Assoc bool `json:"assoc"` Authorized bool `json:"authorized"` Signal int `json:"signal"` Bytes struct { Rx uint64 `json:"rx"` Tx uint64 `json:"tx"` } `json:"bytes"` } `json:"clients"` } // ParseHostapdClients (#368) parsea el output de CmdHostapdClients: bloques // "==AP==hostapd.phy0-ap0" seguidos del JSON de get_clients. Solo cuenta // estaciones asociadas y autorizadas (equivalente a iwinfo assoclist); la // banda sale del "freq" del bloque (>=5 GHz = "5 GHz"). Mismo shape que // ParseWirelessClients. RxBytes/TxBytes son los contadores acumulados de la // estación si el driver los reportó (issue #551). func ParseHostapdClients(out string) map[string]WirelessClient { m := map[string]WirelessClient{} // Sección de SSIDs (iw dev) al final de la salida: iface → SSID. head := out ssidByIface := map[string]string{} if i := strings.Index(out, "==SSID=="); i >= 0 { head = out[:i] for _, line := range strings.Split(out[i:], "\n") { p := strings.Fields(line) if len(p) == 2 && p[0] != "==SSID==" { ssidByIface[p[0]] = p[1] } } } for _, chunk := range strings.Split(head, "==AP==") { chunk = strings.TrimSpace(chunk) if chunk == "" { continue } // La marca lleva el objeto ubus delante; el JSON empieza en "{". i := strings.Index(chunk, "{") if i < 0 { continue } // #1757: el objeto ubus ES la interfaz AP ("hostapd.phy1-ap2"). Sin // este dato el cliente wifi viajaba sin `Iface`, y el mapa no podía // casarlo con el puerto del bridge para leer su VLAN: todo cliente // wifi de un OpenWrt con hostapd (o sea, casi todos) salía sin VLAN. iface := strings.TrimSpace(chunk[:i]) iface = strings.TrimPrefix(iface, "hostapd.") iface = strings.TrimSpace(strings.TrimPrefix(iface, "/")) var j hostapdClientsJSON if err := json.Unmarshal([]byte(chunk[i:]), &j); err != nil || j.Freq == 0 { continue } freq := j.Freq if freq >= 1000 { // ubus get_clients da MHz; iwinfo da GHz freq /= 1000 } band := "2.4 GHz" if freq >= 5 { band = "5 GHz" } for mac, st := range j.Clients { if !st.Assoc || !st.Authorized { continue } m[strings.ToUpper(mac)] = WirelessClient{ SignalDbm: st.Signal, Band: band, Iface: iface, SSID: ssidByIface[iface], RxBytes: st.Bytes.Rx, TxBytes: st.Bytes.Tx, } } } return m } // ParseWirelessCombined (#368) parsea CmdWirelessCombined: líneas "C|mac|sig| // freq" (clientes, mismo shape que ParseWirelessClients) y "R|freq|ch|ht|tx|n" // (radios, mismo shape que ParseRadios, que se reutiliza). func ParseWirelessCombined(out string) (map[string]WirelessClient, []Radio) { clients := map[string]WirelessClient{} var radioLines []string for _, line := range strings.Split(strings.TrimSpace(out), "\n") { line = strings.TrimSpace(line) switch { case strings.HasPrefix(line, "C|"): p := strings.Split(line, "|") if len(p) < 4 { continue } sig, _ := strconv.Atoi(p[2]) freq, _ := strconv.ParseFloat(p[3], 64) band := "2.4 GHz" if freq >= 5 { band = "5 GHz" } clients[strings.ToUpper(p[1])] = WirelessClient{SignalDbm: sig, Band: band} case strings.HasPrefix(line, "R|"): radioLines = append(radioLines, strings.TrimPrefix(line, "R|")) } } return clients, ParseRadios(strings.Join(radioLines, "\n")) } func ParseRadios(out string) []Radio { byBand := map[string]*Radio{} order := []string{} for _, line := range strings.Split(strings.TrimSpace(out), "\n") { if line == "" { continue } p := strings.Split(line, "|") if len(p) < 5 { continue } freq, _ := strconv.ParseFloat(p[0], 64) if freq == 0 { continue } band := "2.4 GHz" if freq >= 5 { band = "5 GHz" } width, _ := strconv.Atoi(nonDigitRe.ReplaceAllString(p[2], "")) if width == 0 { width = 20 } ch, _ := strconv.Atoi(p[1]) tx, _ := strconv.Atoi(p[3]) // #1213: formato nuevo "freq|ch|ht|tx|bssid|noise|n" (7 campos); // el histórico "freq|ch|ht|tx|n" (5) sigue parseando igual. var noise *int var bssid string n := 0 if len(p) >= 7 { bssid = strings.ToUpper(strings.TrimSpace(p[4])) if v, err := strconv.Atoi(strings.TrimSpace(p[5])); err == nil && v != 0 { noise = &v } n, _ = strconv.Atoi(p[6]) } else { n, _ = strconv.Atoi(p[4]) } if cur, ok := byBand[band]; ok { cur.Clients += n if cur.NoiseDbm == nil { cur.NoiseDbm = noise } if cur.BSSID == "" { cur.BSSID = bssid } } else { byBand[band] = &Radio{Name: band, Channel: ch, WidthMhz: width, PowerDbm: float64(tx), Clients: n, NoiseDbm: noise, BSSID: bssid} order = append(order, band) } } radios := []Radio{} for _, b := range order { radios = append(radios, *byBand[b]) } return radios } // ParseRadioSections parsea la salida de CmdRadioSections y devuelve // banda ("2.4 GHz"|"5 GHz"|"6 GHz") → sección UCI ("radio0"). Solo se queda // con la primera sección por banda (si hay varias, la primera gana; el // channel plan trabaja por banda). func ParseRadioSections(out string) map[string]string { sections := map[string]string{} secBand := map[string]string{} for _, line := range strings.Split(strings.TrimSpace(out), "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "wireless.") { continue } parts := strings.SplitN(line, "=", 2) if len(parts) != 2 { continue } key := strings.TrimPrefix(parts[0], "wireless.") val := strings.Trim(parts[1], "'") rel, opt, hasOpt := strings.Cut(key, ".") if !hasOpt { if val == "wifi-device" { secBand[rel] = "" // sección conocida, banda pendiente } continue } band, ok := secBand[rel] if !ok || band != "" { continue } switch { case opt == "band" || (opt == "hwmode" && (val == "11g" || val == "11a")): switch { case val == "2g" || val == "11g": secBand[rel] = "2.4 GHz" case val == "5g" || val == "11a": secBand[rel] = "5 GHz" case val == "6g": secBand[rel] = "6 GHz" } } } for sec, band := range secBand { if band != "" { if _, exists := sections[band]; !exists { sections[band] = sec } } } return sections } // ParseScan parsea la salida de CmdScan: bloques "==IFACE==" seguidos de // la salida de `iw dev scan`. Extrae BSS, freq, signal y SSID. func ParseScan(out string) []ScanResult { var res []ScanResult iface := "" var current *ScanResult // Estado del bloque HT/VHT en curso para el ancho de canal (#1087). section := "" ht40, vhtWidth := false, 0 flush := func() { if current != nil && current.BSSID != "" && current.Freq > 0 { current.Channel = FreqToChannel(current.Freq) if current.Channel > 0 { switch { case vhtWidth > 0: current.WidthMhz = vhtWidth case ht40: current.WidthMhz = 40 default: current.WidthMhz = 20 } res = append(res, *current) } } current = nil } for _, raw := range strings.Split(out, "\n") { line := strings.TrimSpace(raw) if strings.HasPrefix(line, "==IFACE==") { flush() iface = strings.TrimPrefix(line, "==IFACE==") continue } if strings.HasPrefix(line, "BSS ") { flush() fields := strings.Fields(line) if len(fields) < 2 { continue } bssid := strings.ToUpper(strings.Split(fields[1], "(")[0]) current = &ScanResult{Iface: iface, BSSID: bssid} section, ht40, vhtWidth = "", false, 0 continue } if current == nil { continue } // Ancho de canal anunciado por el vecino (#1087): HT operation da // el salto de 40 MHz; VHT operation el de 80/160. switch { case strings.HasPrefix(line, "HT operation:"): section = "ht" continue case strings.HasPrefix(line, "VHT operation:"): section = "vht" continue case strings.HasPrefix(line, "HE operation:") || strings.HasPrefix(line, "EHT operation:"): section = "" continue } if section == "ht" && strings.Contains(line, "secondary channel offset:") { ht40 = !strings.Contains(line, "no secondary") continue } if section == "vht" && strings.Contains(line, "channel width:") { // "* channel width: 1 (80 MHz)": 1 = 80 MHz, 2 = 160 MHz. re := vhtWidthRe.FindStringSubmatch(line) if re != nil { n, _ := strconv.Atoi(re[1]) switch n { case 1: vhtWidth = 80 case 2: vhtWidth = 160 } } continue } if strings.HasPrefix(line, "freq:") { // iw imprime la frecuencia como float ("freq: 5260.0"): Atoi // fallaba en silencio, Freq quedaba 0 y el flush descartaba TODOS // los BSS (scans siempre vacíos, #475). if f, err := strconv.ParseFloat(strings.TrimSpace(strings.TrimPrefix(line, "freq:")), 64); err == nil { current.Freq = int(f) } continue } if strings.HasPrefix(line, "signal:") { v, _ := strconv.ParseFloat(strings.Fields(strings.TrimPrefix(line, "signal:"))[0], 64) current.Signal = int(v) continue } if strings.HasPrefix(line, "SSID:") { current.SSID = strings.TrimSpace(strings.TrimPrefix(line, "SSID:")) continue } } flush() return res } var vhtWidthRe = regexp.MustCompile(`channel width:\s*(\d)\s*\(`) // ParseIwDev parsea la salida de CmdIwDev (`iw dev`) y devuelve las // interfaces AP de ESTE equipo con su BSSID y SSID (#1087). Los bloques // "Interface " traen addr, ssid y type; solo type AP interesa (los // STA/clientes managed no son red propia). func ParseIwDev(out string) []OwnBSSID { var res []OwnBSSID iface, addr, ssid, ifType := "", "", "", "" flush := func() { if iface != "" && addr != "" && ifType == "AP" { res = append(res, OwnBSSID{Iface: iface, BSSID: strings.ToUpper(addr), SSID: ssid}) } } for _, raw := range strings.Split(out, "\n") { line := strings.TrimSpace(raw) fields := strings.Fields(line) if len(fields) >= 2 && fields[0] == "Interface" { flush() iface, addr, ssid, ifType = fields[1], "", "", "" continue } if len(fields) >= 2 && fields[0] == "addr" { addr = fields[1] continue } if len(fields) >= 2 && fields[0] == "ssid" { ssid = strings.TrimSpace(strings.TrimPrefix(line, "ssid")) continue } if len(fields) >= 2 && fields[0] == "type" { ifType = fields[1] continue } } flush() return res } // IwDevIfaces (#1338) lists EVERY interface of `iw dev` (any type, not only // AP like ParseIwDev). Since #1560 the scan groups them by radio with // ParseIwDevDetailed instead of scanning each one. func IwDevIfaces(out string) []string { var res []string for _, i := range ParseIwDevDetailed(out) { res = append(res, i.Iface) } return res } // FreqToChannel convierte frecuencia (MHz) a número de canal 802.11. func FreqToChannel(freq int) int { switch { case freq >= 2412 && freq <= 2484: if freq == 2484 { return 14 } return (freq-2412)/5 + 1 case freq >= 5180 && freq <= 5885: // 5 GHz UNII-1/2/3: 36, 40, 44, ... 165 return (freq-5180)/5 + 36 case freq >= 5955 && freq <= 7115: // 6 GHz: 1-229 (PSCO no se soporta en esta fase) return (freq-5955)/5 + 1 } return 0 } var ( sfpTempRe = regexp.MustCompile(`(?i)Module temperature\s*:\s*(-?[\d.]+)`) sfpVoltRe = regexp.MustCompile(`(?i)Module voltage\s*:\s*([\d.]+)`) sfpTxPwrRe = regexp.MustCompile(`(?i)Laser output power\s*:.*?/\s*(-?[\d.]+)\s*dBm`) sfpRxPwrRe = regexp.MustCompile(`(?i)Laser receiver power\s*:.*?/\s*(-?[\d.]+)\s*dBm`) sfpVendorRe = regexp.MustCompile(`(?i)Vendor [Nn]ame\s*:\s*(.+)`) sfpPNRe = regexp.MustCompile(`(?i)Vendor [Pp]art [Nn]umber\s*:\s*(.+)`) ) // ParseEthtoolSFP parsea la salida de `ethtool -m ` y extrae los // valores DDM/DOM del módulo (#313). Devuelve nil si la salida está vacía o // no contiene datos de SFP. func ParseEthtoolSFP(out string) *SfpInfo { if strings.TrimSpace(out) == "" { return nil } info := &SfpInfo{} if m := sfpTempRe.FindStringSubmatch(out); m != nil { info.Temperature, _ = strconv.ParseFloat(m[1], 64) info.Present = true } if m := sfpVoltRe.FindStringSubmatch(out); m != nil { info.Voltage, _ = strconv.ParseFloat(m[1], 64) } if m := sfpTxPwrRe.FindStringSubmatch(out); m != nil { info.TxPower, _ = strconv.ParseFloat(m[1], 64) } if m := sfpRxPwrRe.FindStringSubmatch(out); m != nil { info.RxPower, _ = strconv.ParseFloat(m[1], 64) } if m := sfpVendorRe.FindStringSubmatch(out); m != nil { info.Vendor = strings.TrimSpace(m[1]) } if m := sfpPNRe.FindStringSubmatch(out); m != nil { info.PartNumber = strings.TrimSpace(m[1]) } if !info.Present { return nil } return info } func round0(v float64) float64 { return float64(int64(v + 0.5)) } func max0(v float64) float64 { if v < 0 { return 0 } return v } // ParseMdnsHosts (#338): parses `ubus call umdns hosts` into IP -> hostname. // The trailing ".local" is dropped: it is the mDNS suffix, not part of the // name anyone recognises. Entries without an IPv4 are skipped. func ParseMdnsHosts(raw []byte) map[string]string { var hosts map[string]struct { IPv4 string `json:"ipv4"` } out := map[string]string{} if json.Unmarshal(raw, &hosts) != nil { return out } for name, h := range hosts { if h.IPv4 == "" { continue } out[h.IPv4] = strings.TrimSuffix(name, ".local") } return out } // ParseMdnsBrowse (#338): parsea la salida de `ubus call umdns browse`. // Formato típico (JSON): // // { "hostname._service._tcp.local": { "port": 1234, "txt": [...] }, ... } // // Extrae: hostname (de la clave, antes del primer punto) y tipos de servicio // (el segmento _service._tcp). También recoge IPs si aparecen en registros A. func ParseMdnsBrowse(raw []byte) *DiscoveryData { if len(raw) == 0 { return nil } // umdns browse devuelve un objeto JSON con claves "fqdn" y valores que // contienen "port", "txt", "ipv4", etc. Parseamos como map genérico. var browse map[string]json.RawMessage if json.Unmarshal(raw, &browse) != nil { return nil } if len(browse) == 0 { return nil } dd := &DiscoveryData{ Services: map[string][]string{}, HostByIP: map[string]string{}, } for fqdn, val := range browse { // Extraer hostname: primera parte antes del "." hostname := fqdn if idx := strings.Index(fqdn, "."); idx > 0 { hostname = fqdn[:idx] } // Extraer tipo de servicio: segundo segmento "_svc._tcp" o "_svc._udp" parts := strings.SplitN(fqdn, ".", 3) if len(parts) >= 2 && strings.HasPrefix(parts[1], "_") { svcType := parts[1] if len(parts) >= 3 { svcType = parts[1] + "." + strings.SplitN(parts[2], ".", 2)[0] } dd.Services[hostname] = appendUnique(dd.Services[hostname], svcType) } // Extraer IP si disponible var entry struct { IPv4 string `json:"ipv4"` } if json.Unmarshal(val, &entry) == nil && entry.IPv4 != "" { dd.HostByIP[entry.IPv4] = hostname } } if len(dd.Services) == 0 && len(dd.HostByIP) == 0 { return nil } return dd } func appendUnique(slice []string, s string) []string { for _, x := range slice { if x == s { return slice } } return append(slice, s) } // IsRandomizedMAC returns true if the MAC address has the locally-administered // bit set (bit 1 of byte 0). Apple, Google, and Samsung use this for WiFi // privacy features — the device appears as a new MAC periodically. func IsRandomizedMAC(mac string) bool { return macaddr.IsLocallyAdministered(mac) } // ParseArp parsea /proc/net/arp (#377): cabecera + líneas // "IP net/arp HW flags MAC mask device". Devuelve MAC (upper) → IP, // ignorando entradas incompletas (flags 0x0) y MACs nulas. func ParseArp(out string) map[string]string { m := map[string]string{} for _, line := range strings.Split(out, "\n") { f := strings.Fields(line) if len(f) < 4 || f[0] == "IP" { continue } mac := strings.ToUpper(f[3]) if mac == "" || mac == "00:00:00:00:00:00" { continue } // flags 0x0 = incomplete: el kernel retiene la IP sin vecino válido. if f[2] == "0x0" { continue } if net.ParseIP(f[0]) == nil { continue } m[mac] = f[0] } return m } // neighConfirmed: the states in which the kernel vouches for the neighbour // being there right now. REACHABLE was confirmed within the reachable time; // DELAY and PROBE are on their way to being reconfirmed; PERMANENT and NOARP // were put there by hand or by a link that needs no resolution. // // Everything else -- STALE, FAILED, INCOMPLETE, NONE -- is an address the // kernel remembers without being able to say the host is still connected. var neighConfirmed = map[string]bool{ "REACHABLE": true, "DELAY": true, "PROBE": true, "PERMANENT": true, "NOARP": true, } // ParseIPNeigh parses `ip neigh show`, whose lines read // "IP dev IFACE lladdr MAC STATE" (an entry being resolved has no lladdr). // It returns the same MAC→IP map as ParseArp plus the set of MACs whose // every entry is unconfirmed: remembered addresses, not present hosts. // // A MAC with several addresses counts as confirmed when any one of them is, // since one confirmed neighbour is enough to prove the host is there. func ParseIPNeigh(out string) (arp map[string]string, stale map[string]bool) { arp, stale = map[string]string{}, map[string]bool{} confirmed := map[string]bool{} for _, line := range strings.Split(out, "\n") { f := strings.Fields(line) // "IP dev IFACE lladdr MAC STATE" is the shortest useful line. if len(f) < 6 || net.ParseIP(f[0]) == nil { continue } var mac string for i := 1; i+1 < len(f); i++ { if f[i] == "lladdr" { mac = strings.ToUpper(f[i+1]) break } } if mac == "" || mac == "00:00:00:00:00:00" { continue } // The state is the last word of the line; an entry without one is // not something to claim presence from. if neighConfirmed[f[len(f)-1]] { // Confirmed wins for good: a later unconfirmed address for the // same host must not undo it. arp[mac] = f[0] confirmed[mac] = true delete(stale, mac) continue } if !confirmed[mac] { if _, ok := arp[mac]; !ok { arp[mac] = f[0] } stale[mac] = true } } return arp, stale } // ParseIPNeighDevs devuelve MAC -> interfaz de `ip neigh show` (#1485). Solo // entradas confirmadas, con la misma regla que ParseIPNeigh: una entrada STALE // no prueba presencia y su interfaz tampoco sirve para atribuir el lado WAN. func ParseIPNeighDevs(out string) map[string]string { devs := map[string]string{} for _, line := range strings.Split(out, "\n") { f := strings.Fields(line) if len(f) < 6 || net.ParseIP(f[0]) == nil { continue } var mac, dev string for i := 1; i+1 < len(f); i++ { switch f[i] { case "lladdr": mac = strings.ToUpper(f[i+1]) case "dev": dev = f[i+1] } } if mac == "" || mac == "00:00:00:00:00:00" || dev == "" { continue } if !neighConfirmed[f[len(f)-1]] { continue } devs[mac] = dev } return devs } // ParseIPNeighDevsAll devuelve MAC -> interfaz de `ip neigh show` sin mirar el // estado (#2109). ParseIPNeighDevs solo devuelve confirmadas porque su uso es // atribuir el lado WAN; el recheck de vecinos necesita la interfaz de una // entrada STALE para poder mandarle un echo a una link-local. func ParseIPNeighDevsAll(out string) map[string]string { devs := map[string]string{} for _, line := range strings.Split(out, "\n") { f := strings.Fields(line) if len(f) < 6 || net.ParseIP(f[0]) == nil { continue } var mac, dev string for i := 1; i+1 < len(f); i++ { switch f[i] { case "lladdr": mac = strings.ToUpper(f[i+1]) case "dev": dev = f[i+1] } } if mac == "" || mac == "00:00:00:00:00:00" || dev == "" { continue } devs[mac] = dev } return devs } // ParseArpDevs devuelve MAC -> interfaz de /proc/net/arp (#1485), con el mismo // filtro de entradas incompletas que ParseArp. Es el fallback cuando el equipo // no tiene `ip`. func ParseArpDevs(out string) map[string]string { devs := map[string]string{} for _, line := range strings.Split(out, "\n") { f := strings.Fields(line) if len(f) < 6 || f[0] == "IP" { continue } mac := strings.ToUpper(f[3]) if mac == "" || mac == "00:00:00:00:00:00" || f[2] == "0x0" || net.ParseIP(f[0]) == nil { continue } devs[mac] = f[5] } return devs } // sumProcRSS returns the total VmRSS (bytes) of every user-space process // (/proc//status): the memory actually held by processes, excluding the // kernel page cache that inflates (total-available) on ubifs/overlay routers. func sumProcRSS() float64 { entries, err := os.ReadDir("/proc") if err != nil { return 0 } var total float64 for _, e := range entries { if !allDigits(e.Name()) { continue } b, err := os.ReadFile("/proc/" + e.Name() + "/status") if err != nil { continue } for _, line := range strings.Split(string(b), "\n") { if !strings.HasPrefix(line, "VmRSS:") { continue } f := strings.Fields(line) if len(f) >= 2 { if v, err := strconv.ParseFloat(f[1], 64); err == nil { total += v * 1024 } } break } } return total } func allDigits(s string) bool { for _, r := range s { if r < '0' || r > '9' { return false } } return s != "" } // ParseUciBridgeVlans reads the bridge VLANs out of `uci show network`. // // `bridge vlan show` is the truth, but its binary is part of an optional // package and plenty of routers do not carry it — including ones with VLANs // configured, where the panel then shows nothing at all. The declared // configuration is the next best answer: it is what the router was told to // do, and on a healthy box it is what the kernel is doing. // // A bridge-vlan section names a device, a VLAN id and its ports, each port // written "[:u|:t][*]": ":t" tagged, ":u" untagged, a trailing "*" // marking the port's own ingress VLAN. func ParseUciBridgeVlans(out string) []VlanPort { type section struct { vlan int ports []string } sections := map[string]*section{} order := []string{} for _, line := range strings.Split(out, "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "network.") { continue } key, val, ok := strings.Cut(strings.TrimPrefix(line, "network."), "=") if !ok { continue } val = strings.Trim(val, "'") name, attr, isAttr := strings.Cut(key, ".") if !isAttr { if val == "bridge-vlan" { if _, seen := sections[name]; !seen { sections[name] = §ion{} order = append(order, name) } } continue } sec, ok := sections[name] if !ok { continue } switch attr { case "vlan": if id, err := strconv.Atoi(val); err == nil { sec.vlan = id } case "ports": // A list option prints all its values on one line, each in // its own quotes. for _, part := range strings.Split(val, "' '") { if p := strings.TrimSpace(strings.Trim(part, "'")); p != "" { sec.ports = append(sec.ports, p) } } } } // Group by port, the way `bridge vlan show` reports it: the panel is a // list of ports, each with the VLANs it carries. byPort := map[string][]VlanEntry{} portOrder := []string{} for _, name := range order { sec := sections[name] if sec.vlan < 1 || sec.vlan > 4094 { continue } for _, raw := range sec.ports { port, entry := parseUciVlanPort(raw, sec.vlan) if port == "" { continue } if _, seen := byPort[port]; !seen { portOrder = append(portOrder, port) } byPort[port] = append(byPort[port], entry) } } out2 := make([]VlanPort, 0, len(portOrder)) for _, port := range portOrder { out2 = append(out2, VlanPort{Port: port, Vlans: byPort[port]}) } return out2 } // parseUciVlanPort splits one "[:u|:t][*]" entry. func parseUciVlanPort(raw string, vlan int) (string, VlanEntry) { name := raw entry := VlanEntry{ID: vlan} if strings.HasSuffix(name, "*") { entry.PVID = true name = strings.TrimSuffix(name, "*") } switch { case strings.HasSuffix(name, ":t"): entry.Tagged = true name = strings.TrimSuffix(name, ":t") case strings.HasSuffix(name, ":u"): name = strings.TrimSuffix(name, ":u") } return name, entry }