forked from SagerNet/sing-box
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrule_item_cidr.go
94 lines (85 loc) · 2 KB
/
rule_item_cidr.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
88
89
90
91
92
93
94
package route
import (
"net/netip"
"strings"
"github.com/sagernet/sing-box/adapter"
E "github.com/sagernet/sing/common/exceptions"
"go4.org/netipx"
)
var _ RuleItem = (*IPCIDRItem)(nil)
type IPCIDRItem struct {
ipSet *netipx.IPSet
isSource bool
description string
}
func NewIPCIDRItem(isSource bool, prefixStrings []string) (*IPCIDRItem, error) {
var builder netipx.IPSetBuilder
for i, prefixString := range prefixStrings {
prefix, err := netip.ParsePrefix(prefixString)
if err == nil {
builder.AddPrefix(prefix)
continue
}
addr, addrErr := netip.ParseAddr(prefixString)
if addrErr == nil {
builder.Add(addr)
continue
}
return nil, E.Cause(err, "parse [", i, "]")
}
var description string
if isSource {
description = "source_ip_cidr="
} else {
description = "ip_cidr="
}
if dLen := len(prefixStrings); dLen == 1 {
description += prefixStrings[0]
} else if dLen > 3 {
description += "[" + strings.Join(prefixStrings[:3], " ") + "...]"
} else {
description += "[" + strings.Join(prefixStrings, " ") + "]"
}
ipSet, err := builder.IPSet()
if err != nil {
return nil, err
}
return &IPCIDRItem{
ipSet: ipSet,
isSource: isSource,
description: description,
}, nil
}
func NewRawIPCIDRItem(isSource bool, ipSet *netipx.IPSet) *IPCIDRItem {
var description string
if isSource {
description = "source_ip_cidr="
} else {
description = "ip_cidr="
}
description += "<binary>"
return &IPCIDRItem{
ipSet: ipSet,
isSource: isSource,
description: description,
}
}
func (r *IPCIDRItem) Match(metadata *adapter.InboundContext) bool {
if r.isSource || metadata.IPCIDRMatchSource {
return r.ipSet.Contains(metadata.Source.Addr)
} else {
if metadata.Destination.IsIP() {
return r.ipSet.Contains(metadata.Destination.Addr)
} else {
for _, address := range metadata.DestinationAddresses {
if r.ipSet.Contains(address) {
return true
}
}
}
}
return false
}
func (r *IPCIDRItem) String() string {
return r.description
}