config.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package router
  2. import (
  3. "errors"
  4. "net"
  5. v2net "v2ray.com/core/common/net"
  6. )
  7. type Rule struct {
  8. Tag string
  9. Condition Condition
  10. }
  11. func (this *Rule) Apply(dest v2net.Destination) bool {
  12. return this.Condition.Apply(dest)
  13. }
  14. func (this *RoutingRule) BuildCondition() (Condition, error) {
  15. conds := NewConditionChan()
  16. if len(this.Domain) > 0 {
  17. anyCond := NewAnyCondition()
  18. for _, domain := range this.Domain {
  19. if domain.Type == Domain_Plain {
  20. anyCond.Add(NewPlainDomainMatcher(domain.Value))
  21. } else {
  22. matcher, err := NewRegexpDomainMatcher(domain.Value)
  23. if err != nil {
  24. return nil, err
  25. }
  26. anyCond.Add(matcher)
  27. }
  28. }
  29. conds.Add(anyCond)
  30. }
  31. if len(this.Cidr) > 0 {
  32. ipv4Net := v2net.NewIPNet()
  33. ipv6Cond := NewAnyCondition()
  34. hasIpv6 := false
  35. for _, ip := range this.Cidr {
  36. switch len(ip.Ip) {
  37. case net.IPv4len:
  38. ipv4Net.AddIP(ip.Ip, byte(ip.Prefix))
  39. case net.IPv6len:
  40. hasIpv6 = true
  41. matcher, err := NewCIDRMatcher(ip.Ip, ip.Prefix)
  42. if err != nil {
  43. return nil, err
  44. }
  45. ipv6Cond.Add(matcher)
  46. default:
  47. return nil, errors.New("Router: Invalid IP length.")
  48. }
  49. }
  50. if !ipv4Net.IsEmpty() && hasIpv6 {
  51. cond := NewAnyCondition()
  52. cond.Add(NewIPv4Matcher(ipv4Net))
  53. cond.Add(ipv6Cond)
  54. conds.Add(cond)
  55. } else if !ipv4Net.IsEmpty() {
  56. conds.Add(NewIPv4Matcher(ipv4Net))
  57. } else if hasIpv6 {
  58. conds.Add(ipv6Cond)
  59. }
  60. }
  61. if this.PortRange != nil {
  62. conds.Add(NewPortMatcher(*this.PortRange))
  63. }
  64. if this.NetworkList != nil {
  65. conds.Add(NewNetworkMatcher(this.NetworkList))
  66. }
  67. if conds.Len() == 0 {
  68. return nil, errors.New("Router: This rule has no effective fields.")
  69. }
  70. return conds, nil
  71. }