router.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. if len(country) == 0 {
  334. return nil, newError("empty country name in rule")
  335. }
  336. geoip, err := loadGeoIP(country)
  337. if err != nil {
  338. return nil, newError("failed to load geoip: ", country).Base(err)
  339. }
  340. geoipList = append(geoipList, &router.GeoIP{
  341. CountryCode: strings.ToUpper(country),
  342. Cidr: geoip,
  343. })
  344. continue
  345. }
  346. var isExtDatFile = 0
  347. {
  348. const prefix = "ext:"
  349. if strings.HasPrefix(ip, prefix) {
  350. isExtDatFile = len(prefix)
  351. }
  352. const prefixQualified = "ext-ip:"
  353. if strings.HasPrefix(ip, prefixQualified) {
  354. isExtDatFile = len(prefixQualified)
  355. }
  356. }
  357. if isExtDatFile != 0 {
  358. kv := strings.Split(ip[isExtDatFile:], ":")
  359. if len(kv) != 2 {
  360. return nil, newError("invalid external resource: ", ip)
  361. }
  362. filename := kv[0]
  363. country := kv[1]
  364. if len(filename) == 0 || len(country) == 0 {
  365. return nil, newError("empty filename or empty country in rule")
  366. }
  367. geoip, err := loadIP(filename, country)
  368. if err != nil {
  369. return nil, newError("failed to load geoip: ", country, " from ", filename).Base(err)
  370. }
  371. geoipList = append(geoipList, &router.GeoIP{
  372. CountryCode: strings.ToUpper(filename + "_" + country),
  373. Cidr: geoip,
  374. })
  375. continue
  376. }
  377. ipRule, err := ParseIP(ip)
  378. if err != nil {
  379. return nil, newError("invalid IP: ", ip).Base(err)
  380. }
  381. customCidrs = append(customCidrs, ipRule)
  382. }
  383. if len(customCidrs) > 0 {
  384. geoipList = append(geoipList, &router.GeoIP{
  385. Cidr: customCidrs,
  386. })
  387. }
  388. return geoipList, nil
  389. }
  390. func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
  391. type RawFieldRule struct {
  392. RouterRule
  393. Domain *StringList `json:"domain"`
  394. Domains *StringList `json:"domains"`
  395. IP *StringList `json:"ip"`
  396. Port *PortList `json:"port"`
  397. Network *NetworkList `json:"network"`
  398. SourceIP *StringList `json:"source"`
  399. SourcePort *PortList `json:"sourcePort"`
  400. User *StringList `json:"user"`
  401. InboundTag *StringList `json:"inboundTag"`
  402. Protocols *StringList `json:"protocol"`
  403. Attributes string `json:"attrs"`
  404. }
  405. rawFieldRule := new(RawFieldRule)
  406. err := json.Unmarshal(msg, rawFieldRule)
  407. if err != nil {
  408. return nil, err
  409. }
  410. rule := new(router.RoutingRule)
  411. switch {
  412. case len(rawFieldRule.OutboundTag) > 0:
  413. rule.TargetTag = &router.RoutingRule_Tag{
  414. Tag: rawFieldRule.OutboundTag,
  415. }
  416. case len(rawFieldRule.BalancerTag) > 0:
  417. rule.TargetTag = &router.RoutingRule_BalancingTag{
  418. BalancingTag: rawFieldRule.BalancerTag,
  419. }
  420. default:
  421. return nil, newError("neither outboundTag nor balancerTag is specified in routing rule")
  422. }
  423. if rawFieldRule.DomainMatcher != "" {
  424. rule.DomainMatcher = rawFieldRule.DomainMatcher
  425. }
  426. if rawFieldRule.Domain != nil {
  427. for _, domain := range *rawFieldRule.Domain {
  428. rules, err := parseDomainRule(domain)
  429. if err != nil {
  430. return nil, newError("failed to parse domain rule: ", domain).Base(err)
  431. }
  432. rule.Domain = append(rule.Domain, rules...)
  433. }
  434. }
  435. if rawFieldRule.Domains != nil {
  436. for _, domain := range *rawFieldRule.Domains {
  437. rules, err := parseDomainRule(domain)
  438. if err != nil {
  439. return nil, newError("failed to parse domain rule: ", domain).Base(err)
  440. }
  441. rule.Domain = append(rule.Domain, rules...)
  442. }
  443. }
  444. if rawFieldRule.IP != nil {
  445. geoipList, err := toCidrList(*rawFieldRule.IP)
  446. if err != nil {
  447. return nil, err
  448. }
  449. rule.Geoip = geoipList
  450. }
  451. if rawFieldRule.Port != nil {
  452. rule.PortList = rawFieldRule.Port.Build()
  453. }
  454. if rawFieldRule.Network != nil {
  455. rule.Networks = rawFieldRule.Network.Build()
  456. }
  457. if rawFieldRule.SourceIP != nil {
  458. geoipList, err := toCidrList(*rawFieldRule.SourceIP)
  459. if err != nil {
  460. return nil, err
  461. }
  462. rule.SourceGeoip = geoipList
  463. }
  464. if rawFieldRule.SourcePort != nil {
  465. rule.SourcePortList = rawFieldRule.SourcePort.Build()
  466. }
  467. if rawFieldRule.User != nil {
  468. for _, s := range *rawFieldRule.User {
  469. rule.UserEmail = append(rule.UserEmail, s)
  470. }
  471. }
  472. if rawFieldRule.InboundTag != nil {
  473. for _, s := range *rawFieldRule.InboundTag {
  474. rule.InboundTag = append(rule.InboundTag, s)
  475. }
  476. }
  477. if rawFieldRule.Protocols != nil {
  478. for _, s := range *rawFieldRule.Protocols {
  479. rule.Protocol = append(rule.Protocol, s)
  480. }
  481. }
  482. if len(rawFieldRule.Attributes) > 0 {
  483. rule.Attributes = rawFieldRule.Attributes
  484. }
  485. return rule, nil
  486. }
  487. func ParseRule(msg json.RawMessage) (*router.RoutingRule, error) {
  488. rawRule := new(RouterRule)
  489. err := json.Unmarshal(msg, rawRule)
  490. if err != nil {
  491. return nil, newError("invalid router rule").Base(err)
  492. }
  493. if strings.EqualFold(rawRule.Type, "field") {
  494. fieldrule, err := parseFieldRule(msg)
  495. if err != nil {
  496. return nil, newError("invalid field rule").Base(err)
  497. }
  498. return fieldrule, nil
  499. }
  500. return nil, newError("unknown router rule type: ", rawRule.Type)
  501. }