router.go 15 KB

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