router.go 16 KB

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