dns.go 8.2 KB

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