router.go 14 KB

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