rule_item_rule_set.go 1.2 KB

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