config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package router
  2. import (
  3. "context"
  4. "net"
  5. v2net "v2ray.com/core/common/net"
  6. )
  7. type Rule struct {
  8. Tag string
  9. Condition Condition
  10. }
  11. func (r *Rule) Apply(ctx context.Context) bool {
  12. return r.Condition.Apply(ctx)
  13. }
  14. func cidrToCondition(cidr []*CIDR, source bool) (Condition, error) {
  15. ipv4Net := v2net.NewIPNet()
  16. ipv6Cond := NewAnyCondition()
  17. hasIpv6 := false
  18. for _, ip := range cidr {
  19. switch len(ip.Ip) {
  20. case net.IPv4len:
  21. ipv4Net.AddIP(ip.Ip, byte(ip.Prefix))
  22. case net.IPv6len:
  23. hasIpv6 = true
  24. matcher, err := NewCIDRMatcher(ip.Ip, ip.Prefix, source)
  25. if err != nil {
  26. return nil, err
  27. }
  28. ipv6Cond.Add(matcher)
  29. default:
  30. return nil, newError("invalid IP length").AtError()
  31. }
  32. }
  33. if !ipv4Net.IsEmpty() && hasIpv6 {
  34. cond := NewAnyCondition()
  35. cond.Add(NewIPv4Matcher(ipv4Net, source))
  36. cond.Add(ipv6Cond)
  37. return cond, nil
  38. } else if !ipv4Net.IsEmpty() {
  39. return NewIPv4Matcher(ipv4Net, source), nil
  40. } else {
  41. return ipv6Cond, nil
  42. }
  43. }
  44. func (rr *RoutingRule) BuildCondition() (Condition, error) {
  45. conds := NewConditionChan()
  46. if len(rr.Domain) > 0 {
  47. anyCond := NewAnyCondition()
  48. for _, domain := range rr.Domain {
  49. switch domain.Type {
  50. case Domain_Plain:
  51. anyCond.Add(NewPlainDomainMatcher(domain.Value))
  52. case Domain_Regex:
  53. matcher, err := NewRegexpDomainMatcher(domain.Value)
  54. if err != nil {
  55. return nil, err
  56. }
  57. anyCond.Add(matcher)
  58. case Domain_Domain:
  59. anyCond.Add(NewSubDomainMatcher(domain.Value))
  60. default:
  61. panic("Unknown domain type.")
  62. }
  63. }
  64. conds.Add(anyCond)
  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 rr.PortRange != nil {
  74. conds.Add(NewPortMatcher(*rr.PortRange))
  75. }
  76. if rr.NetworkList != nil {
  77. conds.Add(NewNetworkMatcher(rr.NetworkList))
  78. }
  79. if len(rr.SourceCidr) > 0 {
  80. cond, err := cidrToCondition(rr.SourceCidr, true)
  81. if err != nil {
  82. return nil, err
  83. }
  84. conds.Add(cond)
  85. }
  86. if len(rr.UserEmail) > 0 {
  87. conds.Add(NewUserMatcher(rr.UserEmail))
  88. }
  89. if len(rr.InboundTag) > 0 {
  90. conds.Add(NewInboundTagMatcher(rr.InboundTag))
  91. }
  92. if conds.Len() == 0 {
  93. return nil, newError("this rule has no effective fields").AtError()
  94. }
  95. return conds, nil
  96. }