• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/dns/dns_transaction.h"
6 
7 #include <cstdint>
8 #include <memory>
9 #include <set>
10 #include <string>
11 #include <unordered_map>
12 #include <utility>
13 #include <vector>
14 
15 #include "base/base64url.h"
16 #include "base/big_endian.h"
17 #include "base/containers/circular_deque.h"
18 #include "base/containers/span.h"
19 #include "base/functional/bind.h"
20 #include "base/functional/callback_helpers.h"
21 #include "base/location.h"
22 #include "base/memory/ptr_util.h"
23 #include "base/memory/raw_ptr.h"
24 #include "base/memory/ref_counted.h"
25 #include "base/memory/safe_ref.h"
26 #include "base/memory/weak_ptr.h"
27 #include "base/metrics/histogram_functions.h"
28 #include "base/metrics/histogram_macros.h"
29 #include "base/rand_util.h"
30 #include "base/ranges/algorithm.h"
31 #include "base/strings/string_piece.h"
32 #include "base/strings/stringprintf.h"
33 #include "base/task/sequenced_task_runner.h"
34 #include "base/task/single_thread_task_runner.h"
35 #include "base/threading/thread_checker.h"
36 #include "base/timer/elapsed_timer.h"
37 #include "base/timer/timer.h"
38 #include "base/values.h"
39 #include "build/build_config.h"
40 #include "net/base/backoff_entry.h"
41 #include "net/base/completion_once_callback.h"
42 #include "net/base/elements_upload_data_stream.h"
43 #include "net/base/idempotency.h"
44 #include "net/base/io_buffer.h"
45 #include "net/base/ip_address.h"
46 #include "net/base/ip_endpoint.h"
47 #include "net/base/load_flags.h"
48 #include "net/base/net_errors.h"
49 #include "net/base/upload_bytes_element_reader.h"
50 #include "net/dns/dns_config.h"
51 #include "net/dns/dns_names_util.h"
52 #include "net/dns/dns_query.h"
53 #include "net/dns/dns_response.h"
54 #include "net/dns/dns_response_result_extractor.h"
55 #include "net/dns/dns_server_iterator.h"
56 #include "net/dns/dns_session.h"
57 #include "net/dns/dns_udp_tracker.h"
58 #include "net/dns/dns_util.h"
59 #include "net/dns/host_cache.h"
60 #include "net/dns/host_resolver_internal_result.h"
61 #include "net/dns/public/dns_over_https_config.h"
62 #include "net/dns/public/dns_over_https_server_config.h"
63 #include "net/dns/public/dns_protocol.h"
64 #include "net/dns/public/dns_query_type.h"
65 #include "net/dns/public/secure_dns_policy.h"
66 #include "net/dns/resolve_context.h"
67 #include "net/http/http_request_headers.h"
68 #include "net/log/net_log.h"
69 #include "net/log/net_log_capture_mode.h"
70 #include "net/log/net_log_event_type.h"
71 #include "net/log/net_log_source.h"
72 #include "net/log/net_log_values.h"
73 #include "net/log/net_log_with_source.h"
74 #include "net/socket/client_socket_factory.h"
75 #include "net/socket/datagram_client_socket.h"
76 #include "net/socket/stream_socket.h"
77 #include "net/third_party/uri_template/uri_template.h"
78 #include "net/traffic_annotation/network_traffic_annotation.h"
79 #include "net/url_request/url_request.h"
80 #include "net/url_request/url_request_context.h"
81 #include "net/url_request/url_request_context_builder.h"
82 #include "third_party/abseil-cpp/absl/types/optional.h"
83 #include "url/url_constants.h"
84 
85 namespace net {
86 
87 namespace {
88 
89 constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation =
90     net::DefineNetworkTrafficAnnotation("dns_transaction", R"(
91         semantics {
92           sender: "DNS Transaction"
93           description:
94             "DNS Transaction implements a stub DNS resolver as defined in RFC "
95             "1034."
96           trigger:
97             "Any network request that may require DNS resolution, including "
98             "navigations, connecting to a proxy server, detecting proxy "
99             "settings, getting proxy config, certificate checking, and more."
100           data:
101             "Domain name that needs resolution."
102           destination: OTHER
103           destination_other:
104             "The connection is made to a DNS server based on user's network "
105             "settings."
106         }
107         policy {
108           cookies_allowed: NO
109           setting:
110             "This feature cannot be disabled. Without DNS Transactions Chrome "
111             "cannot resolve host names."
112           policy_exception_justification:
113             "Essential for Chrome's navigation."
114         })");
115 
116 const char kDnsOverHttpResponseContentType[] = "application/dns-message";
117 
118 // The maximum size of the DNS message for DoH, per
119 // https://datatracker.ietf.org/doc/html/rfc8484#section-6
120 const int64_t kDnsOverHttpResponseMaximumSize = 65535;
121 
122 // Count labels in the fully-qualified name in DNS format.
CountLabels(base::span<const uint8_t> name)123 int CountLabels(base::span<const uint8_t> name) {
124   size_t count = 0;
125   for (size_t i = 0; i < name.size() && name[i]; i += name[i] + 1)
126     ++count;
127   return count;
128 }
129 
IsIPLiteral(const std::string & hostname)130 bool IsIPLiteral(const std::string& hostname) {
131   IPAddress ip;
132   return ip.AssignFromIPLiteral(hostname);
133 }
134 
NetLogStartParams(const std::string & hostname,uint16_t qtype)135 base::Value::Dict NetLogStartParams(const std::string& hostname,
136                                     uint16_t qtype) {
137   base::Value::Dict dict;
138   dict.Set("hostname", hostname);
139   dict.Set("query_type", qtype);
140   return dict;
141 }
142 
143 // ----------------------------------------------------------------------------
144 
145 // A single asynchronous DNS exchange, which consists of sending out a
146 // DNS query, waiting for a response, and returning the response that it
147 // matches. Logging is done in the socket and in the outer DnsTransaction.
148 class DnsAttempt {
149  public:
DnsAttempt(size_t server_index)150   explicit DnsAttempt(size_t server_index) : server_index_(server_index) {}
151 
152   DnsAttempt(const DnsAttempt&) = delete;
153   DnsAttempt& operator=(const DnsAttempt&) = delete;
154 
155   virtual ~DnsAttempt() = default;
156   // Starts the attempt. Returns ERR_IO_PENDING if cannot complete synchronously
157   // and calls |callback| upon completion.
158   virtual int Start(CompletionOnceCallback callback) = 0;
159 
160   // Returns the query of this attempt.
161   virtual const DnsQuery* GetQuery() const = 0;
162 
163   // Returns the response or NULL if has not received a matching response from
164   // the server.
165   virtual const DnsResponse* GetResponse() const = 0;
166 
167   virtual base::Value GetRawResponseBufferForLog() const = 0;
168 
169   // Returns the net log bound to the source of the socket.
170   virtual const NetLogWithSource& GetSocketNetLog() const = 0;
171 
172   // Returns the index of the destination server within DnsConfig::nameservers
173   // (or DnsConfig::dns_over_https_servers for secure transactions).
server_index() const174   size_t server_index() const { return server_index_; }
175 
176   // Returns a Value representing the received response, along with a reference
177   // to the NetLog source source of the UDP socket used.  The request must have
178   // completed before this is called.
NetLogResponseParams(NetLogCaptureMode capture_mode) const179   base::Value::Dict NetLogResponseParams(NetLogCaptureMode capture_mode) const {
180     base::Value::Dict dict;
181 
182     if (GetResponse()) {
183       DCHECK(GetResponse()->IsValid());
184       dict.Set("rcode", GetResponse()->rcode());
185       dict.Set("answer_count", static_cast<int>(GetResponse()->answer_count()));
186       dict.Set("additional_answer_count",
187                static_cast<int>(GetResponse()->additional_answer_count()));
188     }
189 
190     GetSocketNetLog().source().AddToEventParameters(dict);
191 
192     if (capture_mode == NetLogCaptureMode::kEverything) {
193       dict.Set("response_buffer", GetRawResponseBufferForLog());
194     }
195 
196     return dict;
197   }
198 
199   // True if current attempt is pending (waiting for server response).
200   virtual bool IsPending() const = 0;
201 
202  private:
203   const size_t server_index_;
204 };
205 
206 class DnsUDPAttempt : public DnsAttempt {
207  public:
DnsUDPAttempt(size_t server_index,std::unique_ptr<DatagramClientSocket> socket,const IPEndPoint & server,std::unique_ptr<DnsQuery> query,DnsUdpTracker * udp_tracker)208   DnsUDPAttempt(size_t server_index,
209                 std::unique_ptr<DatagramClientSocket> socket,
210                 const IPEndPoint& server,
211                 std::unique_ptr<DnsQuery> query,
212                 DnsUdpTracker* udp_tracker)
213       : DnsAttempt(server_index),
214         socket_(std::move(socket)),
215         server_(server),
216         query_(std::move(query)),
217         udp_tracker_(udp_tracker) {}
218 
219   DnsUDPAttempt(const DnsUDPAttempt&) = delete;
220   DnsUDPAttempt& operator=(const DnsUDPAttempt&) = delete;
221 
222   // DnsAttempt methods.
223 
Start(CompletionOnceCallback callback)224   int Start(CompletionOnceCallback callback) override {
225     DCHECK_EQ(STATE_NONE, next_state_);
226     callback_ = std::move(callback);
227     start_time_ = base::TimeTicks::Now();
228     next_state_ = STATE_CONNECT_COMPLETE;
229 
230     int rv = socket_->ConnectAsync(
231         server_,
232         base::BindOnce(&DnsUDPAttempt::OnIOComplete, base::Unretained(this)));
233     if (rv == ERR_IO_PENDING) {
234       return rv;
235     }
236     return DoLoop(rv);
237   }
238 
GetQuery() const239   const DnsQuery* GetQuery() const override { return query_.get(); }
240 
GetResponse() const241   const DnsResponse* GetResponse() const override {
242     const DnsResponse* resp = response_.get();
243     return (resp != nullptr && resp->IsValid()) ? resp : nullptr;
244   }
245 
GetRawResponseBufferForLog() const246   base::Value GetRawResponseBufferForLog() const override {
247     if (!response_)
248       return base::Value();
249     return NetLogBinaryValue(response_->io_buffer()->data(), read_size_);
250   }
251 
GetSocketNetLog() const252   const NetLogWithSource& GetSocketNetLog() const override {
253     return socket_->NetLog();
254   }
255 
IsPending() const256   bool IsPending() const override { return next_state_ != STATE_NONE; }
257 
258  private:
259   enum State {
260     STATE_CONNECT_COMPLETE,
261     STATE_SEND_QUERY,
262     STATE_SEND_QUERY_COMPLETE,
263     STATE_READ_RESPONSE,
264     STATE_READ_RESPONSE_COMPLETE,
265     STATE_NONE,
266   };
267 
DoLoop(int result)268   int DoLoop(int result) {
269     CHECK_NE(STATE_NONE, next_state_);
270     int rv = result;
271     do {
272       State state = next_state_;
273       next_state_ = STATE_NONE;
274       switch (state) {
275         case STATE_CONNECT_COMPLETE:
276           rv = DoConnectComplete(rv);
277           break;
278         case STATE_SEND_QUERY:
279           rv = DoSendQuery(rv);
280           break;
281         case STATE_SEND_QUERY_COMPLETE:
282           rv = DoSendQueryComplete(rv);
283           break;
284         case STATE_READ_RESPONSE:
285           rv = DoReadResponse();
286           break;
287         case STATE_READ_RESPONSE_COMPLETE:
288           rv = DoReadResponseComplete(rv);
289           break;
290         default:
291           NOTREACHED();
292           break;
293       }
294     } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
295 
296     if (rv != ERR_IO_PENDING)
297       DCHECK_EQ(STATE_NONE, next_state_);
298 
299     return rv;
300   }
301 
DoConnectComplete(int rv)302   int DoConnectComplete(int rv) {
303     if (rv != OK) {
304       DVLOG(1) << "Failed to connect socket: " << rv;
305       udp_tracker_->RecordConnectionError(rv);
306       return ERR_CONNECTION_REFUSED;
307     }
308     next_state_ = STATE_SEND_QUERY;
309     IPEndPoint local_address;
310     if (socket_->GetLocalAddress(&local_address) == OK)
311       udp_tracker_->RecordQuery(local_address.port(), query_->id());
312     return OK;
313   }
314 
DoSendQuery(int rv)315   int DoSendQuery(int rv) {
316     DCHECK_NE(ERR_IO_PENDING, rv);
317     if (rv < 0)
318       return rv;
319     next_state_ = STATE_SEND_QUERY_COMPLETE;
320     return socket_->Write(
321         query_->io_buffer(), query_->io_buffer()->size(),
322         base::BindOnce(&DnsUDPAttempt::OnIOComplete, base::Unretained(this)),
323         kTrafficAnnotation);
324   }
325 
DoSendQueryComplete(int rv)326   int DoSendQueryComplete(int rv) {
327     DCHECK_NE(ERR_IO_PENDING, rv);
328     if (rv < 0)
329       return rv;
330 
331     // Writing to UDP should not result in a partial datagram.
332     if (rv != query_->io_buffer()->size())
333       return ERR_MSG_TOO_BIG;
334 
335     next_state_ = STATE_READ_RESPONSE;
336     return OK;
337   }
338 
DoReadResponse()339   int DoReadResponse() {
340     next_state_ = STATE_READ_RESPONSE_COMPLETE;
341     response_ = std::make_unique<DnsResponse>();
342     return socket_->Read(
343         response_->io_buffer(), response_->io_buffer_size(),
344         base::BindOnce(&DnsUDPAttempt::OnIOComplete, base::Unretained(this)));
345   }
346 
DoReadResponseComplete(int rv)347   int DoReadResponseComplete(int rv) {
348     DCHECK_NE(ERR_IO_PENDING, rv);
349     if (rv < 0)
350       return rv;
351     read_size_ = rv;
352 
353     bool parse_result = response_->InitParse(rv, *query_);
354     if (response_->id())
355       udp_tracker_->RecordResponseId(query_->id(), response_->id().value());
356 
357     if (!parse_result)
358       return ERR_DNS_MALFORMED_RESPONSE;
359     if (response_->flags() & dns_protocol::kFlagTC)
360       return ERR_DNS_SERVER_REQUIRES_TCP;
361     if (response_->rcode() == dns_protocol::kRcodeNXDOMAIN)
362       return ERR_NAME_NOT_RESOLVED;
363     if (response_->rcode() != dns_protocol::kRcodeNOERROR)
364       return ERR_DNS_SERVER_FAILED;
365 
366     return OK;
367   }
368 
OnIOComplete(int rv)369   void OnIOComplete(int rv) {
370     rv = DoLoop(rv);
371     if (rv != ERR_IO_PENDING)
372       std::move(callback_).Run(rv);
373   }
374 
375   State next_state_ = STATE_NONE;
376   base::TimeTicks start_time_;
377 
378   std::unique_ptr<DatagramClientSocket> socket_;
379   IPEndPoint server_;
380   std::unique_ptr<DnsQuery> query_;
381 
382   // Should be owned by the DnsSession, to which the transaction should own a
383   // reference.
384   const raw_ptr<DnsUdpTracker> udp_tracker_;
385 
386   std::unique_ptr<DnsResponse> response_;
387   int read_size_ = 0;
388 
389   CompletionOnceCallback callback_;
390 };
391 
392 class DnsHTTPAttempt : public DnsAttempt, public URLRequest::Delegate {
393  public:
DnsHTTPAttempt(size_t doh_server_index,std::unique_ptr<DnsQuery> query,const string & server_template,const GURL & gurl_without_parameters,bool use_post,URLRequestContext * url_request_context,const IsolationInfo & isolation_info,RequestPriority request_priority_,bool is_probe)394   DnsHTTPAttempt(size_t doh_server_index,
395                  std::unique_ptr<DnsQuery> query,
396                  const string& server_template,
397                  const GURL& gurl_without_parameters,
398                  bool use_post,
399                  URLRequestContext* url_request_context,
400                  const IsolationInfo& isolation_info,
401                  RequestPriority request_priority_,
402                  bool is_probe)
403       : DnsAttempt(doh_server_index),
404         query_(std::move(query)),
405         net_log_(NetLogWithSource::Make(NetLog::Get(),
406                                         NetLogSourceType::DNS_OVER_HTTPS)) {
407     GURL url;
408     if (use_post) {
409       // Set url for a POST request
410       url = gurl_without_parameters;
411     } else {
412       // Set url for a GET request
413       std::string url_string;
414       std::unordered_map<string, string> parameters;
415       std::string encoded_query;
416       base::Base64UrlEncode(base::StringPiece(query_->io_buffer()->data(),
417                                               query_->io_buffer()->size()),
418                             base::Base64UrlEncodePolicy::OMIT_PADDING,
419                             &encoded_query);
420       parameters.emplace("dns", encoded_query);
421       uri_template::Expand(server_template, parameters, &url_string);
422       url = GURL(url_string);
423     }
424 
425     net_log_.BeginEvent(NetLogEventType::DOH_URL_REQUEST, [&] {
426       if (is_probe) {
427         return NetLogStartParams("(probe)", query_->qtype());
428       }
429       absl::optional<std::string> hostname =
430           dns_names_util::NetworkToDottedName(query_->qname());
431       DCHECK(hostname.has_value());
432       return NetLogStartParams(*hostname, query_->qtype());
433     });
434 
435     HttpRequestHeaders extra_request_headers;
436     extra_request_headers.SetHeader(HttpRequestHeaders::kAccept,
437                                     kDnsOverHttpResponseContentType);
438     // Send minimal request headers where possible.
439     extra_request_headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "*");
440     extra_request_headers.SetHeader(HttpRequestHeaders::kUserAgent, "Chrome");
441     extra_request_headers.SetHeader(HttpRequestHeaders::kAcceptEncoding,
442                                     "identity");
443 
444     DCHECK(url_request_context);
445     request_ = url_request_context->CreateRequest(
446         url, request_priority_, this,
447         net::DefineNetworkTrafficAnnotation("dns_over_https", R"(
448         semantics {
449           sender: "DNS over HTTPS"
450           description: "Domain name resolution over HTTPS"
451           trigger: "User enters a navigates to a domain or Chrome otherwise "
452                    "makes a connection to a domain whose IP address isn't cached"
453           data: "The domain name that is being requested"
454           destination: OTHER
455           destination_other: "The user configured DNS over HTTPS server, which"
456                              "may be dns.google.com"
457         }
458         policy {
459           cookies_allowed: NO
460           setting:
461             "You can configure this feature via that 'dns_over_https_servers' and"
462             "'dns_over_https.method' prefs. Empty lists imply this feature is"
463             "disabled"
464           policy_exception_justification: "Experimental feature that"
465                                           "is disabled by default"
466         }
467       )"),
468         /*is_for_websockets=*/false, net_log_.source());
469 
470     if (use_post) {
471       request_->set_method("POST");
472       request_->SetIdempotency(IDEMPOTENT);
473       std::unique_ptr<UploadElementReader> reader =
474           std::make_unique<UploadBytesElementReader>(
475               query_->io_buffer()->data(), query_->io_buffer()->size());
476       request_->set_upload(
477           ElementsUploadDataStream::CreateWithReader(std::move(reader), 0));
478       extra_request_headers.SetHeader(HttpRequestHeaders::kContentType,
479                                       kDnsOverHttpResponseContentType);
480     }
481 
482     request_->SetExtraRequestHeaders(extra_request_headers);
483     // Apply special policy to DNS lookups for for a DoH server hostname to
484     // avoid deadlock and enable the use of preconfigured IP addresses.
485     request_->SetSecureDnsPolicy(SecureDnsPolicy::kBootstrap);
486     request_->SetLoadFlags(request_->load_flags() | LOAD_DISABLE_CACHE |
487                            LOAD_BYPASS_PROXY);
488     request_->set_allow_credentials(false);
489     request_->set_isolation_info(isolation_info);
490   }
491 
492   DnsHTTPAttempt(const DnsHTTPAttempt&) = delete;
493   DnsHTTPAttempt& operator=(const DnsHTTPAttempt&) = delete;
494 
495   // DnsAttempt overrides.
496 
497   int Start(CompletionOnceCallback callback) override {
498     callback_ = std::move(callback);
499     // Start the request asynchronously to avoid reentrancy in
500     // the network stack.
501     base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
502         FROM_HERE, base::BindOnce(&DnsHTTPAttempt::StartAsync,
503                                   weak_factory_.GetWeakPtr()));
504     return ERR_IO_PENDING;
505   }
506 
507   const DnsQuery* GetQuery() const override { return query_.get(); }
508   const DnsResponse* GetResponse() const override {
509     const DnsResponse* resp = response_.get();
510     return (resp != nullptr && resp->IsValid()) ? resp : nullptr;
511   }
512   base::Value GetRawResponseBufferForLog() const override {
513     if (!response_)
514       return base::Value();
515 
516     return NetLogBinaryValue(response_->io_buffer()->data(),
517                              response_->io_buffer_size());
518   }
519   const NetLogWithSource& GetSocketNetLog() const override { return net_log_; }
520 
521   // URLRequest::Delegate overrides
522 
523   void OnResponseStarted(net::URLRequest* request, int net_error) override {
524     DCHECK_NE(net::ERR_IO_PENDING, net_error);
525     std::string content_type;
526     if (net_error != OK) {
527       // Update the error code if there was an issue resolving the secure
528       // server hostname.
529       if (IsHostnameResolutionError(net_error))
530         net_error = ERR_DNS_SECURE_RESOLVER_HOSTNAME_RESOLUTION_FAILED;
531       ResponseCompleted(net_error);
532       return;
533     }
534 
535     if (request_->GetResponseCode() != 200 ||
536         !request->response_headers()->GetMimeType(&content_type) ||
537         0 != content_type.compare(kDnsOverHttpResponseContentType)) {
538       ResponseCompleted(ERR_DNS_MALFORMED_RESPONSE);
539       return;
540     }
541 
542     buffer_ = base::MakeRefCounted<GrowableIOBuffer>();
543 
544     if (request->response_headers()->HasHeader(
545             HttpRequestHeaders::kContentLength)) {
546       if (request_->response_headers()->GetContentLength() >
547           kDnsOverHttpResponseMaximumSize) {
548         ResponseCompleted(ERR_DNS_MALFORMED_RESPONSE);
549         return;
550       }
551 
552       buffer_->SetCapacity(request_->response_headers()->GetContentLength() +
553                            1);
554     } else {
555       buffer_->SetCapacity(kDnsOverHttpResponseMaximumSize + 1);
556     }
557 
558     DCHECK(buffer_->data());
559     DCHECK_GT(buffer_->capacity(), 0);
560 
561     int bytes_read =
562         request_->Read(buffer_.get(), buffer_->RemainingCapacity());
563 
564     // If IO is pending, wait for the URLRequest to call OnReadCompleted.
565     if (bytes_read == net::ERR_IO_PENDING)
566       return;
567 
568     OnReadCompleted(request_.get(), bytes_read);
569   }
570 
571   void OnReceivedRedirect(URLRequest* request,
572                           const RedirectInfo& redirect_info,
573                           bool* defer_redirect) override {
574     // Section 5 of RFC 8484 states that scheme must be https.
575     if (!redirect_info.new_url.SchemeIs(url::kHttpsScheme)) {
576       request->Cancel();
577     }
578   }
579 
580   void OnReadCompleted(net::URLRequest* request, int bytes_read) override {
581     // bytes_read can be an error.
582     if (bytes_read < 0) {
583       ResponseCompleted(bytes_read);
584       return;
585     }
586 
587     DCHECK_GE(bytes_read, 0);
588 
589     if (bytes_read > 0) {
590       if (buffer_->offset() + bytes_read > kDnsOverHttpResponseMaximumSize) {
591         ResponseCompleted(ERR_DNS_MALFORMED_RESPONSE);
592         return;
593       }
594 
595       buffer_->set_offset(buffer_->offset() + bytes_read);
596 
597       if (buffer_->RemainingCapacity() == 0) {
598         buffer_->SetCapacity(buffer_->capacity() + 16384);  // Grow by 16kb.
599       }
600 
601       DCHECK(buffer_->data());
602       DCHECK_GT(buffer_->capacity(), 0);
603 
604       int read_result =
605           request_->Read(buffer_.get(), buffer_->RemainingCapacity());
606 
607       // If IO is pending, wait for the URLRequest to call OnReadCompleted.
608       if (read_result == net::ERR_IO_PENDING)
609         return;
610 
611       if (read_result <= 0) {
612         OnReadCompleted(request_.get(), read_result);
613       } else {
614         // Else, trigger OnReadCompleted asynchronously to avoid starving the IO
615         // thread in case the URLRequest can provide data synchronously.
616         base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
617             FROM_HERE, base::BindOnce(&DnsHTTPAttempt::OnReadCompleted,
618                                       weak_factory_.GetWeakPtr(),
619                                       request_.get(), read_result));
620       }
621     } else {
622       // URLRequest reported an EOF. Call ResponseCompleted.
623       DCHECK_EQ(0, bytes_read);
624       ResponseCompleted(net::OK);
625     }
626   }
627 
628   bool IsPending() const override { return !callback_.is_null(); }
629 
630  private:
631   void StartAsync() {
632     DCHECK(request_);
633     request_->Start();
634   }
635 
636   void ResponseCompleted(int net_error) {
637     request_.reset();
638     std::move(callback_).Run(CompleteResponse(net_error));
639   }
640 
641   int CompleteResponse(int net_error) {
642     net_log_.EndEventWithNetErrorCode(NetLogEventType::DOH_URL_REQUEST,
643                                       net_error);
644     DCHECK_NE(net::ERR_IO_PENDING, net_error);
645     if (net_error != OK) {
646       return net_error;
647     }
648     if (!buffer_.get() || 0 == buffer_->capacity())
649       return ERR_DNS_MALFORMED_RESPONSE;
650 
651     size_t size = buffer_->offset();
652     buffer_->set_offset(0);
653     if (size == 0u)
654       return ERR_DNS_MALFORMED_RESPONSE;
655     response_ = std::make_unique<DnsResponse>(buffer_, size);
656     if (!response_->InitParse(size, *query_))
657       return ERR_DNS_MALFORMED_RESPONSE;
658     if (response_->rcode() == dns_protocol::kRcodeNXDOMAIN)
659       return ERR_NAME_NOT_RESOLVED;
660     if (response_->rcode() != dns_protocol::kRcodeNOERROR)
661       return ERR_DNS_SERVER_FAILED;
662     return OK;
663   }
664 
665   scoped_refptr<GrowableIOBuffer> buffer_;
666   std::unique_ptr<DnsQuery> query_;
667   CompletionOnceCallback callback_;
668   std::unique_ptr<DnsResponse> response_;
669   std::unique_ptr<URLRequest> request_;
670   NetLogWithSource net_log_;
671 
672   base::WeakPtrFactory<DnsHTTPAttempt> weak_factory_{this};
673 };
674 
675 void ConstructDnsHTTPAttempt(DnsSession* session,
676                              size_t doh_server_index,
677                              base::span<const uint8_t> qname,
678                              uint16_t qtype,
679                              const OptRecordRdata* opt_rdata,
680                              std::vector<std::unique_ptr<DnsAttempt>>* attempts,
681                              URLRequestContext* url_request_context,
682                              const IsolationInfo& isolation_info,
683                              RequestPriority request_priority,
684                              bool is_probe) {
685   DCHECK(url_request_context);
686 
687   std::unique_ptr<DnsQuery> query;
688   if (attempts->empty()) {
689     query =
690         std::make_unique<DnsQuery>(/*id=*/0, qname, qtype, opt_rdata,
691                                    DnsQuery::PaddingStrategy::BLOCK_LENGTH_128);
692   } else {
693     query = std::make_unique<DnsQuery>(*attempts->at(0)->GetQuery());
694   }
695 
696   DCHECK_LT(doh_server_index, session->config().doh_config.servers().size());
697   const DnsOverHttpsServerConfig& doh_server =
698       session->config().doh_config.servers()[doh_server_index];
699   GURL gurl_without_parameters(
700       GetURLFromTemplateWithoutParameters(doh_server.server_template()));
701   attempts->push_back(std::make_unique<DnsHTTPAttempt>(
702       doh_server_index, std::move(query), doh_server.server_template(),
703       gurl_without_parameters, doh_server.use_post(), url_request_context,
704       isolation_info, request_priority, is_probe));
705 }
706 
707 class DnsTCPAttempt : public DnsAttempt {
708  public:
709   DnsTCPAttempt(size_t server_index,
710                 std::unique_ptr<StreamSocket> socket,
711                 std::unique_ptr<DnsQuery> query)
712       : DnsAttempt(server_index),
713         socket_(std::move(socket)),
714         query_(std::move(query)),
715         length_buffer_(
716             base::MakeRefCounted<IOBufferWithSize>(sizeof(uint16_t))) {}
717 
718   DnsTCPAttempt(const DnsTCPAttempt&) = delete;
719   DnsTCPAttempt& operator=(const DnsTCPAttempt&) = delete;
720 
721   // DnsAttempt:
722   int Start(CompletionOnceCallback callback) override {
723     DCHECK_EQ(STATE_NONE, next_state_);
724     callback_ = std::move(callback);
725     start_time_ = base::TimeTicks::Now();
726     next_state_ = STATE_CONNECT_COMPLETE;
727     int rv = socket_->Connect(
728         base::BindOnce(&DnsTCPAttempt::OnIOComplete, base::Unretained(this)));
729     if (rv == ERR_IO_PENDING) {
730       return rv;
731     }
732     return DoLoop(rv);
733   }
734 
735   const DnsQuery* GetQuery() const override { return query_.get(); }
736 
737   const DnsResponse* GetResponse() const override {
738     const DnsResponse* resp = response_.get();
739     return (resp != nullptr && resp->IsValid()) ? resp : nullptr;
740   }
741 
742   base::Value GetRawResponseBufferForLog() const override {
743     if (!response_)
744       return base::Value();
745 
746     return NetLogBinaryValue(response_->io_buffer()->data(),
747                              response_->io_buffer_size());
748   }
749 
750   const NetLogWithSource& GetSocketNetLog() const override {
751     return socket_->NetLog();
752   }
753 
754   bool IsPending() const override { return next_state_ != STATE_NONE; }
755 
756  private:
757   enum State {
758     STATE_CONNECT_COMPLETE,
759     STATE_SEND_LENGTH,
760     STATE_SEND_QUERY,
761     STATE_READ_LENGTH,
762     STATE_READ_LENGTH_COMPLETE,
763     STATE_READ_RESPONSE,
764     STATE_READ_RESPONSE_COMPLETE,
765     STATE_NONE,
766   };
767 
768   int DoLoop(int result) {
769     CHECK_NE(STATE_NONE, next_state_);
770     int rv = result;
771     do {
772       State state = next_state_;
773       next_state_ = STATE_NONE;
774       switch (state) {
775         case STATE_CONNECT_COMPLETE:
776           rv = DoConnectComplete(rv);
777           break;
778         case STATE_SEND_LENGTH:
779           rv = DoSendLength(rv);
780           break;
781         case STATE_SEND_QUERY:
782           rv = DoSendQuery(rv);
783           break;
784         case STATE_READ_LENGTH:
785           rv = DoReadLength(rv);
786           break;
787         case STATE_READ_LENGTH_COMPLETE:
788           rv = DoReadLengthComplete(rv);
789           break;
790         case STATE_READ_RESPONSE:
791           rv = DoReadResponse(rv);
792           break;
793         case STATE_READ_RESPONSE_COMPLETE:
794           rv = DoReadResponseComplete(rv);
795           break;
796         default:
797           NOTREACHED();
798           break;
799       }
800     } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
801 
802     if (rv != ERR_IO_PENDING)
803       DCHECK_EQ(STATE_NONE, next_state_);
804 
805     return rv;
806   }
807 
808   int DoConnectComplete(int rv) {
809     DCHECK_NE(ERR_IO_PENDING, rv);
810     if (rv < 0)
811       return rv;
812 
813     uint16_t query_size = static_cast<uint16_t>(query_->io_buffer()->size());
814     if (static_cast<int>(query_size) != query_->io_buffer()->size())
815       return ERR_FAILED;
816     base::WriteBigEndian<uint16_t>(length_buffer_->data(), query_size);
817     buffer_ = base::MakeRefCounted<DrainableIOBuffer>(length_buffer_,
818                                                       length_buffer_->size());
819     next_state_ = STATE_SEND_LENGTH;
820     return OK;
821   }
822 
823   int DoSendLength(int rv) {
824     DCHECK_NE(ERR_IO_PENDING, rv);
825     if (rv < 0)
826       return rv;
827 
828     buffer_->DidConsume(rv);
829     if (buffer_->BytesRemaining() > 0) {
830       next_state_ = STATE_SEND_LENGTH;
831       return socket_->Write(
832           buffer_.get(), buffer_->BytesRemaining(),
833           base::BindOnce(&DnsTCPAttempt::OnIOComplete, base::Unretained(this)),
834           kTrafficAnnotation);
835     }
836     buffer_ = base::MakeRefCounted<DrainableIOBuffer>(
837         query_->io_buffer(), query_->io_buffer()->size());
838     next_state_ = STATE_SEND_QUERY;
839     return OK;
840   }
841 
842   int DoSendQuery(int rv) {
843     DCHECK_NE(ERR_IO_PENDING, rv);
844     if (rv < 0)
845       return rv;
846 
847     buffer_->DidConsume(rv);
848     if (buffer_->BytesRemaining() > 0) {
849       next_state_ = STATE_SEND_QUERY;
850       return socket_->Write(
851           buffer_.get(), buffer_->BytesRemaining(),
852           base::BindOnce(&DnsTCPAttempt::OnIOComplete, base::Unretained(this)),
853           kTrafficAnnotation);
854     }
855     buffer_ = base::MakeRefCounted<DrainableIOBuffer>(length_buffer_,
856                                                       length_buffer_->size());
857     next_state_ = STATE_READ_LENGTH;
858     return OK;
859   }
860 
861   int DoReadLength(int rv) {
862     DCHECK_EQ(OK, rv);
863 
864     next_state_ = STATE_READ_LENGTH_COMPLETE;
865     return ReadIntoBuffer();
866   }
867 
868   int DoReadLengthComplete(int rv) {
869     DCHECK_NE(ERR_IO_PENDING, rv);
870     if (rv < 0)
871       return rv;
872     if (rv == 0)
873       return ERR_CONNECTION_CLOSED;
874 
875     buffer_->DidConsume(rv);
876     if (buffer_->BytesRemaining() > 0) {
877       next_state_ = STATE_READ_LENGTH;
878       return OK;
879     }
880 
881     base::ReadBigEndian(
882         reinterpret_cast<const uint8_t*>(length_buffer_->data()),
883         &response_length_);
884     // Check if advertised response is too short. (Optimization only.)
885     if (response_length_ < query_->io_buffer()->size())
886       return ERR_DNS_MALFORMED_RESPONSE;
887     response_ = std::make_unique<DnsResponse>(response_length_);
888     buffer_ = base::MakeRefCounted<DrainableIOBuffer>(response_->io_buffer(),
889                                                       response_length_);
890     next_state_ = STATE_READ_RESPONSE;
891     return OK;
892   }
893 
894   int DoReadResponse(int rv) {
895     DCHECK_EQ(OK, rv);
896 
897     next_state_ = STATE_READ_RESPONSE_COMPLETE;
898     return ReadIntoBuffer();
899   }
900 
901   int DoReadResponseComplete(int rv) {
902     DCHECK_NE(ERR_IO_PENDING, rv);
903     if (rv < 0)
904       return rv;
905     if (rv == 0)
906       return ERR_CONNECTION_CLOSED;
907 
908     buffer_->DidConsume(rv);
909     if (buffer_->BytesRemaining() > 0) {
910       next_state_ = STATE_READ_RESPONSE;
911       return OK;
912     }
913     DCHECK_GT(buffer_->BytesConsumed(), 0);
914     if (!response_->InitParse(buffer_->BytesConsumed(), *query_))
915       return ERR_DNS_MALFORMED_RESPONSE;
916     if (response_->flags() & dns_protocol::kFlagTC)
917       return ERR_UNEXPECTED;
918     // TODO(szym): Frankly, none of these are expected.
919     if (response_->rcode() == dns_protocol::kRcodeNXDOMAIN)
920       return ERR_NAME_NOT_RESOLVED;
921     if (response_->rcode() != dns_protocol::kRcodeNOERROR)
922       return ERR_DNS_SERVER_FAILED;
923 
924     return OK;
925   }
926 
927   void OnIOComplete(int rv) {
928     rv = DoLoop(rv);
929     if (rv != ERR_IO_PENDING)
930       std::move(callback_).Run(rv);
931   }
932 
933   int ReadIntoBuffer() {
934     return socket_->Read(
935         buffer_.get(), buffer_->BytesRemaining(),
936         base::BindOnce(&DnsTCPAttempt::OnIOComplete, base::Unretained(this)));
937   }
938 
939   State next_state_ = STATE_NONE;
940   base::TimeTicks start_time_;
941 
942   std::unique_ptr<StreamSocket> socket_;
943   std::unique_ptr<DnsQuery> query_;
944   scoped_refptr<IOBufferWithSize> length_buffer_;
945   scoped_refptr<DrainableIOBuffer> buffer_;
946 
947   uint16_t response_length_ = 0;
948   std::unique_ptr<DnsResponse> response_;
949 
950   CompletionOnceCallback callback_;
951 };
952 
953 // ----------------------------------------------------------------------------
954 
955 const net::BackoffEntry::Policy kProbeBackoffPolicy = {
956     // Apply exponential backoff rules after the first error.
957     0,
958     // Begin with a 1s delay between probes.
959     1000,
960     // Increase the delay between consecutive probes by a factor of 1.5.
961     1.5,
962     // Fuzz the delay between consecutive probes between 80%-100% of the
963     // calculated time.
964     0.2,
965     // Cap the maximum delay between consecutive probes at 1 hour.
966     1000 * 60 * 60,
967     // Never expire entries.
968     -1,
969     // Do not apply an initial delay.
970     false,
971 };
972 
973 // Probe runner that continually sends test queries (with backoff) to DoH
974 // servers to determine availability.
975 //
976 // Expected to be contained in request classes owned externally to HostResolver,
977 // so no assumptions are made regarding cancellation compared to the DnsSession
978 // or ResolveContext. Instead, uses WeakPtrs to gracefully clean itself up and
979 // stop probing after session or context destruction.
980 class DnsOverHttpsProbeRunner : public DnsProbeRunner {
981  public:
982   DnsOverHttpsProbeRunner(base::WeakPtr<DnsSession> session,
983                           base::WeakPtr<ResolveContext> context)
984       : session_(session), context_(context) {
985     DCHECK(session_);
986     DCHECK(!session_->config().doh_config.servers().empty());
987     DCHECK(context_);
988 
989     absl::optional<std::vector<uint8_t>> qname =
990         dns_names_util::DottedNameToNetwork(kDohProbeHostname);
991     DCHECK(qname.has_value());
992     formatted_probe_qname_ = std::move(qname).value();
993 
994     for (size_t i = 0; i < session_->config().doh_config.servers().size();
995          i++) {
996       probe_stats_list_.push_back(nullptr);
997     }
998   }
999 
1000   ~DnsOverHttpsProbeRunner() override = default;
1001 
1002   void Start(bool network_change) override {
1003     DCHECK(session_);
1004     DCHECK(context_);
1005 
1006     const auto& config = session_->config().doh_config;
1007     // Start probe sequences for any servers where it is not currently running.
1008     for (size_t i = 0; i < config.servers().size(); i++) {
1009       if (!probe_stats_list_[i]) {
1010         probe_stats_list_[i] = std::make_unique<ProbeStats>();
1011         ContinueProbe(i, probe_stats_list_[i]->weak_factory.GetWeakPtr(),
1012                       network_change,
1013                       base::TimeTicks::Now() /* sequence_start_time */);
1014       }
1015     }
1016   }
1017 
1018   base::TimeDelta GetDelayUntilNextProbeForTest(
1019       size_t doh_server_index) const override {
1020     if (doh_server_index >= probe_stats_list_.size() ||
1021         !probe_stats_list_[doh_server_index])
1022       return base::TimeDelta();
1023 
1024     return probe_stats_list_[doh_server_index]
1025         ->backoff_entry->GetTimeUntilRelease();
1026   }
1027 
1028  private:
1029   struct ProbeStats {
1030     ProbeStats()
1031         : backoff_entry(
1032               std::make_unique<net::BackoffEntry>(&kProbeBackoffPolicy)) {}
1033 
1034     std::unique_ptr<net::BackoffEntry> backoff_entry;
1035     std::vector<std::unique_ptr<DnsAttempt>> probe_attempts;
1036     base::WeakPtrFactory<ProbeStats> weak_factory{this};
1037   };
1038 
1039   void ContinueProbe(size_t doh_server_index,
1040                      base::WeakPtr<ProbeStats> probe_stats,
1041                      bool network_change,
1042                      base::TimeTicks sequence_start_time) {
1043     // If the DnsSession or ResolveContext has been destroyed, no reason to
1044     // continue probing.
1045     if (!session_ || !context_) {
1046       probe_stats_list_.clear();
1047       return;
1048     }
1049 
1050     // If the ProbeStats for which this probe was scheduled has been deleted,
1051     // don't continue to send probes.
1052     if (!probe_stats)
1053       return;
1054 
1055     // Cancel the probe sequence for this server if the server is already
1056     // available.
1057     if (context_->GetDohServerAvailability(doh_server_index, session_.get())) {
1058       probe_stats_list_[doh_server_index] = nullptr;
1059       return;
1060     }
1061 
1062     // Schedule a new probe assuming this one will fail. The newly scheduled
1063     // probe will not run if an earlier probe has already succeeded. Probes may
1064     // take awhile to fail, which is why we schedule the next one here rather
1065     // than on probe completion.
1066     DCHECK(probe_stats);
1067     DCHECK(probe_stats->backoff_entry);
1068     probe_stats->backoff_entry->InformOfRequest(false /* success */);
1069     base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
1070         FROM_HERE,
1071         base::BindOnce(&DnsOverHttpsProbeRunner::ContinueProbe,
1072                        weak_ptr_factory_.GetWeakPtr(), doh_server_index,
1073                        probe_stats, network_change, sequence_start_time),
1074         probe_stats->backoff_entry->GetTimeUntilRelease());
1075 
1076     unsigned attempt_number = probe_stats->probe_attempts.size();
1077     ConstructDnsHTTPAttempt(
1078         session_.get(), doh_server_index, formatted_probe_qname_,
1079         dns_protocol::kTypeA, /*opt_rdata=*/nullptr,
1080         &probe_stats->probe_attempts, context_->url_request_context(),
1081         context_->isolation_info(), RequestPriority::DEFAULT_PRIORITY,
1082         /*is_probe=*/true);
1083 
1084     DnsAttempt* probe_attempt = probe_stats->probe_attempts.back().get();
1085     probe_attempt->Start(base::BindOnce(
1086         &DnsOverHttpsProbeRunner::ProbeComplete, weak_ptr_factory_.GetWeakPtr(),
1087         attempt_number, doh_server_index, std::move(probe_stats),
1088         network_change, sequence_start_time,
1089         base::TimeTicks::Now() /* query_start_time */));
1090   }
1091 
ProbeComplete(unsigned attempt_number,size_t doh_server_index,base::WeakPtr<ProbeStats> probe_stats,bool network_change,base::TimeTicks sequence_start_time,base::TimeTicks query_start_time,int rv)1092   void ProbeComplete(unsigned attempt_number,
1093                      size_t doh_server_index,
1094                      base::WeakPtr<ProbeStats> probe_stats,
1095                      bool network_change,
1096                      base::TimeTicks sequence_start_time,
1097                      base::TimeTicks query_start_time,
1098                      int rv) {
1099     bool success = false;
1100     if (rv == OK && probe_stats && session_ && context_) {
1101       // Check that the response parses properly before considering it a
1102       // success.
1103       DCHECK_LT(attempt_number, probe_stats->probe_attempts.size());
1104       const DnsAttempt* attempt =
1105           probe_stats->probe_attempts[attempt_number].get();
1106       const DnsResponse* response = attempt->GetResponse();
1107       if (response) {
1108         DnsResponseResultExtractor extractor(*response);
1109         DnsResponseResultExtractor::ResultsOrError results =
1110             extractor.ExtractDnsResults(
1111                 DnsQueryType::A,
1112                 /*original_domain_name=*/kDohProbeHostname,
1113                 /*request_port=*/0);
1114 
1115         if (results.has_value()) {
1116           for (const auto& result : results.value()) {
1117             if (result->type() == HostResolverInternalResult::Type::kData &&
1118                 !result->AsData().endpoints().empty()) {
1119               // The DoH probe queries don't go through the standard DnsAttempt
1120               // path, so the ServerStats have not been updated yet.
1121               context_->RecordServerSuccess(
1122                   doh_server_index, /*is_doh_server=*/true, session_.get());
1123               context_->RecordRtt(doh_server_index, /*is_doh_server=*/true,
1124                                   base::TimeTicks::Now() - query_start_time, rv,
1125                                   session_.get());
1126               success = true;
1127 
1128               // Do not delete the ProbeStats and cancel the probe sequence. It
1129               // will cancel itself on the next scheduled ContinueProbe() call
1130               // if the server is still available. This way, the backoff
1131               // schedule will be maintained if a server quickly becomes
1132               // unavailable again before that scheduled call.
1133               break;
1134             }
1135           }
1136         }
1137       }
1138     }
1139 
1140     base::UmaHistogramLongTimes(
1141         base::JoinString({"Net.DNS.ProbeSequence",
1142                           network_change ? "NetworkChange" : "ConfigChange",
1143                           success ? "Success" : "Failure", "AttemptTime"},
1144                          "."),
1145         base::TimeTicks::Now() - sequence_start_time);
1146   }
1147 
1148   base::WeakPtr<DnsSession> session_;
1149   base::WeakPtr<ResolveContext> context_;
1150   std::vector<uint8_t> formatted_probe_qname_;
1151 
1152   // List of ProbeStats, one for each DoH server, indexed by the DoH server
1153   // config index.
1154   std::vector<std::unique_ptr<ProbeStats>> probe_stats_list_;
1155 
1156   base::WeakPtrFactory<DnsOverHttpsProbeRunner> weak_ptr_factory_{this};
1157 };
1158 
1159 // ----------------------------------------------------------------------------
1160 
1161 // Implements DnsTransaction. Configuration is supplied by DnsSession.
1162 // The suffix list is built according to the DnsConfig from the session.
1163 // The fallback period for each DnsUDPAttempt is given by
1164 // ResolveContext::NextClassicFallbackPeriod(). The first server to attempt on
1165 // each query is given by ResolveContext::NextFirstServerIndex, and the order is
1166 // round-robin afterwards. Each server is attempted DnsConfig::attempts times.
1167 class DnsTransactionImpl : public DnsTransaction,
1168                            public base::SupportsWeakPtr<DnsTransactionImpl> {
1169  public:
DnsTransactionImpl(DnsSession * session,std::string hostname,uint16_t qtype,const NetLogWithSource & parent_net_log,const OptRecordRdata * opt_rdata,bool secure,SecureDnsMode secure_dns_mode,ResolveContext * resolve_context,bool fast_timeout)1170   DnsTransactionImpl(DnsSession* session,
1171                      std::string hostname,
1172                      uint16_t qtype,
1173                      const NetLogWithSource& parent_net_log,
1174                      const OptRecordRdata* opt_rdata,
1175                      bool secure,
1176                      SecureDnsMode secure_dns_mode,
1177                      ResolveContext* resolve_context,
1178                      bool fast_timeout)
1179       : session_(session),
1180         hostname_(std::move(hostname)),
1181         qtype_(qtype),
1182         opt_rdata_(opt_rdata),
1183         secure_(secure),
1184         secure_dns_mode_(secure_dns_mode),
1185         fast_timeout_(fast_timeout),
1186         net_log_(NetLogWithSource::Make(NetLog::Get(),
1187                                         NetLogSourceType::DNS_TRANSACTION)),
1188         resolve_context_(resolve_context->AsSafeRef()) {
1189     DCHECK(session_.get());
1190     DCHECK(!hostname_.empty());
1191     DCHECK(!IsIPLiteral(hostname_));
1192     parent_net_log.AddEventReferencingSource(NetLogEventType::DNS_TRANSACTION,
1193                                              net_log_.source());
1194   }
1195 
1196   DnsTransactionImpl(const DnsTransactionImpl&) = delete;
1197   DnsTransactionImpl& operator=(const DnsTransactionImpl&) = delete;
1198 
~DnsTransactionImpl()1199   ~DnsTransactionImpl() override {
1200     DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
1201     if (!callback_.is_null()) {
1202       net_log_.EndEventWithNetErrorCode(NetLogEventType::DNS_TRANSACTION,
1203                                         ERR_ABORTED);
1204     }  // otherwise logged in DoCallback or Start
1205   }
1206 
GetHostname() const1207   const std::string& GetHostname() const override {
1208     DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
1209     return hostname_;
1210   }
1211 
GetType() const1212   uint16_t GetType() const override {
1213     DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
1214     return qtype_;
1215   }
1216 
Start(ResponseCallback callback)1217   void Start(ResponseCallback callback) override {
1218     DCHECK(!callback.is_null());
1219     DCHECK(callback_.is_null());
1220     DCHECK(attempts_.empty());
1221 
1222     callback_ = std::move(callback);
1223 
1224     net_log_.BeginEvent(NetLogEventType::DNS_TRANSACTION,
1225                         [&] { return NetLogStartParams(hostname_, qtype_); });
1226     time_from_start_ = std::make_unique<base::ElapsedTimer>();
1227     AttemptResult result(PrepareSearch(), nullptr);
1228     if (result.rv == OK) {
1229       qnames_initial_size_ = qnames_.size();
1230       result = ProcessAttemptResult(StartQuery());
1231     }
1232 
1233     // Must always return result asynchronously, to avoid reentrancy.
1234     if (result.rv != ERR_IO_PENDING) {
1235       // Clear all other non-completed attempts. They are no longer needed and
1236       // they may interfere with this posted result.
1237       ClearAttempts(result.attempt);
1238       base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
1239           FROM_HERE,
1240           base::BindOnce(&DnsTransactionImpl::DoCallback, AsWeakPtr(), result));
1241     }
1242   }
1243 
SetRequestPriority(RequestPriority priority)1244   void SetRequestPriority(RequestPriority priority) override {
1245     request_priority_ = priority;
1246   }
1247 
1248  private:
1249   // Wrapper for the result of a DnsUDPAttempt.
1250   struct AttemptResult {
1251     AttemptResult() = default;
AttemptResultnet::__anon72bb64c70111::DnsTransactionImpl::AttemptResult1252     AttemptResult(int rv, const DnsAttempt* attempt)
1253         : rv(rv), attempt(attempt) {}
1254 
1255     int rv;
1256     raw_ptr<const DnsAttempt, AcrossTasksDanglingUntriaged> attempt;
1257   };
1258 
1259   // Used in UMA (DNS.AttemptType). Do not renumber or remove values.
1260   enum class DnsAttemptType {
1261     kUdp = 0,
1262     kTcpLowEntropy = 1,
1263     kTcpTruncationRetry = 2,
1264     kHttp = 3,
1265     kMaxValue = kHttp,
1266   };
1267 
1268   // Prepares |qnames_| according to the DnsConfig.
PrepareSearch()1269   int PrepareSearch() {
1270     const DnsConfig& config = session_->config();
1271 
1272     absl::optional<std::vector<uint8_t>> labeled_qname =
1273         dns_names_util::DottedNameToNetwork(
1274             hostname_,
1275             /*require_valid_internet_hostname=*/true);
1276     if (!labeled_qname.has_value())
1277       return ERR_INVALID_ARGUMENT;
1278 
1279     if (hostname_.back() == '.') {
1280       // It's a fully-qualified name, no suffix search.
1281       qnames_.push_back(std::move(labeled_qname).value());
1282       return OK;
1283     }
1284 
1285     int ndots = CountLabels(labeled_qname.value()) - 1;
1286 
1287     if (ndots > 0 && !config.append_to_multi_label_name) {
1288       qnames_.push_back(std::move(labeled_qname).value());
1289       return OK;
1290     }
1291 
1292     // Set true when `labeled_qname` is put on the list.
1293     bool had_qname = false;
1294 
1295     if (ndots >= config.ndots) {
1296       qnames_.push_back(labeled_qname.value());
1297       had_qname = true;
1298     }
1299 
1300     for (const auto& suffix : config.search) {
1301       absl::optional<std::vector<uint8_t>> qname =
1302           dns_names_util::DottedNameToNetwork(
1303               hostname_ + "." + suffix,
1304               /*require_valid_internet_hostname=*/true);
1305       // Ignore invalid (too long) combinations.
1306       if (!qname.has_value())
1307         continue;
1308       if (qname.value().size() == labeled_qname.value().size()) {
1309         if (had_qname)
1310           continue;
1311         had_qname = true;
1312       }
1313       qnames_.push_back(std::move(qname).value());
1314     }
1315 
1316     if (ndots > 0 && !had_qname)
1317       qnames_.push_back(std::move(labeled_qname).value());
1318 
1319     return qnames_.empty() ? ERR_DNS_SEARCH_EMPTY : OK;
1320   }
1321 
DoCallback(AttemptResult result)1322   void DoCallback(AttemptResult result) {
1323     DCHECK_NE(ERR_IO_PENDING, result.rv);
1324 
1325     // TODO(mgersh): consider changing back to a DCHECK once
1326     // https://crbug.com/779589 is fixed.
1327     if (callback_.is_null())
1328       return;
1329 
1330     const DnsResponse* response =
1331         result.attempt ? result.attempt->GetResponse() : nullptr;
1332     CHECK(result.rv != OK || response != nullptr);
1333 
1334     timer_.Stop();
1335 
1336     net_log_.EndEventWithNetErrorCode(NetLogEventType::DNS_TRANSACTION,
1337                                       result.rv);
1338 
1339     std::move(callback_).Run(result.rv, response);
1340   }
1341 
RecordAttemptUma(DnsAttemptType attempt_type)1342   void RecordAttemptUma(DnsAttemptType attempt_type) {
1343     UMA_HISTOGRAM_ENUMERATION("Net.DNS.DnsTransaction.AttemptType",
1344                               attempt_type);
1345   }
1346 
MakeAttempt()1347   AttemptResult MakeAttempt() {
1348     DCHECK(MoreAttemptsAllowed());
1349 
1350     DnsConfig config = session_->config();
1351     if (secure_) {
1352       DCHECK(!config.doh_config.servers().empty());
1353       RecordAttemptUma(DnsAttemptType::kHttp);
1354       return MakeHTTPAttempt();
1355     }
1356 
1357     DCHECK_GT(config.nameservers.size(), 0u);
1358     return MakeClassicDnsAttempt();
1359   }
1360 
MakeClassicDnsAttempt()1361   AttemptResult MakeClassicDnsAttempt() {
1362     uint16_t id = session_->NextQueryId();
1363     std::unique_ptr<DnsQuery> query;
1364     if (attempts_.empty()) {
1365       query =
1366           std::make_unique<DnsQuery>(id, qnames_.front(), qtype_, opt_rdata_);
1367     } else {
1368       query = attempts_[0]->GetQuery()->CloneWithNewId(id);
1369     }
1370     DCHECK(dns_server_iterator_->AttemptAvailable());
1371     size_t server_index = dns_server_iterator_->GetNextAttemptIndex();
1372 
1373     size_t attempt_number = attempts_.size();
1374     AttemptResult result;
1375     if (session_->udp_tracker()->low_entropy()) {
1376       result = MakeTcpAttempt(server_index, std::move(query));
1377       RecordAttemptUma(DnsAttemptType::kTcpLowEntropy);
1378     } else {
1379       result = MakeUdpAttempt(server_index, std::move(query));
1380       RecordAttemptUma(DnsAttemptType::kUdp);
1381     }
1382 
1383     if (result.rv == ERR_IO_PENDING) {
1384       base::TimeDelta fallback_period =
1385           resolve_context_->NextClassicFallbackPeriod(
1386               server_index, attempt_number, session_.get());
1387       timer_.Start(FROM_HERE, fallback_period, this,
1388                    &DnsTransactionImpl::OnFallbackPeriodExpired);
1389     }
1390 
1391     return result;
1392   }
1393 
1394   // Makes another attempt at the current name, |qnames_.front()|, using the
1395   // next nameserver.
MakeUdpAttempt(size_t server_index,std::unique_ptr<DnsQuery> query)1396   AttemptResult MakeUdpAttempt(size_t server_index,
1397                                std::unique_ptr<DnsQuery> query) {
1398     DCHECK(!secure_);
1399     DCHECK(!session_->udp_tracker()->low_entropy());
1400 
1401     const DnsConfig& config = session_->config();
1402     DCHECK_LT(server_index, config.nameservers.size());
1403     size_t attempt_number = attempts_.size();
1404 
1405     std::unique_ptr<DatagramClientSocket> socket =
1406         resolve_context_->url_request_context()
1407             ->GetNetworkSessionContext()
1408             ->client_socket_factory->CreateDatagramClientSocket(
1409                 DatagramSocket::RANDOM_BIND, net_log_.net_log(),
1410                 net_log_.source());
1411 
1412     attempts_.push_back(std::make_unique<DnsUDPAttempt>(
1413         server_index, std::move(socket), config.nameservers[server_index],
1414         std::move(query), session_->udp_tracker()));
1415     ++attempts_count_;
1416 
1417     DnsAttempt* attempt = attempts_.back().get();
1418     net_log_.AddEventReferencingSource(NetLogEventType::DNS_TRANSACTION_ATTEMPT,
1419                                        attempt->GetSocketNetLog().source());
1420 
1421     int rv = attempt->Start(base::BindOnce(
1422         &DnsTransactionImpl::OnAttemptComplete, base::Unretained(this),
1423         attempt_number, true /* record_rtt */, base::TimeTicks::Now()));
1424     return AttemptResult(rv, attempt);
1425   }
1426 
MakeHTTPAttempt()1427   AttemptResult MakeHTTPAttempt() {
1428     DCHECK(secure_);
1429 
1430     size_t doh_server_index = dns_server_iterator_->GetNextAttemptIndex();
1431 
1432     unsigned attempt_number = attempts_.size();
1433     ConstructDnsHTTPAttempt(session_.get(), doh_server_index, qnames_.front(),
1434                             qtype_, opt_rdata_, &attempts_,
1435                             resolve_context_->url_request_context(),
1436                             resolve_context_->isolation_info(),
1437                             request_priority_, /*is_probe=*/false);
1438     ++attempts_count_;
1439     DnsAttempt* attempt = attempts_.back().get();
1440     // Associate this attempt with the DoH request in NetLog.
1441     net_log_.AddEventReferencingSource(
1442         NetLogEventType::DNS_TRANSACTION_HTTPS_ATTEMPT,
1443         attempt->GetSocketNetLog().source());
1444     attempt->GetSocketNetLog().AddEventReferencingSource(
1445         NetLogEventType::DNS_TRANSACTION_HTTPS_ATTEMPT, net_log_.source());
1446     int rv = attempt->Start(base::BindOnce(
1447         &DnsTransactionImpl::OnAttemptComplete, base::Unretained(this),
1448         attempt_number, true /* record_rtt */, base::TimeTicks::Now()));
1449     if (rv == ERR_IO_PENDING) {
1450       base::TimeDelta fallback_period = resolve_context_->NextDohFallbackPeriod(
1451           doh_server_index, session_.get());
1452       timer_.Start(FROM_HERE, fallback_period, this,
1453                    &DnsTransactionImpl::OnFallbackPeriodExpired);
1454     }
1455     return AttemptResult(rv, attempts_.back().get());
1456   }
1457 
RetryUdpAttemptAsTcp(const DnsAttempt * previous_attempt)1458   AttemptResult RetryUdpAttemptAsTcp(const DnsAttempt* previous_attempt) {
1459     DCHECK(previous_attempt);
1460     DCHECK(!had_tcp_retry_);
1461 
1462     // Only allow a single TCP retry per query.
1463     had_tcp_retry_ = true;
1464 
1465     size_t server_index = previous_attempt->server_index();
1466     // Use a new query ID instead of reusing the same one from the UDP attempt.
1467     // RFC5452, section 9.2 requires an unpredictable ID for all outgoing
1468     // queries, with no distinction made between queries made via TCP or UDP.
1469     std::unique_ptr<DnsQuery> query =
1470         previous_attempt->GetQuery()->CloneWithNewId(session_->NextQueryId());
1471 
1472     // Cancel all attempts that have not received a response, as they will
1473     // likely similarly require TCP retry.
1474     ClearAttempts(nullptr);
1475 
1476     AttemptResult result = MakeTcpAttempt(server_index, std::move(query));
1477     RecordAttemptUma(DnsAttemptType::kTcpTruncationRetry);
1478 
1479     if (result.rv == ERR_IO_PENDING) {
1480       // On TCP upgrade, use 2x the upgraded fallback period.
1481       base::TimeDelta fallback_period = timer_.GetCurrentDelay() * 2;
1482       timer_.Start(FROM_HERE, fallback_period, this,
1483                    &DnsTransactionImpl::OnFallbackPeriodExpired);
1484     }
1485 
1486     return result;
1487   }
1488 
MakeTcpAttempt(size_t server_index,std::unique_ptr<DnsQuery> query)1489   AttemptResult MakeTcpAttempt(size_t server_index,
1490                                std::unique_ptr<DnsQuery> query) {
1491     DCHECK(!secure_);
1492     const DnsConfig& config = session_->config();
1493     DCHECK_LT(server_index, config.nameservers.size());
1494 
1495     // TODO(https://crbug.com/1123197): Pass a non-null NetworkQualityEstimator.
1496     NetworkQualityEstimator* network_quality_estimator = nullptr;
1497 
1498     std::unique_ptr<StreamSocket> socket =
1499         resolve_context_->url_request_context()
1500             ->GetNetworkSessionContext()
1501             ->client_socket_factory->CreateTransportClientSocket(
1502                 AddressList(config.nameservers[server_index]), nullptr,
1503                 network_quality_estimator, net_log_.net_log(),
1504                 net_log_.source());
1505 
1506     unsigned attempt_number = attempts_.size();
1507 
1508     attempts_.push_back(std::make_unique<DnsTCPAttempt>(
1509         server_index, std::move(socket), std::move(query)));
1510     ++attempts_count_;
1511 
1512     DnsAttempt* attempt = attempts_.back().get();
1513     net_log_.AddEventReferencingSource(
1514         NetLogEventType::DNS_TRANSACTION_TCP_ATTEMPT,
1515         attempt->GetSocketNetLog().source());
1516 
1517     int rv = attempt->Start(base::BindOnce(
1518         &DnsTransactionImpl::OnAttemptComplete, base::Unretained(this),
1519         attempt_number, false /* record_rtt */, base::TimeTicks::Now()));
1520     return AttemptResult(rv, attempt);
1521   }
1522 
1523   // Begins query for the current name. Makes the first attempt.
StartQuery()1524   AttemptResult StartQuery() {
1525     absl::optional<std::string> dotted_qname =
1526         dns_names_util::NetworkToDottedName(qnames_.front());
1527     net_log_.BeginEventWithStringParams(
1528         NetLogEventType::DNS_TRANSACTION_QUERY, "qname",
1529         dotted_qname.value_or("???MALFORMED_NAME???"));
1530 
1531     attempts_.clear();
1532     had_tcp_retry_ = false;
1533     if (secure_) {
1534       dns_server_iterator_ = resolve_context_->GetDohIterator(
1535           session_->config(), secure_dns_mode_, session_.get());
1536     } else {
1537       dns_server_iterator_ = resolve_context_->GetClassicDnsIterator(
1538           session_->config(), session_.get());
1539     }
1540     DCHECK(dns_server_iterator_);
1541     // Check for available server before starting as DoH servers might be
1542     // unavailable.
1543     if (!dns_server_iterator_->AttemptAvailable())
1544       return AttemptResult(ERR_BLOCKED_BY_CLIENT, nullptr);
1545 
1546     return MakeAttempt();
1547   }
1548 
OnAttemptComplete(unsigned attempt_number,bool record_rtt,base::TimeTicks start,int rv)1549   void OnAttemptComplete(unsigned attempt_number,
1550                          bool record_rtt,
1551                          base::TimeTicks start,
1552                          int rv) {
1553     DCHECK_LT(attempt_number, attempts_.size());
1554     const DnsAttempt* attempt = attempts_[attempt_number].get();
1555     if (record_rtt && attempt->GetResponse()) {
1556       resolve_context_->RecordRtt(
1557           attempt->server_index(), secure_ /* is_doh_server */,
1558           base::TimeTicks::Now() - start, rv, session_.get());
1559     }
1560     if (callback_.is_null())
1561       return;
1562     AttemptResult result = ProcessAttemptResult(AttemptResult(rv, attempt));
1563     if (result.rv != ERR_IO_PENDING)
1564       DoCallback(result);
1565   }
1566 
LogResponse(const DnsAttempt * attempt)1567   void LogResponse(const DnsAttempt* attempt) {
1568     if (attempt) {
1569       net_log_.AddEvent(NetLogEventType::DNS_TRANSACTION_RESPONSE,
1570                         [&](NetLogCaptureMode capture_mode) {
1571                           return attempt->NetLogResponseParams(capture_mode);
1572                         });
1573     }
1574   }
1575 
MoreAttemptsAllowed() const1576   bool MoreAttemptsAllowed() const {
1577     if (had_tcp_retry_)
1578       return false;
1579 
1580     return dns_server_iterator_->AttemptAvailable();
1581   }
1582 
1583   // Resolves the result of a DnsAttempt until a terminal result is reached
1584   // or it will complete asynchronously (ERR_IO_PENDING).
ProcessAttemptResult(AttemptResult result)1585   AttemptResult ProcessAttemptResult(AttemptResult result) {
1586     while (result.rv != ERR_IO_PENDING) {
1587       LogResponse(result.attempt);
1588 
1589       switch (result.rv) {
1590         case OK:
1591           resolve_context_->RecordServerSuccess(result.attempt->server_index(),
1592                                                 secure_ /* is_doh_server */,
1593                                                 session_.get());
1594           net_log_.EndEventWithNetErrorCode(
1595               NetLogEventType::DNS_TRANSACTION_QUERY, result.rv);
1596           DCHECK(result.attempt);
1597           DCHECK(result.attempt->GetResponse());
1598           return result;
1599         case ERR_NAME_NOT_RESOLVED:
1600           resolve_context_->RecordServerSuccess(result.attempt->server_index(),
1601                                                 secure_ /* is_doh_server */,
1602                                                 session_.get());
1603           net_log_.EndEventWithNetErrorCode(
1604               NetLogEventType::DNS_TRANSACTION_QUERY, result.rv);
1605           // Try next suffix. Check that qnames_ isn't already empty first,
1606           // which can happen when there are two attempts running at once.
1607           // TODO(mgersh): remove this workaround for https://crbug.com/774846
1608           // when https://crbug.com/779589 is fixed.
1609           if (!qnames_.empty())
1610             qnames_.pop_front();
1611           if (qnames_.empty()) {
1612             return result;
1613           } else {
1614             result = StartQuery();
1615           }
1616           break;
1617         case ERR_DNS_TIMED_OUT:
1618           timer_.Stop();
1619 
1620           if (result.attempt) {
1621             DCHECK(result.attempt == attempts_.back().get());
1622             resolve_context_->RecordServerFailure(
1623                 result.attempt->server_index(), secure_ /* is_doh_server */,
1624                 result.rv, session_.get());
1625           }
1626           if (MoreAttemptsAllowed()) {
1627             result = MakeAttempt();
1628             break;
1629           }
1630 
1631           if (!fast_timeout_ && AnyAttemptPending()) {
1632             StartTimeoutTimer();
1633             return AttemptResult(ERR_IO_PENDING, nullptr);
1634           }
1635 
1636           return result;
1637         case ERR_DNS_SERVER_REQUIRES_TCP:
1638           result = RetryUdpAttemptAsTcp(result.attempt);
1639           break;
1640         case ERR_BLOCKED_BY_CLIENT:
1641           net_log_.EndEventWithNetErrorCode(
1642               NetLogEventType::DNS_TRANSACTION_QUERY, result.rv);
1643           return result;
1644         default:
1645           // Server failure.
1646           DCHECK(result.attempt);
1647 
1648           // If attempt is not the most recent attempt, means this error is for
1649           // a previous attempt that already passed its fallback period and
1650           // continued attempting in parallel with new attempts (see the
1651           // ERR_DNS_TIMED_OUT case above). As the failure was already recorded
1652           // at fallback time and is no longer being waited on, ignore this
1653           // failure.
1654           if (result.attempt == attempts_.back().get()) {
1655             timer_.Stop();
1656             resolve_context_->RecordServerFailure(
1657                 result.attempt->server_index(), secure_ /* is_doh_server */,
1658                 result.rv, session_.get());
1659 
1660             if (MoreAttemptsAllowed()) {
1661               result = MakeAttempt();
1662               break;
1663             }
1664 
1665             if (fast_timeout_) {
1666               return result;
1667             }
1668 
1669             // No more attempts can be made, but there may be other attempts
1670             // still pending, so start the timeout timer.
1671             StartTimeoutTimer();
1672           }
1673 
1674           // If any attempts are still pending, continue to wait for them.
1675           if (AnyAttemptPending()) {
1676             DCHECK(timer_.IsRunning());
1677             return AttemptResult(ERR_IO_PENDING, nullptr);
1678           }
1679 
1680           return result;
1681       }
1682     }
1683     return result;
1684   }
1685 
1686   // Clears and cancels all pending attempts. If |leave_attempt| is not
1687   // null, that attempt is not cleared even if pending.
ClearAttempts(const DnsAttempt * leave_attempt)1688   void ClearAttempts(const DnsAttempt* leave_attempt) {
1689     for (auto it = attempts_.begin(); it != attempts_.end();) {
1690       if ((*it)->IsPending() && it->get() != leave_attempt) {
1691         it = attempts_.erase(it);
1692       } else {
1693         ++it;
1694       }
1695     }
1696   }
1697 
AnyAttemptPending()1698   bool AnyAttemptPending() {
1699     return base::ranges::any_of(attempts_,
1700                                 [](std::unique_ptr<DnsAttempt>& attempt) {
1701                                   return attempt->IsPending();
1702                                 });
1703   }
1704 
OnFallbackPeriodExpired()1705   void OnFallbackPeriodExpired() {
1706     if (callback_.is_null())
1707       return;
1708     DCHECK(!attempts_.empty());
1709     AttemptResult result = ProcessAttemptResult(
1710         AttemptResult(ERR_DNS_TIMED_OUT, attempts_.back().get()));
1711     if (result.rv != ERR_IO_PENDING)
1712       DoCallback(result);
1713   }
1714 
StartTimeoutTimer()1715   void StartTimeoutTimer() {
1716     DCHECK(!fast_timeout_);
1717     DCHECK(!timer_.IsRunning());
1718     DCHECK(!callback_.is_null());
1719 
1720     base::TimeDelta timeout;
1721     if (secure_) {
1722       timeout = resolve_context_->SecureTransactionTimeout(secure_dns_mode_,
1723                                                            session_.get());
1724     } else {
1725       timeout = resolve_context_->ClassicTransactionTimeout(session_.get());
1726     }
1727     timeout -= time_from_start_->Elapsed();
1728 
1729     timer_.Start(FROM_HERE, timeout, this, &DnsTransactionImpl::OnTimeout);
1730   }
1731 
OnTimeout()1732   void OnTimeout() {
1733     if (callback_.is_null())
1734       return;
1735     DoCallback(AttemptResult(ERR_DNS_TIMED_OUT, nullptr));
1736   }
1737 
1738   scoped_refptr<DnsSession> session_;
1739   std::string hostname_;
1740   uint16_t qtype_;
1741   raw_ptr<const OptRecordRdata, DanglingUntriaged> opt_rdata_;
1742   const bool secure_;
1743   const SecureDnsMode secure_dns_mode_;
1744   // Cleared in DoCallback.
1745   ResponseCallback callback_;
1746 
1747   // When true, transaction should time out immediately on expiration of the
1748   // last attempt fallback period rather than waiting the overall transaction
1749   // timeout period.
1750   const bool fast_timeout_;
1751 
1752   NetLogWithSource net_log_;
1753 
1754   // Search list of fully-qualified DNS names to query next (in DNS format).
1755   base::circular_deque<std::vector<uint8_t>> qnames_;
1756   size_t qnames_initial_size_ = 0;
1757 
1758   // List of attempts for the current name.
1759   std::vector<std::unique_ptr<DnsAttempt>> attempts_;
1760   // Count of attempts, not reset when |attempts_| vector is cleared.
1761   int attempts_count_ = 0;
1762 
1763   // Records when an attempt was retried via TCP due to a truncation error.
1764   bool had_tcp_retry_ = false;
1765 
1766   // Iterator to get the index of the DNS server for each search query.
1767   std::unique_ptr<DnsServerIterator> dns_server_iterator_;
1768 
1769   base::OneShotTimer timer_;
1770   std::unique_ptr<base::ElapsedTimer> time_from_start_;
1771 
1772   base::SafeRef<ResolveContext> resolve_context_;
1773   RequestPriority request_priority_ = DEFAULT_PRIORITY;
1774 
1775   THREAD_CHECKER(thread_checker_);
1776 };
1777 
1778 // ----------------------------------------------------------------------------
1779 
1780 // Implementation of DnsTransactionFactory that returns instances of
1781 // DnsTransactionImpl.
1782 class DnsTransactionFactoryImpl : public DnsTransactionFactory {
1783  public:
DnsTransactionFactoryImpl(DnsSession * session)1784   explicit DnsTransactionFactoryImpl(DnsSession* session) {
1785     session_ = session;
1786   }
1787 
CreateTransaction(std::string hostname,uint16_t qtype,const NetLogWithSource & net_log,bool secure,SecureDnsMode secure_dns_mode,ResolveContext * resolve_context,bool fast_timeout)1788   std::unique_ptr<DnsTransaction> CreateTransaction(
1789       std::string hostname,
1790       uint16_t qtype,
1791       const NetLogWithSource& net_log,
1792       bool secure,
1793       SecureDnsMode secure_dns_mode,
1794       ResolveContext* resolve_context,
1795       bool fast_timeout) override {
1796     return std::make_unique<DnsTransactionImpl>(
1797         session_.get(), std::move(hostname), qtype, net_log, opt_rdata_.get(),
1798         secure, secure_dns_mode, resolve_context, fast_timeout);
1799   }
1800 
CreateDohProbeRunner(ResolveContext * resolve_context)1801   std::unique_ptr<DnsProbeRunner> CreateDohProbeRunner(
1802       ResolveContext* resolve_context) override {
1803     // Start a timer that will emit metrics after a timeout to indicate whether
1804     // DoH auto-upgrade was successful for this session.
1805     resolve_context->StartDohAutoupgradeSuccessTimer(session_.get());
1806 
1807     return std::make_unique<DnsOverHttpsProbeRunner>(
1808         session_->GetWeakPtr(), resolve_context->GetWeakPtr());
1809   }
1810 
AddEDNSOption(std::unique_ptr<OptRecordRdata::Opt> opt)1811   void AddEDNSOption(std::unique_ptr<OptRecordRdata::Opt> opt) override {
1812     DCHECK(opt);
1813     if (opt_rdata_ == nullptr)
1814       opt_rdata_ = std::make_unique<OptRecordRdata>();
1815 
1816     opt_rdata_->AddOpt(std::move(opt));
1817   }
1818 
GetSecureDnsModeForTest()1819   SecureDnsMode GetSecureDnsModeForTest() override {
1820     return session_->config().secure_dns_mode;
1821   }
1822 
1823  private:
1824   scoped_refptr<DnsSession> session_;
1825   std::unique_ptr<OptRecordRdata> opt_rdata_;
1826 };
1827 
1828 }  // namespace
1829 
1830 DnsTransactionFactory::DnsTransactionFactory() = default;
1831 DnsTransactionFactory::~DnsTransactionFactory() = default;
1832 
1833 // static
CreateFactory(DnsSession * session)1834 std::unique_ptr<DnsTransactionFactory> DnsTransactionFactory::CreateFactory(
1835     DnsSession* session) {
1836   return std::make_unique<DnsTransactionFactoryImpl>(session);
1837 }
1838 
1839 }  // namespace net
1840