dns.go 16 KB

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