dns.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 *HostsWrapper `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. type HostAddress struct {
  120. addr *Address
  121. addrs []*Address
  122. }
  123. // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
  124. func (h *HostAddress) UnmarshalJSON(data []byte) error {
  125. addr := new(Address)
  126. var addrs []*Address
  127. switch {
  128. case json.Unmarshal(data, &addr) == nil:
  129. h.addr = addr
  130. case json.Unmarshal(data, &addrs) == nil:
  131. h.addrs = addrs
  132. default:
  133. return newError("invalid address")
  134. }
  135. return nil
  136. }
  137. type HostsWrapper struct {
  138. Hosts map[string]*HostAddress
  139. }
  140. func getHostMapping(ha *HostAddress) *dns.Config_HostMapping {
  141. if ha.addr != nil {
  142. if ha.addr.Family().IsDomain() {
  143. return &dns.Config_HostMapping{
  144. ProxiedDomain: ha.addr.Domain(),
  145. }
  146. }
  147. return &dns.Config_HostMapping{
  148. Ip: [][]byte{ha.addr.IP()},
  149. }
  150. }
  151. ips := make([][]byte, 0, len(ha.addrs))
  152. for _, addr := range ha.addrs {
  153. if addr.Family().IsDomain() {
  154. return &dns.Config_HostMapping{
  155. ProxiedDomain: addr.Domain(),
  156. }
  157. }
  158. ips = append(ips, []byte(addr.IP()))
  159. }
  160. return &dns.Config_HostMapping{
  161. Ip: ips,
  162. }
  163. }
  164. // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
  165. func (m *HostsWrapper) UnmarshalJSON(data []byte) error {
  166. hosts := make(map[string]*HostAddress)
  167. err := json.Unmarshal(data, &hosts)
  168. if err == nil {
  169. m.Hosts = hosts
  170. return nil
  171. }
  172. return newError("invalid DNS hosts").Base(err)
  173. }
  174. // Build implements Buildable
  175. func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
  176. mappings := make([]*dns.Config_HostMapping, 0, 20)
  177. domains := make([]string, 0, len(m.Hosts))
  178. for domain := range m.Hosts {
  179. domains = append(domains, domain)
  180. }
  181. sort.Strings(domains)
  182. for _, domain := range domains {
  183. switch {
  184. case strings.HasPrefix(domain, "domain:"):
  185. domainName := domain[7:]
  186. if len(domainName) == 0 {
  187. return nil, newError("empty domain type of rule: ", domain)
  188. }
  189. mapping := getHostMapping(m.Hosts[domain])
  190. mapping.Type = dns.DomainMatchingType_Subdomain
  191. mapping.Domain = domainName
  192. mappings = append(mappings, mapping)
  193. case strings.HasPrefix(domain, "geosite:"):
  194. listName := domain[8:]
  195. if len(listName) == 0 {
  196. return nil, newError("empty geosite rule: ", domain)
  197. }
  198. geositeList, err := loadGeosite(listName)
  199. if err != nil {
  200. return nil, newError("failed to load geosite: ", listName).Base(err)
  201. }
  202. for _, d := range geositeList {
  203. mapping := getHostMapping(m.Hosts[domain])
  204. mapping.Type = typeMap[d.Type]
  205. mapping.Domain = d.Value
  206. mappings = append(mappings, mapping)
  207. }
  208. case strings.HasPrefix(domain, "regexp:"):
  209. regexpVal := domain[7:]
  210. if len(regexpVal) == 0 {
  211. return nil, newError("empty regexp type of rule: ", domain)
  212. }
  213. mapping := getHostMapping(m.Hosts[domain])
  214. mapping.Type = dns.DomainMatchingType_Regex
  215. mapping.Domain = regexpVal
  216. mappings = append(mappings, mapping)
  217. case strings.HasPrefix(domain, "keyword:"):
  218. keywordVal := domain[8:]
  219. if len(keywordVal) == 0 {
  220. return nil, newError("empty keyword type of rule: ", domain)
  221. }
  222. mapping := getHostMapping(m.Hosts[domain])
  223. mapping.Type = dns.DomainMatchingType_Keyword
  224. mapping.Domain = keywordVal
  225. mappings = append(mappings, mapping)
  226. case strings.HasPrefix(domain, "full:"):
  227. fullVal := domain[5:]
  228. if len(fullVal) == 0 {
  229. return nil, newError("empty full domain type of rule: ", domain)
  230. }
  231. mapping := getHostMapping(m.Hosts[domain])
  232. mapping.Type = dns.DomainMatchingType_Full
  233. mapping.Domain = fullVal
  234. mappings = append(mappings, mapping)
  235. case strings.HasPrefix(domain, "dotless:"):
  236. mapping := getHostMapping(m.Hosts[domain])
  237. mapping.Type = dns.DomainMatchingType_Regex
  238. switch substr := domain[8:]; {
  239. case substr == "":
  240. mapping.Domain = "^[^.]*$"
  241. case !strings.Contains(substr, "."):
  242. mapping.Domain = "^[^.]*" + substr + "[^.]*$"
  243. default:
  244. return nil, newError("substr in dotless rule should not contain a dot: ", substr)
  245. }
  246. mappings = append(mappings, mapping)
  247. case strings.HasPrefix(domain, "ext:"):
  248. kv := strings.Split(domain[4:], ":")
  249. if len(kv) != 2 {
  250. return nil, newError("invalid external resource: ", domain)
  251. }
  252. filename := kv[0]
  253. list := kv[1]
  254. geositeList, err := loadGeositeWithAttr(filename, list)
  255. if err != nil {
  256. return nil, newError("failed to load domain list: ", list, " from ", filename).Base(err)
  257. }
  258. for _, d := range geositeList {
  259. mapping := getHostMapping(m.Hosts[domain])
  260. mapping.Type = typeMap[d.Type]
  261. mapping.Domain = d.Value
  262. mappings = append(mappings, mapping)
  263. }
  264. default:
  265. mapping := getHostMapping(m.Hosts[domain])
  266. mapping.Type = dns.DomainMatchingType_Full
  267. mapping.Domain = domain
  268. mappings = append(mappings, mapping)
  269. }
  270. }
  271. return mappings, nil
  272. }
  273. // Build implements Buildable
  274. func (c *DNSConfig) Build() (*dns.Config, error) {
  275. config := &dns.Config{
  276. Tag: c.Tag,
  277. DisableCache: c.DisableCache,
  278. DisableFallback: c.DisableFallback,
  279. }
  280. if c.ClientIP != nil {
  281. if !c.ClientIP.Family().IsIP() {
  282. return nil, newError("not an IP address:", c.ClientIP.String())
  283. }
  284. config.ClientIp = []byte(c.ClientIP.IP())
  285. }
  286. config.QueryStrategy = dns.QueryStrategy_USE_IP
  287. switch strings.ToLower(c.QueryStrategy) {
  288. case "useip", "use_ip", "use-ip":
  289. config.QueryStrategy = dns.QueryStrategy_USE_IP
  290. case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4":
  291. config.QueryStrategy = dns.QueryStrategy_USE_IP4
  292. case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6":
  293. config.QueryStrategy = dns.QueryStrategy_USE_IP6
  294. }
  295. for _, server := range c.Servers {
  296. ns, err := server.Build()
  297. if err != nil {
  298. return nil, newError("failed to build nameserver").Base(err)
  299. }
  300. config.NameServer = append(config.NameServer, ns)
  301. }
  302. if c.Hosts != nil {
  303. staticHosts, err := c.Hosts.Build()
  304. if err != nil {
  305. return nil, newError("failed to build hosts").Base(err)
  306. }
  307. config.StaticHosts = append(config.StaticHosts, staticHosts...)
  308. }
  309. return config, nil
  310. }