condition.go 7.3 KB

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