router.go 15 KB

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