router.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. package conf
  2. import (
  3. "encoding/json"
  4. "runtime"
  5. "strconv"
  6. "strings"
  7. "github.com/xtls/xray-core/app/router"
  8. "github.com/xtls/xray-core/common/errors"
  9. "github.com/xtls/xray-core/common/net"
  10. "github.com/xtls/xray-core/common/platform/filesystem"
  11. "github.com/xtls/xray-core/common/serial"
  12. "google.golang.org/protobuf/proto"
  13. )
  14. type RouterRulesConfig struct {
  15. RuleList []json.RawMessage `json:"rules"`
  16. DomainStrategy string `json:"domainStrategy"`
  17. }
  18. // StrategyConfig represents a strategy config
  19. type StrategyConfig struct {
  20. Type string `json:"type"`
  21. Settings *json.RawMessage `json:"settings"`
  22. }
  23. type BalancingRule struct {
  24. Tag string `json:"tag"`
  25. Selectors StringList `json:"selector"`
  26. Strategy StrategyConfig `json:"strategy"`
  27. FallbackTag string `json:"fallbackTag"`
  28. }
  29. // Build builds the balancing rule
  30. func (r *BalancingRule) Build() (*router.BalancingRule, error) {
  31. if r.Tag == "" {
  32. return nil, errors.New("empty balancer tag")
  33. }
  34. if len(r.Selectors) == 0 {
  35. return nil, errors.New("empty selector list")
  36. }
  37. r.Strategy.Type = strings.ToLower(r.Strategy.Type)
  38. switch r.Strategy.Type {
  39. case "":
  40. r.Strategy.Type = strategyRandom
  41. case strategyRandom, strategyLeastLoad, strategyLeastPing, strategyRoundRobin:
  42. default:
  43. return nil, errors.New("unknown balancing strategy: " + r.Strategy.Type)
  44. }
  45. settings := []byte("{}")
  46. if r.Strategy.Settings != nil {
  47. settings = ([]byte)(*r.Strategy.Settings)
  48. }
  49. rawConfig, err := strategyConfigLoader.LoadWithID(settings, r.Strategy.Type)
  50. if err != nil {
  51. return nil, errors.New("failed to parse to strategy config.").Base(err)
  52. }
  53. var ts proto.Message
  54. if builder, ok := rawConfig.(Buildable); ok {
  55. ts, err = builder.Build()
  56. if err != nil {
  57. return nil, err
  58. }
  59. }
  60. return &router.BalancingRule{
  61. Strategy: r.Strategy.Type,
  62. StrategySettings: serial.ToTypedMessage(ts),
  63. FallbackTag: r.FallbackTag,
  64. OutboundSelector: r.Selectors,
  65. Tag: r.Tag,
  66. }, nil
  67. }
  68. type RouterConfig struct {
  69. Settings *RouterRulesConfig `json:"settings"` // Deprecated
  70. RuleList []json.RawMessage `json:"rules"`
  71. DomainStrategy *string `json:"domainStrategy"`
  72. Balancers []*BalancingRule `json:"balancers"`
  73. DomainMatcher string `json:"domainMatcher"`
  74. }
  75. func (c *RouterConfig) getDomainStrategy() router.Config_DomainStrategy {
  76. ds := ""
  77. if c.DomainStrategy != nil {
  78. ds = *c.DomainStrategy
  79. } else if c.Settings != nil {
  80. ds = c.Settings.DomainStrategy
  81. }
  82. switch strings.ToLower(ds) {
  83. case "alwaysip":
  84. return router.Config_UseIp
  85. case "ipifnonmatch":
  86. return router.Config_IpIfNonMatch
  87. case "ipondemand":
  88. return router.Config_IpOnDemand
  89. default:
  90. return router.Config_AsIs
  91. }
  92. }
  93. func (c *RouterConfig) Build() (*router.Config, error) {
  94. config := new(router.Config)
  95. config.DomainStrategy = c.getDomainStrategy()
  96. var rawRuleList []json.RawMessage
  97. if c != nil {
  98. rawRuleList = c.RuleList
  99. if c.Settings != nil {
  100. c.RuleList = append(c.RuleList, c.Settings.RuleList...)
  101. rawRuleList = c.RuleList
  102. }
  103. }
  104. for _, rawRule := range rawRuleList {
  105. rule, err := ParseRule(rawRule)
  106. if err != nil {
  107. return nil, err
  108. }
  109. if rule.DomainMatcher == "" {
  110. rule.DomainMatcher = c.DomainMatcher
  111. }
  112. config.Rule = append(config.Rule, rule)
  113. }
  114. for _, rawBalancer := range c.Balancers {
  115. balancer, err := rawBalancer.Build()
  116. if err != nil {
  117. return nil, err
  118. }
  119. config.BalancingRule = append(config.BalancingRule, balancer)
  120. }
  121. return config, nil
  122. }
  123. type RouterRule struct {
  124. RuleTag string `json:"ruleTag"`
  125. Type string `json:"type"`
  126. OutboundTag string `json:"outboundTag"`
  127. BalancerTag string `json:"balancerTag"`
  128. DomainMatcher string `json:"domainMatcher"`
  129. }
  130. func ParseIP(s string) (*router.CIDR, error) {
  131. var addr, mask string
  132. i := strings.Index(s, "/")
  133. if i < 0 {
  134. addr = s
  135. } else {
  136. addr = s[:i]
  137. mask = s[i+1:]
  138. }
  139. ip := net.ParseAddress(addr)
  140. switch ip.Family() {
  141. case net.AddressFamilyIPv4:
  142. bits := uint32(32)
  143. if len(mask) > 0 {
  144. bits64, err := strconv.ParseUint(mask, 10, 32)
  145. if err != nil {
  146. return nil, errors.New("invalid network mask for router: ", mask).Base(err)
  147. }
  148. bits = uint32(bits64)
  149. }
  150. if bits > 32 {
  151. return nil, errors.New("invalid network mask for router: ", bits)
  152. }
  153. return &router.CIDR{
  154. Ip: []byte(ip.IP()),
  155. Prefix: bits,
  156. }, nil
  157. case net.AddressFamilyIPv6:
  158. bits := uint32(128)
  159. if len(mask) > 0 {
  160. bits64, err := strconv.ParseUint(mask, 10, 32)
  161. if err != nil {
  162. return nil, errors.New("invalid network mask for router: ", mask).Base(err)
  163. }
  164. bits = uint32(bits64)
  165. }
  166. if bits > 128 {
  167. return nil, errors.New("invalid network mask for router: ", bits)
  168. }
  169. return &router.CIDR{
  170. Ip: []byte(ip.IP()),
  171. Prefix: bits,
  172. }, nil
  173. default:
  174. return nil, errors.New("unsupported address for router: ", s)
  175. }
  176. }
  177. func loadGeoIP(code string) ([]*router.CIDR, error) {
  178. return loadIP("geoip.dat", code)
  179. }
  180. var (
  181. FileCache = make(map[string][]byte)
  182. IPCache = make(map[string]*router.GeoIP)
  183. SiteCache = make(map[string]*router.GeoSite)
  184. )
  185. func loadFile(file string) ([]byte, error) {
  186. if FileCache[file] == nil {
  187. bs, err := filesystem.ReadAsset(file)
  188. if err != nil {
  189. return nil, errors.New("failed to open file: ", file).Base(err)
  190. }
  191. if len(bs) == 0 {
  192. return nil, errors.New("empty file: ", file)
  193. }
  194. // Do not cache file, may save RAM when there
  195. // are many files, but consume CPU each time.
  196. return bs, nil
  197. FileCache[file] = bs
  198. }
  199. return FileCache[file], nil
  200. }
  201. func loadIP(file, code string) ([]*router.CIDR, error) {
  202. index := file + ":" + code
  203. if IPCache[index] == nil {
  204. bs, err := loadFile(file)
  205. if err != nil {
  206. return nil, errors.New("failed to load file: ", file).Base(err)
  207. }
  208. bs = find(bs, []byte(code))
  209. if bs == nil {
  210. return nil, errors.New("code not found in ", file, ": ", code)
  211. }
  212. var geoip router.GeoIP
  213. if err := proto.Unmarshal(bs, &geoip); err != nil {
  214. return nil, errors.New("error unmarshal IP in ", file, ": ", code).Base(err)
  215. }
  216. defer runtime.GC() // or debug.FreeOSMemory()
  217. return geoip.Cidr, nil // do not cache geoip
  218. IPCache[index] = &geoip
  219. }
  220. return IPCache[index].Cidr, nil
  221. }
  222. func loadSite(file, code string) ([]*router.Domain, error) {
  223. index := file + ":" + code
  224. if SiteCache[index] == nil {
  225. bs, err := loadFile(file)
  226. if err != nil {
  227. return nil, errors.New("failed to load file: ", file).Base(err)
  228. }
  229. bs = find(bs, []byte(code))
  230. if bs == nil {
  231. return nil, errors.New("list not found in ", file, ": ", code)
  232. }
  233. var geosite router.GeoSite
  234. if err := proto.Unmarshal(bs, &geosite); err != nil {
  235. return nil, errors.New("error unmarshal Site in ", file, ": ", code).Base(err)
  236. }
  237. defer runtime.GC() // or debug.FreeOSMemory()
  238. return geosite.Domain, nil // do not cache geosite
  239. SiteCache[index] = &geosite
  240. }
  241. return SiteCache[index].Domain, nil
  242. }
  243. func DecodeVarint(buf []byte) (x uint64, n int) {
  244. for shift := uint(0); shift < 64; shift += 7 {
  245. if n >= len(buf) {
  246. return 0, 0
  247. }
  248. b := uint64(buf[n])
  249. n++
  250. x |= (b & 0x7F) << shift
  251. if (b & 0x80) == 0 {
  252. return x, n
  253. }
  254. }
  255. // The number is too large to represent in a 64-bit value.
  256. return 0, 0
  257. }
  258. func find(data, code []byte) []byte {
  259. codeL := len(code)
  260. if codeL == 0 {
  261. return nil
  262. }
  263. for {
  264. dataL := len(data)
  265. if dataL < 2 {
  266. return nil
  267. }
  268. x, y := DecodeVarint(data[1:])
  269. if x == 0 && y == 0 {
  270. return nil
  271. }
  272. headL, bodyL := 1+y, int(x)
  273. dataL -= headL
  274. if dataL < bodyL {
  275. return nil
  276. }
  277. data = data[headL:]
  278. if int(data[1]) == codeL {
  279. for i := 0; i < codeL && data[2+i] == code[i]; i++ {
  280. if i+1 == codeL {
  281. return data[:bodyL]
  282. }
  283. }
  284. }
  285. if dataL == bodyL {
  286. return nil
  287. }
  288. data = data[bodyL:]
  289. }
  290. }
  291. type AttributeMatcher interface {
  292. Match(*router.Domain) bool
  293. }
  294. type BooleanMatcher string
  295. func (m BooleanMatcher) Match(domain *router.Domain) bool {
  296. for _, attr := range domain.Attribute {
  297. if attr.Key == string(m) {
  298. return true
  299. }
  300. }
  301. return false
  302. }
  303. type AttributeList struct {
  304. matcher []AttributeMatcher
  305. }
  306. func (al *AttributeList) Match(domain *router.Domain) bool {
  307. for _, matcher := range al.matcher {
  308. if !matcher.Match(domain) {
  309. return false
  310. }
  311. }
  312. return true
  313. }
  314. func (al *AttributeList) IsEmpty() bool {
  315. return len(al.matcher) == 0
  316. }
  317. func parseAttrs(attrs []string) *AttributeList {
  318. al := new(AttributeList)
  319. for _, attr := range attrs {
  320. lc := strings.ToLower(attr)
  321. al.matcher = append(al.matcher, BooleanMatcher(lc))
  322. }
  323. return al
  324. }
  325. func loadGeositeWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
  326. parts := strings.Split(siteWithAttr, "@")
  327. if len(parts) == 0 {
  328. return nil, errors.New("empty site")
  329. }
  330. country := strings.ToUpper(parts[0])
  331. attrs := parseAttrs(parts[1:])
  332. domains, err := loadSite(file, country)
  333. if err != nil {
  334. return nil, err
  335. }
  336. if attrs.IsEmpty() {
  337. return domains, nil
  338. }
  339. filteredDomains := make([]*router.Domain, 0, len(domains))
  340. for _, domain := range domains {
  341. if attrs.Match(domain) {
  342. filteredDomains = append(filteredDomains, domain)
  343. }
  344. }
  345. return filteredDomains, nil
  346. }
  347. func parseDomainRule(domain string) ([]*router.Domain, error) {
  348. if strings.HasPrefix(domain, "geosite:") {
  349. country := strings.ToUpper(domain[8:])
  350. domains, err := loadGeositeWithAttr("geosite.dat", country)
  351. if err != nil {
  352. return nil, errors.New("failed to load geosite: ", country).Base(err)
  353. }
  354. return domains, nil
  355. }
  356. isExtDatFile := 0
  357. {
  358. const prefix = "ext:"
  359. if strings.HasPrefix(domain, prefix) {
  360. isExtDatFile = len(prefix)
  361. }
  362. const prefixQualified = "ext-domain:"
  363. if strings.HasPrefix(domain, prefixQualified) {
  364. isExtDatFile = len(prefixQualified)
  365. }
  366. }
  367. if isExtDatFile != 0 {
  368. kv := strings.Split(domain[isExtDatFile:], ":")
  369. if len(kv) != 2 {
  370. return nil, errors.New("invalid external resource: ", domain)
  371. }
  372. filename := kv[0]
  373. country := kv[1]
  374. domains, err := loadGeositeWithAttr(filename, country)
  375. if err != nil {
  376. return nil, errors.New("failed to load external sites: ", country, " from ", filename).Base(err)
  377. }
  378. return domains, nil
  379. }
  380. domainRule := new(router.Domain)
  381. switch {
  382. case strings.HasPrefix(domain, "regexp:"):
  383. domainRule.Type = router.Domain_Regex
  384. domainRule.Value = domain[7:]
  385. case strings.HasPrefix(domain, "domain:"):
  386. domainRule.Type = router.Domain_Domain
  387. domainRule.Value = domain[7:]
  388. case strings.HasPrefix(domain, "full:"):
  389. domainRule.Type = router.Domain_Full
  390. domainRule.Value = domain[5:]
  391. case strings.HasPrefix(domain, "keyword:"):
  392. domainRule.Type = router.Domain_Plain
  393. domainRule.Value = domain[8:]
  394. case strings.HasPrefix(domain, "dotless:"):
  395. domainRule.Type = router.Domain_Regex
  396. switch substr := domain[8:]; {
  397. case substr == "":
  398. domainRule.Value = "^[^.]*$"
  399. case !strings.Contains(substr, "."):
  400. domainRule.Value = "^[^.]*" + substr + "[^.]*$"
  401. default:
  402. return nil, errors.New("substr in dotless rule should not contain a dot: ", substr)
  403. }
  404. default:
  405. domainRule.Type = router.Domain_Plain
  406. domainRule.Value = domain
  407. }
  408. return []*router.Domain{domainRule}, nil
  409. }
  410. func ToCidrList(ips StringList) ([]*router.GeoIP, error) {
  411. var geoipList []*router.GeoIP
  412. var customCidrs []*router.CIDR
  413. for _, ip := range ips {
  414. if strings.HasPrefix(ip, "geoip:") {
  415. country := ip[6:]
  416. isReverseMatch := false
  417. if strings.HasPrefix(ip, "geoip:!") {
  418. country = ip[7:]
  419. isReverseMatch = true
  420. }
  421. if len(country) == 0 {
  422. return nil, errors.New("empty country name in rule")
  423. }
  424. geoip, err := loadGeoIP(strings.ToUpper(country))
  425. if err != nil {
  426. return nil, errors.New("failed to load GeoIP: ", country).Base(err)
  427. }
  428. geoipList = append(geoipList, &router.GeoIP{
  429. CountryCode: strings.ToUpper(country),
  430. Cidr: geoip,
  431. ReverseMatch: isReverseMatch,
  432. })
  433. continue
  434. }
  435. isExtDatFile := 0
  436. {
  437. const prefix = "ext:"
  438. if strings.HasPrefix(ip, prefix) {
  439. isExtDatFile = len(prefix)
  440. }
  441. const prefixQualified = "ext-ip:"
  442. if strings.HasPrefix(ip, prefixQualified) {
  443. isExtDatFile = len(prefixQualified)
  444. }
  445. }
  446. if isExtDatFile != 0 {
  447. kv := strings.Split(ip[isExtDatFile:], ":")
  448. if len(kv) != 2 {
  449. return nil, errors.New("invalid external resource: ", ip)
  450. }
  451. filename := kv[0]
  452. country := kv[1]
  453. if len(filename) == 0 || len(country) == 0 {
  454. return nil, errors.New("empty filename or empty country in rule")
  455. }
  456. isReverseMatch := false
  457. if strings.HasPrefix(country, "!") {
  458. country = country[1:]
  459. isReverseMatch = true
  460. }
  461. geoip, err := loadIP(filename, strings.ToUpper(country))
  462. if err != nil {
  463. return nil, errors.New("failed to load IPs: ", country, " from ", filename).Base(err)
  464. }
  465. geoipList = append(geoipList, &router.GeoIP{
  466. CountryCode: strings.ToUpper(filename + "_" + country),
  467. Cidr: geoip,
  468. ReverseMatch: isReverseMatch,
  469. })
  470. continue
  471. }
  472. ipRule, err := ParseIP(ip)
  473. if err != nil {
  474. return nil, errors.New("invalid IP: ", ip).Base(err)
  475. }
  476. customCidrs = append(customCidrs, ipRule)
  477. }
  478. if len(customCidrs) > 0 {
  479. geoipList = append(geoipList, &router.GeoIP{
  480. Cidr: customCidrs,
  481. })
  482. }
  483. return geoipList, nil
  484. }
  485. func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
  486. type RawFieldRule struct {
  487. RouterRule
  488. Domain *StringList `json:"domain"`
  489. Domains *StringList `json:"domains"`
  490. IP *StringList `json:"ip"`
  491. Port *PortList `json:"port"`
  492. Network *NetworkList `json:"network"`
  493. SourceIP *StringList `json:"source"`
  494. SourcePort *PortList `json:"sourcePort"`
  495. User *StringList `json:"user"`
  496. InboundTag *StringList `json:"inboundTag"`
  497. Protocols *StringList `json:"protocol"`
  498. Attributes map[string]string `json:"attrs"`
  499. }
  500. rawFieldRule := new(RawFieldRule)
  501. err := json.Unmarshal(msg, rawFieldRule)
  502. if err != nil {
  503. return nil, err
  504. }
  505. rule := new(router.RoutingRule)
  506. rule.RuleTag = rawFieldRule.RuleTag
  507. switch {
  508. case len(rawFieldRule.OutboundTag) > 0:
  509. rule.TargetTag = &router.RoutingRule_Tag{
  510. Tag: rawFieldRule.OutboundTag,
  511. }
  512. case len(rawFieldRule.BalancerTag) > 0:
  513. rule.TargetTag = &router.RoutingRule_BalancingTag{
  514. BalancingTag: rawFieldRule.BalancerTag,
  515. }
  516. default:
  517. return nil, errors.New("neither outboundTag nor balancerTag is specified in routing rule")
  518. }
  519. if rawFieldRule.DomainMatcher != "" {
  520. rule.DomainMatcher = rawFieldRule.DomainMatcher
  521. }
  522. if rawFieldRule.Domain != nil {
  523. for _, domain := range *rawFieldRule.Domain {
  524. rules, err := parseDomainRule(domain)
  525. if err != nil {
  526. return nil, errors.New("failed to parse domain rule: ", domain).Base(err)
  527. }
  528. rule.Domain = append(rule.Domain, rules...)
  529. }
  530. }
  531. if rawFieldRule.Domains != nil {
  532. for _, domain := range *rawFieldRule.Domains {
  533. rules, err := parseDomainRule(domain)
  534. if err != nil {
  535. return nil, errors.New("failed to parse domain rule: ", domain).Base(err)
  536. }
  537. rule.Domain = append(rule.Domain, rules...)
  538. }
  539. }
  540. if rawFieldRule.IP != nil {
  541. geoipList, err := ToCidrList(*rawFieldRule.IP)
  542. if err != nil {
  543. return nil, err
  544. }
  545. rule.Geoip = geoipList
  546. }
  547. if rawFieldRule.Port != nil {
  548. rule.PortList = rawFieldRule.Port.Build()
  549. }
  550. if rawFieldRule.Network != nil {
  551. rule.Networks = rawFieldRule.Network.Build()
  552. }
  553. if rawFieldRule.SourceIP != nil {
  554. geoipList, err := ToCidrList(*rawFieldRule.SourceIP)
  555. if err != nil {
  556. return nil, err
  557. }
  558. rule.SourceGeoip = geoipList
  559. }
  560. if rawFieldRule.SourcePort != nil {
  561. rule.SourcePortList = rawFieldRule.SourcePort.Build()
  562. }
  563. if rawFieldRule.User != nil {
  564. for _, s := range *rawFieldRule.User {
  565. rule.UserEmail = append(rule.UserEmail, s)
  566. }
  567. }
  568. if rawFieldRule.InboundTag != nil {
  569. for _, s := range *rawFieldRule.InboundTag {
  570. rule.InboundTag = append(rule.InboundTag, s)
  571. }
  572. }
  573. if rawFieldRule.Protocols != nil {
  574. for _, s := range *rawFieldRule.Protocols {
  575. rule.Protocol = append(rule.Protocol, s)
  576. }
  577. }
  578. if len(rawFieldRule.Attributes) > 0 {
  579. rule.Attributes = rawFieldRule.Attributes
  580. }
  581. return rule, nil
  582. }
  583. func ParseRule(msg json.RawMessage) (*router.RoutingRule, error) {
  584. rawRule := new(RouterRule)
  585. err := json.Unmarshal(msg, rawRule)
  586. if err != nil {
  587. return nil, errors.New("invalid router rule").Base(err)
  588. }
  589. if rawRule.Type == "" || strings.EqualFold(rawRule.Type, "field") {
  590. fieldrule, err := parseFieldRule(msg)
  591. if err != nil {
  592. return nil, errors.New("invalid field rule").Base(err)
  593. }
  594. return fieldrule, nil
  595. }
  596. return nil, errors.New("unknown router rule type: ", rawRule.Type)
  597. }