// Package rdns resolves reverse DNS names in the background with a cache. package rdns import ( "context" "errors" "net" "net/netip" "strings" "sync" "time" ) type fcrEntry struct { ok bool exp time.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) forward func(ctx context.Context, name string) ([]string, error) fcr map[string]fcrEntry 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) } r.forward = func(ctx context.Context, name string) ([]string, error) { return net.DefaultResolver.LookupHost(ctx, name) } r.fcr = map[string]fcrEntry{} return r } // FCrDNS checks forward-confirmed reverse DNS for a crawler that claims to be // one: the reverse name must end in one of suffixes (each given as // "googlebot.com") and a forward lookup of that name must give the address // back. It is synchronous with a short timeout (1.5 s) and cached for 24 h. func (r *Resolver) FCrDNS(ip string, suffixes []string) bool { a, err := netip.ParseAddr(ip) if err != nil || a.Zone() != "" || a.IsPrivate() || a.IsLoopback() || a.IsUnspecified() { return false } a = a.Unmap() key := a.String() + "|" + strings.Join(suffixes, ",") r.mu.Lock() if e, ok := r.fcr[key]; ok && time.Now().Before(e.exp) { r.mu.Unlock() return e.ok } r.mu.Unlock() ok, transient := r.fcrdns(a, suffixes) ttl := r.TTL if transient { ttl = time.Minute // a timeout or a server failure says nothing: look again soon } r.mu.Lock() if len(r.fcr) >= r.MaxSize { r.fcr = map[string]fcrEntry{} } r.fcr[key] = fcrEntry{ok, time.Now().Add(ttl)} r.mu.Unlock() return ok } // isFinal reports whether a DNS error is an answer (the name does not exist) // rather than a transient failure. func isFinal(err error) bool { var de *net.DNSError return errors.As(err, &de) && de.IsNotFound } func (r *Resolver) fcrdns(a netip.Addr, suffixes []string) (ok, transient bool) { ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond) defer cancel() names, err := r.lookup(ctx, a.String()) if err != nil { return false, !isFinal(err) } for i, n := range names { if i >= 3 { break } n = strings.ToLower(strings.TrimSuffix(n, ".")) match := false for _, s := range suffixes { if n == s || strings.HasSuffix(n, "."+s) { match = true } } if !match { continue } addrs, err := r.forward(ctx, n) if err != nil { if !isFinal(err) { transient = true } continue } for _, x := range addrs { if b, err := netip.ParseAddr(x); err == nil && b.Unmap() == a { return true, false } } } return false, transient } // 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() } } }