rdns.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package adapters
  2. import (
  3. "context"
  4. "net"
  5. "net/netip"
  6. "os"
  7. "strings"
  8. "sync"
  9. "time"
  10. )
  11. // rdns.go — reverse DNS fallback for device names.
  12. //
  13. // Hosts with a static address never take a DHCP lease, so a network made of
  14. // fixed-IP servers, switches and access points shows most of them as bare
  15. // MACs even when the local DNS already knows every name. When nothing else
  16. // named a device (lease, reservation, alias, override, mDNS) its PTR record
  17. // is the last source tried.
  18. //
  19. // buildDevices runs on every poll and must never wait on DNS, so lookups are
  20. // asynchronous: Name answers from the cache and queues a background lookup
  21. // on a miss; the name shows up on the next poll. Only private and link-local
  22. // addresses are looked up, so the server does not send PTR queries for
  23. // public addresses to an upstream resolver. NETPULSE_RDNS=0 turns it off.
  24. const (
  25. rdnsTTL = time.Hour
  26. rdnsNegativeTTL = 15 * time.Minute
  27. rdnsTimeout = 3 * time.Second
  28. rdnsConcurrency = 4
  29. )
  30. type rdnsResolver interface {
  31. LookupAddr(ctx context.Context, addr string) ([]string, error)
  32. LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
  33. }
  34. type rdnsEntry struct {
  35. name string
  36. expires time.Time
  37. }
  38. type rdnsCache struct {
  39. enabled bool
  40. resolver rdnsResolver
  41. now func() time.Time
  42. mu sync.Mutex
  43. entries map[string]rdnsEntry
  44. inflight map[string]bool
  45. sem chan struct{}
  46. wg sync.WaitGroup
  47. }
  48. func newRDNSCache() *rdnsCache {
  49. c := &rdnsCache{
  50. enabled: true,
  51. resolver: net.DefaultResolver,
  52. now: time.Now,
  53. entries: map[string]rdnsEntry{},
  54. inflight: map[string]bool{},
  55. sem: make(chan struct{}, rdnsConcurrency),
  56. }
  57. if v, ok := os.LookupEnv("NETPULSE_RDNS"); ok {
  58. switch strings.ToLower(strings.TrimSpace(v)) {
  59. case "0", "false", "off", "no":
  60. c.enabled = false
  61. }
  62. }
  63. return c
  64. }
  65. // Name returns the cached PTR name for ip, or "" when there is none yet. A
  66. // missing or expired entry queues one background lookup.
  67. func (c *rdnsCache) Name(ip string) string {
  68. if c == nil || !c.enabled {
  69. return ""
  70. }
  71. addr, err := netip.ParseAddr(ip)
  72. if err != nil {
  73. return ""
  74. }
  75. // An IPv4-mapped IPv6 address (::ffff:172.16.16.4) has to be unmapped
  76. // before it is used as a cache key and compared with the forward lookup,
  77. // which returns plain IPv4 addresses.
  78. addr = addr.Unmap()
  79. if !rdnsEligible(addr) {
  80. return ""
  81. }
  82. key := addr.String()
  83. c.mu.Lock()
  84. defer c.mu.Unlock()
  85. e, ok := c.entries[key]
  86. if ok && c.now().Before(e.expires) {
  87. return e.name
  88. }
  89. if !c.inflight[key] {
  90. // Take a worker slot before spawning, so a network full of unnamed
  91. // hosts queues lookups for later polls instead of one goroutine per
  92. // address waiting on the semaphore.
  93. select {
  94. case c.sem <- struct{}{}:
  95. c.inflight[key] = true
  96. c.wg.Add(1)
  97. go c.resolve(addr)
  98. default:
  99. }
  100. }
  101. // A stale name is still better than a MAC while the refresh runs.
  102. return e.name
  103. }
  104. func (c *rdnsCache) resolve(addr netip.Addr) {
  105. defer c.wg.Done()
  106. // The worker slot was taken by Name before this goroutine started.
  107. defer func() { <-c.sem }()
  108. name := c.lookup(addr)
  109. ttl := rdnsTTL
  110. if name == "" {
  111. ttl = rdnsNegativeTTL
  112. }
  113. key := addr.String()
  114. c.mu.Lock()
  115. c.entries[key] = rdnsEntry{name: name, expires: c.now().Add(ttl)}
  116. delete(c.inflight, key)
  117. c.mu.Unlock()
  118. }
  119. // lookup returns the short name of the first PTR target that resolves back
  120. // to addr (forward-confirmed), skipping names generated from the address.
  121. func (c *rdnsCache) lookup(addr netip.Addr) string {
  122. ctx, cancel := context.WithTimeout(context.Background(), rdnsTimeout)
  123. defer cancel()
  124. names, err := c.resolver.LookupAddr(ctx, addr.String())
  125. if err != nil {
  126. return ""
  127. }
  128. for _, n := range names {
  129. fqdn := strings.TrimSuffix(n, ".")
  130. if fqdn == "" || rdnsEmbedsAddr(fqdn, addr) {
  131. continue
  132. }
  133. ips, err := c.resolver.LookupNetIP(ctx, "ip", fqdn)
  134. if err != nil {
  135. continue
  136. }
  137. for _, ip := range ips {
  138. if ip.Unmap() == addr {
  139. return rdnsShortName(fqdn)
  140. }
  141. }
  142. }
  143. return ""
  144. }
  145. // rdnsEligible keeps lookups on the local resolver's own zones: private,
  146. // shared CGNAT and link-local space only.
  147. func rdnsEligible(addr netip.Addr) bool {
  148. addr = addr.Unmap()
  149. if addr.IsPrivate() || addr.IsLinkLocalUnicast() {
  150. return true
  151. }
  152. return rdnsCGNAT.Contains(addr)
  153. }
  154. var rdnsCGNAT = netip.MustParsePrefix("100.64.0.0/10")
  155. // rdnsEmbedsAddr rejects synthesized PTRs such as "192-168-8-217.example.net"
  156. // or "ip-10-0-0-5.ec2.internal": they name the address, not the device, and
  157. // some public wildcard zones answer for private ranges.
  158. func rdnsEmbedsAddr(fqdn string, addr netip.Addr) bool {
  159. host := strings.ToLower(fqdn)
  160. s := addr.String()
  161. return strings.Contains(host, strings.NewReplacer(".", "-", ":", "-").Replace(s)) ||
  162. strings.Contains(host, s)
  163. }
  164. // rdnsShortName drops the domain, matching the bare hostnames DHCP leases
  165. // report ("switch-garage.home.arpa" -> "switch-garage").
  166. func rdnsShortName(fqdn string) string {
  167. if i := strings.IndexByte(fqdn, '.'); i > 0 {
  168. return fqdn[:i]
  169. }
  170. return fqdn
  171. }