dns.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package conf
  2. import (
  3. "context"
  4. "encoding/json"
  5. "sort"
  6. "strings"
  7. "github.com/v2fly/v2ray-core/v4/app/dns"
  8. "github.com/v2fly/v2ray-core/v4/app/router"
  9. "github.com/v2fly/v2ray-core/v4/common/net"
  10. "github.com/v2fly/v2ray-core/v4/common/platform"
  11. "github.com/v2fly/v2ray-core/v4/infra/conf/cfgcommon"
  12. "github.com/v2fly/v2ray-core/v4/infra/conf/geodata"
  13. rule2 "github.com/v2fly/v2ray-core/v4/infra/conf/rule"
  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. DisableFallbackIfMatch bool `json:"disableFallbackIfMatch"`
  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. DisableFallbackIfMatch: c.DisableFallbackIfMatch,
  187. }
  188. if c.ClientIP != nil {
  189. if !c.ClientIP.Family().IsIP() {
  190. return nil, newError("not an IP address:", c.ClientIP.String())
  191. }
  192. config.ClientIp = []byte(c.ClientIP.IP())
  193. }
  194. config.QueryStrategy = dns.QueryStrategy_USE_IP
  195. switch strings.ToLower(c.QueryStrategy) {
  196. case "useip", "use_ip", "use-ip":
  197. config.QueryStrategy = dns.QueryStrategy_USE_IP
  198. case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4":
  199. config.QueryStrategy = dns.QueryStrategy_USE_IP4
  200. case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6":
  201. config.QueryStrategy = dns.QueryStrategy_USE_IP6
  202. }
  203. for _, server := range c.Servers {
  204. server.cfgctx = cfgctx
  205. ns, err := server.Build()
  206. if err != nil {
  207. return nil, newError("failed to build nameserver").Base(err)
  208. }
  209. config.NameServer = append(config.NameServer, ns)
  210. }
  211. if c.Hosts != nil {
  212. mappings := make([]*dns.Config_HostMapping, 0, 20)
  213. domains := make([]string, 0, len(c.Hosts))
  214. for domain := range c.Hosts {
  215. domains = append(domains, domain)
  216. }
  217. sort.Strings(domains)
  218. for _, domain := range domains {
  219. switch {
  220. case strings.HasPrefix(domain, "domain:"):
  221. domainName := domain[7:]
  222. if len(domainName) == 0 {
  223. return nil, newError("empty domain type of rule: ", domain)
  224. }
  225. mapping := getHostMapping(c.Hosts[domain])
  226. mapping.Type = dns.DomainMatchingType_Subdomain
  227. mapping.Domain = domainName
  228. mappings = append(mappings, mapping)
  229. case strings.HasPrefix(domain, "geosite:"):
  230. listName := domain[8:]
  231. if len(listName) == 0 {
  232. return nil, newError("empty geosite rule: ", domain)
  233. }
  234. geositeList, err := geoLoader.LoadGeoSite(listName)
  235. if err != nil {
  236. return nil, newError("failed to load geosite: ", listName).Base(err)
  237. }
  238. for _, d := range geositeList {
  239. mapping := getHostMapping(c.Hosts[domain])
  240. mapping.Type = typeMap[d.Type]
  241. mapping.Domain = d.Value
  242. mappings = append(mappings, mapping)
  243. }
  244. case strings.HasPrefix(domain, "regexp:"):
  245. regexpVal := domain[7:]
  246. if len(regexpVal) == 0 {
  247. return nil, newError("empty regexp type of rule: ", domain)
  248. }
  249. mapping := getHostMapping(c.Hosts[domain])
  250. mapping.Type = dns.DomainMatchingType_Regex
  251. mapping.Domain = regexpVal
  252. mappings = append(mappings, mapping)
  253. case strings.HasPrefix(domain, "keyword:"):
  254. keywordVal := domain[8:]
  255. if len(keywordVal) == 0 {
  256. return nil, newError("empty keyword type of rule: ", domain)
  257. }
  258. mapping := getHostMapping(c.Hosts[domain])
  259. mapping.Type = dns.DomainMatchingType_Keyword
  260. mapping.Domain = keywordVal
  261. mappings = append(mappings, mapping)
  262. case strings.HasPrefix(domain, "full:"):
  263. fullVal := domain[5:]
  264. if len(fullVal) == 0 {
  265. return nil, newError("empty full domain type of rule: ", domain)
  266. }
  267. mapping := getHostMapping(c.Hosts[domain])
  268. mapping.Type = dns.DomainMatchingType_Full
  269. mapping.Domain = fullVal
  270. mappings = append(mappings, mapping)
  271. case strings.HasPrefix(domain, "dotless:"):
  272. mapping := getHostMapping(c.Hosts[domain])
  273. mapping.Type = dns.DomainMatchingType_Regex
  274. switch substr := domain[8:]; {
  275. case substr == "":
  276. mapping.Domain = "^[^.]*$"
  277. case !strings.Contains(substr, "."):
  278. mapping.Domain = "^[^.]*" + substr + "[^.]*$"
  279. default:
  280. return nil, newError("substr in dotless rule should not contain a dot: ", substr)
  281. }
  282. mappings = append(mappings, mapping)
  283. case strings.HasPrefix(domain, "ext:"):
  284. kv := strings.Split(domain[4:], ":")
  285. if len(kv) != 2 {
  286. return nil, newError("invalid external resource: ", domain)
  287. }
  288. filename := kv[0]
  289. list := kv[1]
  290. geositeList, err := geoLoader.LoadGeoSiteWithAttr(filename, list)
  291. if err != nil {
  292. return nil, newError("failed to load domain list: ", list, " from ", filename).Base(err)
  293. }
  294. for _, d := range geositeList {
  295. mapping := getHostMapping(c.Hosts[domain])
  296. mapping.Type = typeMap[d.Type]
  297. mapping.Domain = d.Value
  298. mappings = append(mappings, mapping)
  299. }
  300. default:
  301. mapping := getHostMapping(c.Hosts[domain])
  302. mapping.Type = dns.DomainMatchingType_Full
  303. mapping.Domain = domain
  304. mappings = append(mappings, mapping)
  305. }
  306. }
  307. config.StaticHosts = append(config.StaticHosts, mappings...)
  308. }
  309. return config, nil
  310. }