router.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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: " + 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("country not found: " + 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. default:
  269. domainRule.Type = router.Domain_Plain
  270. domainRule.Value = domain
  271. }
  272. return []*router.Domain{domainRule}, nil
  273. }
  274. func toCidrList(ips StringList) ([]*router.GeoIP, error) {
  275. var geoipList []*router.GeoIP
  276. var customCidrs []*router.CIDR
  277. for _, ip := range ips {
  278. if strings.HasPrefix(ip, "geoip:") {
  279. country := ip[6:]
  280. geoip, err := loadGeoIP(strings.ToUpper(country))
  281. if err != nil {
  282. return nil, newError("failed to load GeoIP: ", country).Base(err)
  283. }
  284. geoipList = append(geoipList, &router.GeoIP{
  285. CountryCode: strings.ToUpper(country),
  286. Cidr: geoip,
  287. })
  288. continue
  289. }
  290. var isExtDatFile = 0
  291. {
  292. const prefix = "ext:"
  293. if strings.HasPrefix(ip, prefix) {
  294. isExtDatFile = len(prefix)
  295. }
  296. const prefixQualified = "ext-ip:"
  297. if strings.HasPrefix(ip, prefixQualified) {
  298. isExtDatFile = len(prefixQualified)
  299. }
  300. }
  301. if isExtDatFile != 0 {
  302. kv := strings.Split(ip[isExtDatFile:], ":")
  303. if len(kv) != 2 {
  304. return nil, newError("invalid external resource: ", ip)
  305. }
  306. filename := kv[0]
  307. country := kv[1]
  308. geoip, err := loadIP(filename, strings.ToUpper(country))
  309. if err != nil {
  310. return nil, newError("failed to load IPs: ", country, " from ", filename).Base(err)
  311. }
  312. geoipList = append(geoipList, &router.GeoIP{
  313. CountryCode: strings.ToUpper(filename + "_" + country),
  314. Cidr: geoip,
  315. })
  316. continue
  317. }
  318. ipRule, err := ParseIP(ip)
  319. if err != nil {
  320. return nil, newError("invalid IP: ", ip).Base(err)
  321. }
  322. customCidrs = append(customCidrs, ipRule)
  323. }
  324. if len(customCidrs) > 0 {
  325. geoipList = append(geoipList, &router.GeoIP{
  326. Cidr: customCidrs,
  327. })
  328. }
  329. return geoipList, nil
  330. }
  331. func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
  332. type RawFieldRule struct {
  333. RouterRule
  334. Domain *StringList `json:"domain"`
  335. IP *StringList `json:"ip"`
  336. Port *PortList `json:"port"`
  337. Network *NetworkList `json:"network"`
  338. SourceIP *StringList `json:"source"`
  339. SourcePort *PortList `json:"sourcePort"`
  340. User *StringList `json:"user"`
  341. InboundTag *StringList `json:"inboundTag"`
  342. Protocols *StringList `json:"protocol"`
  343. Attributes string `json:"attrs"`
  344. }
  345. rawFieldRule := new(RawFieldRule)
  346. err := json.Unmarshal(msg, rawFieldRule)
  347. if err != nil {
  348. return nil, err
  349. }
  350. rule := new(router.RoutingRule)
  351. if len(rawFieldRule.OutboundTag) > 0 {
  352. rule.TargetTag = &router.RoutingRule_Tag{
  353. Tag: rawFieldRule.OutboundTag,
  354. }
  355. } else if len(rawFieldRule.BalancerTag) > 0 {
  356. rule.TargetTag = &router.RoutingRule_BalancingTag{
  357. BalancingTag: rawFieldRule.BalancerTag,
  358. }
  359. } else {
  360. return nil, newError("neither outboundTag nor balancerTag is specified in routing rule")
  361. }
  362. if rawFieldRule.Domain != nil {
  363. for _, domain := range *rawFieldRule.Domain {
  364. rules, err := parseDomainRule(domain)
  365. if err != nil {
  366. return nil, newError("failed to parse domain rule: ", domain).Base(err)
  367. }
  368. rule.Domain = append(rule.Domain, rules...)
  369. }
  370. }
  371. if rawFieldRule.IP != nil {
  372. geoipList, err := toCidrList(*rawFieldRule.IP)
  373. if err != nil {
  374. return nil, err
  375. }
  376. rule.Geoip = geoipList
  377. }
  378. if rawFieldRule.Port != nil {
  379. rule.PortList = rawFieldRule.Port.Build()
  380. }
  381. if rawFieldRule.Network != nil {
  382. rule.Networks = rawFieldRule.Network.Build()
  383. }
  384. if rawFieldRule.SourceIP != nil {
  385. geoipList, err := toCidrList(*rawFieldRule.SourceIP)
  386. if err != nil {
  387. return nil, err
  388. }
  389. rule.SourceGeoip = geoipList
  390. }
  391. if rawFieldRule.SourcePort != nil {
  392. rule.SourcePortList = rawFieldRule.SourcePort.Build()
  393. }
  394. if rawFieldRule.User != nil {
  395. for _, s := range *rawFieldRule.User {
  396. rule.UserEmail = append(rule.UserEmail, s)
  397. }
  398. }
  399. if rawFieldRule.InboundTag != nil {
  400. for _, s := range *rawFieldRule.InboundTag {
  401. rule.InboundTag = append(rule.InboundTag, s)
  402. }
  403. }
  404. if rawFieldRule.Protocols != nil {
  405. for _, s := range *rawFieldRule.Protocols {
  406. rule.Protocol = append(rule.Protocol, s)
  407. }
  408. }
  409. if len(rawFieldRule.Attributes) > 0 {
  410. rule.Attributes = rawFieldRule.Attributes
  411. }
  412. return rule, nil
  413. }
  414. func ParseRule(msg json.RawMessage) (*router.RoutingRule, error) {
  415. rawRule := new(RouterRule)
  416. err := json.Unmarshal(msg, rawRule)
  417. if err != nil {
  418. return nil, newError("invalid router rule").Base(err)
  419. }
  420. if rawRule.Type == "field" {
  421. fieldrule, err := parseFieldRule(msg)
  422. if err != nil {
  423. return nil, newError("invalid field rule").Base(err)
  424. }
  425. return fieldrule, nil
  426. }
  427. if rawRule.Type == "chinaip" {
  428. chinaiprule, err := parseChinaIPRule(msg)
  429. if err != nil {
  430. return nil, newError("invalid chinaip rule").Base(err)
  431. }
  432. return chinaiprule, nil
  433. }
  434. if rawRule.Type == "chinasites" {
  435. chinasitesrule, err := parseChinaSitesRule(msg)
  436. if err != nil {
  437. return nil, newError("invalid chinasites rule").Base(err)
  438. }
  439. return chinasitesrule, nil
  440. }
  441. return nil, newError("unknown router rule type: ", rawRule.Type)
  442. }
  443. func parseChinaIPRule(data []byte) (*router.RoutingRule, error) {
  444. rawRule := new(RouterRule)
  445. err := json.Unmarshal(data, rawRule)
  446. if err != nil {
  447. return nil, newError("invalid router rule").Base(err)
  448. }
  449. chinaIPs, err := loadGeoIP("CN")
  450. if err != nil {
  451. return nil, newError("failed to load geoip:cn").Base(err)
  452. }
  453. return &router.RoutingRule{
  454. TargetTag: &router.RoutingRule_Tag{
  455. Tag: rawRule.OutboundTag,
  456. },
  457. Cidr: chinaIPs,
  458. }, nil
  459. }
  460. func parseChinaSitesRule(data []byte) (*router.RoutingRule, error) {
  461. rawRule := new(RouterRule)
  462. err := json.Unmarshal(data, rawRule)
  463. if err != nil {
  464. return nil, newError("invalid router rule").Base(err).AtError()
  465. }
  466. domains, err := loadGeositeWithAttr("geosite.dat", "CN")
  467. if err != nil {
  468. return nil, newError("failed to load geosite:cn.").Base(err)
  469. }
  470. return &router.RoutingRule{
  471. TargetTag: &router.RoutingRule_Tag{
  472. Tag: rawRule.OutboundTag,
  473. },
  474. Domain: domains,
  475. }, nil
  476. }