sing-box/route/rule_geosite.go

62 lines
1.2 KiB
Go
Raw Normal View History

2022-07-05 09:05:35 +08:00
package route
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
logger log.Logger
codes []string
matchers []adapter.Rule
2022-07-05 09:05:35 +08:00
}
func NewGeositeItem(router adapter.Router, logger log.Logger, codes []string) *GeositeItem {
return &GeositeItem{
router: router,
logger: logger,
codes: codes,
}
}
2022-07-05 13:23:47 +08:00
func (r *GeositeItem) Update() error {
2022-07-08 11:00:46 +08:00
var matchers []adapter.Rule
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
}