dns.go 9.7 KB

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