router.go 14 KB

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