rule_item_rule_set.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package rule
  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. ipCidrAcceptEmpty bool
  16. }
  17. func NewRuleSetItem(router adapter.Router, tagList []string, ipCIDRMatchSource bool, ipCidrAcceptEmpty bool) *RuleSetItem {
  18. return &RuleSetItem{
  19. router: router,
  20. tagList: tagList,
  21. ipCidrMatchSource: ipCIDRMatchSource,
  22. ipCidrAcceptEmpty: ipCidrAcceptEmpty,
  23. }
  24. }
  25. func (r *RuleSetItem) Start() error {
  26. for _, tag := range r.tagList {
  27. ruleSet, loaded := r.router.RuleSet(tag)
  28. if !loaded {
  29. return E.New("rule-set not found: ", tag)
  30. }
  31. ruleSet.IncRef()
  32. r.setList = append(r.setList, ruleSet)
  33. }
  34. return nil
  35. }
  36. func (r *RuleSetItem) Match(metadata *adapter.InboundContext) bool {
  37. metadata.IPCIDRMatchSource = r.ipCidrMatchSource
  38. metadata.IPCIDRAcceptEmpty = r.ipCidrAcceptEmpty
  39. for _, ruleSet := range r.setList {
  40. if ruleSet.Match(metadata) {
  41. return true
  42. }
  43. }
  44. return false
  45. }
  46. func (r *RuleSetItem) ContainsDestinationIPCIDRRule() bool {
  47. if r.ipCidrMatchSource {
  48. return false
  49. }
  50. return common.Any(r.setList, func(ruleSet adapter.RuleSet) bool {
  51. return ruleSet.Metadata().ContainsIPCIDRRule
  52. })
  53. }
  54. func (r *RuleSetItem) String() string {
  55. if len(r.tagList) == 1 {
  56. return F.ToString("rule_set=", r.tagList[0])
  57. } else {
  58. return F.ToString("rule_set=[", strings.Join(r.tagList, " "), "]")
  59. }
  60. }