router.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 loadGeosite(list string) ([]*router.Domain, error) {
  212. return loadGeositeWithAttr("geosite.dat", list)
  213. }
  214. func loadGeositeWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
  215. parts := strings.Split(siteWithAttr, "@")
  216. if len(parts) == 0 {
  217. return nil, newError("empty rule")
  218. }
  219. list := strings.TrimSpace(parts[0])
  220. attrVal := parts[1:]
  221. if len(list) == 0 {
  222. return nil, newError("empty listname in rule: ", siteWithAttr)
  223. }
  224. domains, err := loadSite(file, list)
  225. if err != nil {
  226. return nil, err
  227. }
  228. attrs := parseAttrs(attrVal)
  229. if attrs.IsEmpty() {
  230. if strings.Contains(siteWithAttr, "@") {
  231. newError("empty attribute list: ", siteWithAttr)
  232. }
  233. return domains, nil
  234. }
  235. filteredDomains := make([]*router.Domain, 0, len(domains))
  236. hasAttrMatched := false
  237. for _, domain := range domains {
  238. if attrs.Match(domain) {
  239. hasAttrMatched = true
  240. filteredDomains = append(filteredDomains, domain)
  241. }
  242. }
  243. if !hasAttrMatched {
  244. newError("attribute match no rule: geosite:", siteWithAttr)
  245. }
  246. return filteredDomains, nil
  247. }
  248. func parseDomainRule(domain string) ([]*router.Domain, error) {
  249. if strings.HasPrefix(domain, "geosite:") {
  250. list := domain[8:]
  251. if len(list) == 0 {
  252. return nil, newError("empty listname in rule: ", domain)
  253. }
  254. domains, err := loadGeosite(list)
  255. if err != nil {
  256. return nil, newError("failed to load geosite: ", list).Base(err)
  257. }
  258. return domains, nil
  259. }
  260. var isExtDatFile = 0
  261. {
  262. const prefix = "ext:"
  263. if strings.HasPrefix(domain, prefix) {
  264. isExtDatFile = len(prefix)
  265. }
  266. const prefixQualified = "ext-domain:"
  267. if strings.HasPrefix(domain, prefixQualified) {
  268. isExtDatFile = len(prefixQualified)
  269. }
  270. }
  271. if isExtDatFile != 0 {
  272. kv := strings.Split(domain[isExtDatFile:], ":")
  273. if len(kv) != 2 {
  274. return nil, newError("invalid external resource: ", domain)
  275. }
  276. filename := kv[0]
  277. list := kv[1]
  278. domains, err := loadGeositeWithAttr(filename, list)
  279. if err != nil {
  280. return nil, newError("failed to load external geosite: ", list, " from ", filename).Base(err)
  281. }
  282. return domains, nil
  283. }
  284. domainRule := new(router.Domain)
  285. switch {
  286. case strings.HasPrefix(domain, "regexp:"):
  287. regexpVal := domain[7:]
  288. if len(regexpVal) == 0 {
  289. return nil, newError("empty regexp type of rule: ", domain)
  290. }
  291. domainRule.Type = router.Domain_Regex
  292. domainRule.Value = regexpVal
  293. case strings.HasPrefix(domain, "domain:"):
  294. domainName := domain[7:]
  295. if len(domainName) == 0 {
  296. return nil, newError("empty domain type of rule: ", domain)
  297. }
  298. domainRule.Type = router.Domain_Domain
  299. domainRule.Value = domainName
  300. case strings.HasPrefix(domain, "full:"):
  301. fullVal := domain[5:]
  302. if len(fullVal) == 0 {
  303. return nil, newError("empty full domain type of rule: ", domain)
  304. }
  305. domainRule.Type = router.Domain_Full
  306. domainRule.Value = fullVal
  307. case strings.HasPrefix(domain, "keyword:"):
  308. keywordVal := domain[8:]
  309. if len(keywordVal) == 0 {
  310. return nil, newError("empty keyword type of rule: ", domain)
  311. }
  312. domainRule.Type = router.Domain_Plain
  313. domainRule.Value = keywordVal
  314. case strings.HasPrefix(domain, "dotless:"):
  315. domainRule.Type = router.Domain_Regex
  316. switch substr := domain[8:]; {
  317. case substr == "":
  318. domainRule.Value = "^[^.]*$"
  319. case !strings.Contains(substr, "."):
  320. domainRule.Value = "^[^.]*" + substr + "[^.]*$"
  321. default:
  322. return nil, newError("substr in dotless rule should not contain a dot: ", substr)
  323. }
  324. default:
  325. domainRule.Type = router.Domain_Plain
  326. domainRule.Value = domain
  327. }
  328. return []*router.Domain{domainRule}, nil
  329. }
  330. func toCidrList(ips StringList) ([]*router.GeoIP, error) {
  331. var geoipList []*router.GeoIP
  332. var customCidrs []*router.CIDR
  333. for _, ip := range ips {
  334. if strings.HasPrefix(ip, "geoip:") {
  335. country := ip[6:]
  336. isReverseMatch := false
  337. if strings.HasPrefix(ip, "geoip:!") {
  338. country = ip[7:]
  339. isReverseMatch = true
  340. }
  341. if len(country) == 0 {
  342. return nil, newError("empty country name in rule")
  343. }
  344. geoip, err := loadGeoIP(country)
  345. if err != nil {
  346. return nil, newError("failed to load geoip: ", country).Base(err)
  347. }
  348. geoipList = append(geoipList, &router.GeoIP{
  349. CountryCode: strings.ToUpper(country),
  350. Cidr: geoip,
  351. ReverseMatch: isReverseMatch,
  352. })
  353. continue
  354. }
  355. var isExtDatFile = 0
  356. {
  357. const prefix = "ext:"
  358. if strings.HasPrefix(ip, prefix) {
  359. isExtDatFile = len(prefix)
  360. }
  361. const prefixQualified = "ext-ip:"
  362. if strings.HasPrefix(ip, prefixQualified) {
  363. isExtDatFile = len(prefixQualified)
  364. }
  365. }
  366. if isExtDatFile != 0 {
  367. kv := strings.Split(ip[isExtDatFile:], ":")
  368. if len(kv) != 2 {
  369. return nil, newError("invalid external resource: ", ip)
  370. }
  371. filename := kv[0]
  372. country := kv[1]
  373. if len(filename) == 0 || len(country) == 0 {
  374. return nil, newError("empty filename or empty country in rule")
  375. }
  376. isReverseMatch := false
  377. if strings.HasPrefix(country, "!") {
  378. country = country[1:]
  379. isReverseMatch = true
  380. }
  381. geoip, err := loadIP(filename, country)
  382. if err != nil {
  383. return nil, newError("failed to load geoip: ", country, " from ", filename).Base(err)
  384. }
  385. geoipList = append(geoipList, &router.GeoIP{
  386. CountryCode: strings.ToUpper(filename + "_" + country),
  387. Cidr: geoip,
  388. ReverseMatch: isReverseMatch,
  389. })
  390. continue
  391. }
  392. ipRule, err := ParseIP(ip)
  393. if err != nil {
  394. return nil, newError("invalid IP: ", ip).Base(err)
  395. }
  396. customCidrs = append(customCidrs, ipRule)
  397. }
  398. if len(customCidrs) > 0 {
  399. geoipList = append(geoipList, &router.GeoIP{
  400. Cidr: customCidrs,
  401. })
  402. }
  403. return geoipList, nil
  404. }
  405. func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
  406. type RawFieldRule struct {
  407. RouterRule
  408. Domain *StringList `json:"domain"`
  409. Domains *StringList `json:"domains"`
  410. IP *StringList `json:"ip"`
  411. Port *PortList `json:"port"`
  412. Network *NetworkList `json:"network"`
  413. SourceIP *StringList `json:"source"`
  414. SourcePort *PortList `json:"sourcePort"`
  415. User *StringList `json:"user"`
  416. InboundTag *StringList `json:"inboundTag"`
  417. Protocols *StringList `json:"protocol"`
  418. Attributes string `json:"attrs"`
  419. }
  420. rawFieldRule := new(RawFieldRule)
  421. err := json.Unmarshal(msg, rawFieldRule)
  422. if err != nil {
  423. return nil, err
  424. }
  425. rule := new(router.RoutingRule)
  426. switch {
  427. case len(rawFieldRule.OutboundTag) > 0:
  428. rule.TargetTag = &router.RoutingRule_Tag{
  429. Tag: rawFieldRule.OutboundTag,
  430. }
  431. case len(rawFieldRule.BalancerTag) > 0:
  432. rule.TargetTag = &router.RoutingRule_BalancingTag{
  433. BalancingTag: rawFieldRule.BalancerTag,
  434. }
  435. default:
  436. return nil, newError("neither outboundTag nor balancerTag is specified in routing rule")
  437. }
  438. if rawFieldRule.DomainMatcher != "" {
  439. rule.DomainMatcher = rawFieldRule.DomainMatcher
  440. }
  441. if rawFieldRule.Domain != nil {
  442. for _, domain := range *rawFieldRule.Domain {
  443. rules, err := parseDomainRule(domain)
  444. if err != nil {
  445. return nil, newError("failed to parse domain rule: ", domain).Base(err)
  446. }
  447. rule.Domain = append(rule.Domain, rules...)
  448. }
  449. }
  450. if rawFieldRule.Domains != nil {
  451. for _, domain := range *rawFieldRule.Domains {
  452. rules, err := parseDomainRule(domain)
  453. if err != nil {
  454. return nil, newError("failed to parse domain rule: ", domain).Base(err)
  455. }
  456. rule.Domain = append(rule.Domain, rules...)
  457. }
  458. }
  459. if rawFieldRule.IP != nil {
  460. geoipList, err := toCidrList(*rawFieldRule.IP)
  461. if err != nil {
  462. return nil, err
  463. }
  464. rule.Geoip = geoipList
  465. }
  466. if rawFieldRule.Port != nil {
  467. rule.PortList = rawFieldRule.Port.Build()
  468. }
  469. if rawFieldRule.Network != nil {
  470. rule.Networks = rawFieldRule.Network.Build()
  471. }
  472. if rawFieldRule.SourceIP != nil {
  473. geoipList, err := toCidrList(*rawFieldRule.SourceIP)
  474. if err != nil {
  475. return nil, err
  476. }
  477. rule.SourceGeoip = geoipList
  478. }
  479. if rawFieldRule.SourcePort != nil {
  480. rule.SourcePortList = rawFieldRule.SourcePort.Build()
  481. }
  482. if rawFieldRule.User != nil {
  483. for _, s := range *rawFieldRule.User {
  484. rule.UserEmail = append(rule.UserEmail, s)
  485. }
  486. }
  487. if rawFieldRule.InboundTag != nil {
  488. for _, s := range *rawFieldRule.InboundTag {
  489. rule.InboundTag = append(rule.InboundTag, s)
  490. }
  491. }
  492. if rawFieldRule.Protocols != nil {
  493. for _, s := range *rawFieldRule.Protocols {
  494. rule.Protocol = append(rule.Protocol, s)
  495. }
  496. }
  497. if len(rawFieldRule.Attributes) > 0 {
  498. rule.Attributes = rawFieldRule.Attributes
  499. }
  500. return rule, nil
  501. }
  502. func ParseRule(msg json.RawMessage) (*router.RoutingRule, error) {
  503. rawRule := new(RouterRule)
  504. err := json.Unmarshal(msg, rawRule)
  505. if err != nil {
  506. return nil, newError("invalid router rule").Base(err)
  507. }
  508. if strings.EqualFold(rawRule.Type, "field") {
  509. fieldrule, err := parseFieldRule(msg)
  510. if err != nil {
  511. return nil, newError("invalid field rule").Base(err)
  512. }
  513. return fieldrule, nil
  514. }
  515. return nil, newError("unknown router rule type: ", rawRule.Type)
  516. }