condition.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package router
  2. import (
  3. "strings"
  4. "github.com/xtls/xray-core/common/net"
  5. "github.com/xtls/xray-core/common/strmatcher"
  6. "github.com/xtls/xray-core/features/routing"
  7. "go.starlark.net/starlark"
  8. "go.starlark.net/syntax"
  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_Domain: 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. } else {
  147. return v.port.Contains(ctx.GetTargetPort())
  148. }
  149. }
  150. type NetworkMatcher struct {
  151. list [8]bool
  152. }
  153. func NewNetworkMatcher(network []net.Network) NetworkMatcher {
  154. var matcher NetworkMatcher
  155. for _, n := range network {
  156. matcher.list[int(n)] = true
  157. }
  158. return matcher
  159. }
  160. // Apply implements Condition.
  161. func (v NetworkMatcher) Apply(ctx routing.Context) bool {
  162. return v.list[int(ctx.GetNetwork())]
  163. }
  164. type UserMatcher struct {
  165. user []string
  166. }
  167. func NewUserMatcher(users []string) *UserMatcher {
  168. usersCopy := make([]string, 0, len(users))
  169. for _, user := range users {
  170. if len(user) > 0 {
  171. usersCopy = append(usersCopy, user)
  172. }
  173. }
  174. return &UserMatcher{
  175. user: usersCopy,
  176. }
  177. }
  178. // Apply implements Condition.
  179. func (v *UserMatcher) Apply(ctx routing.Context) bool {
  180. user := ctx.GetUser()
  181. if len(user) == 0 {
  182. return false
  183. }
  184. for _, u := range v.user {
  185. if u == user {
  186. return true
  187. }
  188. }
  189. return false
  190. }
  191. type InboundTagMatcher struct {
  192. tags []string
  193. }
  194. func NewInboundTagMatcher(tags []string) *InboundTagMatcher {
  195. tagsCopy := make([]string, 0, len(tags))
  196. for _, tag := range tags {
  197. if len(tag) > 0 {
  198. tagsCopy = append(tagsCopy, tag)
  199. }
  200. }
  201. return &InboundTagMatcher{
  202. tags: tagsCopy,
  203. }
  204. }
  205. // Apply implements Condition.
  206. func (v *InboundTagMatcher) Apply(ctx routing.Context) bool {
  207. tag := ctx.GetInboundTag()
  208. if len(tag) == 0 {
  209. return false
  210. }
  211. for _, t := range v.tags {
  212. if t == tag {
  213. return true
  214. }
  215. }
  216. return false
  217. }
  218. type ProtocolMatcher struct {
  219. protocols []string
  220. }
  221. func NewProtocolMatcher(protocols []string) *ProtocolMatcher {
  222. pCopy := make([]string, 0, len(protocols))
  223. for _, p := range protocols {
  224. if len(p) > 0 {
  225. pCopy = append(pCopy, p)
  226. }
  227. }
  228. return &ProtocolMatcher{
  229. protocols: pCopy,
  230. }
  231. }
  232. // Apply implements Condition.
  233. func (m *ProtocolMatcher) Apply(ctx routing.Context) bool {
  234. protocol := ctx.GetProtocol()
  235. if len(protocol) == 0 {
  236. return false
  237. }
  238. for _, p := range m.protocols {
  239. if strings.HasPrefix(protocol, p) {
  240. return true
  241. }
  242. }
  243. return false
  244. }
  245. type AttributeMatcher struct {
  246. program *starlark.Program
  247. }
  248. func NewAttributeMatcher(code string) (*AttributeMatcher, error) {
  249. starFile, err := syntax.Parse("attr.star", "satisfied=("+code+")", 0)
  250. if err != nil {
  251. return nil, newError("attr rule").Base(err)
  252. }
  253. p, err := starlark.FileProgram(starFile, func(name string) bool {
  254. return name == "attrs"
  255. })
  256. if err != nil {
  257. return nil, err
  258. }
  259. return &AttributeMatcher{
  260. program: p,
  261. }, nil
  262. }
  263. // Match implements attributes matching.
  264. func (m *AttributeMatcher) Match(attrs map[string]string) bool {
  265. attrsDict := new(starlark.Dict)
  266. for key, value := range attrs {
  267. attrsDict.SetKey(starlark.String(key), starlark.String(value))
  268. }
  269. predefined := make(starlark.StringDict)
  270. predefined["attrs"] = attrsDict
  271. thread := &starlark.Thread{
  272. Name: "matcher",
  273. }
  274. results, err := m.program.Init(thread, predefined)
  275. if err != nil {
  276. newError("attr matcher").Base(err).WriteToLog()
  277. }
  278. satisfied := results["satisfied"]
  279. return satisfied != nil && bool(satisfied.Truth())
  280. }
  281. // Apply implements Condition.
  282. func (m *AttributeMatcher) Apply(ctx routing.Context) bool {
  283. attributes := ctx.GetAttributes()
  284. if attributes == nil {
  285. return false
  286. }
  287. return m.Match(attributes)
  288. }