config.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. matcher.Add(domain)
  49. }
  50. conds.Add(matcher)
  51. }
  52. if len(rr.UserEmail) > 0 {
  53. conds.Add(NewUserMatcher(rr.UserEmail))
  54. }
  55. if len(rr.InboundTag) > 0 {
  56. conds.Add(NewInboundTagMatcher(rr.InboundTag))
  57. }
  58. if rr.PortRange != nil {
  59. conds.Add(NewPortMatcher(*rr.PortRange))
  60. }
  61. if rr.NetworkList != nil {
  62. conds.Add(NewNetworkMatcher(rr.NetworkList))
  63. }
  64. if len(rr.Cidr) > 0 {
  65. cond, err := cidrToCondition(rr.Cidr, false)
  66. if err != nil {
  67. return nil, err
  68. }
  69. conds.Add(cond)
  70. }
  71. if len(rr.SourceCidr) > 0 {
  72. cond, err := cidrToCondition(rr.SourceCidr, true)
  73. if err != nil {
  74. return nil, err
  75. }
  76. conds.Add(cond)
  77. }
  78. if len(rr.Protocol) > 0 {
  79. conds.Add(NewProtocolMatcher(rr.Protocol))
  80. }
  81. if conds.Len() == 0 {
  82. return nil, newError("this rule has no effective fields").AtWarning()
  83. }
  84. return conds, nil
  85. }