sing-box/route/rule_item_geosite.go

62 lines
1.3 KiB
Go
Raw Normal View History

2022-07-05 01:05:35 +00:00
package route
import (
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
2022-07-08 15:03:57 +00:00
E "github.com/sagernet/sing/common/exceptions"
2022-07-05 01:05:35 +00:00
)
var _ RuleItem = (*GeositeItem)(nil)
type GeositeItem struct {
2022-07-08 03:00:46 +00:00
router adapter.Router
2022-07-12 07:17:29 +00:00
logger log.ContextLogger
2022-07-08 03:00:46 +00:00
codes []string
matchers []adapter.Rule
2022-07-05 01:05:35 +00:00
}
2022-07-12 07:17:29 +00:00
func NewGeositeItem(router adapter.Router, logger log.ContextLogger, codes []string) *GeositeItem {
2022-07-05 01:05:35 +00:00
return &GeositeItem{
router: router,
logger: logger,
codes: codes,
}
}
2022-07-05 05:23:47 +00:00
func (r *GeositeItem) Update() error {
matchers := make([]adapter.Rule, 0, len(r.codes))
2022-07-05 01:05:35 +00:00
for _, code := range r.codes {
2022-07-08 03:00:46 +00:00
matcher, err := r.router.LoadGeosite(code)
2022-07-05 01:05:35 +00:00
if err != nil {
return E.Cause(err, "read geosite")
}
2022-07-08 03:00:46 +00:00
matchers = append(matchers, matcher)
2022-07-05 01:05:35 +00:00
}
2022-07-08 03:00:46 +00:00
r.matchers = matchers
2022-07-05 01:05:35 +00:00
return nil
}
func (r *GeositeItem) Match(metadata *adapter.InboundContext) bool {
2022-07-08 03:00:46 +00:00
for _, matcher := range r.matchers {
if matcher.Match(metadata) {
return true
}
2022-07-05 05:23:47 +00:00
}
2022-07-08 03:00:46 +00:00
return false
2022-07-05 01:05:35 +00:00
}
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
}