sing-box/route/rule_geosite.go

63 lines
1.2 KiB
Go
Raw Normal View History

2022-07-05 01:05:35 +00:00
package route
import (
"strings"
2022-07-06 07:01:09 +00:00
E "github.com/sagernet/sing/common/exceptions"
2022-07-05 01:05:35 +00:00
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
)
var _ RuleItem = (*GeositeItem)(nil)
type GeositeItem struct {
2022-07-08 03:00:46 +00:00
router adapter.Router
logger log.Logger
codes []string
matchers []adapter.Rule
2022-07-05 01:05:35 +00:00
}
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-08 03:00:46 +00:00
var matchers []adapter.Rule
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
}