router.go 16 KB

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