router.go 13 KB

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