condition.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. remove := make([]string, 0, 128)
  137. now := time.Now()
  138. for k, v := range m.cache {
  139. if now.Sub(v.timestamp)/time.Second > 60 {
  140. remove = append(remove, k)
  141. }
  142. }
  143. for _, v := range remove {
  144. delete(m.cache, v)
  145. }
  146. m.lastScan = now
  147. }
  148. return r
  149. }
  150. func (m *CachableDomainMatcher) Apply(ctx context.Context) bool {
  151. dest, ok := proxy.TargetFromContext(ctx)
  152. if !ok {
  153. return false
  154. }
  155. if !dest.Address.Family().IsDomain() {
  156. return false
  157. }
  158. return m.ApplyDomain(dest.Address.Domain())
  159. }
  160. type domainMatcher interface {
  161. Apply(domain string) bool
  162. }
  163. type PlainDomainMatcher string
  164. func NewPlainDomainMatcher(pattern string) PlainDomainMatcher {
  165. return PlainDomainMatcher(pattern)
  166. }
  167. func (v PlainDomainMatcher) Apply(domain string) bool {
  168. return strings.Contains(domain, string(v))
  169. }
  170. type RegexpDomainMatcher struct {
  171. pattern *regexp.Regexp
  172. }
  173. func NewRegexpDomainMatcher(pattern string) (*RegexpDomainMatcher, error) {
  174. r, err := regexp.Compile(pattern)
  175. if err != nil {
  176. return nil, err
  177. }
  178. return &RegexpDomainMatcher{
  179. pattern: r,
  180. }, nil
  181. }
  182. func (v *RegexpDomainMatcher) Apply(domain string) bool {
  183. return v.pattern.MatchString(strings.ToLower(domain))
  184. }
  185. type SubDomainMatcher string
  186. func NewSubDomainMatcher(p string) SubDomainMatcher {
  187. return SubDomainMatcher(p)
  188. }
  189. func (m SubDomainMatcher) Apply(domain string) bool {
  190. pattern := string(m)
  191. if !strings.HasSuffix(domain, pattern) {
  192. return false
  193. }
  194. return len(domain) == len(pattern) || domain[len(domain)-len(pattern)-1] == '.'
  195. }
  196. type CIDRMatcher struct {
  197. cidr *net.IPNet
  198. onSource bool
  199. }
  200. func NewCIDRMatcher(ip []byte, mask uint32, onSource bool) (*CIDRMatcher, error) {
  201. cidr := &net.IPNet{
  202. IP: net.IP(ip),
  203. Mask: net.CIDRMask(int(mask), len(ip)*8),
  204. }
  205. return &CIDRMatcher{
  206. cidr: cidr,
  207. onSource: onSource,
  208. }, nil
  209. }
  210. func (v *CIDRMatcher) Apply(ctx context.Context) bool {
  211. ips := make([]net.IP, 0, 4)
  212. if resolver, ok := proxy.ResolvedIPsFromContext(ctx); ok {
  213. resolvedIPs := resolver.Resolve()
  214. for _, rip := range resolvedIPs {
  215. if !rip.Family().IsIPv6() {
  216. continue
  217. }
  218. ips = append(ips, rip.IP())
  219. }
  220. }
  221. var dest net.Destination
  222. var ok bool
  223. if v.onSource {
  224. dest, ok = proxy.SourceFromContext(ctx)
  225. } else {
  226. dest, ok = proxy.TargetFromContext(ctx)
  227. }
  228. if ok && dest.Address.Family().IsIPv6() {
  229. ips = append(ips, dest.Address.IP())
  230. }
  231. for _, ip := range ips {
  232. if v.cidr.Contains(ip) {
  233. return true
  234. }
  235. }
  236. return false
  237. }
  238. type IPv4Matcher struct {
  239. ipv4net *net.IPNetTable
  240. onSource bool
  241. }
  242. func NewIPv4Matcher(ipnet *net.IPNetTable, onSource bool) *IPv4Matcher {
  243. return &IPv4Matcher{
  244. ipv4net: ipnet,
  245. onSource: onSource,
  246. }
  247. }
  248. func (v *IPv4Matcher) Apply(ctx context.Context) bool {
  249. ips := make([]net.IP, 0, 4)
  250. if resolver, ok := proxy.ResolvedIPsFromContext(ctx); ok {
  251. resolvedIPs := resolver.Resolve()
  252. for _, rip := range resolvedIPs {
  253. if !rip.Family().IsIPv4() {
  254. continue
  255. }
  256. ips = append(ips, rip.IP())
  257. }
  258. }
  259. var dest net.Destination
  260. var ok bool
  261. if v.onSource {
  262. dest, ok = proxy.SourceFromContext(ctx)
  263. } else {
  264. dest, ok = proxy.TargetFromContext(ctx)
  265. }
  266. if ok && dest.Address.Family().IsIPv4() {
  267. ips = append(ips, dest.Address.IP())
  268. }
  269. for _, ip := range ips {
  270. if v.ipv4net.Contains(ip) {
  271. return true
  272. }
  273. }
  274. return false
  275. }
  276. type PortMatcher struct {
  277. port net.PortRange
  278. }
  279. func NewPortMatcher(portRange net.PortRange) *PortMatcher {
  280. return &PortMatcher{
  281. port: portRange,
  282. }
  283. }
  284. func (v *PortMatcher) Apply(ctx context.Context) bool {
  285. dest, ok := proxy.TargetFromContext(ctx)
  286. if !ok {
  287. return false
  288. }
  289. return v.port.Contains(dest.Port)
  290. }
  291. type NetworkMatcher struct {
  292. network *net.NetworkList
  293. }
  294. func NewNetworkMatcher(network *net.NetworkList) *NetworkMatcher {
  295. return &NetworkMatcher{
  296. network: network,
  297. }
  298. }
  299. func (v *NetworkMatcher) Apply(ctx context.Context) bool {
  300. dest, ok := proxy.TargetFromContext(ctx)
  301. if !ok {
  302. return false
  303. }
  304. return v.network.HasNetwork(dest.Network)
  305. }
  306. type UserMatcher struct {
  307. user []string
  308. }
  309. func NewUserMatcher(users []string) *UserMatcher {
  310. usersCopy := make([]string, 0, len(users))
  311. for _, user := range users {
  312. if len(user) > 0 {
  313. usersCopy = append(usersCopy, user)
  314. }
  315. }
  316. return &UserMatcher{
  317. user: usersCopy,
  318. }
  319. }
  320. func (v *UserMatcher) Apply(ctx context.Context) bool {
  321. user := protocol.UserFromContext(ctx)
  322. if user == nil {
  323. return false
  324. }
  325. for _, u := range v.user {
  326. if u == user.Email {
  327. return true
  328. }
  329. }
  330. return false
  331. }
  332. type InboundTagMatcher struct {
  333. tags []string
  334. }
  335. func NewInboundTagMatcher(tags []string) *InboundTagMatcher {
  336. tagsCopy := make([]string, 0, len(tags))
  337. for _, tag := range tags {
  338. if len(tag) > 0 {
  339. tagsCopy = append(tagsCopy, tag)
  340. }
  341. }
  342. return &InboundTagMatcher{
  343. tags: tagsCopy,
  344. }
  345. }
  346. func (v *InboundTagMatcher) Apply(ctx context.Context) bool {
  347. tag, ok := proxy.InboundTagFromContext(ctx)
  348. if !ok {
  349. return false
  350. }
  351. for _, t := range v.tags {
  352. if t == tag {
  353. return true
  354. }
  355. }
  356. return false
  357. }