Просмотр исходного кода

fix(devices): recompute the type and unmapped address for PTR names

gnacho 1 месяц назад
Родитель
Сommit
bf8cea80d6

+ 2 - 0
docs/manual.en.md

@@ -204,6 +204,8 @@ The detail is fed by the read-only SSH polling and by the extras the backend ret
 
 Clients are discovered from three sources running on the monitored routers: (1) the DHCP lease table, (2) the bridge FDB for wired clients and (3) mDNS/Bonjour when `umdns` is installed. Type classification uses hostname patterns and manufacturer OUI. Discovery requires the agent to run on the router that sees the clients; without an agent on the gateway, the list stays empty.
 
+A host that nothing else names, typically a server, switch or access point with a static address that never takes a lease, falls back to the PTR record of its address as the last source. The PTR has to be forward-confirmed, the domain is dropped and only private, shared CGNAT and link-local addresses are queried, so a public address is never sent to an upstream resolver. The lookup runs in the background: the device shows its name on the next poll and never blocks it. `NETPULSE_RDNS=0` turns the fallback off. A host named this way is no longer reported as an unknown device, the same as a host named by mDNS.
+
 ### How to read it
 
 - The **signal** follows the usual scale: green above -55 dBm, cyan between -55 and -70, amber below -70 (considered weak).

+ 2 - 0
docs/manual.es.md

@@ -204,6 +204,8 @@ El detalle se alimenta del sondeo SSH de solo lectura y de los extras que devuel
 
 Los clientes se descubren desde tres fuentes que corren en los routers monitorizados: (1) la tabla de concesiones DHCP, (2) el bridge FDB para clientes por cable y (3) mDNS/Bonjour cuando `umdns` está instalado. La clasificación por tipo usa patrones de hostname y OUI del fabricante. El descubrimiento exige que el agente corra en el router que ve a los clientes; sin agente en el gateway, la lista estará vacía.
 
+Cuando nada más pone nombre a un equipo (típicamente un servidor, switch o punto de acceso con dirección fija que nunca pide concesión), se recurre como última fuente al registro PTR de su dirección. El PTR tiene que resolver de vuelta a la misma dirección, se descarta el dominio y solo se consultan direcciones privadas, CGNAT compartido y link-local, así que una dirección pública nunca se envía a un resolver externo. La consulta va en segundo plano: el equipo aparece con nombre en el siguiente sondeo y nunca lo bloquea. `NETPULSE_RDNS=0` desactiva el recurso. Un equipo nombrado así deja de contarse como dispositivo desconocido, igual que uno nombrado por mDNS.
+
 ### Cómo leerlo
 
 - La **señal** sigue la escala habitual: verde por encima de -55 dBm, cian entre -55 y -70, ámbar por debajo de -70 (se considera débil).

+ 3 - 0
server-go/internal/adapters/live.go

@@ -3416,6 +3416,9 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 		if d.Name == mac && d.IP != "" {
 			if host := l.rdns.Name(d.IP); host != "" {
 				d.Name = host
+				// The type above was guessed from the MAC, which says
+				// nothing. Guess it again now that there is a hostname.
+				d.Type = GuessDeviceType(d.Name, d.Manufacturer, vendorClass, clientID, lldpCapsByMac[mac])
 			}
 		}
 		if randomMACs[mac] {

+ 19 - 5
server-go/internal/adapters/rdns.go

@@ -78,7 +78,14 @@ func (c *rdnsCache) Name(ip string) string {
 		return ""
 	}
 	addr, err := netip.ParseAddr(ip)
-	if err != nil || !rdnsEligible(addr) {
+	if err != nil {
+		return ""
+	}
+	// An IPv4-mapped IPv6 address (::ffff:172.16.16.4) has to be unmapped
+	// before it is used as a cache key and compared with the forward lookup,
+	// which returns plain IPv4 addresses.
+	addr = addr.Unmap()
+	if !rdnsEligible(addr) {
 		return ""
 	}
 	key := addr.String()
@@ -89,9 +96,16 @@ func (c *rdnsCache) Name(ip string) string {
 		return e.name
 	}
 	if !c.inflight[key] {
-		c.inflight[key] = true
-		c.wg.Add(1)
-		go c.resolve(addr)
+		// Take a worker slot before spawning, so a network full of unnamed
+		// hosts queues lookups for later polls instead of one goroutine per
+		// address waiting on the semaphore.
+		select {
+		case c.sem <- struct{}{}:
+			c.inflight[key] = true
+			c.wg.Add(1)
+			go c.resolve(addr)
+		default:
+		}
 	}
 	// A stale name is still better than a MAC while the refresh runs.
 	return e.name
@@ -99,7 +113,7 @@ func (c *rdnsCache) Name(ip string) string {
 
 func (c *rdnsCache) resolve(addr netip.Addr) {
 	defer c.wg.Done()
-	c.sem <- struct{}{}
+	// The worker slot was taken by Name before this goroutine started.
 	defer func() { <-c.sem }()
 	name := c.lookup(addr)
 	ttl := rdnsTTL

+ 5 - 0
server-go/internal/adapters/rdns_builddevices_test.go

@@ -50,6 +50,11 @@ func TestBuildDevicesNamesFromReverseDNS(t *testing.T) {
 	if got := devs["5C:E2:8C:00:00:04"].Name; got != "switch-garage" {
 		t.Fatalf("static host: got %q, want switch-garage", got)
 	}
+	// The type is guessed again after the PTR name lands: "switch-garage"
+	// matches the switch rule, while a bare MAC can only be "desconocido".
+	if got := devs["5C:E2:8C:00:00:04"].Type; got != "switch" {
+		t.Fatalf("static host type: got %q, want switch", got)
+	}
 	if got := devs["AA:BB:CC:00:00:70"].Name; got != "laptop" {
 		t.Fatalf("leased host: got %q, want laptop", got)
 	}

+ 50 - 0
server-go/internal/adapters/rdns_test.go

@@ -114,6 +114,56 @@ func TestRDNSName(t *testing.T) {
 	}
 }
 
+func TestRDNSIPv4MappedAddress(t *testing.T) {
+	f := &fakeRDNS{
+		ptr: map[string][]string{
+			"172.16.16.6": {"ap-hall.home.arpa."},
+		},
+		forward: map[string][]string{
+			"ap-hall.home.arpa": {"172.16.16.6"},
+		},
+	}
+	c := newTestRDNS(f, time.Now)
+	// A mapped address has to be unmapped before the forward comparison,
+	// otherwise LookupNetIP returns a plain IPv4 and the match never happens.
+	if got := resolved(c, "::ffff:172.16.16.6"); got != "ap-hall" {
+		t.Fatalf("mapped address: got %q, want ap-hall", got)
+	}
+	if n := f.count("172.16.16.6"); n != 1 {
+		t.Fatalf("lookup used %v, want the unmapped 172.16.16.6", f.calls)
+	}
+}
+
+func TestRDNSDoesNotQueueBeyondConcurrency(t *testing.T) {
+	f := &fakeRDNS{ptr: map[string][]string{}, forward: map[string][]string{}}
+	c := newTestRDNS(f, time.Now)
+	for i := 0; i < rdnsConcurrency; i++ {
+		c.sem <- struct{}{}
+	}
+	c.Name("172.16.16.61")
+	c.mu.Lock()
+	queued := len(c.inflight)
+	c.mu.Unlock()
+	if queued != 0 {
+		t.Fatalf("queued %d lookups while every worker was busy", queued)
+	}
+	for i := 0; i < rdnsConcurrency; i++ {
+		<-c.sem
+	}
+	// With a slot free the next poll queues it normally.
+	c.Name("172.16.16.61")
+	c.wg.Wait()
+	c.mu.Lock()
+	queued = len(c.inflight)
+	c.mu.Unlock()
+	if queued != 0 {
+		t.Fatalf("%d lookups still in flight after the worker finished", queued)
+	}
+	if _, ok := c.entries["172.16.16.61"]; !ok {
+		t.Fatal("lookup was never resolved once a slot was free")
+	}
+}
+
 func TestRDNSCachesAndExpires(t *testing.T) {
 	f := &fakeRDNS{
 		ptr:     map[string][]string{"172.16.16.4": {"switch-garage.home.arpa."}},