Преглед изворни кода

fix(vlans): tag each client with the vlan its bridge learned (#1757) (#1888)

* fix(vlans): tag each client with the vlan its bridge learned (#1757)

* fix(vlans): stop a guest from inheriting the vlan of its host (#1757)

* docs(changelog): cover the vlan fixes for clients and guests (#1757)
Nacho пре 4 недеља
родитељ
комит
ad058b89b3

+ 6 - 0
CHANGELOG.md

@@ -7,6 +7,12 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Fixed
+
+- A client is tagged with the VLAN its bridge actually sees (#1757). The forwarding table was read from one bridge only and every port carrying a dot was thrown away, so a router that segments with 802.1Q subinterfaces, where the real ports are `eth0.777` and `eth0.999`, lost its wired clients altogether: no port, no VLAN and no line in the topology. Every bridge the unit has is read now, a subinterface counts as a port, and each MAC carries the VLAN the bridge learned it on, which is the only evidence of where a client lives. A forwarding table without that field leaves the client without a VLAN instead of guessing one from the default of the port.
+- A wireless client keeps the interface and the SSID that served it (#1757). The hostapd path built each station without either, so on any OpenWrt that answers over ubus every WiFi client arrived with an empty interface, and the topology, which resolves the VLAN of a station through its AP interface, had nothing to colour. The interface is taken from the object that was queried and the SSID from `iw dev`, and the VLAN of an AP interface now carries the name and the subnet of the network it serves.
+- A guest without a tag is no longer painted with a VLAN it does not have (#1757). When Proxmox declares no `tag=`, the guest sits in the native VLAN of the bridge of the host, not in the VLAN of the port where the host is plugged. Inheriting the VLAN of the host chip marked those guests with an unrelated network, so a container on an untagged bridge showed up in the VLAN of a segmented one.
+
 ## [2.51.1] - 2026-11-05
 
 ### Fixed

+ 1 - 1
agent/probe/local.go

@@ -819,7 +819,7 @@ func (p *Prober) probeFDB(ctx context.Context, lldpPorts map[string]bool, radios
 	fd := &FDBData{}
 	any := false
 	if out := p.runBest(ctx, CmdBridgeFDB, 0); out != "" {
-		fd.MACs, fd.WirelessSide = ParseBridgeFdbSplit(out)
+		fd.MACs, fd.WirelessSide, fd.VLANs = ParseBridgeFdbVlans(out)
 		fd.WirelessSide = bandTagWirelessSide(fd.WirelessSide, radios)
 		any = true
 	}

+ 7 - 0
agent/probe/payload.go

@@ -218,6 +218,13 @@ type FDBData struct {
 	// cableados. Valor = banda de la radio cuyo BSSID es la MAC del puerto
 	// ("2.4 GHz"|"5 GHz"|"6 GHz"); sin radio que casar, la MAC se omite.
 	WirelessSide map[string]string `json:"wirelessSide,omitempty"`
+	// VLANs: MAC → VLAN con la que el bridge aprendió esa MAC (el `vlan
+	// <id>` de `bridge fdb show`). Solo existe en bridges con VLAN
+	// filtering; ausente = sin dato, no "VLAN 0". Es la prueba exacta del
+	// segmento de un cliente cableado: sin ella el server solo podía
+	// deducir la VLAN del PVID del puerto, que es la del puerto y no la del
+	// cliente (#1757).
+	VLANs map[string]int `json:"vlans,omitempty"`
 }
 
 // DawnData: estado de DAWN (roaming/band-steering, Fase 14). Solo si DAWN

+ 103 - 22
agent/probe/probe.go

@@ -69,7 +69,11 @@ const (
 	// 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`
+		`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
@@ -188,10 +192,8 @@ const (
 	// 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: "==PORTS==" (port_no ifname) + "==MACS==" (port mac).
-	// No asume `brctl`: prueba brctl y, si no existe o no aporta, `bridge fdb
-	// show` (OpenWrt/GLuON modernos usan iproute2). Issue #253. El bridge lo
-	// resuelve bridgeDetect (#1435).
+	// 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
@@ -205,10 +207,28 @@ const (
 	// 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 = bridgeDetect +
-		`echo "==PORTS=="; for d in /sys/class/net/$BR/brif/*; do [ -r "$d/port_no" ] && echo "$(cat $d/port_no) $(basename $d)"; done; ` +
-		`echo "==MACS=="; (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/ {for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1), $1}}') 2>/dev/null; true`
+	//
+	// CmdBridgeFDB: "==PORTS==<bridge>" (port_no ifname) + "==MACS==<bridge>"
+	// (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 <id>` 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
@@ -1440,20 +1460,27 @@ var (
 )
 
 // fdbPortWired: ¿cuenta este puerto como cableado para el mapa MAC→puerto?
-// Las subinterfaces VLAN (lan1.10, eth0.100) tampoco cuentan: el FDB de un
-// bridge con VLAN filtering reporta el puerto físico.
+// 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.ContainsAny(port, ".@") {
+	if port == "" || strings.Contains(port, "@") {
 		return false
 	}
-	return !fdbWirelessRe.MatchString(port) && !fdbVirtualRe.MatchString(port)
+	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 (`<port_no> <mac>`) y
-// `bridge fdb show` (`<ifname> <mac>`, emitido por CmdBridgeFDB).
+// `bridge fdb show` (`<ifname> <mac> [vlan <id>]`).
 func ParseBridgeFdb(out string) map[string]string {
-	wired, _ := ParseBridgeFdbSplit(out)
+	wired, _, _ := ParseBridgeFdbVlans(out)
 	return wired
 }
 
@@ -1464,18 +1491,45 @@ func ParseBridgeFdb(out string) map[string]string {
 // 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 <id>` 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{}
-	portNames := map[string]string{} // port_no → ifname
+	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)
@@ -1490,15 +1544,22 @@ func ParseBridgeFdbSplit(out string) (wired, wirelessSide map[string]string) {
 					no = strconv.FormatInt(n, 10)
 				}
 			}
-			portNames[no] = name
-			portNames[name] = name // puerto también localizable por nombre (bridge fdb)
+			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]
-			port, ok := portNames[no]
+			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
@@ -1507,7 +1568,7 @@ func ParseBridgeFdbSplit(out string) (wired, wirelessSide map[string]string) {
 			}
 		}
 	}
-	return wired, wirelessSide
+	return wired, wirelessSide, vlans
 }
 
 // fdbPortWirelessSide: puertos del bridge que son radios o subinterfaces de
@@ -1692,7 +1753,19 @@ type hostapdClientsJSON struct {
 // estación si el driver los reportó (issue #551).
 func ParseHostapdClients(out string) map[string]WirelessClient {
 	m := map[string]WirelessClient{}
-	for _, chunk := range strings.Split(out, "==AP==") {
+	// 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
@@ -1702,6 +1775,13 @@ func ParseHostapdClients(out string) map[string]WirelessClient {
 		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
@@ -1719,7 +1799,8 @@ func ParseHostapdClients(out string) map[string]WirelessClient {
 				continue
 			}
 			m[strings.ToUpper(mac)] = WirelessClient{
-				SignalDbm: st.Signal, Band: band,
+				SignalDbm: st.Signal, Band: band, Iface: iface,
+				SSID:    ssidByIface[iface],
 				RxBytes: st.Bytes.Rx, TxBytes: st.Bytes.Tx,
 			}
 		}

+ 7 - 4
agent/probe/probe_test.go

@@ -572,13 +572,14 @@ func TestParseFdbExcluyeWireless(t *testing.T) {
 // silencio puertos físicos con nombres no enumerados (las jaulas SFP del
 // BPI-R4 se llaman sfp-lan/sfp-wan; también "lan" suelto o usb0). El filtro
 // invertido conserva cualquier miembro físico del bridge y solo excluye
-// wireless (phy*-ap*, wlan*) y virtuales (br*, lo, veth*, wg*, túneles,
-// subinterfaces VLAN).
+// wireless (phy*-ap*, wlan*, wl*) y virtuales (br*, lo, veth*, wg*, túneles).
+// #1757: la subinterfaz VLAN (lan1.10, eth0.999) SÍ es un puerto cableado —
+// es como se llama el puerto del bridge en un router que segmenta con 802.1Q.
 func TestParseFdbDenylistPuertos(t *testing.T) {
 	out := "==PORTS==\n" +
 		"1 sfp-lan\n2 sfp-wan\n3 eth1\n4 lan\n5 usb0\n6 swp1\n7 enp2s0\n" +
 		"8 phy0-ap0\n9 phy1-ap1\n10 wlan0\n11 br-lan\n12 br0\n13 lo\n" +
-		"14 veth0\n15 wg0\n16 tunl0\n17 tap0\n18 pppoe-wan\n19 lan1.10\n" +
+		"14 veth0\n15 wg0\n16 tunl0\n17 tap0\n18 pppoe-wan\n19 lan1.10\n20 eth0.999\n" +
 		"==MACS==\n" +
 		// sfp-lan resuelto por port_no (vía brctl); el resto por nombre.
 		"1 aa:00:00:00:00:01\n" +
@@ -587,7 +588,7 @@ func TestParseFdbDenylistPuertos(t *testing.T) {
 		"phy0-ap0 bb:00:00:00:00:01\nphy1-ap1 bb:00:00:00:00:02\nwlan0 bb:00:00:00:00:03\n" +
 		"br-lan bb:00:00:00:00:04\nbr0 bb:00:00:00:00:05\nlo bb:00:00:00:00:06\nveth0 bb:00:00:00:00:07\n" +
 		"wg0 bb:00:00:00:00:08\ntunl0 bb:00:00:00:00:09\ntap0 bb:00:00:00:00:0a\n" +
-		"pppoe-wan bb:00:00:00:00:0b\nlan1.10 bb:00:00:00:00:0c\n"
+		"pppoe-wan bb:00:00:00:00:0b\nlan1.10 bb:00:00:00:00:0c\neth0.999 bb:00:00:00:00:0d\n"
 	fdb := ParseBridgeFdb(out)
 	want := map[string]string{
 		"AA:00:00:00:00:01": "sfp-lan",
@@ -597,6 +598,8 @@ func TestParseFdbDenylistPuertos(t *testing.T) {
 		"AA:00:00:00:00:05": "usb0",
 		"AA:00:00:00:00:06": "swp1",
 		"AA:00:00:00:00:07": "enp2s0",
+		"BB:00:00:00:00:0C": "lan1.10",
+		"BB:00:00:00:00:0D": "eth0.999",
 	}
 	if len(fdb) != len(want) {
 		t.Fatalf("esperaba %d MACs (solo puertos físicos), tengo %d: %+v", len(want), len(fdb), fdb)

+ 52 - 2
agent/probe/vlan_network.go

@@ -159,7 +159,7 @@ func MergeVlanPorts(kernel, declared []VlanPort) []VlanPort {
 		return kernel
 	}
 	if len(kernel) == 0 {
-		return declared
+		return labelVlanPorts(declared)
 	}
 	idx := make(map[string]int, len(kernel)+len(declared))
 	out := make([]VlanPort, 0, len(kernel)+len(declared))
@@ -175,7 +175,57 @@ func MergeVlanPorts(kernel, declared []VlanPort) []VlanPort {
 		idx[p.Port] = len(out)
 		out = append(out, VlanPort{Port: p.Port, Vlans: append([]VlanEntry(nil), p.Vlans...)})
 	}
-	return out
+	return labelVlanPorts(out)
+}
+
+// labelVlanPorts names the VLANs of the ports that only carry the id. The name
+// of a network is declared once, on the pseudo-port of its subinterface
+// (br_switch.777), while the ports that actually carry it (a radio AP, an
+// uplink) come from the kernel with the id and nothing else: the wifi panel of
+// a dumb AP showed "777" with no way to know which network that was (#1757).
+//
+// An id that names exactly one network on the whole box inherits that name.
+// Two different networks sharing a number stay unnamed: a wrong name is worse
+// than no name.
+func labelVlanPorts(ports []VlanPort) []VlanPort {
+	names := map[int]map[string]bool{}
+	subnets := map[int]map[string]bool{}
+	note := func(m map[int]map[string]bool, id int, v string) {
+		if v == "" {
+			return
+		}
+		if m[id] == nil {
+			m[id] = map[string]bool{}
+		}
+		m[id][v] = true
+	}
+	for _, p := range ports {
+		for _, e := range p.Vlans {
+			note(names, e.ID, e.Name)
+			note(subnets, e.ID, e.Subnet)
+		}
+	}
+	only := func(m map[int]map[string]bool, id int) string {
+		if len(m[id]) != 1 {
+			return ""
+		}
+		for v := range m[id] {
+			return v
+		}
+		return ""
+	}
+	for i := range ports {
+		for j := range ports[i].Vlans {
+			e := &ports[i].Vlans[j]
+			if e.Name == "" {
+				e.Name = only(names, e.ID)
+			}
+			if e.Subnet == "" {
+				e.Subnet = only(subnets, e.ID)
+			}
+		}
+	}
+	return ports
 }
 
 func mergeVlanEntries(kernel, declared []VlanEntry) []VlanEntry {

+ 171 - 0
agent/probe/vlans_1757_test.go

@@ -0,0 +1,171 @@
+package probe
+
+import "testing"
+
+// #1757: los datos reales del router x86 y del AP de un usuario que segmenta
+// con subinterfaces 802.1Q (router) y con bridge vlan filtering (AP). Los tres
+// fallos que destaparon: el FDB descartaba el puerto de la subinterfaz, solo se
+// leía un bridge y la VLAN de cada cliente (`vlan <id>`) se tiraba.
+
+// Router x86: cinco bridges, cada uno colgado de una subinterfaz del mismo
+// eth0. El FDB reporta el puerto como `eth0.999`.
+func TestFdbRuterSubinterfaces(t *testing.T) {
+	out := "==PORTS==br-iot\n" +
+		"1 eth0.999\n" +
+		"==MACS==br-iot\n" +
+		"eth0.999 aa:bb:cc:00:00:99\n" +
+		"==PORTS==br-guest\n" +
+		"1 eth0.777\n" +
+		"==MACS==br-guest\n" +
+		"eth0.777 aa:bb:cc:00:00:77\n"
+	wired, wirelessSide, _ := ParseBridgeFdbVlans(out)
+	if wired["AA:BB:CC:00:00:99"] != "eth0.999" {
+		t.Fatalf("cliente de br-iot sin puerto: %+v", wired)
+	}
+	if wired["AA:BB:CC:00:00:77"] != "eth0.777" {
+		t.Fatalf("cliente de br-guest sin puerto: %+v", wired)
+	}
+	if len(wirelessSide) != 0 {
+		t.Fatalf("una subinterfaz cableada no es lado wireless: %+v", wirelessSide)
+	}
+}
+
+// AP con bridge vlan filtering: el FDB trae la VLAN real de cada cliente y las
+// tablas de puertos de dos bridges no se pisan (cada uno numera desde 1).
+func TestFdbVlanPorClienteYDosBridges(t *testing.T) {
+	out := "==PORTS==br_switch\n" +
+		"1 eth1\n2 lan1\n3 phy1-ap2\n" +
+		"==MACS==br_switch\n" +
+		"lan1 aa:bb:cc:00:00:01 777\n" +
+		"phy1-ap2 aa:bb:cc:00:00:02 999\n" +
+		"==PORTS==br-guest\n" +
+		"1 eth0.777\n2 lan1\n" +
+		"==MACS==br-guest\n" +
+		"eth0.777 aa:bb:cc:00:00:03 777\n" +
+		"lan1 aa:bb:cc:00:00:04 0\n"
+	wired, wirelessSide, vlans := ParseBridgeFdbVlans(out)
+	if wired["AA:BB:CC:00:00:01"] != "lan1" {
+		t.Fatalf("cableado: %+v", wired)
+	}
+	if wirelessSide["AA:BB:CC:00:00:02"] != "phy1-ap2" {
+		t.Fatalf("wifi: %+v", wirelessSide)
+	}
+	if vlans["AA:BB:CC:00:00:01"] != 777 || vlans["AA:BB:CC:00:00:02"] != 999 {
+		t.Fatalf("VLAN por cliente: %+v", vlans)
+	}
+	// El segundo bridge reusa port_no 1 y 2 para otros puertos: la tabla del
+	// primero no debe filtrarse a la del segundo.
+	if wired["AA:BB:CC:00:00:03"] != "eth0.777" {
+		t.Fatalf("segundo bridge mal resuelto: %+v", wired)
+	}
+	if got, ok := vlans["AA:BB:CC:00:00:04"]; ok || got != 0 {
+		t.Fatalf("sin campo vlan no hay VLAN que inventar: %+v", vlans)
+	}
+}
+
+// La salida de un agente viejo (una sola tabla, sin sufijo ni vlan) sigue
+// valiendo: no se puede romper la flota al actualizar el servidor.
+func TestFdbFormatoAntiguo(t *testing.T) {
+	out := "==PORTS==\n1 lan1\n2 phy0-ap0\n" +
+		"==MACS==\n1 aa:bb:cc:00:00:01\nphy0-ap0 aa:bb:cc:00:00:02\n"
+	wired, wirelessSide, vlans := ParseBridgeFdbVlans(out)
+	if wired["AA:BB:CC:00:00:01"] != "lan1" {
+		t.Fatalf("cableado: %+v", wired)
+	}
+	if wirelessSide["AA:BB:CC:00:00:02"] != "phy0-ap0" {
+		t.Fatalf("wifi: %+v", wirelessSide)
+	}
+	if len(vlans) != 0 {
+		t.Fatalf("formato antiguo no trae VLANs: %+v", vlans)
+	}
+}
+
+// #1757: `ubus call hostapd.<if> get_clients` es la fuente primaria en
+// cualquier OpenWrt, y el objeto ubus es la interfaz AP. Sin rellenar Iface el
+// cliente wifi no se puede casar con el puerto del bridge y sale sin VLAN.
+func TestHostapdClientsRellenaIfaceYSSID(t *testing.T) {
+	out := "==AP==hostapd.phy0-ap0\n" +
+		`{"freq":2437,"clients":{"aa:bb:cc:00:00:01":{"auth":true,"assoc":true,"authorized":true,"signal":-55,"bytes":{"rx":10,"tx":20}}}}` + "\n" +
+		"==AP==hostapd.phy1-ap2\n" +
+		`{"freq":5180,"clients":{"aa:bb:cc:00:00:02":{"auth":true,"assoc":true,"authorized":true,"signal":-60,"bytes":{"rx":30,"tx":40}}}}` + "\n" +
+		"==SSID==\nphy0-ap0 Iot\nphy1-ap2 Paperopoli\n"
+	got := ParseHostapdClients(out)
+	if c := got["AA:BB:CC:00:00:01"]; c.Iface != "phy0-ap0" || c.SSID != "Iot" {
+		t.Fatalf("cliente 2.4G: %+v", c)
+	}
+	if c := got["AA:BB:CC:00:00:02"]; c.Iface != "phy1-ap2" || c.SSID != "Paperopoli" {
+		t.Fatalf("cliente 5G: %+v", c)
+	}
+}
+
+// El nombre de la red vive en el pseudo-puerto de la subinterfaz
+// (br_switch.777); los puertos wifi solo traen el id. Un id que nombra una
+// sola red en el equipo hereda su nombre.
+func TestMergeVlanPortsNombraPuertosWifi(t *testing.T) {
+	kernel := ParseBridgeVlan(`port              vlan-id
+eth1              1 PVID Egress Untagged
+                  777
+                  999
+br_switch         1
+                  777
+                  999
+phy1-ap2          777 PVID Egress Untagged
+phy1-ap1          999 PVID Egress Untagged
+`)
+	declared := ParseUciNetworkVlans(`network.lan=interface
+network.lan.device='br_switch.1'
+network.lan.ipaddr='192.168.1.2'
+network.lan.netmask='255.255.255.0'
+network.Iot=interface
+network.Iot.proto='none'
+network.Iot.device='br_switch.999'
+network.Guest=interface
+network.Guest.proto='none'
+network.Guest.device='br_switch.777'
+`)
+	got := MergeVlanPorts(kernel, declared)
+	byPort := map[string]VlanPort{}
+	for _, p := range got {
+		byPort[p.Port] = p
+	}
+	entry := func(port string, id int) VlanEntry {
+		for _, e := range byPort[port].Vlans {
+			if e.ID == id {
+				return e
+			}
+		}
+		t.Fatalf("%s no lleva la VLAN %d: %+v", port, id, byPort[port])
+		return VlanEntry{}
+	}
+	if e := entry("phy1-ap2", 777); e.Name != "Guest" || !e.PVID {
+		t.Fatalf("phy1-ap2 debería heredar el nombre de la VLAN 777: %+v", e)
+	}
+	if e := entry("phy1-ap1", 999); e.Name != "Iot" {
+		t.Fatalf("phy1-ap1 debería heredar el nombre de la VLAN 999: %+v", e)
+	}
+	if e := entry("br_switch.1", 1); e.Name != "lan" || e.Subnet != "192.168.1.2/24" {
+		t.Fatalf("br_switch.1: %+v", e)
+	}
+}
+
+// Dos redes distintas con el mismo número en el equipo: mejor sin nombre que
+// con el de la otra.
+func TestMergeVlanPortsNoInventaNombreAmbiguo(t *testing.T) {
+	kernel := ParseBridgeVlan(`port              vlan-id
+phy1-ap2          100 PVID Egress Untagged
+br-a              100
+br-b              100
+`)
+	declared := []VlanPort{
+		{Port: "br-a.100", Vlans: []VlanEntry{{ID: 100, PVID: true, Name: "Oficina"}}},
+		{Port: "br-b.100", Vlans: []VlanEntry{{ID: 100, PVID: true, Name: "Invitados"}}},
+	}
+	for _, p := range MergeVlanPorts(kernel, declared) {
+		if p.Port != "phy1-ap2" {
+			continue
+		}
+		if len(p.Vlans) != 1 || p.Vlans[0].Name != "" {
+			t.Fatalf("no debe heredar un nombre ambiguo: %+v", p.Vlans)
+		}
+	}
+}

+ 22 - 14
app/src/components/topology/model.ts

@@ -1050,15 +1050,25 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
 
   // -- chips de dispositivos --------------------------------------------------
   const chips: ChipNode[] = []
-  // #1757: VLAN del puerto del cliente cableado. El bridge VLAN filtering del
-  // router dice qué VLANs lleva cada puerto; PVID es la nativa y manda, y sin
-  // PVID se toma la primera entrada. Solo cableado: la API no declara la VLAN
-  // de un cliente WiFi, y suponerla sería inventar el dato.
+  // #1757: nombre de la red para una VLAN conocida por su id. El router
+  // declara qué subred/nombre vive en cada VLAN y el agregado sale de ahí: el
+  // dato del cliente (FDB o tag= del hipervisor) solo trae el id.
+  const vlanNameOf = (id: number): string | undefined => {
+    for (const r of routers) {
+      for (const entry of r.vlans ?? []) {
+        for (const v of entry.vlans) {
+          if (v.id === id && v.name) return v.name
+        }
+      }
+    }
+    return undefined
+  }
   const vlanOf = (d: Device): ChipNode['vlan'] => {
-    // #1757: la VLAN que declara el propio device (inventario de Proxmox,
-    // tag= de la config del invitado) manda: el router no puede verla porque
-    // el invitado cuelga del bridge del host, no de un puerto suyo.
-    if (d.vlan) return { id: d.vlan, pvid: false }
+    // #1757: la VLAN que el servidor resolvió para este cliente manda. Sale de
+    // la evidencia exacta del bridge (la VLAN con la que aprendió su MAC) o del
+    // `tag=` que declara el hipervisor para el invitado. El puerto solo se usa
+    // cuando no hay dato.
+    if (d.vlan) return { id: d.vlan, name: vlanNameOf(d.vlan), pvid: false }
     // #1757: `bridge vlan show` lista también las interfaces AP (wlan0,
     // wlan1) como puertos del bridge, así que la estación inalámbrica se
     // resuelve por su interfaz igual que un cliente cableado por su puerto.
@@ -1298,13 +1308,11 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     const hostChip = chips.find((c) => c.id === hostId)
     const kids = childrenOf(hostId).map((d) => mkChip(d, hostId, true))
     if (!hostChip || kids.length === 0) continue
-    // #1757: un invitado cuelga del bridge del host, no de un puerto del
-    // router, así que su VLAN no está en `bridge vlan show`. Cuando Proxmox no
-    // declara tag= (invitado en la VLAN nativa del bridge) hereda la VLAN del
-    // chip del host, que es la del puerto donde ese host está conectado.
-    const hostVlan = hostChip.vlan
+    // #1757: sin herencia. Un invitado sin `tag=` en Proxmox no vive en la
+    // VLAN del puerto donde cuelga el host, vive en la VLAN nativa del bridge
+    // del host (la 1, sin etiquetar). Heredar la del host pintaba invitados no
+    // etiquetados con la VLAN del puerto del hipervisor, que no es la suya.
     kids.forEach((c, i) => {
-      if (!c.vlan && hostVlan) c.vlan = hostVlan
       c.x = hostChip.x - ((Math.min(kids.length, CT_COLS) - 1) * CT_DX) / 2 + (i % CT_COLS) * CT_DX
       c.y = hostChip.y + CT_OFFSET_Y + Math.floor(i / CT_COLS) * CT_DY
       c.size = 22

+ 8 - 1
server-go/internal/adapters/agent.go

@@ -954,6 +954,10 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 		// push SIN sección FDB (event-driven) recicla el cache, mismo contrato
 		// anti-parpadeo que fdb.
 		out.wirelessSide = fd.WirelessSide
+		// #1757: VLAN real de cada cliente cableado, tal como el bridge la
+		// aprendió. Se pisa tal cual (incluso vacío) por la misma razón que el
+		// hint wireless-side: una sección fresca es la verdad del equipo.
+		out.fdbVlans = fd.VLANs
 		if len(fd.Ports) > 0 {
 			out.ports = ethPortsToAdapter(fd.Ports)
 			// #291: los pushers externos declaran el puerto del FDB como
@@ -1048,6 +1052,9 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	if out.wirelessSide == nil && p.Data.FDB == nil {
 		out.wirelessSide = cached.wirelessSide
 	}
+	if out.fdbVlans == nil && p.Data.FDB == nil {
+		out.fdbVlans = cached.fdbVlans
+	}
 	if out.luci == nil {
 		out.luci = cached.luci
 	}
@@ -1095,7 +1102,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 		lldpSnap = cached.lldp // conserva la última sección buena (#489)
 	}
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
-		wireless: out.wireless, fdb: out.fdb, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, systemKind: sysSnapKind, lldp: lldpSnap,
+		wireless: out.wireless, fdb: out.fdb, fdbVlans: out.fdbVlans, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, systemKind: sysSnapKind, lldp: lldpSnap,
 		clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
 	l.mu.Unlock()
 

+ 31 - 2
server-go/internal/adapters/live.go

@@ -154,6 +154,11 @@ type routerPolled struct {
 	ports    []EthPort
 	radios   []Radio
 	fdb      map[string]string
+	// fdbVlans: MAC → VLAN con la que el bridge aprendió esa MAC (#1757). El
+	// PVID de un puerto dice por dónde entra una trama sin etiquetar, no en
+	// qué VLAN vive el cliente: solo este dato lo dice. Vacío = sin dato (el
+	// bridge no tiene VLAN filtering, o la sonda es por SSH y no lo reporta).
+	fdbVlans map[string]int
 	// wirelessSide: MACs que el bridge del router aprende en sus propios
 	// puertos de radio (wl0.1, wlan0…) pero que la tabla de estaciones no
 	// lista (MACs rotadas que siguen emitiendo, backhaul 4-address). El
@@ -217,6 +222,9 @@ type extrasSnapshot struct {
 	radios   []Radio
 	wireless map[string]WirelessClient
 	fdb      map[string]string
+	// fdbVlans: MAC → VLAN del FDB (#1757). Mismo anti-parpadeo que fdb: solo
+	// nace del payload del agente y una sonda SSH exitosa lo limpia.
+	fdbVlans map[string]int
 	// wirelessSide: último hint bueno de MACs detrás de radios propias
 	// (ver routerPolled.wirelessSide). Mismo anti-parpadeo que fdb.
 	wirelessSide map[string]string
@@ -1324,6 +1332,13 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	if fdb != nil {
 		wsGood = nil
 	}
+	// La VLAN del FDB viaja solo en el payload del agente: la sonda SSH no la
+	// lee y una lectura buena sin ella LIMPIA el cache (un valor viejo pintaría
+	// al cliente en un segmento que ya dejó).
+	fdbVlansGood := cached.fdbVlans
+	if fdb != nil {
+		fdbVlansGood = nil
+	}
 	luciGood := cached.luci
 	if luci := client.GetLuCILabels(); luci != nil {
 		luciGood = luci
@@ -1333,7 +1348,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		vlansGood = vlans
 	}
 	l.mu.Lock()
-	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood, luci: luciGood, vlans: vlansGood}
+	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood, fdbVlans: fdbVlansGood, luci: luciGood, vlans: vlansGood}
 	l.mu.Unlock()
 
 	// Uso de RAM: #513. Si el agente reporta memory.used (procesos) lo
@@ -1383,7 +1398,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		cpu: cpuV, ram: ramPct, temp: tempV,
 		uptimeSec: sysInfo.Uptime, net: net, leases: leases, reservations: reservations, arp: arp, arpStale: arpStale, arpDevs: arpDevs, glClients: glClients,
 		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
-		fdb: fdbGood, wirelessSide: wsGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
+		fdb: fdbGood, fdbVlans: fdbVlansGood, wirelessSide: wsGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
 		backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
 		luci: luciGood, wanInfo: wanInfo, vlans: vlansGood,
 		polledAt: l.now().UnixMilli(),
@@ -3791,6 +3806,20 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 		}
 		devices = append(devices, d)
 	}
+	// #1757: la VLAN de un cliente sale de la evidencia exacta del bridge (la
+	// VLAN con la que aprendió su MAC), no del PVID del puerto por el que
+	// entró. Solo rellena el hueco: el `tag=` que declara el hipervisor para un
+	// invitado manda y se aplica después.
+	for i := range devices {
+		if devices[i].Vlan > 0 || devices[i].MAC == "" {
+			continue
+		}
+		if p := polled[devices[i].RouterID]; p != nil {
+			if v := p.fdbVlans[strings.ToUpper(devices[i].MAC)]; v > 0 {
+				devices[i].Vlan = v
+			}
+		}
+	}
 	// Give clients learned only in an SNMP switch's FDB a traffic figure from
 	// that port's counters (see switchporttraffic.go).
 	l.applySnmpSwitchPortTraffic(polled, devices)

+ 77 - 0
server-go/internal/adapters/vlans_client_1757_test.go

@@ -0,0 +1,77 @@
+// vlans_client_1757_test.go — VLAN de cada cliente desde el FDB del bridge
+// (#1757). El PVID de un puerto dice por dónde entra una trama sin etiquetar,
+// no en qué VLAN vive el cliente: el dato bueno es la VLAN con la que el
+// bridge aprendió su MAC.
+package adapters
+
+import "testing"
+
+func TestBuildDevicesVlanDesdeFdb(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := map[string]*routerPolled{
+		"rutto": {
+			cfg: RouterConfig{ID: "rutto", Name: "RUTTO", Host: "192.168.1.3"},
+			fdb: map[string]string{
+				"AA:BB:CC:DD:EE:01": "eth0.999",
+				"AA:BB:CC:DD:EE:02": "eth0.777",
+			},
+			fdbVlans: map[string]int{
+				"AA:BB:CC:DD:EE:01": 999,
+				"AA:BB:CC:DD:EE:02": 777,
+			},
+		},
+	}
+	devs := l.buildDevices(polled, "")
+	got := map[string]int{}
+	for _, d := range devs {
+		got[d.MAC] = d.Vlan
+	}
+	if got["AA:BB:CC:DD:EE:01"] != 999 {
+		t.Fatalf("cliente de eth0.999 esperado en VLAN 999, got %d (%+v)", got["AA:BB:CC:DD:EE:01"], devs)
+	}
+	if got["AA:BB:CC:DD:EE:02"] != 777 {
+		t.Fatalf("cliente de eth0.777 esperado en VLAN 777, got %d (%+v)", got["AA:BB:CC:DD:EE:02"], devs)
+	}
+}
+
+// Un FDB sin campo vlan (bridge sin VLAN filtering) NO inventa VLAN: el
+// cliente se queda sin dato y la UI no pinta ninguna.
+func TestBuildDevicesSinVlanEnFdbNoInventa(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := map[string]*routerPolled{
+		"rutto": {
+			cfg: RouterConfig{ID: "rutto", Name: "RUTTO"},
+			fdb: map[string]string{"AA:BB:CC:DD:EE:03": "lan1"},
+		},
+	}
+	devs := l.buildDevices(polled, "")
+	if len(devs) != 1 {
+		t.Fatalf("esperado 1 dispositivo, got %+v", devs)
+	}
+	if devs[0].Vlan != 0 {
+		t.Fatalf("sin dato de VLAN el dispositivo no debe llevar ninguna, got %d", devs[0].Vlan)
+	}
+}
+
+// La VLAN del FDB es de SU router: una MAC que otro router declara en una VLAN
+// no se le pega al dispositivo del primero.
+func TestBuildDevicesVlanNoCruzaRouters(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := map[string]*routerPolled{
+		"rutto": {
+			cfg:  RouterConfig{ID: "rutto", Name: "RUTTO"},
+			fdb:  map[string]string{"AA:BB:CC:DD:EE:04": "eth0"},
+			arp:  map[string]string{"AA:BB:CC:DD:EE:04": "192.168.1.40"},
+		},
+		"ap": {
+			cfg:      RouterConfig{ID: "ap", Name: "AP"},
+			fdbVlans: map[string]int{"AA:BB:CC:DD:EE:04": 888},
+		},
+	}
+	devs := l.buildDevices(polled, "")
+	for _, d := range devs {
+		if d.MAC == "AA:BB:CC:DD:EE:04" && d.Vlan == 888 {
+			t.Fatalf("la VLAN del FDB de otro router no debe aplicarse: %+v", d)
+		}
+	}
+}