config.go 1.9 KB

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