This commit is contained in:
世界 2022-04-16 18:03:58 +08:00
parent 12408d60a0
commit 12e645e9d2
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
7 changed files with 121 additions and 56 deletions

View file

@ -1,21 +1,50 @@
package geosite
import (
"regexp"
"strings"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/trieset"
)
type Matcher struct {
ds *trieset.DomainSet
ds *trieset.DomainSet
regex []*regexp.Regexp
}
func (m *Matcher) Match(domain string) bool {
return m.ds.Has(domain)
match := m.ds.Has(domain)
if match {
return match
}
if m.regex != nil {
for _, pattern := range m.regex {
match = pattern.MatchString(domain)
if match {
return match
}
}
}
return false
}
func NewMatcher(domains []string) (*Matcher, error) {
var regex []*regexp.Regexp
for i := range domains {
domain := domains[i]
if strings.HasPrefix(domain, "regexp:") {
domain = domain[7:]
pattern, err := regexp.Compile(domain)
if err != nil {
return nil, E.CauseF(err, "compile regex rule ", domain)
}
regex = append(regex, pattern)
}
}
ds, err := trieset.New(domains)
if err != nil {
return nil, err
}
return &Matcher{ds}, nil
return &Matcher{ds, regex}, nil
}

View file

@ -72,19 +72,19 @@ func (ds *DomainSet) has(key []byte, nodeId, bmIdx int) bool {
}
func New(domains []string) (*DomainSet, error) {
list := make([]string, len(domains))
list := make([]string, 0, len(domains))
for i, domain := range domains {
if domain == "" || domain[len(domain)-1] == '.' {
return nil, ErrInvalidDomain
for _, domain := range domains {
if domain == "" || domain[len(domain)-1] == '.' || strings.HasPrefix(domain, "regexp:") {
continue
}
domain = string(reverse(domain))
if strings.HasSuffix(domain, "+") {
list[i] = domain[:len(domain)-1]
list = append(list, domain[:len(domain)-1])
list = append(list, domain[:len(domain)-2])
} else {
list[i] = domain
list = append(list, domain)
}
}