2023-12-01 05:24:12 +00:00
|
|
|
package route
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/sagernet/sing-box/adapter"
|
2024-02-03 09:45:27 +00:00
|
|
|
"github.com/sagernet/sing/common"
|
2023-12-01 05:24:12 +00:00
|
|
|
E "github.com/sagernet/sing/common/exceptions"
|
|
|
|
F "github.com/sagernet/sing/common/format"
|
|
|
|
)
|
|
|
|
|
|
|
|
var _ RuleItem = (*RuleSetItem)(nil)
|
|
|
|
|
|
|
|
type RuleSetItem struct {
|
|
|
|
router adapter.Router
|
|
|
|
tagList []string
|
2024-02-03 09:45:27 +00:00
|
|
|
setList []adapter.RuleSet
|
2024-06-24 01:41:00 +00:00
|
|
|
ipCidrMatchSource bool
|
|
|
|
ipCidrAcceptEmpty bool
|
2023-12-01 05:24:12 +00:00
|
|
|
}
|
|
|
|
|
2024-06-24 01:41:00 +00:00
|
|
|
func NewRuleSetItem(router adapter.Router, tagList []string, ipCIDRMatchSource bool, ipCidrAcceptEmpty bool) *RuleSetItem {
|
2023-12-01 05:24:12 +00:00
|
|
|
return &RuleSetItem{
|
|
|
|
router: router,
|
|
|
|
tagList: tagList,
|
2024-06-24 01:41:00 +00:00
|
|
|
ipCidrMatchSource: ipCIDRMatchSource,
|
|
|
|
ipCidrAcceptEmpty: ipCidrAcceptEmpty,
|
2023-12-01 05:24:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RuleSetItem) Start() error {
|
|
|
|
for _, tag := range r.tagList {
|
|
|
|
ruleSet, loaded := r.router.RuleSet(tag)
|
|
|
|
if !loaded {
|
|
|
|
return E.New("rule-set not found: ", tag)
|
|
|
|
}
|
2024-06-07 07:55:21 +00:00
|
|
|
ruleSet.IncRef()
|
2023-12-01 05:24:12 +00:00
|
|
|
r.setList = append(r.setList, ruleSet)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *RuleSetItem) Match(metadata *adapter.InboundContext) bool {
|
2024-06-24 01:41:00 +00:00
|
|
|
metadata.IPCIDRMatchSource = r.ipCidrMatchSource
|
|
|
|
metadata.IPCIDRAcceptEmpty = r.ipCidrAcceptEmpty
|
2023-12-01 05:24:12 +00:00
|
|
|
for _, ruleSet := range r.setList {
|
|
|
|
if ruleSet.Match(metadata) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-02-21 06:27:55 +00:00
|
|
|
func (r *RuleSetItem) ContainsDestinationIPCIDRRule() bool {
|
2024-06-24 01:41:00 +00:00
|
|
|
if r.ipCidrMatchSource {
|
2024-02-21 06:27:55 +00:00
|
|
|
return false
|
|
|
|
}
|
2024-02-03 09:45:27 +00:00
|
|
|
return common.Any(r.setList, func(ruleSet adapter.RuleSet) bool {
|
|
|
|
return ruleSet.Metadata().ContainsIPCIDRRule
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-12-01 05:24:12 +00:00
|
|
|
func (r *RuleSetItem) String() string {
|
|
|
|
if len(r.tagList) == 1 {
|
|
|
|
return F.ToString("rule_set=", r.tagList[0])
|
|
|
|
} else {
|
|
|
|
return F.ToString("rule_set=[", strings.Join(r.tagList, " "), "]")
|
|
|
|
}
|
|
|
|
}
|