router.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. package conf
  2. import (
  3. "encoding/json"
  4. "strconv"
  5. "strings"
  6. "github.com/v2fly/v2ray-core/v4/app/router"
  7. "github.com/v2fly/v2ray-core/v4/common/geodata"
  8. "github.com/v2fly/v2ray-core/v4/common/net"
  9. )
  10. type RouterRulesConfig struct {
  11. RuleList []json.RawMessage `json:"rules"`
  12. DomainStrategy string `json:"domainStrategy"`
  13. }
  14. // StrategyConfig represents a strategy config
  15. type StrategyConfig struct {
  16. Type string `json:"type"`
  17. Settings *json.RawMessage `json:"settings"`
  18. }
  19. type BalancingRule struct {
  20. Tag string `json:"tag"`
  21. Selectors StringList `json:"selector"`
  22. Strategy StrategyConfig `json:"strategy"`
  23. }
  24. func (r *BalancingRule) Build() (*router.BalancingRule, error) {
  25. if r.Tag == "" {
  26. return nil, newError("empty balancer tag")
  27. }
  28. if len(r.Selectors) == 0 {
  29. return nil, newError("empty selector list")
  30. }
  31. var strategy string
  32. switch strings.ToLower(r.Strategy.Type) {
  33. case strategyRandom, "":
  34. strategy = strategyRandom
  35. case strategyLeastPing:
  36. strategy = "leastPing"
  37. default:
  38. return nil, newError("unknown balancing strategy: " + r.Strategy.Type)
  39. }
  40. return &router.BalancingRule{
  41. Tag: r.Tag,
  42. OutboundSelector: []string(r.Selectors),
  43. Strategy: strategy,
  44. }, nil
  45. }
  46. type RouterConfig struct {
  47. Settings *RouterRulesConfig `json:"settings"` // Deprecated
  48. RuleList []json.RawMessage `json:"rules"`
  49. DomainStrategy *string `json:"domainStrategy"`
  50. Balancers []*BalancingRule `json:"balancers"`
  51. DomainMatcher string `json:"domainMatcher"`
  52. }
  53. func (c *RouterConfig) getDomainStrategy() router.Config_DomainStrategy {
  54. ds := ""
  55. if c.DomainStrategy != nil {
  56. ds = *c.DomainStrategy
  57. } else if c.Settings != nil {
  58. ds = c.Settings.DomainStrategy
  59. }
  60. switch strings.ToLower(ds) {
  61. case "alwaysip", "always_ip", "always-ip":
  62. return router.Config_UseIp
  63. case "ipifnonmatch", "ip_if_non_match", "ip-if-non-match":
  64. return router.Config_IpIfNonMatch
  65. case "ipondemand", "ip_on_demand", "ip-on-demand":
  66. return router.Config_IpOnDemand
  67. default:
  68. return router.Config_AsIs
  69. }
  70. }
  71. func (c *RouterConfig) Build() (*router.Config, error) {
  72. config := new(router.Config)
  73. config.DomainStrategy = c.getDomainStrategy()
  74. var rawRuleList []json.RawMessage
  75. if c != nil {
  76. rawRuleList = c.RuleList
  77. if c.Settings != nil {
  78. c.RuleList = append(c.RuleList, c.Settings.RuleList...)
  79. rawRuleList = c.RuleList
  80. }
  81. }
  82. for _, rawRule := range rawRuleList {
  83. rule, err := ParseRule(rawRule)
  84. if err != nil {
  85. return nil, err
  86. }
  87. if rule.DomainMatcher == "" {
  88. rule.DomainMatcher = c.DomainMatcher
  89. }
  90. config.Rule = append(config.Rule, rule)
  91. }
  92. for _, rawBalancer := range c.Balancers {
  93. balancer, err := rawBalancer.Build()
  94. if err != nil {
  95. return nil, err
  96. }
  97. config.BalancingRule = append(config.BalancingRule, balancer)
  98. }
  99. return config, nil
  100. }
  101. type RouterRule struct {
  102. Type string `json:"type"`
  103. OutboundTag string `json:"outboundTag"`
  104. BalancerTag string `json:"balancerTag"`
  105. DomainMatcher string `json:"domainMatcher"`
  106. }
  107. func ParseIP(s string) (*router.CIDR, error) {
  108. var addr, mask string
  109. i := strings.Index(s, "/")
  110. if i < 0 {
  111. addr = s
  112. } else {
  113. addr = s[:i]
  114. mask = s[i+1:]
  115. }
  116. ip := net.ParseAddress(addr)
  117. switch ip.Family() {
  118. case net.AddressFamilyIPv4:
  119. bits := uint32(32)
  120. if len(mask) > 0 {
  121. bits64, err := strconv.ParseUint(mask, 10, 32)
  122. if err != nil {
  123. return nil, newError("invalid network mask for router: ", mask).Base(err)
  124. }
  125. bits = uint32(bits64)
  126. }
  127. if bits > 32 {
  128. return nil, newError("invalid network mask for router: ", bits)
  129. }
  130. return &router.CIDR{
  131. Ip: []byte(ip.IP()),
  132. Prefix: bits,
  133. }, nil
  134. case net.AddressFamilyIPv6:
  135. bits := uint32(128)
  136. if len(mask) > 0 {
  137. bits64, err := strconv.ParseUint(mask, 10, 32)
  138. if err != nil {
  139. return nil, newError("invalid network mask for router: ", mask).Base(err)
  140. }
  141. bits = uint32(bits64)
  142. }
  143. if bits > 128 {
  144. return nil, newError("invalid network mask for router: ", bits)
  145. }
  146. return &router.CIDR{
  147. Ip: []byte(ip.IP()),
  148. Prefix: bits,
  149. }, nil
  150. default:
  151. return nil, newError("unsupported address for router: ", s)
  152. }
  153. }
  154. type AttributeMatcher interface {
  155. Match(*router.Domain) bool
  156. }
  157. type BooleanMatcher string
  158. func (m BooleanMatcher) Match(domain *router.Domain) bool {
  159. for _, attr := range domain.Attribute {
  160. if strings.EqualFold(attr.GetKey(), string(m)) {
  161. return true
  162. }
  163. }
  164. return false
  165. }
  166. type AttributeList struct {
  167. matcher []AttributeMatcher
  168. }
  169. func (al *AttributeList) Match(domain *router.Domain) bool {
  170. for _, matcher := range al.matcher {
  171. if !matcher.Match(domain) {
  172. return false
  173. }
  174. }
  175. return true
  176. }
  177. func (al *AttributeList) IsEmpty() bool {
  178. return len(al.matcher) == 0
  179. }
  180. func parseAttrs(attrs []string) *AttributeList {
  181. al := new(AttributeList)
  182. for _, attr := range attrs {
  183. trimmedAttr := strings.ToLower(strings.TrimSpace(attr))
  184. if len(trimmedAttr) == 0 {
  185. continue
  186. }
  187. al.matcher = append(al.matcher, BooleanMatcher(trimmedAttr))
  188. }
  189. return al
  190. }
  191. func parseDomainRule(domain string) ([]*router.Domain, error) {
  192. if strings.HasPrefix(domain, "geosite:") {
  193. list := domain[8:]
  194. if len(list) == 0 {
  195. return nil, newError("empty listname in rule: ", domain)
  196. }
  197. domains, err := loadGeosite(list)
  198. if err != nil {
  199. return nil, newError("failed to load geosite: ", list).Base(err)
  200. }
  201. return domains, nil
  202. }
  203. var isExtDatFile = 0
  204. {
  205. const prefix = "ext:"
  206. if strings.HasPrefix(domain, prefix) {
  207. isExtDatFile = len(prefix)
  208. }
  209. const prefixQualified = "ext-domain:"
  210. if strings.HasPrefix(domain, prefixQualified) {
  211. isExtDatFile = len(prefixQualified)
  212. }
  213. }
  214. if isExtDatFile != 0 {
  215. kv := strings.Split(domain[isExtDatFile:], ":")
  216. if len(kv) != 2 {
  217. return nil, newError("invalid external resource: ", domain)
  218. }
  219. filename := kv[0]
  220. list := kv[1]
  221. domains, err := loadGeositeWithAttr(filename, list)
  222. if err != nil {
  223. return nil, newError("failed to load external geosite: ", list, " from ", filename).Base(err)
  224. }
  225. return domains, nil
  226. }
  227. domainRule := new(router.Domain)
  228. switch {
  229. case strings.HasPrefix(domain, "regexp:"):
  230. regexpVal := domain[7:]
  231. if len(regexpVal) == 0 {
  232. return nil, newError("empty regexp type of rule: ", domain)
  233. }
  234. domainRule.Type = router.Domain_Regex
  235. domainRule.Value = regexpVal
  236. case strings.HasPrefix(domain, "domain:"):
  237. domainName := domain[7:]
  238. if len(domainName) == 0 {
  239. return nil, newError("empty domain type of rule: ", domain)
  240. }
  241. domainRule.Type = router.Domain_Domain
  242. domainRule.Value = domainName
  243. case strings.HasPrefix(domain, "full:"):
  244. fullVal := domain[5:]
  245. if len(fullVal) == 0 {
  246. return nil, newError("empty full domain type of rule: ", domain)
  247. }
  248. domainRule.Type = router.Domain_Full
  249. domainRule.Value = fullVal
  250. case strings.HasPrefix(domain, "keyword:"):
  251. keywordVal := domain[8:]
  252. if len(keywordVal) == 0 {
  253. return nil, newError("empty keyword type of rule: ", domain)
  254. }
  255. domainRule.Type = router.Domain_Plain
  256. domainRule.Value = keywordVal
  257. case strings.HasPrefix(domain, "dotless:"):
  258. domainRule.Type = router.Domain_Regex
  259. switch substr := domain[8:]; {
  260. case substr == "":
  261. domainRule.Value = "^[^.]*$"
  262. case !strings.Contains(substr, "."):
  263. domainRule.Value = "^[^.]*" + substr + "[^.]*$"
  264. default:
  265. return nil, newError("substr in dotless rule should not contain a dot: ", substr)
  266. }
  267. default:
  268. domainRule.Type = router.Domain_Plain
  269. domainRule.Value = domain
  270. }
  271. return []*router.Domain{domainRule}, nil
  272. }
  273. func toCidrList(ips StringList) ([]*router.GeoIP, error) {
  274. var geoipList []*router.GeoIP
  275. var customCidrs []*router.CIDR
  276. for _, ip := range ips {
  277. if strings.HasPrefix(ip, "geoip:") {
  278. country := ip[6:]
  279. isReverseMatch := false
  280. if strings.HasPrefix(ip, "geoip:!") {
  281. country = ip[7:]
  282. isReverseMatch = true
  283. }
  284. if len(country) == 0 {
  285. return nil, newError("empty country name in rule")
  286. }
  287. geoip, err := loadGeoIP(country)
  288. if err != nil {
  289. return nil, newError("failed to load geoip:", country).Base(err)
  290. }
  291. geoipList = append(geoipList, &router.GeoIP{
  292. CountryCode: strings.ToUpper(country),
  293. Cidr: geoip,
  294. ReverseMatch: isReverseMatch,
  295. })
  296. continue
  297. }
  298. var isExtDatFile = 0
  299. {
  300. const prefix = "ext:"
  301. if strings.HasPrefix(ip, prefix) {
  302. isExtDatFile = len(prefix)
  303. }
  304. const prefixQualified = "ext-ip:"
  305. if strings.HasPrefix(ip, prefixQualified) {
  306. isExtDatFile = len(prefixQualified)
  307. }
  308. }
  309. if isExtDatFile != 0 {
  310. kv := strings.Split(ip[isExtDatFile:], ":")
  311. if len(kv) != 2 {
  312. return nil, newError("invalid external resource: ", ip)
  313. }
  314. filename := kv[0]
  315. country := kv[1]
  316. if len(filename) == 0 || len(country) == 0 {
  317. return nil, newError("empty filename or empty country in rule")
  318. }
  319. isReverseMatch := false
  320. if strings.HasPrefix(country, "!") {
  321. country = country[1:]
  322. isReverseMatch = true
  323. }
  324. geoip, err := geodata.LoadIP(filename, country)
  325. if err != nil {
  326. return nil, newError("failed to load geoip:", country, " from ", filename).Base(err)
  327. }
  328. geoipList = append(geoipList, &router.GeoIP{
  329. CountryCode: strings.ToUpper(filename + "_" + country),
  330. Cidr: geoip,
  331. ReverseMatch: isReverseMatch,
  332. })
  333. continue
  334. }
  335. ipRule, err := ParseIP(ip)
  336. if err != nil {
  337. return nil, newError("invalid IP: ", ip).Base(err)
  338. }
  339. customCidrs = append(customCidrs, ipRule)
  340. }
  341. if len(customCidrs) > 0 {
  342. geoipList = append(geoipList, &router.GeoIP{
  343. Cidr: customCidrs,
  344. })
  345. }
  346. return geoipList, nil
  347. }
  348. func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
  349. type RawFieldRule struct {
  350. RouterRule
  351. Domain *StringList `json:"domain"`
  352. Domains *StringList `json:"domains"`
  353. IP *StringList `json:"ip"`
  354. Port *PortList `json:"port"`
  355. Network *NetworkList `json:"network"`
  356. SourceIP *StringList `json:"source"`
  357. SourcePort *PortList `json:"sourcePort"`
  358. User *StringList `json:"user"`
  359. InboundTag *StringList `json:"inboundTag"`
  360. Protocols *StringList `json:"protocol"`
  361. Attributes string `json:"attrs"`
  362. }
  363. rawFieldRule := new(RawFieldRule)
  364. err := json.Unmarshal(msg, rawFieldRule)
  365. if err != nil {
  366. return nil, err
  367. }
  368. rule := new(router.RoutingRule)
  369. switch {
  370. case len(rawFieldRule.OutboundTag) > 0:
  371. rule.TargetTag = &router.RoutingRule_Tag{
  372. Tag: rawFieldRule.OutboundTag,
  373. }
  374. case len(rawFieldRule.BalancerTag) > 0:
  375. rule.TargetTag = &router.RoutingRule_BalancingTag{
  376. BalancingTag: rawFieldRule.BalancerTag,
  377. }
  378. default:
  379. return nil, newError("neither outboundTag nor balancerTag is specified in routing rule")
  380. }
  381. if rawFieldRule.DomainMatcher != "" {
  382. rule.DomainMatcher = rawFieldRule.DomainMatcher
  383. }
  384. if rawFieldRule.Domain != nil {
  385. for _, domain := range *rawFieldRule.Domain {
  386. rules, err := parseDomainRule(domain)
  387. if err != nil {
  388. return nil, newError("failed to parse domain rule: ", domain).Base(err)
  389. }
  390. rule.Domain = append(rule.Domain, rules...)
  391. }
  392. }
  393. if rawFieldRule.Domains != nil {
  394. for _, domain := range *rawFieldRule.Domains {
  395. rules, err := parseDomainRule(domain)
  396. if err != nil {
  397. return nil, newError("failed to parse domain rule: ", domain).Base(err)
  398. }
  399. rule.Domain = append(rule.Domain, rules...)
  400. }
  401. }
  402. if rawFieldRule.IP != nil {
  403. geoipList, err := toCidrList(*rawFieldRule.IP)
  404. if err != nil {
  405. return nil, err
  406. }
  407. rule.Geoip = geoipList
  408. }
  409. if rawFieldRule.Port != nil {
  410. rule.PortList = rawFieldRule.Port.Build()
  411. }
  412. if rawFieldRule.Network != nil {
  413. rule.Networks = rawFieldRule.Network.Build()
  414. }
  415. if rawFieldRule.SourceIP != nil {
  416. geoipList, err := toCidrList(*rawFieldRule.SourceIP)
  417. if err != nil {
  418. return nil, err
  419. }
  420. rule.SourceGeoip = geoipList
  421. }
  422. if rawFieldRule.SourcePort != nil {
  423. rule.SourcePortList = rawFieldRule.SourcePort.Build()
  424. }
  425. if rawFieldRule.User != nil {
  426. for _, s := range *rawFieldRule.User {
  427. rule.UserEmail = append(rule.UserEmail, s)
  428. }
  429. }
  430. if rawFieldRule.InboundTag != nil {
  431. for _, s := range *rawFieldRule.InboundTag {
  432. rule.InboundTag = append(rule.InboundTag, s)
  433. }
  434. }
  435. if rawFieldRule.Protocols != nil {
  436. for _, s := range *rawFieldRule.Protocols {
  437. rule.Protocol = append(rule.Protocol, s)
  438. }
  439. }
  440. if len(rawFieldRule.Attributes) > 0 {
  441. rule.Attributes = rawFieldRule.Attributes
  442. }
  443. return rule, nil
  444. }
  445. func ParseRule(msg json.RawMessage) (*router.RoutingRule, error) {
  446. rawRule := new(RouterRule)
  447. err := json.Unmarshal(msg, rawRule)
  448. if err != nil {
  449. return nil, newError("invalid router rule").Base(err)
  450. }
  451. if strings.EqualFold(rawRule.Type, "field") {
  452. fieldrule, err := parseFieldRule(msg)
  453. if err != nil {
  454. return nil, newError("invalid field rule").Base(err)
  455. }
  456. return fieldrule, nil
  457. }
  458. return nil, newError("unknown router rule type: ", rawRule.Type)
  459. }