dns.go 10.0 KB

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