config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package router
  2. import (
  3. "context"
  4. )
  5. // CIDRList is an alias of []*CIDR to provide sort.Interface.
  6. type CIDRList []*CIDR
  7. // Len implements sort.Interface.
  8. func (l *CIDRList) Len() int {
  9. return len(*l)
  10. }
  11. // Less implements sort.Interface.
  12. func (l *CIDRList) Less(i int, j int) bool {
  13. ci := (*l)[i]
  14. cj := (*l)[j]
  15. if len(ci.Ip) < len(cj.Ip) {
  16. return true
  17. }
  18. if len(ci.Ip) > len(cj.Ip) {
  19. return false
  20. }
  21. for k := 0; k < len(ci.Ip); k++ {
  22. if ci.Ip[k] < cj.Ip[k] {
  23. return true
  24. }
  25. if ci.Ip[k] > cj.Ip[k] {
  26. return false
  27. }
  28. }
  29. return ci.Prefix < cj.Prefix
  30. }
  31. // Swap implements sort.Interface.
  32. func (l *CIDRList) Swap(i int, j int) {
  33. (*l)[i], (*l)[j] = (*l)[j], (*l)[i]
  34. }
  35. type Rule struct {
  36. Tag string
  37. Condition Condition
  38. }
  39. func (r *Rule) Apply(ctx context.Context) bool {
  40. return r.Condition.Apply(ctx)
  41. }
  42. func (rr *RoutingRule) BuildCondition() (Condition, error) {
  43. conds := NewConditionChan()
  44. if len(rr.Domain) > 0 {
  45. matcher, err := NewDomainMatcher(rr.Domain)
  46. if err != nil {
  47. return nil, newError("failed to build domain condition").Base(err)
  48. }
  49. conds.Add(matcher)
  50. }
  51. if len(rr.UserEmail) > 0 {
  52. conds.Add(NewUserMatcher(rr.UserEmail))
  53. }
  54. if len(rr.InboundTag) > 0 {
  55. conds.Add(NewInboundTagMatcher(rr.InboundTag))
  56. }
  57. if rr.PortRange != nil {
  58. conds.Add(NewPortMatcher(*rr.PortRange))
  59. }
  60. if rr.NetworkList != nil {
  61. conds.Add(NewNetworkMatcher(rr.NetworkList))
  62. }
  63. if len(rr.Geoip) > 0 {
  64. cond, err := NewMultiGeoIPMatcher(rr.Geoip, false)
  65. if err != nil {
  66. return nil, err
  67. }
  68. conds.Add(cond)
  69. } else if len(rr.Cidr) > 0 {
  70. cond, err := NewMultiGeoIPMatcher([]*GeoIP{{Cidr: rr.Cidr}}, false)
  71. if err != nil {
  72. return nil, err
  73. }
  74. conds.Add(cond)
  75. }
  76. if len(rr.SourceGeoip) > 0 {
  77. cond, err := NewMultiGeoIPMatcher(rr.SourceGeoip, true)
  78. if err != nil {
  79. return nil, err
  80. }
  81. conds.Add(cond)
  82. } else if len(rr.SourceCidr) > 0 {
  83. cond, err := NewMultiGeoIPMatcher([]*GeoIP{{Cidr: rr.SourceCidr}}, true)
  84. if err != nil {
  85. return nil, err
  86. }
  87. conds.Add(cond)
  88. }
  89. if len(rr.Protocol) > 0 {
  90. conds.Add(NewProtocolMatcher(rr.Protocol))
  91. }
  92. if conds.Len() == 0 {
  93. return nil, newError("this rule has no effective fields").AtWarning()
  94. }
  95. return conds, nil
  96. }