dns.go 10 KB

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