2022-07-05 01:05:35 +00:00
|
|
|
package route
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/sagernet/sing-box/adapter"
|
|
|
|
"github.com/sagernet/sing-box/common/geosite"
|
|
|
|
"github.com/sagernet/sing-box/log"
|
|
|
|
"github.com/sagernet/sing-box/option"
|
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
|
|
|
)
|
|
|
|
|
|
|
|
var _ RuleItem = (*GeositeItem)(nil)
|
|
|
|
|
|
|
|
type GeositeItem struct {
|
|
|
|
router adapter.Router
|
|
|
|
logger log.Logger
|
|
|
|
codes []string
|
|
|
|
matcher *DefaultRule
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewGeositeItem(router adapter.Router, logger log.Logger, codes []string) *GeositeItem {
|
|
|
|
return &GeositeItem{
|
|
|
|
router: router,
|
|
|
|
logger: logger,
|
|
|
|
codes: codes,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-05 05:23:47 +00:00
|
|
|
func (r *GeositeItem) Update() error {
|
2022-07-05 01:05:35 +00:00
|
|
|
geositeReader := r.router.GeositeReader()
|
|
|
|
if geositeReader == nil {
|
|
|
|
return E.New("geosite reader is not initialized")
|
|
|
|
}
|
|
|
|
var subRules []option.DefaultRule
|
|
|
|
for _, code := range r.codes {
|
|
|
|
items, err := geositeReader.Read(code)
|
|
|
|
if err != nil {
|
|
|
|
return E.Cause(err, "read geosite")
|
|
|
|
}
|
|
|
|
subRules = append(subRules, geosite.Compile(items))
|
|
|
|
}
|
|
|
|
matcherRule := geosite.Merge(subRules)
|
|
|
|
matcher, err := NewDefaultRule(r.router, r.logger, matcherRule)
|
|
|
|
if err != nil {
|
|
|
|
return E.Cause(err, "compile geosite")
|
|
|
|
}
|
|
|
|
r.matcher = matcher
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *GeositeItem) Match(metadata *adapter.InboundContext) bool {
|
2022-07-05 05:23:47 +00:00
|
|
|
if r.matcher == nil {
|
|
|
|
return false
|
|
|
|
}
|
2022-07-05 01:05:35 +00:00
|
|
|
return r.matcher.Match(metadata)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *GeositeItem) String() string {
|
|
|
|
description := "geosite="
|
|
|
|
cLen := len(r.codes)
|
|
|
|
if cLen == 1 {
|
2022-07-05 05:23:47 +00:00
|
|
|
description += r.codes[0]
|
2022-07-05 01:05:35 +00:00
|
|
|
} else if cLen > 3 {
|
2022-07-05 05:23:47 +00:00
|
|
|
description += "[" + strings.Join(r.codes[:3], " ") + "...]"
|
2022-07-05 01:05:35 +00:00
|
|
|
} else {
|
2022-07-05 05:23:47 +00:00
|
|
|
description += "[" + strings.Join(r.codes, " ") + "]"
|
2022-07-05 01:05:35 +00:00
|
|
|
}
|
|
|
|
return description
|
|
|
|
}
|