// Package rdns resolves reverse DNS names in the background with a cache. package rdns import ( "context" "net" "net/netip" "strings" "sync" "time" ) type entry struct { name string exp time.Time } // Resolver answers from cache and queues unknown addresses for a worker. type Resolver struct { TTL time.Duration Timeout time.Duration MaxSize int lookup func(ctx context.Context, ip string) ([]string, error) mu sync.Mutex cache map[string]entry pending map[string]bool queue chan string } // New creates a resolver using the system resolver. func New() *Resolver { r := &Resolver{TTL: 24 * time.Hour, Timeout: 2 * time.Second, MaxSize: 4000, cache: map[string]entry{}, pending: map[string]bool{}, queue: make(chan string, 256)} r.lookup = func(ctx context.Context, ip string) ([]string, error) { return net.DefaultResolver.LookupAddr(ctx, ip) } return r } // Lookup returns the cached name ("" when unknown or not resolvable yet) and // queues the address for resolution. It never blocks. func (r *Resolver) Lookup(ip string) string { if a, err := netip.ParseAddr(ip); err != nil || a.IsPrivate() || a.IsLoopback() || a.IsUnspecified() { return "" } r.mu.Lock() e, ok := r.cache[ip] if ok && time.Now().Before(e.exp) { r.mu.Unlock() return e.name } if r.pending[ip] { r.mu.Unlock() return e.name } r.pending[ip] = true r.mu.Unlock() select { case r.queue <- ip: default: r.mu.Lock() delete(r.pending, ip) r.mu.Unlock() } return e.name } // Run resolves queued addresses until ctx is done. func (r *Resolver) Run(ctx context.Context) { for { select { case <-ctx.Done(): return case ip := <-r.queue: cctx, cancel := context.WithTimeout(ctx, r.Timeout) names, err := r.lookup(cctx, ip) cancel() name := "" if err == nil && len(names) > 0 { name = strings.TrimSuffix(names[0], ".") if len(name) > 200 { name = name[:200] } name = strings.Map(func(c rune) rune { if c < 0x21 || c > 0x7e { return -1 } return c }, name) } r.mu.Lock() if len(r.cache) >= r.MaxSize { r.cache = map[string]entry{} } r.cache[ip] = entry{name, time.Now().Add(r.TTL)} delete(r.pending, ip) r.mu.Unlock() } } }