1
0

nameserver_doh.go 10 KB

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