router.go 16 KB

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