sing-box/route/rule/rule_item_geosite.go

62 lines
1.3 KiB
Go
Raw Normal View History

2024-10-21 23:38:34 +08:00
package rule
2022-07-05 09:05:35 +08:00
import (
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
2022-07-08 23:03:57 +08:00
E "github.com/sagernet/sing/common/exceptions"
2022-07-05 09:05:35 +08:00
)
var _ RuleItem = (*GeositeItem)(nil)
type GeositeItem struct {
2022-07-08 11:00:46 +08:00
router adapter.Router
2022-07-12 15:17:29 +08:00
logger log.ContextLogger
2022-07-08 11:00:46 +08:00
codes []string
matchers []adapter.Rule
2022-07-05 09:05:35 +08:00
}
2022-07-12 15:17:29 +08:00
func NewGeositeItem(router adapter.Router, logger log.ContextLogger, codes []string) *GeositeItem {
2022-07-05 09:05:35 +08:00
return &GeositeItem{
router: router,
logger: logger,
codes: codes,
}
}
2022-07-05 13:23:47 +08:00
func (r *GeositeItem) Update() error {
matchers := make([]adapter.Rule, 0, len(r.codes))
2022-07-05 09:05:35 +08:00
for _, code := range r.codes {
2022-07-08 11:00:46 +08:00
matcher, err := r.router.LoadGeosite(code)
2022-07-05 09:05:35 +08:00
if err != nil {
return E.Cause(err, "read geosite")
}
2022-07-08 11:00:46 +08:00
matchers = append(matchers, matcher)
2022-07-05 09:05:35 +08:00
}
2022-07-08 11:00:46 +08:00
r.matchers = matchers
2022-07-05 09:05:35 +08:00
return nil
}
func (r *GeositeItem) Match(metadata *adapter.InboundContext) bool {
2022-07-08 11:00:46 +08:00
for _, matcher := range r.matchers {
if matcher.Match(metadata) {
return true
}
2022-07-05 13:23:47 +08:00
}
2022-07-08 11:00:46 +08:00
return false
2022-07-05 09:05:35 +08:00
}
func (r *GeositeItem) String() string {
description := "geosite="
cLen := len(r.codes)
if cLen == 1 {
2022-07-05 13:23:47 +08:00
description += r.codes[0]
2022-07-05 09:05:35 +08:00
} else if cLen > 3 {
2022-07-05 13:23:47 +08:00
description += "[" + strings.Join(r.codes[:3], " ") + "...]"
2022-07-05 09:05:35 +08:00
} else {
2022-07-05 13:23:47 +08:00
description += "[" + strings.Join(r.codes, " ") + "]"
2022-07-05 09:05:35 +08:00
}
return description
}