dns.go 7.9 KB

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