config.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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.Ip) > 0 {
  32. ipv4Net := make(map[uint32]byte)
  33. ipv6Cond := NewAnyCondition()
  34. hasIpv6 := false
  35. for _, ip := range this.Ip {
  36. switch len(ip.Ip) {
  37. case net.IPv4len:
  38. k := (uint32(ip.Ip[0]) << 24) + (uint32(ip.Ip[1]) << 16) + (uint32(ip.Ip[2]) << 8) + uint32(ip.Ip[3])
  39. ipv4Net[k] = byte(32 - ip.UnmatchingBits)
  40. case net.IPv6len:
  41. hasIpv6 = true
  42. matcher, err := NewCIDRMatcher(ip.Ip, uint32(32)-ip.UnmatchingBits)
  43. if err != nil {
  44. return nil, err
  45. }
  46. ipv6Cond.Add(matcher)
  47. default:
  48. return nil, errors.New("Router: Invalid IP length.")
  49. }
  50. }
  51. if len(ipv4Net) > 0 && hasIpv6 {
  52. cond := NewAnyCondition()
  53. cond.Add(NewIPv4Matcher(v2net.NewIPNetInitialValue(ipv4Net)))
  54. cond.Add(ipv6Cond)
  55. conds.Add(cond)
  56. } else if len(ipv4Net) > 0 {
  57. conds.Add(NewIPv4Matcher(v2net.NewIPNetInitialValue(ipv4Net)))
  58. } else if hasIpv6 {
  59. conds.Add(ipv6Cond)
  60. }
  61. }
  62. if this.PortRange != nil {
  63. conds.Add(NewPortMatcher(*this.PortRange))
  64. }
  65. if this.NetworkList != nil {
  66. conds.Add(NewNetworkMatcher(this.NetworkList))
  67. }
  68. if conds.Len() == 0 {
  69. return nil, errors.New("Router: This rule has no effective fields.")
  70. }
  71. return conds, nil
  72. }