dns.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package conf
  2. import (
  3. "context"
  4. "encoding/json"
  5. "sort"
  6. "strings"
  7. "github.com/v2fly/v2ray-core/v4/infra/conf/cfgcommon"
  8. "github.com/v2fly/v2ray-core/v4/infra/conf/geodata"
  9. rule2 "github.com/v2fly/v2ray-core/v4/infra/conf/rule"
  10. "github.com/v2fly/v2ray-core/v4/app/dns"
  11. "github.com/v2fly/v2ray-core/v4/app/router"
  12. "github.com/v2fly/v2ray-core/v4/common/net"
  13. )
  14. type NameServerConfig struct {
  15. Address *cfgcommon.Address
  16. ClientIP *cfgcommon.Address
  17. Port uint16
  18. SkipFallback bool
  19. Domains []string
  20. ExpectIPs cfgcommon.StringList
  21. cfgctx context.Context
  22. }
  23. func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
  24. var address cfgcommon.Address
  25. if err := json.Unmarshal(data, &address); err == nil {
  26. c.Address = &address
  27. return nil
  28. }
  29. var advanced struct {
  30. Address *cfgcommon.Address `json:"address"`
  31. ClientIP *cfgcommon.Address `json:"clientIp"`
  32. Port uint16 `json:"port"`
  33. SkipFallback bool `json:"skipFallback"`
  34. Domains []string `json:"domains"`
  35. ExpectIPs cfgcommon.StringList `json:"expectIps"`
  36. }
  37. if err := json.Unmarshal(data, &advanced); err == nil {
  38. c.Address = advanced.Address
  39. c.ClientIP = advanced.ClientIP
  40. c.Port = advanced.Port
  41. c.SkipFallback = advanced.SkipFallback
  42. c.Domains = advanced.Domains
  43. c.ExpectIPs = advanced.ExpectIPs
  44. return nil
  45. }
  46. return newError("failed to parse name server: ", string(data))
  47. }
  48. func toDomainMatchingType(t router.Domain_Type) dns.DomainMatchingType {
  49. switch t {
  50. case router.Domain_Domain:
  51. return dns.DomainMatchingType_Subdomain
  52. case router.Domain_Full:
  53. return dns.DomainMatchingType_Full
  54. case router.Domain_Plain:
  55. return dns.DomainMatchingType_Keyword
  56. case router.Domain_Regex:
  57. return dns.DomainMatchingType_Regex
  58. default:
  59. panic("unknown domain type")
  60. }
  61. }
  62. func (c *NameServerConfig) Build() (*dns.NameServer, error) {
  63. cfgctx := c.cfgctx
  64. if c.Address == nil {
  65. return nil, newError("NameServer address is not specified.")
  66. }
  67. var domains []*dns.NameServer_PriorityDomain
  68. var originalRules []*dns.NameServer_OriginalRule
  69. for _, rule := range c.Domains {
  70. parsedDomain, err := rule2.ParseDomainRule(cfgctx, rule)
  71. if err != nil {
  72. return nil, newError("invalid domain rule: ", rule).Base(err)
  73. }
  74. for _, pd := range parsedDomain {
  75. domains = append(domains, &dns.NameServer_PriorityDomain{
  76. Type: toDomainMatchingType(pd.Type),
  77. Domain: pd.Value,
  78. })
  79. }
  80. originalRules = append(originalRules, &dns.NameServer_OriginalRule{
  81. Rule: rule,
  82. Size: uint32(len(parsedDomain)),
  83. })
  84. }
  85. geoipList, err := rule2.ToCidrList(cfgctx, c.ExpectIPs)
  86. if err != nil {
  87. return nil, newError("invalid IP rule: ", c.ExpectIPs).Base(err)
  88. }
  89. var myClientIP []byte
  90. if c.ClientIP != nil {
  91. if !c.ClientIP.Family().IsIP() {
  92. return nil, newError("not an IP address:", c.ClientIP.String())
  93. }
  94. myClientIP = []byte(c.ClientIP.IP())
  95. }
  96. return &dns.NameServer{
  97. Address: &net.Endpoint{
  98. Network: net.Network_UDP,
  99. Address: c.Address.Build(),
  100. Port: uint32(c.Port),
  101. },
  102. ClientIp: myClientIP,
  103. SkipFallback: c.SkipFallback,
  104. PrioritizedDomain: domains,
  105. Geoip: geoipList,
  106. OriginalRules: originalRules,
  107. }, nil
  108. }
  109. var typeMap = map[router.Domain_Type]dns.DomainMatchingType{
  110. router.Domain_Full: dns.DomainMatchingType_Full,
  111. router.Domain_Domain: dns.DomainMatchingType_Subdomain,
  112. router.Domain_Plain: dns.DomainMatchingType_Keyword,
  113. router.Domain_Regex: dns.DomainMatchingType_Regex,
  114. }
  115. // DNSConfig is a JSON serializable object for dns.Config.
  116. type DNSConfig struct {
  117. Servers []*NameServerConfig `json:"servers"`
  118. Hosts map[string]*HostAddress `json:"hosts"`
  119. ClientIP *cfgcommon.Address `json:"clientIp"`
  120. Tag string `json:"tag"`
  121. QueryStrategy string `json:"queryStrategy"`
  122. DisableCache bool `json:"disableCache"`
  123. DisableFallback bool `json:"disableFallback"`
  124. GeoLoader string `json:"geoLoader"`
  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. if c.GeoLoader == "" {
  172. c.GeoLoader = "standard"
  173. }
  174. if loader, err := geodata.GetGeoDataLoader(c.GeoLoader); 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. }