router.go 17 KB

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