dns.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package conf
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "os"
  6. "path/filepath"
  7. "runtime"
  8. "sort"
  9. "strings"
  10. "github.com/xtls/xray-core/app/dns"
  11. "github.com/xtls/xray-core/app/router"
  12. "github.com/xtls/xray-core/common/errors"
  13. "github.com/xtls/xray-core/common/net"
  14. )
  15. type NameServerConfig struct {
  16. Address *Address `json:"address"`
  17. ClientIP *Address `json:"clientIp"`
  18. Port uint16 `json:"port"`
  19. SkipFallback bool `json:"skipFallback"`
  20. Domains []string `json:"domains"`
  21. ExpectedIPs StringList `json:"expectedIPs"`
  22. ExpectIPs StringList `json:"expectIPs"`
  23. QueryStrategy string `json:"queryStrategy"`
  24. Tag string `json:"tag"`
  25. TimeoutMs uint64 `json:"timeoutMs"`
  26. DisableCache bool `json:"disableCache"`
  27. FinalQuery bool `json:"finalQuery"`
  28. UnexpectedIPs StringList `json:"unexpectedIPs"`
  29. }
  30. // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
  31. func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
  32. var address Address
  33. if err := json.Unmarshal(data, &address); err == nil {
  34. c.Address = &address
  35. return nil
  36. }
  37. var advanced struct {
  38. Address *Address `json:"address"`
  39. ClientIP *Address `json:"clientIp"`
  40. Port uint16 `json:"port"`
  41. SkipFallback bool `json:"skipFallback"`
  42. Domains []string `json:"domains"`
  43. ExpectedIPs StringList `json:"expectedIPs"`
  44. ExpectIPs StringList `json:"expectIPs"`
  45. QueryStrategy string `json:"queryStrategy"`
  46. Tag string `json:"tag"`
  47. TimeoutMs uint64 `json:"timeoutMs"`
  48. DisableCache bool `json:"disableCache"`
  49. FinalQuery bool `json:"finalQuery"`
  50. UnexpectedIPs StringList `json:"unexpectedIPs"`
  51. }
  52. if err := json.Unmarshal(data, &advanced); err == nil {
  53. c.Address = advanced.Address
  54. c.ClientIP = advanced.ClientIP
  55. c.Port = advanced.Port
  56. c.SkipFallback = advanced.SkipFallback
  57. c.Domains = advanced.Domains
  58. c.ExpectedIPs = advanced.ExpectedIPs
  59. c.ExpectIPs = advanced.ExpectIPs
  60. c.QueryStrategy = advanced.QueryStrategy
  61. c.Tag = advanced.Tag
  62. c.TimeoutMs = advanced.TimeoutMs
  63. c.DisableCache = advanced.DisableCache
  64. c.FinalQuery = advanced.FinalQuery
  65. c.UnexpectedIPs = advanced.UnexpectedIPs
  66. return nil
  67. }
  68. return errors.New("failed to parse name server: ", string(data))
  69. }
  70. func toDomainMatchingType(t router.Domain_Type) dns.DomainMatchingType {
  71. switch t {
  72. case router.Domain_Domain:
  73. return dns.DomainMatchingType_Subdomain
  74. case router.Domain_Full:
  75. return dns.DomainMatchingType_Full
  76. case router.Domain_Plain:
  77. return dns.DomainMatchingType_Keyword
  78. case router.Domain_Regex:
  79. return dns.DomainMatchingType_Regex
  80. default:
  81. panic("unknown domain type")
  82. }
  83. }
  84. func (c *NameServerConfig) Build() (*dns.NameServer, error) {
  85. if c.Address == nil {
  86. return nil, errors.New("NameServer address is not specified.")
  87. }
  88. var domains []*dns.NameServer_PriorityDomain
  89. var originalRules []*dns.NameServer_OriginalRule
  90. for _, rule := range c.Domains {
  91. parsedDomain, err := parseDomainRule(rule)
  92. if err != nil {
  93. return nil, errors.New("invalid domain rule: ", rule).Base(err)
  94. }
  95. for _, pd := range parsedDomain {
  96. domains = append(domains, &dns.NameServer_PriorityDomain{
  97. Type: toDomainMatchingType(pd.Type),
  98. Domain: pd.Value,
  99. })
  100. }
  101. originalRules = append(originalRules, &dns.NameServer_OriginalRule{
  102. Rule: rule,
  103. Size: uint32(len(parsedDomain)),
  104. })
  105. }
  106. if len(c.ExpectedIPs) == 0 {
  107. c.ExpectedIPs = c.ExpectIPs
  108. }
  109. actPrior := false
  110. var newExpectedIPs StringList
  111. for _, s := range c.ExpectedIPs {
  112. if s == "*" {
  113. actPrior = true
  114. } else {
  115. newExpectedIPs = append(newExpectedIPs, s)
  116. }
  117. }
  118. actUnprior := false
  119. var newUnexpectedIPs StringList
  120. for _, s := range c.UnexpectedIPs {
  121. if s == "*" {
  122. actUnprior = true
  123. } else {
  124. newUnexpectedIPs = append(newUnexpectedIPs, s)
  125. }
  126. }
  127. expectedGeoipList, err := ToCidrList(newExpectedIPs)
  128. if err != nil {
  129. return nil, errors.New("invalid expected IP rule: ", c.ExpectedIPs).Base(err)
  130. }
  131. unexpectedGeoipList, err := ToCidrList(newUnexpectedIPs)
  132. if err != nil {
  133. return nil, errors.New("invalid unexpected IP rule: ", c.UnexpectedIPs).Base(err)
  134. }
  135. var myClientIP []byte
  136. if c.ClientIP != nil {
  137. if !c.ClientIP.Family().IsIP() {
  138. return nil, errors.New("not an IP address:", c.ClientIP.String())
  139. }
  140. myClientIP = []byte(c.ClientIP.IP())
  141. }
  142. return &dns.NameServer{
  143. Address: &net.Endpoint{
  144. Network: net.Network_UDP,
  145. Address: c.Address.Build(),
  146. Port: uint32(c.Port),
  147. },
  148. ClientIp: myClientIP,
  149. SkipFallback: c.SkipFallback,
  150. PrioritizedDomain: domains,
  151. ExpectedGeoip: expectedGeoipList,
  152. OriginalRules: originalRules,
  153. QueryStrategy: resolveQueryStrategy(c.QueryStrategy),
  154. ActPrior: actPrior,
  155. Tag: c.Tag,
  156. TimeoutMs: c.TimeoutMs,
  157. DisableCache: c.DisableCache,
  158. FinalQuery: c.FinalQuery,
  159. UnexpectedGeoip: unexpectedGeoipList,
  160. ActUnprior: actUnprior,
  161. }, nil
  162. }
  163. var typeMap = map[router.Domain_Type]dns.DomainMatchingType{
  164. router.Domain_Full: dns.DomainMatchingType_Full,
  165. router.Domain_Domain: dns.DomainMatchingType_Subdomain,
  166. router.Domain_Plain: dns.DomainMatchingType_Keyword,
  167. router.Domain_Regex: dns.DomainMatchingType_Regex,
  168. }
  169. // DNSConfig is a JSON serializable object for dns.Config.
  170. type DNSConfig struct {
  171. Servers []*NameServerConfig `json:"servers"`
  172. Hosts *HostsWrapper `json:"hosts"`
  173. ClientIP *Address `json:"clientIp"`
  174. Tag string `json:"tag"`
  175. QueryStrategy string `json:"queryStrategy"`
  176. DisableCache bool `json:"disableCache"`
  177. DisableFallback bool `json:"disableFallback"`
  178. DisableFallbackIfMatch bool `json:"disableFallbackIfMatch"`
  179. UseSystemHosts bool `json:"useSystemHosts"`
  180. }
  181. type HostAddress struct {
  182. addr *Address
  183. addrs []*Address
  184. }
  185. // MarshalJSON implements encoding/json.Marshaler.MarshalJSON
  186. func (h *HostAddress) MarshalJSON() ([]byte, error) {
  187. if (h.addr != nil) != (h.addrs != nil) {
  188. if h.addr != nil {
  189. return json.Marshal(h.addr)
  190. } else if h.addrs != nil {
  191. return json.Marshal(h.addrs)
  192. }
  193. }
  194. return nil, errors.New("unexpected config state")
  195. }
  196. // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
  197. func (h *HostAddress) UnmarshalJSON(data []byte) error {
  198. addr := new(Address)
  199. var addrs []*Address
  200. switch {
  201. case json.Unmarshal(data, &addr) == nil:
  202. h.addr = addr
  203. case json.Unmarshal(data, &addrs) == nil:
  204. h.addrs = addrs
  205. default:
  206. return errors.New("invalid address")
  207. }
  208. return nil
  209. }
  210. type HostsWrapper struct {
  211. Hosts map[string]*HostAddress
  212. }
  213. func getHostMapping(ha *HostAddress) *dns.Config_HostMapping {
  214. if ha.addr != nil {
  215. if ha.addr.Family().IsDomain() {
  216. return &dns.Config_HostMapping{
  217. ProxiedDomain: ha.addr.Domain(),
  218. }
  219. }
  220. return &dns.Config_HostMapping{
  221. Ip: [][]byte{ha.addr.IP()},
  222. }
  223. }
  224. ips := make([][]byte, 0, len(ha.addrs))
  225. for _, addr := range ha.addrs {
  226. if addr.Family().IsDomain() {
  227. return &dns.Config_HostMapping{
  228. ProxiedDomain: addr.Domain(),
  229. }
  230. }
  231. ips = append(ips, []byte(addr.IP()))
  232. }
  233. return &dns.Config_HostMapping{
  234. Ip: ips,
  235. }
  236. }
  237. // MarshalJSON implements encoding/json.Marshaler.MarshalJSON
  238. func (m *HostsWrapper) MarshalJSON() ([]byte, error) {
  239. return json.Marshal(m.Hosts)
  240. }
  241. // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
  242. func (m *HostsWrapper) UnmarshalJSON(data []byte) error {
  243. hosts := make(map[string]*HostAddress)
  244. err := json.Unmarshal(data, &hosts)
  245. if err == nil {
  246. m.Hosts = hosts
  247. return nil
  248. }
  249. return errors.New("invalid DNS hosts").Base(err)
  250. }
  251. // Build implements Buildable
  252. func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
  253. mappings := make([]*dns.Config_HostMapping, 0, 20)
  254. domains := make([]string, 0, len(m.Hosts))
  255. for domain := range m.Hosts {
  256. domains = append(domains, domain)
  257. }
  258. sort.Strings(domains)
  259. for _, domain := range domains {
  260. switch {
  261. case strings.HasPrefix(domain, "domain:"):
  262. domainName := domain[7:]
  263. if len(domainName) == 0 {
  264. return nil, errors.New("empty domain type of rule: ", domain)
  265. }
  266. mapping := getHostMapping(m.Hosts[domain])
  267. mapping.Type = dns.DomainMatchingType_Subdomain
  268. mapping.Domain = domainName
  269. mappings = append(mappings, mapping)
  270. case strings.HasPrefix(domain, "geosite:"):
  271. listName := domain[8:]
  272. if len(listName) == 0 {
  273. return nil, errors.New("empty geosite rule: ", domain)
  274. }
  275. geositeList, err := loadGeositeWithAttr("geosite.dat", listName)
  276. if err != nil {
  277. return nil, errors.New("failed to load geosite: ", listName).Base(err)
  278. }
  279. for _, d := range geositeList {
  280. mapping := getHostMapping(m.Hosts[domain])
  281. mapping.Type = typeMap[d.Type]
  282. mapping.Domain = d.Value
  283. mappings = append(mappings, mapping)
  284. }
  285. case strings.HasPrefix(domain, "regexp:"):
  286. regexpVal := domain[7:]
  287. if len(regexpVal) == 0 {
  288. return nil, errors.New("empty regexp type of rule: ", domain)
  289. }
  290. mapping := getHostMapping(m.Hosts[domain])
  291. mapping.Type = dns.DomainMatchingType_Regex
  292. mapping.Domain = regexpVal
  293. mappings = append(mappings, mapping)
  294. case strings.HasPrefix(domain, "keyword:"):
  295. keywordVal := domain[8:]
  296. if len(keywordVal) == 0 {
  297. return nil, errors.New("empty keyword type of rule: ", domain)
  298. }
  299. mapping := getHostMapping(m.Hosts[domain])
  300. mapping.Type = dns.DomainMatchingType_Keyword
  301. mapping.Domain = keywordVal
  302. mappings = append(mappings, mapping)
  303. case strings.HasPrefix(domain, "full:"):
  304. fullVal := domain[5:]
  305. if len(fullVal) == 0 {
  306. return nil, errors.New("empty full domain type of rule: ", domain)
  307. }
  308. mapping := getHostMapping(m.Hosts[domain])
  309. mapping.Type = dns.DomainMatchingType_Full
  310. mapping.Domain = fullVal
  311. mappings = append(mappings, mapping)
  312. case strings.HasPrefix(domain, "dotless:"):
  313. mapping := getHostMapping(m.Hosts[domain])
  314. mapping.Type = dns.DomainMatchingType_Regex
  315. switch substr := domain[8:]; {
  316. case substr == "":
  317. mapping.Domain = "^[^.]*$"
  318. case !strings.Contains(substr, "."):
  319. mapping.Domain = "^[^.]*" + substr + "[^.]*$"
  320. default:
  321. return nil, errors.New("substr in dotless rule should not contain a dot: ", substr)
  322. }
  323. mappings = append(mappings, mapping)
  324. case strings.HasPrefix(domain, "ext:"):
  325. kv := strings.Split(domain[4:], ":")
  326. if len(kv) != 2 {
  327. return nil, errors.New("invalid external resource: ", domain)
  328. }
  329. filename := kv[0]
  330. list := kv[1]
  331. geositeList, err := loadGeositeWithAttr(filename, list)
  332. if err != nil {
  333. return nil, errors.New("failed to load domain list: ", list, " from ", filename).Base(err)
  334. }
  335. for _, d := range geositeList {
  336. mapping := getHostMapping(m.Hosts[domain])
  337. mapping.Type = typeMap[d.Type]
  338. mapping.Domain = d.Value
  339. mappings = append(mappings, mapping)
  340. }
  341. default:
  342. mapping := getHostMapping(m.Hosts[domain])
  343. mapping.Type = dns.DomainMatchingType_Full
  344. mapping.Domain = domain
  345. mappings = append(mappings, mapping)
  346. }
  347. }
  348. return mappings, nil
  349. }
  350. // Build implements Buildable
  351. func (c *DNSConfig) Build() (*dns.Config, error) {
  352. config := &dns.Config{
  353. Tag: c.Tag,
  354. DisableCache: c.DisableCache,
  355. DisableFallback: c.DisableFallback,
  356. DisableFallbackIfMatch: c.DisableFallbackIfMatch,
  357. QueryStrategy: resolveQueryStrategy(c.QueryStrategy),
  358. }
  359. if c.ClientIP != nil {
  360. if !c.ClientIP.Family().IsIP() {
  361. return nil, errors.New("not an IP address:", c.ClientIP.String())
  362. }
  363. config.ClientIp = []byte(c.ClientIP.IP())
  364. }
  365. for _, server := range c.Servers {
  366. ns, err := server.Build()
  367. if err != nil {
  368. return nil, errors.New("failed to build nameserver").Base(err)
  369. }
  370. config.NameServer = append(config.NameServer, ns)
  371. }
  372. if c.Hosts != nil {
  373. staticHosts, err := c.Hosts.Build()
  374. if err != nil {
  375. return nil, errors.New("failed to build hosts").Base(err)
  376. }
  377. config.StaticHosts = append(config.StaticHosts, staticHosts...)
  378. }
  379. if c.UseSystemHosts {
  380. systemHosts, err := readSystemHosts()
  381. if err != nil {
  382. return nil, errors.New("failed to read system hosts").Base(err)
  383. }
  384. for domain, ips := range systemHosts {
  385. config.StaticHosts = append(config.StaticHosts, &dns.Config_HostMapping{Ip: ips, Domain: domain, Type: dns.DomainMatchingType_Full})
  386. }
  387. }
  388. return config, nil
  389. }
  390. func resolveQueryStrategy(queryStrategy string) dns.QueryStrategy {
  391. switch strings.ToLower(queryStrategy) {
  392. case "useip", "use_ip", "use-ip":
  393. return dns.QueryStrategy_USE_IP
  394. case "useip4", "useipv4", "use_ip4", "use_ipv4", "use_ip_v4", "use-ip4", "use-ipv4", "use-ip-v4":
  395. return dns.QueryStrategy_USE_IP4
  396. case "useip6", "useipv6", "use_ip6", "use_ipv6", "use_ip_v6", "use-ip6", "use-ipv6", "use-ip-v6":
  397. return dns.QueryStrategy_USE_IP6
  398. case "usesys", "usesystem", "use_sys", "use_system", "use-sys", "use-system":
  399. return dns.QueryStrategy_USE_SYS
  400. default:
  401. return dns.QueryStrategy_USE_IP
  402. }
  403. }
  404. func readSystemHosts() (map[string][][]byte, error) {
  405. var hostsPath string
  406. switch runtime.GOOS {
  407. case "windows":
  408. hostsPath = filepath.Join(os.Getenv("SystemRoot"), "System32", "drivers", "etc", "hosts")
  409. default:
  410. hostsPath = "/etc/hosts"
  411. }
  412. file, err := os.Open(hostsPath)
  413. if err != nil {
  414. return nil, err
  415. }
  416. defer file.Close()
  417. hostsMap := make(map[string][][]byte)
  418. scanner := bufio.NewScanner(file)
  419. for scanner.Scan() {
  420. line := strings.TrimSpace(scanner.Text())
  421. if i := strings.IndexByte(line, '#'); i >= 0 {
  422. // Discard comments.
  423. line = line[0:i]
  424. }
  425. f := strings.Fields(line)
  426. if len(f) < 2 {
  427. continue
  428. }
  429. addr := net.ParseAddress(f[0])
  430. if addr.Family().IsDomain() {
  431. continue
  432. }
  433. ip := addr.IP()
  434. for i := 1; i < len(f); i++ {
  435. domain := strings.TrimSuffix(f[i], ".")
  436. domain = strings.ToLower(domain)
  437. if v, ok := hostsMap[domain]; ok {
  438. hostsMap[domain] = append(v, ip)
  439. } else {
  440. hostsMap[domain] = [][]byte{ip}
  441. }
  442. }
  443. }
  444. if err := scanner.Err(); err != nil {
  445. return nil, err
  446. }
  447. return hostsMap, nil
  448. }