config.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. switch {
  33. case !ipv4Net.IsEmpty() && hasIpv6:
  34. cond := NewAnyCondition()
  35. cond.Add(NewIPv4Matcher(ipv4Net, source))
  36. cond.Add(ipv6Cond)
  37. return cond, nil
  38. case !ipv4Net.IsEmpty():
  39. return NewIPv4Matcher(ipv4Net, source), nil
  40. default:
  41. return ipv6Cond, nil
  42. }
  43. }
  44. func (rr *RoutingRule) BuildCondition() (Condition, error) {
  45. conds := NewConditionChan()
  46. if len(rr.Domain) > 0 {
  47. matcher, err := NewDomainMatcher(rr.Domain)
  48. if err != nil {
  49. return nil, newError("failed to build domain condition").Base(err)
  50. }
  51. conds.Add(matcher)
  52. }
  53. if len(rr.UserEmail) > 0 {
  54. conds.Add(NewUserMatcher(rr.UserEmail))
  55. }
  56. if len(rr.InboundTag) > 0 {
  57. conds.Add(NewInboundTagMatcher(rr.InboundTag))
  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.Cidr) > 0 {
  66. cond, err := cidrToCondition(rr.Cidr, false)
  67. if err != nil {
  68. return nil, err
  69. }
  70. conds.Add(cond)
  71. }
  72. if len(rr.SourceCidr) > 0 {
  73. cond, err := cidrToCondition(rr.SourceCidr, true)
  74. if err != nil {
  75. return nil, err
  76. }
  77. conds.Add(cond)
  78. }
  79. if len(rr.Protocol) > 0 {
  80. conds.Add(NewProtocolMatcher(rr.Protocol))
  81. }
  82. if conds.Len() == 0 {
  83. return nil, newError("this rule has no effective fields").AtWarning()
  84. }
  85. return conds, nil
  86. }