rule_item_rule_set.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package route
  2. import (
  3. "strings"
  4. "github.com/sagernet/sing-box/adapter"
  5. "github.com/sagernet/sing/common"
  6. E "github.com/sagernet/sing/common/exceptions"
  7. F "github.com/sagernet/sing/common/format"
  8. )
  9. var _ RuleItem = (*RuleSetItem)(nil)
  10. type RuleSetItem struct {
  11. router adapter.Router
  12. tagList []string
  13. setList []adapter.RuleSet
  14. ipcidrMatchSource bool
  15. }
  16. func NewRuleSetItem(router adapter.Router, tagList []string, ipCIDRMatchSource bool) *RuleSetItem {
  17. return &RuleSetItem{
  18. router: router,
  19. tagList: tagList,
  20. ipcidrMatchSource: ipCIDRMatchSource,
  21. }
  22. }
  23. func (r *RuleSetItem) Start() error {
  24. for _, tag := range r.tagList {
  25. ruleSet, loaded := r.router.RuleSet(tag)
  26. if !loaded {
  27. return E.New("rule-set not found: ", tag)
  28. }
  29. r.setList = append(r.setList, ruleSet)
  30. }
  31. return nil
  32. }
  33. func (r *RuleSetItem) Match(metadata *adapter.InboundContext) bool {
  34. metadata.IPCIDRMatchSource = r.ipcidrMatchSource
  35. for _, ruleSet := range r.setList {
  36. if ruleSet.Match(metadata) {
  37. return true
  38. }
  39. }
  40. return false
  41. }
  42. func (r *RuleSetItem) ContainsIPCIDRRule() bool {
  43. return common.Any(r.setList, func(ruleSet adapter.RuleSet) bool {
  44. return ruleSet.Metadata().ContainsIPCIDRRule
  45. })
  46. }
  47. func (r *RuleSetItem) String() string {
  48. if len(r.tagList) == 1 {
  49. return F.ToString("rule_set=", r.tagList[0])
  50. } else {
  51. return F.ToString("rule_set=[", strings.Join(r.tagList, " "), "]")
  52. }
  53. }