router.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 len(r.Tag) == 0 {
  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. if strings.HasPrefix(domain, "ext:") {
  231. kv := strings.Split(domain[4:], ":")
  232. if len(kv) != 2 {
  233. return nil, newError("invalid external resource: ", domain)
  234. }
  235. filename := kv[0]
  236. country := kv[1]
  237. domains, err := loadGeositeWithAttr(filename, country)
  238. if err != nil {
  239. return nil, newError("failed to load external sites: ", country, " from ", filename).Base(err)
  240. }
  241. return domains, nil
  242. }
  243. domainRule := new(router.Domain)
  244. switch {
  245. case strings.HasPrefix(domain, "regexp:"):
  246. domainRule.Type = router.Domain_Regex
  247. domainRule.Value = domain[7:]
  248. case strings.HasPrefix(domain, "domain:"):
  249. domainRule.Type = router.Domain_Domain
  250. domainRule.Value = domain[7:]
  251. case strings.HasPrefix(domain, "full:"):
  252. domainRule.Type = router.Domain_Full
  253. domainRule.Value = domain[5:]
  254. default:
  255. domainRule.Type = router.Domain_Plain
  256. domainRule.Value = domain
  257. }
  258. return []*router.Domain{domainRule}, nil
  259. }
  260. func toCidrList(ips StringList) ([]*router.GeoIP, error) {
  261. var geoipList []*router.GeoIP
  262. var customCidrs []*router.CIDR
  263. for _, ip := range ips {
  264. if strings.HasPrefix(ip, "geoip:") {
  265. country := ip[6:]
  266. geoip, err := loadGeoIP(strings.ToUpper(country))
  267. if err != nil {
  268. return nil, newError("failed to load GeoIP: ", country).Base(err)
  269. }
  270. geoipList = append(geoipList, &router.GeoIP{
  271. CountryCode: strings.ToUpper(country),
  272. Cidr: geoip,
  273. })
  274. continue
  275. }
  276. if strings.HasPrefix(ip, "ext:") {
  277. kv := strings.Split(ip[4:], ":")
  278. if len(kv) != 2 {
  279. return nil, newError("invalid external resource: ", ip)
  280. }
  281. filename := kv[0]
  282. country := kv[1]
  283. geoip, err := loadGeoIP(strings.ToUpper(country))
  284. if err != nil {
  285. return nil, newError("failed to load IPs: ", country, " from ", filename).Base(err)
  286. }
  287. geoipList = append(geoipList, &router.GeoIP{
  288. CountryCode: strings.ToUpper(filename + "_" + country),
  289. Cidr: geoip,
  290. })
  291. continue
  292. }
  293. ipRule, err := ParseIP(ip)
  294. if err != nil {
  295. return nil, newError("invalid IP: ", ip).Base(err)
  296. }
  297. customCidrs = append(customCidrs, ipRule)
  298. }
  299. if len(customCidrs) > 0 {
  300. geoipList = append(geoipList, &router.GeoIP{
  301. Cidr: customCidrs,
  302. })
  303. }
  304. return geoipList, nil
  305. }
  306. func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
  307. type RawFieldRule struct {
  308. RouterRule
  309. Domain *StringList `json:"domain"`
  310. IP *StringList `json:"ip"`
  311. Port *PortRange `json:"port"`
  312. Network *NetworkList `json:"network"`
  313. SourceIP *StringList `json:"source"`
  314. User *StringList `json:"user"`
  315. InboundTag *StringList `json:"inboundTag"`
  316. Protocols *StringList `json:"protocol"`
  317. }
  318. rawFieldRule := new(RawFieldRule)
  319. err := json.Unmarshal(msg, rawFieldRule)
  320. if err != nil {
  321. return nil, err
  322. }
  323. rule := new(router.RoutingRule)
  324. if len(rawFieldRule.OutboundTag) > 0 {
  325. rule.TargetTag = &router.RoutingRule_Tag{
  326. Tag: rawFieldRule.OutboundTag,
  327. }
  328. } else if len(rawFieldRule.BalancerTag) > 0 {
  329. rule.TargetTag = &router.RoutingRule_BalancingTag{
  330. BalancingTag: rawFieldRule.BalancerTag,
  331. }
  332. } else {
  333. return nil, newError("neither outboundTag nor balancerTag is specified in routing rule")
  334. }
  335. if rawFieldRule.Domain != nil {
  336. for _, domain := range *rawFieldRule.Domain {
  337. rules, err := parseDomainRule(domain)
  338. if err != nil {
  339. return nil, newError("failed to parse domain rule: ", domain).Base(err)
  340. }
  341. rule.Domain = append(rule.Domain, rules...)
  342. }
  343. }
  344. if rawFieldRule.IP != nil {
  345. geoipList, err := toCidrList(*rawFieldRule.IP)
  346. if err != nil {
  347. return nil, err
  348. }
  349. rule.Geoip = geoipList
  350. }
  351. if rawFieldRule.Port != nil {
  352. rule.PortRange = rawFieldRule.Port.Build()
  353. }
  354. if rawFieldRule.Network != nil {
  355. rule.Networks = rawFieldRule.Network.Build()
  356. }
  357. if rawFieldRule.SourceIP != nil {
  358. geoipList, err := toCidrList(*rawFieldRule.SourceIP)
  359. if err != nil {
  360. return nil, err
  361. }
  362. rule.SourceGeoip = geoipList
  363. }
  364. if rawFieldRule.User != nil {
  365. for _, s := range *rawFieldRule.User {
  366. rule.UserEmail = append(rule.UserEmail, s)
  367. }
  368. }
  369. if rawFieldRule.InboundTag != nil {
  370. for _, s := range *rawFieldRule.InboundTag {
  371. rule.InboundTag = append(rule.InboundTag, s)
  372. }
  373. }
  374. if rawFieldRule.Protocols != nil {
  375. for _, s := range *rawFieldRule.Protocols {
  376. rule.Protocol = append(rule.Protocol, s)
  377. }
  378. }
  379. return rule, nil
  380. }
  381. func ParseRule(msg json.RawMessage) (*router.RoutingRule, error) {
  382. rawRule := new(RouterRule)
  383. err := json.Unmarshal(msg, rawRule)
  384. if err != nil {
  385. return nil, newError("invalid router rule").Base(err)
  386. }
  387. if rawRule.Type == "field" {
  388. fieldrule, err := parseFieldRule(msg)
  389. if err != nil {
  390. return nil, newError("invalid field rule").Base(err)
  391. }
  392. return fieldrule, nil
  393. }
  394. if rawRule.Type == "chinaip" {
  395. chinaiprule, err := parseChinaIPRule(msg)
  396. if err != nil {
  397. return nil, newError("invalid chinaip rule").Base(err)
  398. }
  399. return chinaiprule, nil
  400. }
  401. if rawRule.Type == "chinasites" {
  402. chinasitesrule, err := parseChinaSitesRule(msg)
  403. if err != nil {
  404. return nil, newError("invalid chinasites rule").Base(err)
  405. }
  406. return chinasitesrule, nil
  407. }
  408. return nil, newError("unknown router rule type: ", rawRule.Type)
  409. }
  410. func parseChinaIPRule(data []byte) (*router.RoutingRule, error) {
  411. rawRule := new(RouterRule)
  412. err := json.Unmarshal(data, rawRule)
  413. if err != nil {
  414. return nil, newError("invalid router rule").Base(err)
  415. }
  416. chinaIPs, err := loadGeoIP("CN")
  417. if err != nil {
  418. return nil, newError("failed to load geoip:cn").Base(err)
  419. }
  420. return &router.RoutingRule{
  421. TargetTag: &router.RoutingRule_Tag{
  422. Tag: rawRule.OutboundTag,
  423. },
  424. Cidr: chinaIPs,
  425. }, nil
  426. }
  427. func parseChinaSitesRule(data []byte) (*router.RoutingRule, error) {
  428. rawRule := new(RouterRule)
  429. err := json.Unmarshal(data, rawRule)
  430. if err != nil {
  431. return nil, newError("invalid router rule").Base(err).AtError()
  432. }
  433. domains, err := loadGeositeWithAttr("geosite.dat", "CN")
  434. if err != nil {
  435. return nil, newError("failed to load geosite:cn.").Base(err)
  436. }
  437. return &router.RoutingRule{
  438. TargetTag: &router.RoutingRule_Tag{
  439. Tag: rawRule.OutboundTag,
  440. },
  441. Domain: domains,
  442. }, nil
  443. }