condition.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. package router
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. "v2ray.com/core/common/net"
  7. "v2ray.com/core/common/protocol"
  8. "v2ray.com/core/common/strmatcher"
  9. "v2ray.com/core/proxy"
  10. )
  11. type Condition interface {
  12. Apply(ctx context.Context) bool
  13. }
  14. type ConditionChan []Condition
  15. func NewConditionChan() *ConditionChan {
  16. var condChan ConditionChan = make([]Condition, 0, 8)
  17. return &condChan
  18. }
  19. func (v *ConditionChan) Add(cond Condition) *ConditionChan {
  20. *v = append(*v, cond)
  21. return v
  22. }
  23. func (v *ConditionChan) Apply(ctx context.Context) bool {
  24. for _, cond := range *v {
  25. if !cond.Apply(ctx) {
  26. return false
  27. }
  28. }
  29. return true
  30. }
  31. func (v *ConditionChan) Len() int {
  32. return len(*v)
  33. }
  34. type AnyCondition []Condition
  35. func NewAnyCondition() *AnyCondition {
  36. var anyCond AnyCondition = make([]Condition, 0, 8)
  37. return &anyCond
  38. }
  39. func (v *AnyCondition) Add(cond Condition) *AnyCondition {
  40. *v = append(*v, cond)
  41. return v
  42. }
  43. func (v *AnyCondition) Apply(ctx context.Context) bool {
  44. for _, cond := range *v {
  45. if cond.Apply(ctx) {
  46. return true
  47. }
  48. }
  49. return false
  50. }
  51. func (v *AnyCondition) Len() int {
  52. return len(*v)
  53. }
  54. type timedResult struct {
  55. timestamp time.Time
  56. result bool
  57. }
  58. type CachableDomainMatcher struct {
  59. sync.Mutex
  60. matchers *strmatcher.MatcherGroup
  61. cache map[string]timedResult
  62. lastScan time.Time
  63. }
  64. func NewCachableDomainMatcher() *CachableDomainMatcher {
  65. return &CachableDomainMatcher{
  66. matchers: strmatcher.NewMatcherGroup(),
  67. cache: make(map[string]timedResult, 512),
  68. }
  69. }
  70. var matcherTypeMap = map[Domain_Type]strmatcher.Type{
  71. Domain_Plain: strmatcher.Substr,
  72. Domain_Regex: strmatcher.Regex,
  73. Domain_Domain: strmatcher.Domain,
  74. }
  75. func (m *CachableDomainMatcher) Add(domain *Domain) error {
  76. matcherType, f := matcherTypeMap[domain.Type]
  77. if !f {
  78. return newError("unsupported domain type", domain.Type)
  79. }
  80. matcher, err := matcherType.New(domain.Value)
  81. if err != nil {
  82. return newError("failed to create domain matcher").Base(err)
  83. }
  84. m.matchers.Add(matcher)
  85. return nil
  86. }
  87. func (m *CachableDomainMatcher) applyInternal(domain string) bool {
  88. return m.matchers.Match(domain) > 0
  89. }
  90. type cacheResult int
  91. const (
  92. cacheMiss cacheResult = iota
  93. cacheHitTrue
  94. cacheHitFalse
  95. )
  96. func (m *CachableDomainMatcher) findInCache(domain string) cacheResult {
  97. m.Lock()
  98. defer m.Unlock()
  99. r, f := m.cache[domain]
  100. if !f {
  101. return cacheMiss
  102. }
  103. r.timestamp = time.Now()
  104. m.cache[domain] = r
  105. if r.result {
  106. return cacheHitTrue
  107. }
  108. return cacheHitFalse
  109. }
  110. func (m *CachableDomainMatcher) ApplyDomain(domain string) bool {
  111. if m.matchers.Size() < 64 {
  112. return m.applyInternal(domain)
  113. }
  114. cr := m.findInCache(domain)
  115. if cr == cacheHitTrue {
  116. return true
  117. }
  118. if cr == cacheHitFalse {
  119. return false
  120. }
  121. r := m.applyInternal(domain)
  122. m.Lock()
  123. defer m.Unlock()
  124. m.cache[domain] = timedResult{
  125. result: r,
  126. timestamp: time.Now(),
  127. }
  128. now := time.Now()
  129. if len(m.cache) > 256 && now.Sub(m.lastScan)/time.Second > 5 {
  130. now := time.Now()
  131. for k, v := range m.cache {
  132. if now.Sub(v.timestamp)/time.Second > 60 {
  133. delete(m.cache, k)
  134. }
  135. }
  136. m.lastScan = now
  137. }
  138. return r
  139. }
  140. func (m *CachableDomainMatcher) Apply(ctx context.Context) bool {
  141. dest, ok := proxy.TargetFromContext(ctx)
  142. if !ok {
  143. return false
  144. }
  145. if !dest.Address.Family().IsDomain() {
  146. return false
  147. }
  148. return m.ApplyDomain(dest.Address.Domain())
  149. }
  150. type CIDRMatcher struct {
  151. cidr *net.IPNet
  152. onSource bool
  153. }
  154. func NewCIDRMatcher(ip []byte, mask uint32, onSource bool) (*CIDRMatcher, error) {
  155. cidr := &net.IPNet{
  156. IP: net.IP(ip),
  157. Mask: net.CIDRMask(int(mask), len(ip)*8),
  158. }
  159. return &CIDRMatcher{
  160. cidr: cidr,
  161. onSource: onSource,
  162. }, nil
  163. }
  164. func (v *CIDRMatcher) Apply(ctx context.Context) bool {
  165. ips := make([]net.IP, 0, 4)
  166. if resolver, ok := proxy.ResolvedIPsFromContext(ctx); ok {
  167. resolvedIPs := resolver.Resolve()
  168. for _, rip := range resolvedIPs {
  169. if !rip.Family().IsIPv6() {
  170. continue
  171. }
  172. ips = append(ips, rip.IP())
  173. }
  174. }
  175. var dest net.Destination
  176. var ok bool
  177. if v.onSource {
  178. dest, ok = proxy.SourceFromContext(ctx)
  179. } else {
  180. dest, ok = proxy.TargetFromContext(ctx)
  181. }
  182. if ok && dest.Address.Family().IsIPv6() {
  183. ips = append(ips, dest.Address.IP())
  184. }
  185. for _, ip := range ips {
  186. if v.cidr.Contains(ip) {
  187. return true
  188. }
  189. }
  190. return false
  191. }
  192. type IPv4Matcher struct {
  193. ipv4net *net.IPNetTable
  194. onSource bool
  195. }
  196. func NewIPv4Matcher(ipnet *net.IPNetTable, onSource bool) *IPv4Matcher {
  197. return &IPv4Matcher{
  198. ipv4net: ipnet,
  199. onSource: onSource,
  200. }
  201. }
  202. func (v *IPv4Matcher) Apply(ctx context.Context) bool {
  203. ips := make([]net.IP, 0, 4)
  204. if resolver, ok := proxy.ResolvedIPsFromContext(ctx); ok {
  205. resolvedIPs := resolver.Resolve()
  206. for _, rip := range resolvedIPs {
  207. if !rip.Family().IsIPv4() {
  208. continue
  209. }
  210. ips = append(ips, rip.IP())
  211. }
  212. }
  213. var dest net.Destination
  214. var ok bool
  215. if v.onSource {
  216. dest, ok = proxy.SourceFromContext(ctx)
  217. } else {
  218. dest, ok = proxy.TargetFromContext(ctx)
  219. }
  220. if ok && dest.Address.Family().IsIPv4() {
  221. ips = append(ips, dest.Address.IP())
  222. }
  223. for _, ip := range ips {
  224. if v.ipv4net.Contains(ip) {
  225. return true
  226. }
  227. }
  228. return false
  229. }
  230. type PortMatcher struct {
  231. port net.PortRange
  232. }
  233. func NewPortMatcher(portRange net.PortRange) *PortMatcher {
  234. return &PortMatcher{
  235. port: portRange,
  236. }
  237. }
  238. func (v *PortMatcher) Apply(ctx context.Context) bool {
  239. dest, ok := proxy.TargetFromContext(ctx)
  240. if !ok {
  241. return false
  242. }
  243. return v.port.Contains(dest.Port)
  244. }
  245. type NetworkMatcher struct {
  246. network *net.NetworkList
  247. }
  248. func NewNetworkMatcher(network *net.NetworkList) *NetworkMatcher {
  249. return &NetworkMatcher{
  250. network: network,
  251. }
  252. }
  253. func (v *NetworkMatcher) Apply(ctx context.Context) bool {
  254. dest, ok := proxy.TargetFromContext(ctx)
  255. if !ok {
  256. return false
  257. }
  258. return v.network.HasNetwork(dest.Network)
  259. }
  260. type UserMatcher struct {
  261. user []string
  262. }
  263. func NewUserMatcher(users []string) *UserMatcher {
  264. usersCopy := make([]string, 0, len(users))
  265. for _, user := range users {
  266. if len(user) > 0 {
  267. usersCopy = append(usersCopy, user)
  268. }
  269. }
  270. return &UserMatcher{
  271. user: usersCopy,
  272. }
  273. }
  274. func (v *UserMatcher) Apply(ctx context.Context) bool {
  275. user := protocol.UserFromContext(ctx)
  276. if user == nil {
  277. return false
  278. }
  279. for _, u := range v.user {
  280. if u == user.Email {
  281. return true
  282. }
  283. }
  284. return false
  285. }
  286. type InboundTagMatcher struct {
  287. tags []string
  288. }
  289. func NewInboundTagMatcher(tags []string) *InboundTagMatcher {
  290. tagsCopy := make([]string, 0, len(tags))
  291. for _, tag := range tags {
  292. if len(tag) > 0 {
  293. tagsCopy = append(tagsCopy, tag)
  294. }
  295. }
  296. return &InboundTagMatcher{
  297. tags: tagsCopy,
  298. }
  299. }
  300. func (v *InboundTagMatcher) Apply(ctx context.Context) bool {
  301. tag, ok := proxy.InboundTagFromContext(ctx)
  302. if !ok {
  303. return false
  304. }
  305. for _, t := range v.tags {
  306. if t == tag {
  307. return true
  308. }
  309. }
  310. return false
  311. }