nameserver_doh.go 10.0 KB

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