nameserver_doh.go 11 KB

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