router.go 13 KB

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