dohdns.go 9.7 KB

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