router.go 12 KB

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