-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rule_item_domain_regex.go
61 lines (54 loc) · 1.41 KB
/
rule_item_domain_regex.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
package route
import (
"regexp"
"strings"
"github.com/kelleygo/sing-box/adapter"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
)
var _ RuleItem = (*DomainRegexItem)(nil)
type DomainRegexItem struct {
matchers []*regexp.Regexp
description string
}
func NewDomainRegexItem(expressions []string) (*DomainRegexItem, error) {
matchers := make([]*regexp.Regexp, 0, len(expressions))
for i, regex := range expressions {
matcher, err := regexp.Compile(regex)
if err != nil {
return nil, E.Cause(err, "parse expression ", i)
}
matchers = append(matchers, matcher)
}
description := "domain_regex="
eLen := len(expressions)
if eLen == 1 {
description += expressions[0]
} else if eLen > 3 {
description += F.ToString("[", strings.Join(expressions[:3], " "), "]")
} else {
description += F.ToString("[", strings.Join(expressions, " "), "]")
}
return &DomainRegexItem{matchers, description}, nil
}
func (r *DomainRegexItem) Match(metadata *adapter.InboundContext) bool {
var domainHost string
if metadata.Domain != "" {
domainHost = metadata.Domain
} else {
domainHost = metadata.Destination.Fqdn
}
if domainHost == "" {
return false
}
domainHost = strings.ToLower(domainHost)
for _, matcher := range r.matchers {
if matcher.MatchString(domainHost) {
return true
}
}
return false
}
func (r *DomainRegexItem) String() string {
return r.description
}