dns.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package dns
  2. //go:generate go run github.com/v2fly/v2ray-core/v4/common/errors/errorgen
  3. import (
  4. "context"
  5. "encoding/json"
  6. "github.com/v2fly/v2ray-core/v4/app/router/routercommon"
  7. "sort"
  8. "strings"
  9. "github.com/v2fly/v2ray-core/v4/app/dns"
  10. "github.com/v2fly/v2ray-core/v4/common/net"
  11. "github.com/v2fly/v2ray-core/v4/common/platform"
  12. "github.com/v2fly/v2ray-core/v4/infra/conf/cfgcommon"
  13. "github.com/v2fly/v2ray-core/v4/infra/conf/geodata"
  14. rule2 "github.com/v2fly/v2ray-core/v4/infra/conf/rule"
  15. )
  16. type NameServerConfig struct {
  17. Address *cfgcommon.Address
  18. ClientIP *cfgcommon.Address
  19. Port uint16
  20. SkipFallback bool
  21. Domains []string
  22. ExpectIPs cfgcommon.StringList
  23. cfgctx context.Context
  24. }
  25. func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
  26. var address cfgcommon.Address
  27. if err := json.Unmarshal(data, &address); err == nil {
  28. c.Address = &address
  29. return nil
  30. }
  31. var advanced struct {
  32. Address *cfgcommon.Address `json:"address"`
  33. ClientIP *cfgcommon.Address `json:"clientIp"`
  34. Port uint16 `json:"port"`
  35. SkipFallback bool `json:"skipFallback"`
  36. Domains []string `json:"domains"`
  37. ExpectIPs cfgcommon.StringList `json:"expectIps"`
  38. }
  39. if err := json.Unmarshal(data, &advanced); err == nil {
  40. c.Address = advanced.Address
  41. c.ClientIP = advanced.ClientIP
  42. c.Port = advanced.Port
  43. c.SkipFallback = advanced.SkipFallback
  44. c.Domains = advanced.Domains
  45. c.ExpectIPs = advanced.ExpectIPs
  46. return nil
  47. }
  48. return newError("failed to parse name server: ", string(data))
  49. }
  50. func toDomainMatchingType(t routercommon.Domain_Type) dns.DomainMatchingType {
  51. switch t {
  52. case routercommon.Domain_RootDomain:
  53. return dns.DomainMatchingType_Subdomain
  54. case routercommon.Domain_Full:
  55. return dns.DomainMatchingType_Full
  56. case routercommon.Domain_Plain:
  57. return dns.DomainMatchingType_Keyword
  58. case routercommon.Domain_Regex:
  59. return dns.DomainMatchingType_Regex
  60. default:
  61. panic("unknown domain type")
  62. }
  63. }
  64. func (c *NameServerConfig) BuildV5(ctx context.Context) (*dns.NameServer, error) {
  65. c.cfgctx = ctx
  66. return c.Build()
  67. }
  68. func (c *NameServerConfig) Build() (*dns.NameServer, error) {
  69. cfgctx := c.cfgctx
  70. if c.Address == nil {
  71. return nil, newError("NameServer address is not specified.")
  72. }
  73. var domains []*dns.NameServer_PriorityDomain
  74. var originalRules []*dns.NameServer_OriginalRule
  75. for _, rule := range c.Domains {
  76. parsedDomain, err := rule2.ParseDomainRule(cfgctx, rule)
  77. if err != nil {
  78. return nil, newError("invalid domain rule: ", rule).Base(err)
  79. }
  80. for _, pd := range parsedDomain {
  81. domains = append(domains, &dns.NameServer_PriorityDomain{
  82. Type: toDomainMatchingType(pd.Type),
  83. Domain: pd.Value,
  84. })
  85. }
  86. originalRules = append(originalRules, &dns.NameServer_OriginalRule{
  87. Rule: rule,
  88. Size: uint32(len(parsedDomain)),
  89. })
  90. }
  91. geoipList, err := rule2.ToCidrList(cfgctx, c.ExpectIPs)
  92. if err != nil {
  93. return nil, newError("invalid IP rule: ", c.ExpectIPs).Base(err)
  94. }
  95. var myClientIP []byte
  96. if c.ClientIP != nil {
  97. if !c.ClientIP.Family().IsIP() {
  98. return nil, newError("not an IP address:", c.ClientIP.String())
  99. }
  100. myClientIP = []byte(c.ClientIP.IP())
  101. }
  102. return &dns.NameServer{
  103. Address: &net.Endpoint{
  104. Network: net.Network_UDP,
  105. Address: c.Address.Build(),
  106. Port: uint32(c.Port),
  107. },
  108. ClientIp: myClientIP,
  109. SkipFallback: c.SkipFallback,
  110. PrioritizedDomain: domains,
  111. Geoip: geoipList,
  112. OriginalRules: originalRules,
  113. }, nil
  114. }
  115. var typeMap = map[routercommon.Domain_Type]dns.DomainMatchingType{
  116. routercommon.Domain_Full: dns.DomainMatchingType_Full,
  117. routercommon.Domain_RootDomain: dns.DomainMatchingType_Subdomain,
  118. routercommon.Domain_Plain: dns.DomainMatchingType_Keyword,
  119. routercommon.Domain_Regex: dns.DomainMatchingType_Regex,
  120. }
  121. // DNSConfig is a JSON serializable object for dns.Config.
  122. type DNSConfig struct {
  123. Servers []*NameServerConfig `json:"servers"`
  124. Hosts map[string]*HostAddress `json:"hosts"`
  125. ClientIP *cfgcommon.Address `json:"clientIp"`
  126. Tag string `json:"tag"`
  127. QueryStrategy string `json:"queryStrategy"`
  128. DisableCache bool `json:"disableCache"`
  129. DisableFallback bool `json:"disableFallback"`
  130. DisableFallbackIfMatch bool `json:"disableFallbackIfMatch"`
  131. cfgctx context.Context
  132. }
  133. type HostAddress struct {
  134. addr *cfgcommon.Address
  135. addrs []*cfgcommon.Address
  136. }
  137. // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
  138. func (h *HostAddress) UnmarshalJSON(data []byte) error {
  139. addr := new(cfgcommon.Address)
  140. var addrs []*cfgcommon.Address
  141. switch {
  142. case json.Unmarshal(data, &addr) == nil:
  143. h.addr = addr
  144. case json.Unmarshal(data, &addrs) == nil:
  145. h.addrs = addrs
  146. default:
  147. return newError("invalid address")
  148. }
  149. return nil
  150. }
  151. func getHostMapping(ha *HostAddress) *dns.HostMapping {
  152. if ha.addr != nil {
  153. if ha.addr.Family().IsDomain() {
  154. return &dns.HostMapping{
  155. ProxiedDomain: ha.addr.Domain(),
  156. }
  157. }
  158. return &dns.HostMapping{
  159. Ip: [][]byte{ha.addr.IP()},
  160. }
  161. }
  162. ips := make([][]byte, 0, len(ha.addrs))
  163. for _, addr := range ha.addrs {
  164. if addr.Family().IsDomain() {
  165. return &dns.HostMapping{
  166. ProxiedDomain: addr.Domain(),
  167. }
  168. }
  169. ips = append(ips, []byte(addr.IP()))
  170. }
  171. return &dns.HostMapping{
  172. Ip: ips,
  173. }
  174. }
  175. func (c *DNSConfig) BuildV5(ctx context.Context) (*dns.Config, error) {
  176. c.cfgctx = ctx
  177. return c.Build()
  178. }
  179. // Build implements Buildable
  180. func (c *DNSConfig) Build() (*dns.Config, error) {
  181. if c.cfgctx == nil {
  182. c.cfgctx = cfgcommon.NewConfigureLoadingContext(context.Background())
  183. geoloadername := platform.NewEnvFlag("v2ray.conf.geoloader").GetValue(func() string {
  184. return "standard"
  185. })
  186. if loader, err := geodata.GetGeoDataLoader(geoloadername); err == nil {
  187. cfgcommon.SetGeoDataLoader(c.cfgctx, loader)
  188. } else {
  189. return nil, newError("unable to create geo data loader ").Base(err)
  190. }
  191. }
  192. cfgEnv := cfgcommon.GetConfigureLoadingEnvironment(c.cfgctx)
  193. geoLoader := cfgEnv.GetGeoLoader()
  194. config := &dns.Config{
  195. Tag: c.Tag,
  196. DisableCache: c.DisableCache,
  197. DisableFallback: c.DisableFallback,
  198. DisableFallbackIfMatch: c.DisableFallbackIfMatch,
  199. }
  200. if c.ClientIP != nil {
  201. if !c.ClientIP.Family().IsIP() {
  202. return nil, newError("not an IP address:", c.ClientIP.String())
  203. }
  204. config.ClientIp = []byte(c.ClientIP.IP())
  205. }
  206. config.QueryStrategy = dns.QueryStrategy_USE_IP
  207. switch strings.ToLower(c.QueryStrategy) {
  208. case "useip", "use_ip", "use-ip":
  209. config.QueryStrategy = dns.QueryStrategy_USE_IP
  210. case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4":
  211. config.QueryStrategy = dns.QueryStrategy_USE_IP4
  212. case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6":
  213. config.QueryStrategy = dns.QueryStrategy_USE_IP6
  214. }
  215. for _, server := range c.Servers {
  216. server.cfgctx = c.cfgctx
  217. ns, err := server.Build()
  218. if err != nil {
  219. return nil, newError("failed to build nameserver").Base(err)
  220. }
  221. config.NameServer = append(config.NameServer, ns)
  222. }
  223. if c.Hosts != nil {
  224. mappings := make([]*dns.HostMapping, 0, 20)
  225. domains := make([]string, 0, len(c.Hosts))
  226. for domain := range c.Hosts {
  227. domains = append(domains, domain)
  228. }
  229. sort.Strings(domains)
  230. for _, domain := range domains {
  231. switch {
  232. case strings.HasPrefix(domain, "domain:"):
  233. domainName := domain[7:]
  234. if len(domainName) == 0 {
  235. return nil, newError("empty domain type of rule: ", domain)
  236. }
  237. mapping := getHostMapping(c.Hosts[domain])
  238. mapping.Type = dns.DomainMatchingType_Subdomain
  239. mapping.Domain = domainName
  240. mappings = append(mappings, mapping)
  241. case strings.HasPrefix(domain, "geosite:"):
  242. listName := domain[8:]
  243. if len(listName) == 0 {
  244. return nil, newError("empty geosite rule: ", domain)
  245. }
  246. geositeList, err := geoLoader.LoadGeoSite(listName)
  247. if err != nil {
  248. return nil, newError("failed to load geosite: ", listName).Base(err)
  249. }
  250. for _, d := range geositeList {
  251. mapping := getHostMapping(c.Hosts[domain])
  252. mapping.Type = typeMap[d.Type]
  253. mapping.Domain = d.Value
  254. mappings = append(mappings, mapping)
  255. }
  256. case strings.HasPrefix(domain, "regexp:"):
  257. regexpVal := domain[7:]
  258. if len(regexpVal) == 0 {
  259. return nil, newError("empty regexp type of rule: ", domain)
  260. }
  261. mapping := getHostMapping(c.Hosts[domain])
  262. mapping.Type = dns.DomainMatchingType_Regex
  263. mapping.Domain = regexpVal
  264. mappings = append(mappings, mapping)
  265. case strings.HasPrefix(domain, "keyword:"):
  266. keywordVal := domain[8:]
  267. if len(keywordVal) == 0 {
  268. return nil, newError("empty keyword type of rule: ", domain)
  269. }
  270. mapping := getHostMapping(c.Hosts[domain])
  271. mapping.Type = dns.DomainMatchingType_Keyword
  272. mapping.Domain = keywordVal
  273. mappings = append(mappings, mapping)
  274. case strings.HasPrefix(domain, "full:"):
  275. fullVal := domain[5:]
  276. if len(fullVal) == 0 {
  277. return nil, newError("empty full domain type of rule: ", domain)
  278. }
  279. mapping := getHostMapping(c.Hosts[domain])
  280. mapping.Type = dns.DomainMatchingType_Full
  281. mapping.Domain = fullVal
  282. mappings = append(mappings, mapping)
  283. case strings.HasPrefix(domain, "dotless:"):
  284. mapping := getHostMapping(c.Hosts[domain])
  285. mapping.Type = dns.DomainMatchingType_Regex
  286. switch substr := domain[8:]; {
  287. case substr == "":
  288. mapping.Domain = "^[^.]*$"
  289. case !strings.Contains(substr, "."):
  290. mapping.Domain = "^[^.]*" + substr + "[^.]*$"
  291. default:
  292. return nil, newError("substr in dotless rule should not contain a dot: ", substr)
  293. }
  294. mappings = append(mappings, mapping)
  295. case strings.HasPrefix(domain, "ext:"):
  296. kv := strings.Split(domain[4:], ":")
  297. if len(kv) != 2 {
  298. return nil, newError("invalid external resource: ", domain)
  299. }
  300. filename := kv[0]
  301. list := kv[1]
  302. geositeList, err := geoLoader.LoadGeoSiteWithAttr(filename, list)
  303. if err != nil {
  304. return nil, newError("failed to load domain list: ", list, " from ", filename).Base(err)
  305. }
  306. for _, d := range geositeList {
  307. mapping := getHostMapping(c.Hosts[domain])
  308. mapping.Type = typeMap[d.Type]
  309. mapping.Domain = d.Value
  310. mappings = append(mappings, mapping)
  311. }
  312. default:
  313. mapping := getHostMapping(c.Hosts[domain])
  314. mapping.Type = dns.DomainMatchingType_Full
  315. mapping.Domain = domain
  316. mappings = append(mappings, mapping)
  317. }
  318. }
  319. config.StaticHosts = append(config.StaticHosts, mappings...)
  320. }
  321. return config, nil
  322. }