doh.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. package dns
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/base64"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "runtime"
  13. "strconv"
  14. "sync"
  15. "time"
  16. "github.com/metacubex/mihomo/component/ca"
  17. C "github.com/metacubex/mihomo/constant"
  18. "github.com/metacubex/mihomo/log"
  19. "github.com/metacubex/quic-go"
  20. "github.com/metacubex/quic-go/http3"
  21. D "github.com/miekg/dns"
  22. "golang.org/x/exp/slices"
  23. "golang.org/x/net/http2"
  24. )
  25. // Values to configure HTTP and HTTP/2 transport.
  26. const (
  27. // transportDefaultReadIdleTimeout is the default timeout for pinging
  28. // idle connections in HTTP/2 transport.
  29. transportDefaultReadIdleTimeout = 30 * time.Second
  30. // transportDefaultIdleConnTimeout is the default timeout for idle
  31. // connections in HTTP transport.
  32. transportDefaultIdleConnTimeout = 5 * time.Minute
  33. // dohMaxConnsPerHost controls the maximum number of connections for
  34. // each host.
  35. dohMaxConnsPerHost = 1
  36. dialTimeout = 10 * time.Second
  37. // dohMaxIdleConns controls the maximum number of connections being idle
  38. // at the same time.
  39. dohMaxIdleConns = 1
  40. maxElapsedTime = time.Second * 30
  41. )
  42. var DefaultHTTPVersions = []C.HTTPVersion{C.HTTPVersion11, C.HTTPVersion2}
  43. // dnsOverHTTPS is a struct that implements the Upstream interface for the
  44. // DNS-over-HTTPS protocol.
  45. type dnsOverHTTPS struct {
  46. // The Client's Transport typically has internal state (cached TCP
  47. // connections), so Clients should be reused instead of created as
  48. // needed. Clients are safe for concurrent use by multiple goroutines.
  49. client *http.Client
  50. clientMu sync.Mutex
  51. // quicConfig is the QUIC configuration that is used if HTTP/3 is enabled
  52. // for this upstream.
  53. quicConfig *quic.Config
  54. quicConfigGuard sync.Mutex
  55. url *url.URL
  56. httpVersions []C.HTTPVersion
  57. dialer *dnsDialer
  58. addr string
  59. skipCertVerify bool
  60. }
  61. // type check
  62. var _ dnsClient = (*dnsOverHTTPS)(nil)
  63. // newDoH returns the DNS-over-HTTPS Upstream.
  64. func newDoHClient(urlString string, r *Resolver, preferH3 bool, params map[string]string, proxyAdapter C.ProxyAdapter, proxyName string) dnsClient {
  65. u, _ := url.Parse(urlString)
  66. httpVersions := DefaultHTTPVersions
  67. if preferH3 {
  68. httpVersions = append(httpVersions, C.HTTPVersion3)
  69. }
  70. if params["h3"] == "true" {
  71. httpVersions = []C.HTTPVersion{C.HTTPVersion3}
  72. }
  73. doh := &dnsOverHTTPS{
  74. url: u,
  75. addr: u.String(),
  76. dialer: newDNSDialer(r, proxyAdapter, proxyName),
  77. quicConfig: &quic.Config{
  78. KeepAlivePeriod: QUICKeepAlivePeriod,
  79. TokenStore: newQUICTokenStore(),
  80. },
  81. httpVersions: httpVersions,
  82. }
  83. if params["skip-cert-verify"] == "true" {
  84. doh.skipCertVerify = true
  85. }
  86. runtime.SetFinalizer(doh, (*dnsOverHTTPS).Close)
  87. return doh
  88. }
  89. // Address implements the Upstream interface for *dnsOverHTTPS.
  90. func (doh *dnsOverHTTPS) Address() string {
  91. return doh.addr
  92. }
  93. func (doh *dnsOverHTTPS) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
  94. // Quote from https://www.rfc-editor.org/rfc/rfc8484.html:
  95. // In order to maximize HTTP cache friendliness, DoH clients using media
  96. // formats that include the ID field from the DNS message header, such
  97. // as "application/dns-message", SHOULD use a DNS ID of 0 in every DNS
  98. // request.
  99. m = m.Copy()
  100. id := m.Id
  101. m.Id = 0
  102. defer func() {
  103. // Restore the original ID to not break compatibility with proxies.
  104. m.Id = id
  105. if msg != nil {
  106. msg.Id = id
  107. }
  108. }()
  109. // Check if there was already an active client before sending the request.
  110. // We'll only attempt to re-connect if there was one.
  111. client, isCached, err := doh.getClient(ctx)
  112. if err != nil {
  113. return nil, fmt.Errorf("failed to init http client: %w", err)
  114. }
  115. // Make the first attempt to send the DNS query.
  116. msg, err = doh.exchangeHTTPS(ctx, client, m)
  117. // Make up to 2 attempts to re-create the HTTP client and send the request
  118. // again. There are several cases (mostly, with QUIC) where this workaround
  119. // is necessary to make HTTP client usable. We need to make 2 attempts in
  120. // the case when the connection was closed (due to inactivity for example)
  121. // AND the server refuses to open a 0-RTT connection.
  122. for i := 0; isCached && doh.shouldRetry(err) && i < 2; i++ {
  123. client, err = doh.resetClient(ctx, err)
  124. if err != nil {
  125. return nil, fmt.Errorf("failed to reset http client: %w", err)
  126. }
  127. msg, err = doh.exchangeHTTPS(ctx, client, m)
  128. }
  129. if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) {
  130. // If the request failed anyway, make sure we don't use this client.
  131. _, resErr := doh.resetClient(ctx, err)
  132. return nil, fmt.Errorf("%w (resErr:%v)", err, resErr)
  133. }
  134. return msg, err
  135. }
  136. // Close implements the Upstream interface for *dnsOverHTTPS.
  137. func (doh *dnsOverHTTPS) Close() (err error) {
  138. doh.clientMu.Lock()
  139. defer doh.clientMu.Unlock()
  140. runtime.SetFinalizer(doh, nil)
  141. if doh.client == nil {
  142. return nil
  143. }
  144. return doh.closeClient(doh.client)
  145. }
  146. // closeClient cleans up resources used by client if necessary. Note, that at
  147. // this point it should only be done for HTTP/3 as it may leak due to keep-alive
  148. // connections.
  149. func (doh *dnsOverHTTPS) closeClient(client *http.Client) (err error) {
  150. if isHTTP3(client) {
  151. return client.Transport.(io.Closer).Close()
  152. }
  153. return nil
  154. }
  155. // exchangeHTTPS sends the DNS query to a DoH resolver using the specified
  156. // http.Client instance.
  157. func (doh *dnsOverHTTPS) exchangeHTTPS(ctx context.Context, client *http.Client, req *D.Msg) (resp *D.Msg, err error) {
  158. buf, err := req.Pack()
  159. if err != nil {
  160. return nil, fmt.Errorf("packing message: %w", err)
  161. }
  162. // It appears, that GET requests are more memory-efficient with Golang
  163. // implementation of HTTP/2.
  164. method := http.MethodGet
  165. if isHTTP3(client) {
  166. // If we're using HTTP/3, use http3.MethodGet0RTT to force using 0-RTT.
  167. method = http3.MethodGet0RTT
  168. }
  169. requestUrl := *doh.url // don't modify origin url
  170. requestUrl.RawQuery = fmt.Sprintf("dns=%s", base64.RawURLEncoding.EncodeToString(buf))
  171. httpReq, err := http.NewRequestWithContext(ctx, method, requestUrl.String(), nil)
  172. if err != nil {
  173. return nil, fmt.Errorf("creating http request to %s: %w", doh.url, err)
  174. }
  175. httpReq.Header.Set("Accept", "application/dns-message")
  176. httpReq.Header.Set("User-Agent", "")
  177. httpResp, err := client.Do(httpReq)
  178. if err != nil {
  179. return nil, fmt.Errorf("requesting %s: %w", doh.url, err)
  180. }
  181. defer httpResp.Body.Close()
  182. body, err := io.ReadAll(httpResp.Body)
  183. if err != nil {
  184. return nil, fmt.Errorf("reading %s: %w", doh.url, err)
  185. }
  186. if httpResp.StatusCode != http.StatusOK {
  187. return nil,
  188. fmt.Errorf(
  189. "expected status %d, got %d from %s",
  190. http.StatusOK,
  191. httpResp.StatusCode,
  192. doh.url,
  193. )
  194. }
  195. resp = &D.Msg{}
  196. err = resp.Unpack(body)
  197. if err != nil {
  198. return nil, fmt.Errorf(
  199. "unpacking response from %s: body is %s: %w",
  200. doh.url,
  201. body,
  202. err,
  203. )
  204. }
  205. if resp.Id != req.Id {
  206. err = D.ErrId
  207. }
  208. return resp, err
  209. }
  210. // shouldRetry checks what error we have received and returns true if we should
  211. // re-create the HTTP client and retry the request.
  212. func (doh *dnsOverHTTPS) shouldRetry(err error) (ok bool) {
  213. if err == nil {
  214. return false
  215. }
  216. var netErr net.Error
  217. if errors.As(err, &netErr) && netErr.Timeout() {
  218. // If this is a timeout error, trying to forcibly re-create the HTTP
  219. // client instance. This is an attempt to fix an issue with DoH client
  220. // stalling after a network change.
  221. //
  222. // See https://github.com/AdguardTeam/AdGuardHome/issues/3217.
  223. return true
  224. }
  225. if isQUICRetryError(err) {
  226. return true
  227. }
  228. return false
  229. }
  230. // resetClient triggers re-creation of the *http.Client that is used by this
  231. // upstream. This method accepts the error that caused resetting client as
  232. // depending on the error we may also reset the QUIC config.
  233. func (doh *dnsOverHTTPS) resetClient(ctx context.Context, resetErr error) (client *http.Client, err error) {
  234. doh.clientMu.Lock()
  235. defer doh.clientMu.Unlock()
  236. if errors.Is(resetErr, quic.Err0RTTRejected) {
  237. // Reset the TokenStore only if 0-RTT was rejected.
  238. doh.resetQUICConfig()
  239. }
  240. oldClient := doh.client
  241. if oldClient != nil {
  242. closeErr := doh.closeClient(oldClient)
  243. if closeErr != nil {
  244. log.Warnln("warning: failed to close the old http client: %v", closeErr)
  245. }
  246. }
  247. log.Debugln("re-creating the http client due to %v", resetErr)
  248. doh.client, err = doh.createClient(ctx)
  249. return doh.client, err
  250. }
  251. // getQUICConfig returns the QUIC config in a thread-safe manner. Note, that
  252. // this method returns a pointer, it is forbidden to change its properties.
  253. func (doh *dnsOverHTTPS) getQUICConfig() (c *quic.Config) {
  254. doh.quicConfigGuard.Lock()
  255. defer doh.quicConfigGuard.Unlock()
  256. return doh.quicConfig
  257. }
  258. // resetQUICConfig Re-create the token store to make sure we're not trying to
  259. // use invalid for 0-RTT.
  260. func (doh *dnsOverHTTPS) resetQUICConfig() {
  261. doh.quicConfigGuard.Lock()
  262. defer doh.quicConfigGuard.Unlock()
  263. doh.quicConfig = doh.quicConfig.Clone()
  264. doh.quicConfig.TokenStore = newQUICTokenStore()
  265. }
  266. // getClient gets or lazily initializes an HTTP client (and transport) that will
  267. // be used for this DoH resolver.
  268. func (doh *dnsOverHTTPS) getClient(ctx context.Context) (c *http.Client, isCached bool, err error) {
  269. startTime := time.Now()
  270. doh.clientMu.Lock()
  271. defer doh.clientMu.Unlock()
  272. if doh.client != nil {
  273. return doh.client, true, nil
  274. }
  275. // Timeout can be exceeded while waiting for the lock. This happens quite
  276. // often on mobile devices.
  277. elapsed := time.Since(startTime)
  278. if elapsed > maxElapsedTime {
  279. return nil, false, fmt.Errorf("timeout exceeded: %s", elapsed)
  280. }
  281. log.Debugln("creating a new http client")
  282. doh.client, err = doh.createClient(ctx)
  283. return doh.client, false, err
  284. }
  285. // createClient creates a new *http.Client instance. The HTTP protocol version
  286. // will depend on whether HTTP3 is allowed and provided by this upstream. Note,
  287. // that we'll attempt to establish a QUIC connection when creating the client in
  288. // order to check whether HTTP3 is supported.
  289. func (doh *dnsOverHTTPS) createClient(ctx context.Context) (*http.Client, error) {
  290. transport, err := doh.createTransport(ctx)
  291. if err != nil {
  292. return nil, fmt.Errorf("[%s] initializing http transport: %w", doh.url.String(), err)
  293. }
  294. client := &http.Client{
  295. Transport: transport,
  296. Timeout: DefaultTimeout,
  297. Jar: nil,
  298. }
  299. doh.client = client
  300. return doh.client, nil
  301. }
  302. // createTransport initializes an HTTP transport that will be used specifically
  303. // for this DoH resolver. This HTTP transport ensures that the HTTP requests
  304. // will be sent exactly to the IP address got from the bootstrap resolver. Note,
  305. // that this function will first attempt to establish a QUIC connection (if
  306. // HTTP3 is enabled in the upstream options). If this attempt is successful,
  307. // it returns an HTTP3 transport, otherwise it returns the H1/H2 transport.
  308. func (doh *dnsOverHTTPS) createTransport(ctx context.Context) (t http.RoundTripper, err error) {
  309. transport := &http.Transport{
  310. DisableCompression: true,
  311. DialContext: doh.dialer.DialContext,
  312. IdleConnTimeout: transportDefaultIdleConnTimeout,
  313. MaxConnsPerHost: dohMaxConnsPerHost,
  314. MaxIdleConns: dohMaxIdleConns,
  315. }
  316. if doh.url.Scheme == "http" {
  317. return transport, nil
  318. }
  319. tlsConfig := ca.GetGlobalTLSConfig(
  320. &tls.Config{
  321. InsecureSkipVerify: doh.skipCertVerify,
  322. MinVersion: tls.VersionTLS12,
  323. SessionTicketsDisabled: false,
  324. })
  325. var nextProtos []string
  326. for _, v := range doh.httpVersions {
  327. nextProtos = append(nextProtos, string(v))
  328. }
  329. tlsConfig.NextProtos = nextProtos
  330. transport.TLSClientConfig = tlsConfig
  331. if slices.Contains(doh.httpVersions, C.HTTPVersion3) {
  332. // First, we attempt to create an HTTP3 transport. If the probe QUIC
  333. // connection is established successfully, we'll be using HTTP3 for this
  334. // upstream.
  335. transportH3, err := doh.createTransportH3(ctx, tlsConfig)
  336. if err == nil {
  337. log.Debugln("[%s] using HTTP/3 for this upstream: QUIC was faster", doh.url.String())
  338. return transportH3, nil
  339. }
  340. }
  341. log.Debugln("[%s] using HTTP/2 for this upstream: %v", doh.url.String(), err)
  342. if !doh.supportsHTTP() {
  343. return nil, errors.New("HTTP1/1 and HTTP2 are not supported by this upstream")
  344. }
  345. // Since we have a custom DialContext, we need to use this field to
  346. // make golang http.Client attempt to use HTTP/2. Otherwise, it would
  347. // only be used when negotiated on the TLS level.
  348. transport.ForceAttemptHTTP2 = true
  349. // Explicitly configure transport to use HTTP/2.
  350. //
  351. // See https://github.com/AdguardTeam/dnsproxy/issues/11.
  352. var transportH2 *http2.Transport
  353. transportH2, err = http2.ConfigureTransports(transport)
  354. if err != nil {
  355. return nil, err
  356. }
  357. // Enable HTTP/2 pings on idle connections.
  358. transportH2.ReadIdleTimeout = transportDefaultReadIdleTimeout
  359. return transport, nil
  360. }
  361. // http3Transport is a wrapper over *http3.RoundTripper that tries to optimize
  362. // its behavior. The main thing that it does is trying to force use a single
  363. // connection to a host instead of creating a new one all the time. It also
  364. // helps mitigate race issues with quic-go.
  365. type http3Transport struct {
  366. baseTransport *http3.RoundTripper
  367. closed bool
  368. mu sync.RWMutex
  369. }
  370. // type check
  371. var _ http.RoundTripper = (*http3Transport)(nil)
  372. // RoundTrip implements the http.RoundTripper interface for *http3Transport.
  373. func (h *http3Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
  374. h.mu.RLock()
  375. defer h.mu.RUnlock()
  376. if h.closed {
  377. return nil, net.ErrClosed
  378. }
  379. // Try to use cached connection to the target host if it's available.
  380. resp, err = h.baseTransport.RoundTripOpt(req, http3.RoundTripOpt{OnlyCachedConn: true})
  381. if errors.Is(err, http3.ErrNoCachedConn) {
  382. // If there are no cached connection, trigger creating a new one.
  383. resp, err = h.baseTransport.RoundTrip(req)
  384. }
  385. return resp, err
  386. }
  387. // type check
  388. var _ io.Closer = (*http3Transport)(nil)
  389. // Close implements the io.Closer interface for *http3Transport.
  390. func (h *http3Transport) Close() (err error) {
  391. h.mu.Lock()
  392. defer h.mu.Unlock()
  393. h.closed = true
  394. return h.baseTransport.Close()
  395. }
  396. // createTransportH3 tries to create an HTTP/3 transport for this upstream.
  397. // We should be able to fall back to H1/H2 in case if HTTP/3 is unavailable or
  398. // if it is too slow. In order to do that, this method will run two probes
  399. // in parallel (one for TLS, the other one for QUIC) and if QUIC is faster it
  400. // will create the *http3.RoundTripper instance.
  401. func (doh *dnsOverHTTPS) createTransportH3(
  402. ctx context.Context,
  403. tlsConfig *tls.Config,
  404. ) (roundTripper http.RoundTripper, err error) {
  405. if !doh.supportsH3() {
  406. return nil, errors.New("HTTP3 support is not enabled")
  407. }
  408. addr, err := doh.probeH3(ctx, tlsConfig)
  409. if err != nil {
  410. return nil, err
  411. }
  412. rt := &http3.RoundTripper{
  413. Dial: func(
  414. ctx context.Context,
  415. // Ignore the address and always connect to the one that we got
  416. // from the bootstrapper.
  417. _ string,
  418. tlsCfg *tls.Config,
  419. cfg *quic.Config,
  420. ) (c quic.EarlyConnection, err error) {
  421. return doh.dialQuic(ctx, addr, tlsCfg, cfg)
  422. },
  423. DisableCompression: true,
  424. TLSClientConfig: tlsConfig,
  425. QUICConfig: doh.getQUICConfig(),
  426. }
  427. return &http3Transport{baseTransport: rt}, nil
  428. }
  429. func (doh *dnsOverHTTPS) dialQuic(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) {
  430. ip, port, err := net.SplitHostPort(addr)
  431. if err != nil {
  432. return nil, err
  433. }
  434. portInt, err := strconv.Atoi(port)
  435. if err != nil {
  436. return nil, err
  437. }
  438. udpAddr := net.UDPAddr{
  439. IP: net.ParseIP(ip),
  440. Port: portInt,
  441. }
  442. conn, err := doh.dialer.ListenPacket(ctx, "udp", addr)
  443. if err != nil {
  444. return nil, err
  445. }
  446. transport := quic.Transport{Conn: conn}
  447. transport.SetCreatedConn(true) // auto close conn
  448. transport.SetSingleUse(true) // auto close transport
  449. tlsCfg = tlsCfg.Clone()
  450. if host, _, err := net.SplitHostPort(doh.url.Host); err == nil {
  451. tlsCfg.ServerName = host
  452. } else {
  453. // It's ok if net.SplitHostPort returns an error - it could be a hostname/IP address without a port.
  454. tlsCfg.ServerName = doh.url.Host
  455. }
  456. return transport.DialEarly(ctx, &udpAddr, tlsCfg, cfg)
  457. }
  458. // probeH3 runs a test to check whether QUIC is faster than TLS for this
  459. // upstream. If the test is successful it will return the address that we
  460. // should use to establish the QUIC connections.
  461. func (doh *dnsOverHTTPS) probeH3(
  462. ctx context.Context,
  463. tlsConfig *tls.Config,
  464. ) (addr string, err error) {
  465. // We're using bootstrapped address instead of what's passed to the function
  466. // it does not create an actual connection, but it helps us determine
  467. // what IP is actually reachable (when there are v4/v6 addresses).
  468. rawConn, err := doh.dialer.DialContext(ctx, "udp", doh.url.Host)
  469. if err != nil {
  470. return "", fmt.Errorf("failed to dial: %w", err)
  471. }
  472. addr = rawConn.RemoteAddr().String()
  473. // It's never actually used.
  474. _ = rawConn.Close()
  475. // Avoid spending time on probing if this upstream only supports HTTP/3.
  476. if doh.supportsH3() && !doh.supportsHTTP() {
  477. return addr, nil
  478. }
  479. // Use a new *tls.Config with empty session cache for probe connections.
  480. // Surprisingly, this is really important since otherwise it invalidates
  481. // the existing cache.
  482. // TODO(ameshkov): figure out why the sessions cache invalidates here.
  483. probeTLSCfg := tlsConfig.Clone()
  484. probeTLSCfg.ClientSessionCache = nil
  485. // Do not expose probe connections to the callbacks that are passed to
  486. // the bootstrap options to avoid side-effects.
  487. // TODO(ameshkov): consider exposing, somehow mark that this is a probe.
  488. probeTLSCfg.VerifyPeerCertificate = nil
  489. probeTLSCfg.VerifyConnection = nil
  490. // Run probeQUIC and probeTLS in parallel and see which one is faster.
  491. chQuic := make(chan error, 1)
  492. chTLS := make(chan error, 1)
  493. go doh.probeQUIC(ctx, addr, probeTLSCfg, chQuic)
  494. go doh.probeTLS(ctx, probeTLSCfg, chTLS)
  495. select {
  496. case quicErr := <-chQuic:
  497. if quicErr != nil {
  498. // QUIC failed, return error since HTTP3 was not preferred.
  499. return "", quicErr
  500. }
  501. // Return immediately, QUIC was faster.
  502. return addr, quicErr
  503. case tlsErr := <-chTLS:
  504. if tlsErr != nil {
  505. // Return immediately, TLS failed.
  506. log.Debugln("probing TLS: %v", tlsErr)
  507. return addr, nil
  508. }
  509. return "", errors.New("TLS was faster than QUIC, prefer it")
  510. }
  511. }
  512. // probeQUIC attempts to establish a QUIC connection to the specified address.
  513. // We run probeQUIC and probeTLS in parallel and see which one is faster.
  514. func (doh *dnsOverHTTPS) probeQUIC(ctx context.Context, addr string, tlsConfig *tls.Config, ch chan error) {
  515. startTime := time.Now()
  516. conn, err := doh.dialQuic(ctx, addr, tlsConfig, doh.getQUICConfig())
  517. if err != nil {
  518. ch <- fmt.Errorf("opening QUIC connection to %s: %w", doh.Address(), err)
  519. return
  520. }
  521. // Ignore the error since there's no way we can use it for anything useful.
  522. _ = conn.CloseWithError(QUICCodeNoError, "")
  523. ch <- nil
  524. elapsed := time.Now().Sub(startTime)
  525. log.Debugln("elapsed on establishing a QUIC connection: %s", elapsed)
  526. }
  527. // probeTLS attempts to establish a TLS connection to the specified address. We
  528. // run probeQUIC and probeTLS in parallel and see which one is faster.
  529. func (doh *dnsOverHTTPS) probeTLS(ctx context.Context, tlsConfig *tls.Config, ch chan error) {
  530. startTime := time.Now()
  531. conn, err := doh.tlsDial(ctx, "tcp", tlsConfig)
  532. if err != nil {
  533. ch <- fmt.Errorf("opening TLS connection: %w", err)
  534. return
  535. }
  536. // Ignore the error since there's no way we can use it for anything useful.
  537. _ = conn.Close()
  538. ch <- nil
  539. elapsed := time.Now().Sub(startTime)
  540. log.Debugln("elapsed on establishing a TLS connection: %s", elapsed)
  541. }
  542. // supportsH3 returns true if HTTP/3 is supported by this upstream.
  543. func (doh *dnsOverHTTPS) supportsH3() (ok bool) {
  544. for _, v := range doh.supportedHTTPVersions() {
  545. if v == C.HTTPVersion3 {
  546. return true
  547. }
  548. }
  549. return false
  550. }
  551. // supportsHTTP returns true if HTTP/1.1 or HTTP2 is supported by this upstream.
  552. func (doh *dnsOverHTTPS) supportsHTTP() (ok bool) {
  553. for _, v := range doh.supportedHTTPVersions() {
  554. if v == C.HTTPVersion11 || v == C.HTTPVersion2 {
  555. return true
  556. }
  557. }
  558. return false
  559. }
  560. // supportedHTTPVersions returns the list of supported HTTP versions.
  561. func (doh *dnsOverHTTPS) supportedHTTPVersions() (v []C.HTTPVersion) {
  562. v = doh.httpVersions
  563. if v == nil {
  564. v = DefaultHTTPVersions
  565. }
  566. return v
  567. }
  568. // isHTTP3 checks if the *http.Client is an HTTP/3 client.
  569. func isHTTP3(client *http.Client) (ok bool) {
  570. _, ok = client.Transport.(*http3Transport)
  571. return ok
  572. }
  573. // tlsDial is basically the same as tls.DialWithDialer, but we will call our own
  574. // dialContext function to get connection.
  575. func (doh *dnsOverHTTPS) tlsDial(ctx context.Context, network string, config *tls.Config) (*tls.Conn, error) {
  576. // We're using bootstrapped address instead of what's passed
  577. // to the function.
  578. rawConn, err := doh.dialer.DialContext(ctx, network, doh.url.Host)
  579. if err != nil {
  580. return nil, err
  581. }
  582. // We want the timeout to cover the whole process: TCP connection and
  583. // TLS handshake dialTimeout will be used as connection deadLine.
  584. conn := tls.Client(rawConn, config)
  585. err = conn.SetDeadline(time.Now().Add(dialTimeout))
  586. if err != nil {
  587. // Must not happen in normal circumstances.
  588. log.Errorln("cannot set deadline: %v", err)
  589. return nil, err
  590. }
  591. err = conn.Handshake()
  592. if err != nil {
  593. defer conn.Close()
  594. return nil, err
  595. }
  596. return conn, nil
  597. }