forked from xiachufang/krakend-ipfilter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.go
87 lines (75 loc) · 1.71 KB
/
filter.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package ipfilter
import (
"fmt"
"net"
"strings"
"github.com/yl2chen/cidranger"
)
// IPFilter is a interface for allow or deny an ip
type IPFilter interface {
Allow(ip string) bool
Deny(ip string) bool
}
// NoopFilter noop, allow always, never deny
type NoopFilter struct{}
// Allow implement IPFilter.Allow
func (noop *NoopFilter) Allow(_ string) bool {
return true
}
// Deny implement IPFilter.Deny
func (noop *NoopFilter) Deny(_ string) bool {
return false
}
// CIDRFilter is an ip filter base on cidranger
type CIDRFilter struct {
allowRanger cidranger.Ranger
denyRanger cidranger.Ranger
}
func newRanger(ips []string) cidranger.Ranger {
ranger := cidranger.NewPCTrieRanger()
for _, ip := range ips {
isCIDR := strings.IndexByte(ip, byte('/'))
if isCIDR < 0 {
ip = fmt.Sprintf("%s/24", ip)
}
_, ipNet, err := net.ParseCIDR(ip)
if err != nil || ipNet == nil {
continue
}
err = ranger.Insert(cidranger.NewBasicRangerEntry(*ipNet))
if err != nil {
continue
}
}
return ranger
}
// NewIPFilter create a cidranger base ip filter
func NewIPFilter(cfg *Config) IPFilter {
// always allow and never deny
if cfg == nil || (len(cfg.Deny) == 0) {
return &NoopFilter{}
}
return &CIDRFilter{
allowRanger: newRanger(cfg.Allow),
denyRanger: newRanger(cfg.Deny),
}
}
// Allow implement IPFilter.Allow
func (f *CIDRFilter) Allow(ip string) bool {
netIP := net.ParseIP(ip)
if netIP == nil {
return false
}
if allow, err := f.allowRanger.Contains(netIP); allow && err == nil {
return true
}
deny, err := f.denyRanger.Contains(netIP)
if deny || err != nil {
return false
}
return true
}
// Deny implement IPFilter.Deny
func (f *CIDRFilter) Deny(ip string) bool {
return !f.Allow(ip)
}