condition.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package router
  2. import (
  3. "strings"
  4. "go.starlark.net/starlark"
  5. "go.starlark.net/syntax"
  6. "github.com/v2fly/v2ray-core/v4/common/net"
  7. "github.com/v2fly/v2ray-core/v4/common/strmatcher"
  8. "github.com/v2fly/v2ray-core/v4/features/routing"
  9. )
  10. type Condition interface {
  11. Apply(ctx routing.Context) bool
  12. }
  13. type ConditionChan []Condition
  14. func NewConditionChan() *ConditionChan {
  15. var condChan ConditionChan = make([]Condition, 0, 8)
  16. return &condChan
  17. }
  18. func (v *ConditionChan) Add(cond Condition) *ConditionChan {
  19. *v = append(*v, cond)
  20. return v
  21. }
  22. // Apply applies all conditions registered in this chan.
  23. func (v *ConditionChan) Apply(ctx routing.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. var matcherTypeMap = map[Domain_Type]strmatcher.Type{
  35. Domain_Plain: strmatcher.Substr,
  36. Domain_Regex: strmatcher.Regex,
  37. Domain_RootDomain: strmatcher.Domain,
  38. Domain_Full: strmatcher.Full,
  39. }
  40. func domainToMatcher(domain *Domain) (strmatcher.Matcher, error) {
  41. matcherType, f := matcherTypeMap[domain.Type]
  42. if !f {
  43. return nil, newError("unsupported domain type", domain.Type)
  44. }
  45. matcher, err := matcherType.New(domain.Value)
  46. if err != nil {
  47. return nil, newError("failed to create domain matcher").Base(err)
  48. }
  49. return matcher, nil
  50. }
  51. type DomainMatcher struct {
  52. matchers strmatcher.IndexMatcher
  53. }
  54. func NewMphMatcherGroup(domains []*Domain) (*DomainMatcher, error) {
  55. g := strmatcher.NewMphMatcherGroup()
  56. for _, d := range domains {
  57. matcherType, f := matcherTypeMap[d.Type]
  58. if !f {
  59. return nil, newError("unsupported domain type", d.Type)
  60. }
  61. _, err := g.AddPattern(d.Value, matcherType)
  62. if err != nil {
  63. return nil, err
  64. }
  65. }
  66. g.Build()
  67. return &DomainMatcher{
  68. matchers: g,
  69. }, nil
  70. }
  71. func NewDomainMatcher(domains []*Domain) (*DomainMatcher, error) {
  72. g := new(strmatcher.MatcherGroup)
  73. for _, d := range domains {
  74. m, err := domainToMatcher(d)
  75. if err != nil {
  76. return nil, err
  77. }
  78. g.Add(m)
  79. }
  80. return &DomainMatcher{
  81. matchers: g,
  82. }, nil
  83. }
  84. func (m *DomainMatcher) ApplyDomain(domain string) bool {
  85. return len(m.matchers.Match(strings.ToLower(domain))) > 0
  86. }
  87. // Apply implements Condition.
  88. func (m *DomainMatcher) Apply(ctx routing.Context) bool {
  89. domain := ctx.GetTargetDomain()
  90. if len(domain) == 0 {
  91. return false
  92. }
  93. return m.ApplyDomain(domain)
  94. }
  95. type MultiGeoIPMatcher struct {
  96. matchers []*GeoIPMatcher
  97. onSource bool
  98. }
  99. func NewMultiGeoIPMatcher(geoips []*GeoIP, onSource bool) (*MultiGeoIPMatcher, error) {
  100. var matchers []*GeoIPMatcher
  101. for _, geoip := range geoips {
  102. matcher, err := globalGeoIPContainer.Add(geoip)
  103. if err != nil {
  104. return nil, err
  105. }
  106. matchers = append(matchers, matcher)
  107. }
  108. matcher := &MultiGeoIPMatcher{
  109. matchers: matchers,
  110. onSource: onSource,
  111. }
  112. return matcher, nil
  113. }
  114. // Apply implements Condition.
  115. func (m *MultiGeoIPMatcher) Apply(ctx routing.Context) bool {
  116. var ips []net.IP
  117. if m.onSource {
  118. ips = ctx.GetSourceIPs()
  119. } else {
  120. ips = ctx.GetTargetIPs()
  121. }
  122. for _, ip := range ips {
  123. for _, matcher := range m.matchers {
  124. if matcher.Match(ip) {
  125. return true
  126. }
  127. }
  128. }
  129. return false
  130. }
  131. type PortMatcher struct {
  132. port net.MemoryPortList
  133. onSource bool
  134. }
  135. // NewPortMatcher create a new port matcher that can match source or destination port
  136. func NewPortMatcher(list *net.PortList, onSource bool) *PortMatcher {
  137. return &PortMatcher{
  138. port: net.PortListFromProto(list),
  139. onSource: onSource,
  140. }
  141. }
  142. // Apply implements Condition.
  143. func (v *PortMatcher) Apply(ctx routing.Context) bool {
  144. if v.onSource {
  145. return v.port.Contains(ctx.GetSourcePort())
  146. }
  147. return v.port.Contains(ctx.GetTargetPort())
  148. }
  149. type NetworkMatcher struct {
  150. list [8]bool
  151. }
  152. func NewNetworkMatcher(network []net.Network) NetworkMatcher {
  153. var matcher NetworkMatcher
  154. for _, n := range network {
  155. matcher.list[int(n)] = true
  156. }
  157. return matcher
  158. }
  159. // Apply implements Condition.
  160. func (v NetworkMatcher) Apply(ctx routing.Context) bool {
  161. return v.list[int(ctx.GetNetwork())]
  162. }
  163. type UserMatcher struct {
  164. user []string
  165. }
  166. func NewUserMatcher(users []string) *UserMatcher {
  167. usersCopy := make([]string, 0, len(users))
  168. for _, user := range users {
  169. if len(user) > 0 {
  170. usersCopy = append(usersCopy, user)
  171. }
  172. }
  173. return &UserMatcher{
  174. user: usersCopy,
  175. }
  176. }
  177. // Apply implements Condition.
  178. func (v *UserMatcher) Apply(ctx routing.Context) bool {
  179. user := ctx.GetUser()
  180. if len(user) == 0 {
  181. return false
  182. }
  183. for _, u := range v.user {
  184. if u == user {
  185. return true
  186. }
  187. }
  188. return false
  189. }
  190. type InboundTagMatcher struct {
  191. tags []string
  192. }
  193. func NewInboundTagMatcher(tags []string) *InboundTagMatcher {
  194. tagsCopy := make([]string, 0, len(tags))
  195. for _, tag := range tags {
  196. if len(tag) > 0 {
  197. tagsCopy = append(tagsCopy, tag)
  198. }
  199. }
  200. return &InboundTagMatcher{
  201. tags: tagsCopy,
  202. }
  203. }
  204. // Apply implements Condition.
  205. func (v *InboundTagMatcher) Apply(ctx routing.Context) bool {
  206. tag := ctx.GetInboundTag()
  207. if len(tag) == 0 {
  208. return false
  209. }
  210. for _, t := range v.tags {
  211. if t == tag {
  212. return true
  213. }
  214. }
  215. return false
  216. }
  217. type ProtocolMatcher struct {
  218. protocols []string
  219. }
  220. func NewProtocolMatcher(protocols []string) *ProtocolMatcher {
  221. pCopy := make([]string, 0, len(protocols))
  222. for _, p := range protocols {
  223. if len(p) > 0 {
  224. pCopy = append(pCopy, p)
  225. }
  226. }
  227. return &ProtocolMatcher{
  228. protocols: pCopy,
  229. }
  230. }
  231. // Apply implements Condition.
  232. func (m *ProtocolMatcher) Apply(ctx routing.Context) bool {
  233. protocol := ctx.GetProtocol()
  234. if len(protocol) == 0 {
  235. return false
  236. }
  237. for _, p := range m.protocols {
  238. if strings.HasPrefix(protocol, p) {
  239. return true
  240. }
  241. }
  242. return false
  243. }
  244. type AttributeMatcher struct {
  245. program *starlark.Program
  246. }
  247. func NewAttributeMatcher(code string) (*AttributeMatcher, error) {
  248. starFile, err := syntax.Parse("attr.star", "satisfied=("+code+")", 0)
  249. if err != nil {
  250. return nil, newError("attr rule").Base(err)
  251. }
  252. p, err := starlark.FileProgram(starFile, func(name string) bool {
  253. return name == "attrs"
  254. })
  255. if err != nil {
  256. return nil, err
  257. }
  258. return &AttributeMatcher{
  259. program: p,
  260. }, nil
  261. }
  262. // Match implements attributes matching.
  263. func (m *AttributeMatcher) Match(attrs map[string]string) bool {
  264. attrsDict := new(starlark.Dict)
  265. for key, value := range attrs {
  266. attrsDict.SetKey(starlark.String(key), starlark.String(value))
  267. }
  268. predefined := make(starlark.StringDict)
  269. predefined["attrs"] = attrsDict
  270. thread := &starlark.Thread{
  271. Name: "matcher",
  272. }
  273. results, err := m.program.Init(thread, predefined)
  274. if err != nil {
  275. newError("attr matcher").Base(err).WriteToLog()
  276. }
  277. satisfied := results["satisfied"]
  278. return satisfied != nil && bool(satisfied.Truth())
  279. }
  280. // Apply implements Condition.
  281. func (m *AttributeMatcher) Apply(ctx routing.Context) bool {
  282. attributes := ctx.GetAttributes()
  283. if attributes == nil {
  284. return false
  285. }
  286. return m.Match(attributes)
  287. }