config.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package router
  2. import (
  3. "context"
  4. "v2ray.com/core/common/net"
  5. )
  6. type Rule struct {
  7. Tag string
  8. Condition Condition
  9. }
  10. func (r *Rule) Apply(ctx context.Context) bool {
  11. return r.Condition.Apply(ctx)
  12. }
  13. func cidrToCondition(cidr []*CIDR, source bool) (Condition, error) {
  14. ipv4Net := net.NewIPNetTable()
  15. ipv6Cond := NewAnyCondition()
  16. hasIpv6 := false
  17. for _, ip := range cidr {
  18. switch len(ip.Ip) {
  19. case net.IPv4len:
  20. ipv4Net.AddIP(ip.Ip, byte(ip.Prefix))
  21. case net.IPv6len:
  22. hasIpv6 = true
  23. matcher, err := NewCIDRMatcher(ip.Ip, ip.Prefix, source)
  24. if err != nil {
  25. return nil, err
  26. }
  27. ipv6Cond.Add(matcher)
  28. default:
  29. return nil, newError("invalid IP length").AtWarning()
  30. }
  31. }
  32. if !ipv4Net.IsEmpty() && hasIpv6 {
  33. cond := NewAnyCondition()
  34. cond.Add(NewIPv4Matcher(ipv4Net, source))
  35. cond.Add(ipv6Cond)
  36. return cond, nil
  37. } else if !ipv4Net.IsEmpty() {
  38. return NewIPv4Matcher(ipv4Net, source), nil
  39. } else {
  40. return ipv6Cond, nil
  41. }
  42. }
  43. func (rr *RoutingRule) BuildCondition() (Condition, error) {
  44. conds := NewConditionChan()
  45. if len(rr.Domain) > 0 {
  46. matcher := NewCachableDomainMatcher()
  47. for _, domain := range rr.Domain {
  48. if err := matcher.Add(domain); err != nil {
  49. return nil, newError("failed to build domain condition").Base(err)
  50. }
  51. }
  52. conds.Add(matcher)
  53. }
  54. if len(rr.UserEmail) > 0 {
  55. conds.Add(NewUserMatcher(rr.UserEmail))
  56. }
  57. if len(rr.InboundTag) > 0 {
  58. conds.Add(NewInboundTagMatcher(rr.InboundTag))
  59. }
  60. if rr.PortRange != nil {
  61. conds.Add(NewPortMatcher(*rr.PortRange))
  62. }
  63. if rr.NetworkList != nil {
  64. conds.Add(NewNetworkMatcher(rr.NetworkList))
  65. }
  66. if len(rr.Cidr) > 0 {
  67. cond, err := cidrToCondition(rr.Cidr, false)
  68. if err != nil {
  69. return nil, err
  70. }
  71. conds.Add(cond)
  72. }
  73. if len(rr.SourceCidr) > 0 {
  74. cond, err := cidrToCondition(rr.SourceCidr, true)
  75. if err != nil {
  76. return nil, err
  77. }
  78. conds.Add(cond)
  79. }
  80. if len(rr.Protocol) > 0 {
  81. conds.Add(NewProtocolMatcher(rr.Protocol))
  82. }
  83. if conds.Len() == 0 {
  84. return nil, newError("this rule has no effective fields").AtWarning()
  85. }
  86. return conds, nil
  87. }