condition.go 7.7 KB

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