dns.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. DisableCache bool `json:"disableCache"`
  112. }
  113. func getHostMapping(addr *Address) *dns.Config_HostMapping {
  114. if addr.Family().IsIP() {
  115. return &dns.Config_HostMapping{
  116. Ip: [][]byte{[]byte(addr.IP())},
  117. }
  118. }
  119. return &dns.Config_HostMapping{
  120. ProxiedDomain: addr.Domain(),
  121. }
  122. }
  123. // Build implements Buildable
  124. func (c *DNSConfig) Build() (*dns.Config, error) {
  125. config := &dns.Config{
  126. Tag: c.Tag,
  127. DisableCache: c.DisableCache,
  128. }
  129. if c.ClientIP != nil {
  130. if !c.ClientIP.Family().IsIP() {
  131. return nil, newError("not an IP address:", c.ClientIP.String())
  132. }
  133. config.ClientIp = []byte(c.ClientIP.IP())
  134. }
  135. for _, server := range c.Servers {
  136. ns, err := server.Build()
  137. if err != nil {
  138. return nil, newError("failed to build nameserver").Base(err)
  139. }
  140. config.NameServer = append(config.NameServer, ns)
  141. }
  142. if BootstrapDNS() {
  143. newError("Bootstrap DNS: ", bootstrapDNS).AtWarning().WriteToLog()
  144. }
  145. if c.Hosts != nil && len(c.Hosts) > 0 {
  146. domains := make([]string, 0, len(c.Hosts))
  147. for domain := range c.Hosts {
  148. domains = append(domains, domain)
  149. }
  150. sort.Strings(domains)
  151. for _, domain := range domains {
  152. addr := c.Hosts[domain]
  153. var mappings []*dns.Config_HostMapping
  154. switch {
  155. case strings.HasPrefix(domain, "domain:"):
  156. domainName := domain[7:]
  157. if len(domainName) == 0 {
  158. return nil, newError("empty domain type of rule: ", domain)
  159. }
  160. mapping := getHostMapping(addr)
  161. mapping.Type = dns.DomainMatchingType_Subdomain
  162. mapping.Domain = domainName
  163. mappings = append(mappings, mapping)
  164. case strings.HasPrefix(domain, "geosite:"):
  165. listName := domain[8:]
  166. if len(listName) == 0 {
  167. return nil, newError("empty geosite rule: ", domain)
  168. }
  169. domains, err := loadGeositeWithAttr("geosite.dat", listName)
  170. if err != nil {
  171. return nil, newError("failed to load geosite: ", listName).Base(err)
  172. }
  173. for _, d := range domains {
  174. mapping := getHostMapping(addr)
  175. mapping.Type = typeMap[d.Type]
  176. mapping.Domain = d.Value
  177. mappings = append(mappings, mapping)
  178. }
  179. case strings.HasPrefix(domain, "regexp:"):
  180. regexpVal := domain[7:]
  181. if len(regexpVal) == 0 {
  182. return nil, newError("empty regexp type of rule: ", domain)
  183. }
  184. mapping := getHostMapping(addr)
  185. mapping.Type = dns.DomainMatchingType_Regex
  186. mapping.Domain = regexpVal
  187. mappings = append(mappings, mapping)
  188. case strings.HasPrefix(domain, "keyword:"):
  189. keywordVal := domain[8:]
  190. if len(keywordVal) == 0 {
  191. return nil, newError("empty keyword type of rule: ", domain)
  192. }
  193. mapping := getHostMapping(addr)
  194. mapping.Type = dns.DomainMatchingType_Keyword
  195. mapping.Domain = keywordVal
  196. mappings = append(mappings, mapping)
  197. case strings.HasPrefix(domain, "full:"):
  198. fullVal := domain[5:]
  199. if len(fullVal) == 0 {
  200. return nil, newError("empty full domain type of rule: ", domain)
  201. }
  202. mapping := getHostMapping(addr)
  203. mapping.Type = dns.DomainMatchingType_Full
  204. mapping.Domain = fullVal
  205. mappings = append(mappings, mapping)
  206. case strings.HasPrefix(domain, "dotless:"):
  207. mapping := getHostMapping(addr)
  208. mapping.Type = dns.DomainMatchingType_Regex
  209. switch substr := domain[8:]; {
  210. case substr == "":
  211. mapping.Domain = "^[^.]*$"
  212. case !strings.Contains(substr, "."):
  213. mapping.Domain = "^[^.]*" + substr + "[^.]*$"
  214. default:
  215. return nil, newError("substr in dotless rule should not contain a dot: ", substr)
  216. }
  217. mappings = append(mappings, mapping)
  218. case strings.HasPrefix(domain, "ext:"):
  219. kv := strings.Split(domain[4:], ":")
  220. if len(kv) != 2 {
  221. return nil, newError("invalid external resource: ", domain)
  222. }
  223. filename := kv[0]
  224. list := kv[1]
  225. domains, err := loadGeositeWithAttr(filename, list)
  226. if err != nil {
  227. return nil, newError("failed to load domain list: ", list, " from ", filename).Base(err)
  228. }
  229. for _, d := range domains {
  230. mapping := getHostMapping(addr)
  231. mapping.Type = typeMap[d.Type]
  232. mapping.Domain = d.Value
  233. mappings = append(mappings, mapping)
  234. }
  235. default:
  236. mapping := getHostMapping(addr)
  237. mapping.Type = dns.DomainMatchingType_Full
  238. mapping.Domain = domain
  239. mappings = append(mappings, mapping)
  240. }
  241. config.StaticHosts = append(config.StaticHosts, mappings...)
  242. }
  243. }
  244. return config, nil
  245. }