router.go 14 KB

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