sing-box/route/rule_item_domain_regex.go

62 lines
1.4 KiB
Go
Raw Permalink Normal View History

2022-07-04 07:51:41 +00:00
package route
import (
"regexp"
"strings"
2022-07-08 15:03:57 +00:00
"github.com/sagernet/sing-box/adapter"
2022-07-04 07:51:41 +00:00
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 {
2022-07-05 05:23:47 +00:00
description += expressions[0]
2022-07-04 07:51:41 +00:00
} else if eLen > 3 {
2022-07-05 05:23:47 +00:00
description += F.ToString("[", strings.Join(expressions[:3], " "), "]")
2022-07-04 07:51:41 +00:00
} else {
2022-07-05 05:23:47 +00:00
description += F.ToString("[", strings.Join(expressions, " "), "]")
2022-07-04 07:51:41 +00:00
}
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
}
2023-02-02 07:14:43 +00:00
domainHost = strings.ToLower(domainHost)
2022-07-04 07:51:41 +00:00
for _, matcher := range r.matchers {
if matcher.MatchString(domainHost) {
return true
}
}
return false
}
func (r *DomainRegexItem) String() string {
return r.description
}