-
Notifications
You must be signed in to change notification settings - Fork 1
/
resolver.go
71 lines (57 loc) · 1.6 KB
/
resolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package filter
import (
"context"
"net"
"time"
"github.com/dgraph-io/ristretto"
"github.com/pkg/errors"
)
// CacheTTL is the duration before a domain name resolution is evict form the cache.
const CacheTTL = 12 * time.Hour
// ErrHostRejected is returned when the host has been flagged as unwanted.
var ErrHostRejected = errors.New("rejected host")
// A NameResolver is used to filter IPs using name resolution.
type NameResolver struct {
allows []*net.IPNet
cache *ristretto.Cache
}
// NewNameResolver return a new NameResolver.
func NewNameResolver(allows []string) (*NameResolver, error) {
cache, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 50_000,
MaxCost: 5000,
BufferItems: 64,
})
if err != nil {
return nil, err
}
resolver := &NameResolver{
allows: make([]*net.IPNet, 0, len(allows)),
cache: cache,
}
for _, allow := range allows {
_, block, err := net.ParseCIDR(allow)
if err != nil {
return nil, err
}
resolver.allows = append(resolver.allows, block)
}
return resolver, nil
}
// Resolve returns the ip for the given domain name.
func (r *NameResolver) Resolve(ctx context.Context, name string) (context.Context, net.IP, error) {
if ip, ok := r.cache.Get(name); ok {
return ctx, ip.(net.IP), nil
}
addr, err := net.ResolveIPAddr("ip", name)
if err != nil {
return ctx, nil, errors.Wrapf(err, "[resolve] %s", name)
}
for _, block := range r.allows {
if block.Contains(addr.IP) {
r.cache.SetWithTTL(name, addr.IP, 1, CacheTTL)
return ctx, addr.IP, nil
}
}
return ctx, nil, errors.Wrapf(ErrHostRejected, "[domain/ip] %s/%s", name, addr.IP)
}