nameserver_doh.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package dns
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "sync"
  11. "time"
  12. "github.com/xtls/xray-core/common"
  13. "github.com/xtls/xray-core/common/errors"
  14. "github.com/xtls/xray-core/common/log"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/common/net/cnc"
  17. "github.com/xtls/xray-core/common/protocol/dns"
  18. "github.com/xtls/xray-core/common/session"
  19. "github.com/xtls/xray-core/common/signal/pubsub"
  20. "github.com/xtls/xray-core/common/task"
  21. dns_feature "github.com/xtls/xray-core/features/dns"
  22. "github.com/xtls/xray-core/features/routing"
  23. "github.com/xtls/xray-core/transport/internet"
  24. "golang.org/x/net/dns/dnsmessage"
  25. "golang.org/x/net/http2"
  26. )
  27. // DoHNameServer implemented DNS over HTTPS (RFC8484) Wire Format,
  28. // which is compatible with traditional dns over udp(RFC1035),
  29. // thus most of the DOH implementation is copied from udpns.go
  30. type DoHNameServer struct {
  31. dispatcher routing.Dispatcher
  32. sync.RWMutex
  33. ips map[string]*record
  34. pub *pubsub.Service
  35. cleanup *task.Periodic
  36. httpClient *http.Client
  37. dohURL string
  38. name string
  39. queryStrategy QueryStrategy
  40. }
  41. // NewDoHNameServer creates DOH server object for remote resolving.
  42. func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher, queryStrategy QueryStrategy, h2c bool) (*DoHNameServer, error) {
  43. url.Scheme = "https"
  44. errors.LogInfo(context.Background(), "DNS: created Remote DNS-over-HTTPS client for ", url.String(), ", with h2c ", h2c)
  45. s := baseDOHNameServer(url, "DOH", queryStrategy)
  46. s.dispatcher = dispatcher
  47. dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
  48. dest, err := net.ParseDestination(network + ":" + addr)
  49. if err != nil {
  50. return nil, err
  51. }
  52. link, err := s.dispatcher.Dispatch(toDnsContext(ctx, s.dohURL), dest)
  53. select {
  54. case <-ctx.Done():
  55. return nil, ctx.Err()
  56. default:
  57. }
  58. if err != nil {
  59. return nil, err
  60. }
  61. cc := common.ChainedClosable{}
  62. if cw, ok := link.Writer.(common.Closable); ok {
  63. cc = append(cc, cw)
  64. }
  65. if cr, ok := link.Reader.(common.Closable); ok {
  66. cc = append(cc, cr)
  67. }
  68. return cnc.NewConnection(
  69. cnc.ConnectionInputMulti(link.Writer),
  70. cnc.ConnectionOutputMulti(link.Reader),
  71. cnc.ConnectionOnClose(cc),
  72. ), nil
  73. }
  74. s.httpClient = &http.Client{
  75. Timeout: time.Second * 180,
  76. Transport: &http.Transport{
  77. MaxIdleConns: 30,
  78. IdleConnTimeout: 90 * time.Second,
  79. TLSHandshakeTimeout: 30 * time.Second,
  80. ForceAttemptHTTP2: true,
  81. DialContext: dialContext,
  82. },
  83. }
  84. if h2c {
  85. s.httpClient.Transport = &http2.Transport{
  86. IdleConnTimeout: 90 * time.Second,
  87. DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
  88. return dialContext(ctx, network, addr)
  89. },
  90. }
  91. }
  92. return s, nil
  93. }
  94. // NewDoHLocalNameServer creates DOH client object for local resolving
  95. func NewDoHLocalNameServer(url *url.URL, queryStrategy QueryStrategy) *DoHNameServer {
  96. url.Scheme = "https"
  97. s := baseDOHNameServer(url, "DOHL", queryStrategy)
  98. tr := &http.Transport{
  99. IdleConnTimeout: 90 * time.Second,
  100. ForceAttemptHTTP2: true,
  101. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  102. dest, err := net.ParseDestination(network + ":" + addr)
  103. if err != nil {
  104. return nil, err
  105. }
  106. conn, err := internet.DialSystem(ctx, dest, nil)
  107. log.Record(&log.AccessMessage{
  108. From: "DNS",
  109. To: s.dohURL,
  110. Status: log.AccessAccepted,
  111. Detour: "local",
  112. })
  113. if err != nil {
  114. return nil, err
  115. }
  116. return conn, nil
  117. },
  118. }
  119. s.httpClient = &http.Client{
  120. Timeout: time.Second * 180,
  121. Transport: tr,
  122. }
  123. errors.LogInfo(context.Background(), "DNS: created Local DNS-over-HTTPS client for ", url.String())
  124. return s
  125. }
  126. func baseDOHNameServer(url *url.URL, prefix string, queryStrategy QueryStrategy) *DoHNameServer {
  127. s := &DoHNameServer{
  128. ips: make(map[string]*record),
  129. pub: pubsub.NewService(),
  130. name: prefix + "//" + url.Host,
  131. dohURL: url.String(),
  132. queryStrategy: queryStrategy,
  133. }
  134. s.cleanup = &task.Periodic{
  135. Interval: time.Minute,
  136. Execute: s.Cleanup,
  137. }
  138. return s
  139. }
  140. // Name implements Server.
  141. func (s *DoHNameServer) Name() string {
  142. return s.name
  143. }
  144. // Cleanup clears expired items from cache
  145. func (s *DoHNameServer) Cleanup() error {
  146. now := time.Now()
  147. s.Lock()
  148. defer s.Unlock()
  149. if len(s.ips) == 0 {
  150. return errors.New("nothing to do. stopping...")
  151. }
  152. for domain, record := range s.ips {
  153. if record.A != nil && record.A.Expire.Before(now) {
  154. record.A = nil
  155. }
  156. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  157. record.AAAA = nil
  158. }
  159. if record.A == nil && record.AAAA == nil {
  160. errors.LogDebug(context.Background(), s.name, " cleanup ", domain)
  161. delete(s.ips, domain)
  162. } else {
  163. s.ips[domain] = record
  164. }
  165. }
  166. if len(s.ips) == 0 {
  167. s.ips = make(map[string]*record)
  168. }
  169. return nil
  170. }
  171. func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  172. elapsed := time.Since(req.start)
  173. s.Lock()
  174. rec, found := s.ips[req.domain]
  175. if !found {
  176. rec = &record{}
  177. }
  178. updated := false
  179. switch req.reqType {
  180. case dnsmessage.TypeA:
  181. if isNewer(rec.A, ipRec) {
  182. rec.A = ipRec
  183. updated = true
  184. }
  185. case dnsmessage.TypeAAAA:
  186. addr := make([]net.Address, 0, len(ipRec.IP))
  187. for _, ip := range ipRec.IP {
  188. if len(ip.IP()) == net.IPv6len {
  189. addr = append(addr, ip)
  190. }
  191. }
  192. ipRec.IP = addr
  193. if isNewer(rec.AAAA, ipRec) {
  194. rec.AAAA = ipRec
  195. updated = true
  196. }
  197. }
  198. errors.LogInfo(context.Background(), s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed)
  199. if updated {
  200. s.ips[req.domain] = rec
  201. }
  202. switch req.reqType {
  203. case dnsmessage.TypeA:
  204. s.pub.Publish(req.domain+"4", nil)
  205. case dnsmessage.TypeAAAA:
  206. s.pub.Publish(req.domain+"6", nil)
  207. }
  208. s.Unlock()
  209. common.Must(s.cleanup.Start())
  210. }
  211. func (s *DoHNameServer) newReqID() uint16 {
  212. return 0
  213. }
  214. func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
  215. errors.LogInfo(ctx, s.name, " querying: ", domain)
  216. if s.name+"." == "DOH//"+domain {
  217. errors.LogError(ctx, s.name, " tries to resolve itself! Use IP or set \"hosts\" instead.")
  218. return
  219. }
  220. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
  221. var deadline time.Time
  222. if d, ok := ctx.Deadline(); ok {
  223. deadline = d
  224. } else {
  225. deadline = time.Now().Add(time.Second * 5)
  226. }
  227. for _, req := range reqs {
  228. go func(r *dnsRequest) {
  229. // generate new context for each req, using same context
  230. // may cause reqs all aborted if any one encounter an error
  231. dnsCtx := ctx
  232. // reserve internal dns server requested Inbound
  233. if inbound := session.InboundFromContext(ctx); inbound != nil {
  234. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  235. }
  236. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  237. Protocol: "https",
  238. SkipDNSResolve: true,
  239. })
  240. // forced to use mux for DOH
  241. // dnsCtx = session.ContextWithMuxPreferred(dnsCtx, true)
  242. var cancel context.CancelFunc
  243. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  244. defer cancel()
  245. b, err := dns.PackMessage(r.msg)
  246. if err != nil {
  247. errors.LogErrorInner(ctx, err, "failed to pack dns query for ", domain)
  248. return
  249. }
  250. resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
  251. if err != nil {
  252. errors.LogErrorInner(ctx, err, "failed to retrieve response for ", domain)
  253. return
  254. }
  255. rec, err := parseResponse(resp)
  256. if err != nil {
  257. errors.LogErrorInner(ctx, err, "failed to handle DOH response for ", domain)
  258. return
  259. }
  260. s.updateIP(r, rec)
  261. }(req)
  262. }
  263. }
  264. func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte, error) {
  265. body := bytes.NewBuffer(b)
  266. req, err := http.NewRequest("POST", s.dohURL, body)
  267. if err != nil {
  268. return nil, err
  269. }
  270. req.Header.Add("Accept", "application/dns-message")
  271. req.Header.Add("Content-Type", "application/dns-message")
  272. hc := s.httpClient
  273. resp, err := hc.Do(req.WithContext(ctx))
  274. if err != nil {
  275. return nil, err
  276. }
  277. defer resp.Body.Close()
  278. if resp.StatusCode != http.StatusOK {
  279. io.Copy(io.Discard, resp.Body) // flush resp.Body so that the conn is reusable
  280. return nil, fmt.Errorf("DOH server returned code %d", resp.StatusCode)
  281. }
  282. return io.ReadAll(resp.Body)
  283. }
  284. func (s *DoHNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  285. s.RLock()
  286. record, found := s.ips[domain]
  287. s.RUnlock()
  288. if !found {
  289. return nil, errRecordNotFound
  290. }
  291. var err4 error
  292. var err6 error
  293. var ips []net.Address
  294. var ip6 []net.Address
  295. if option.IPv4Enable {
  296. ips, err4 = record.A.getIPs()
  297. }
  298. if option.IPv6Enable {
  299. ip6, err6 = record.AAAA.getIPs()
  300. ips = append(ips, ip6...)
  301. }
  302. if len(ips) > 0 {
  303. return toNetIP(ips)
  304. }
  305. if err4 != nil {
  306. return nil, err4
  307. }
  308. if err6 != nil {
  309. return nil, err6
  310. }
  311. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  312. return nil, dns_feature.ErrEmptyResponse
  313. }
  314. return nil, errRecordNotFound
  315. }
  316. // QueryIP implements Server.
  317. func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { // nolint: dupl
  318. fqdn := Fqdn(domain)
  319. option = ResolveIpOptionOverride(s.queryStrategy, option)
  320. if !option.IPv4Enable && !option.IPv6Enable {
  321. return nil, dns_feature.ErrEmptyResponse
  322. }
  323. if disableCache {
  324. errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name)
  325. } else {
  326. ips, err := s.findIPsForDomain(fqdn, option)
  327. if err == nil || err == dns_feature.ErrEmptyResponse {
  328. errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips)
  329. log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err})
  330. return ips, err
  331. }
  332. }
  333. // ipv4 and ipv6 belong to different subscription groups
  334. var sub4, sub6 *pubsub.Subscriber
  335. if option.IPv4Enable {
  336. sub4 = s.pub.Subscribe(fqdn + "4")
  337. defer sub4.Close()
  338. }
  339. if option.IPv6Enable {
  340. sub6 = s.pub.Subscribe(fqdn + "6")
  341. defer sub6.Close()
  342. }
  343. done := make(chan interface{})
  344. go func() {
  345. if sub4 != nil {
  346. select {
  347. case <-sub4.Wait():
  348. case <-ctx.Done():
  349. }
  350. }
  351. if sub6 != nil {
  352. select {
  353. case <-sub6.Wait():
  354. case <-ctx.Done():
  355. }
  356. }
  357. close(done)
  358. }()
  359. s.sendQuery(ctx, fqdn, clientIP, option)
  360. start := time.Now()
  361. for {
  362. ips, err := s.findIPsForDomain(fqdn, option)
  363. if err != errRecordNotFound {
  364. log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
  365. return ips, err
  366. }
  367. select {
  368. case <-ctx.Done():
  369. return nil, ctx.Err()
  370. case <-done:
  371. }
  372. }
  373. }