blob: 77febd302b603e1ee1986d5b1b66c922f0fdb424 [file] [log] [blame]
[email protected]a2730882012-01-21 00:56:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]b59ff372009-07-15 22:04:322// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f2cb3cf2013-03-21 01:40:535#include "net/dns/host_resolver_impl.h"
[email protected]b59ff372009-07-15 22:04:326
[email protected]21526002010-05-16 19:42:467#if defined(OS_WIN)
8#include <Winsock2.h>
Fabrice de Gans-Riberi7de47372018-05-08 20:23:479#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]21526002010-05-16 19:42:4610#include <netdb.h>
tfarinada9e1362017-03-14 16:49:0611#include <netinet/in.h>
12#if !defined(OS_NACL)
13#include <net/if.h>
14#if !defined(OS_ANDROID)
15#include <ifaddrs.h>
16#endif // !defined(OS_ANDROID)
17#endif // !defined(OS_NACL)
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4718#endif // defined(OS_WIN)
tfarinada9e1362017-03-14 16:49:0619
Eric Orth70992982018-07-24 00:25:0020#include <algorithm>
[email protected]68ad3ee2010-01-30 03:45:3921#include <cmath>
Eric Orth70992982018-07-24 00:25:0022#include <limits>
thestiga74ad2b2016-07-11 20:52:3623#include <memory>
Eric Orth192e3bb2018-11-14 19:30:3224#include <unordered_set>
[email protected]0f292de02012-02-01 22:28:2025#include <utility>
[email protected]21526002010-05-16 19:42:4626#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3927
[email protected]33152acc2011-10-20 23:37:1228#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2929#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2030#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1031#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3232#include "base/compiler_specific.h"
David Benjamina5677192018-04-23 23:25:4233#include "base/containers/linked_list.h"
[email protected]58580352010-10-26 04:07:5034#include "base/debug/debugger.h"
35#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4636#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2337#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4538#include "base/metrics/field_trial.h"
Maks Orlovich5393c8682018-02-26 16:17:5039#include "base/metrics/field_trial_params.h"
Ilya Sherman0eb39802017-12-08 20:58:1840#include "base/metrics/histogram_functions.h"
davidbenad6fc442015-05-18 20:59:1341#include "base/metrics/histogram_macros.h"
Paul Jensen41dc3e9f2018-11-06 22:10:1042#include "base/no_destructor.h"
anujk.sharma7c907f02015-05-29 02:55:4443#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4844#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0545#include "base/strings/utf_string_conversions.h"
Gabriel Charette44db1422018-08-06 11:19:3346#include "base/task/post_task.h"
Francois Doraya2d01ba2017-09-25 19:17:4047#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3548#include "base/threading/thread_task_runner_handle.h"
Misha Efimovb99e7da2018-05-30 16:59:0249#include "base/time/default_tick_clock.h"
[email protected]66e96c42013-06-28 15:20:3150#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5651#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4652#include "base/values.h"
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4753#include "build/build_config.h"
[email protected]b3601bc22012-02-21 21:23:2054#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3255#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5156#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5157#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4858#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1559#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4860#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1861#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4662#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2763#include "net/dns/dns_client.h"
tfarina47598f042015-10-07 23:08:3564#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2065#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2066#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0367#include "net/dns/dns_util.h"
Eric Orth9871aafa2018-10-02 19:59:1868#include "net/dns/host_resolver_mdns_task.h"
[email protected]f2cb3cf2013-03-21 01:40:5369#include "net/dns/host_resolver_proc.h"
Eric Orth9871aafa2018-10-02 19:59:1870#include "net/dns/mdns_client.h"
Eric Orth8afaf152018-11-07 21:01:2671#include "net/dns/public/dns_protocol.h"
eroman87c53d62015-04-02 06:51:0772#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1973#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0074#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1975#include "net/log/net_log_parameters_callback.h"
76#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0077#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1978#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5179#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2680#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1481#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3282
Eric Orth9871aafa2018-10-02 19:59:1883#if BUILDFLAG(ENABLE_MDNS)
84#include "net/dns/mdns_client_impl.h"
85#endif
86
[email protected]b59ff372009-07-15 22:04:3287#if defined(OS_WIN)
88#include "net/base/winsock_init.h"
89#endif
90
tfarinada9e1362017-03-14 16:49:0691#if defined(OS_ANDROID)
Paul Jensen41dc3e9f2018-11-06 22:10:1092#include "base/android/build_info.h"
tfarinada9e1362017-03-14 16:49:0693#include "net/android/network_library.h"
94#endif
95
[email protected]b59ff372009-07-15 22:04:3296namespace net {
97
[email protected]e95d3aca2010-01-11 22:47:4398namespace {
99
ttuttlecf1158bf2016-03-18 16:37:44100// Default delay between calls to the system resolver for the same hostname.
101// (Can be overridden by field trial.)
102const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
103
[email protected]6e78dfb2011-07-28 21:34:47104// Limit the size of hostnames that will be resolved to combat issues in
105// some platform's resolvers.
106const size_t kMaxHostLength = 4096;
107
[email protected]a2730882012-01-21 00:56:27108// Default TTL for successful resolutions with ProcTask.
109const unsigned kCacheEntryTTLSeconds = 60;
110
[email protected]b3601bc22012-02-21 21:23:20111// Default TTL for unsuccessful resolutions with ProcTask.
112const unsigned kNegativeCacheEntryTTLSeconds = 0;
113
[email protected]895123222012-10-25 15:21:17114// Minimum TTL for successful resolutions with DnsTask.
115const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
116
sergeyub8cdc212015-05-14 18:50:37117// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
118// cached.
119const int kIPv6ProbePeriodMs = 1000;
120
121// Google DNS address used for IPv6 probes.
122const uint8_t kIPv6ProbeAddress[] =
123 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
124 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
125
[email protected]1def74c2012-03-22 20:07:00126enum DnsResolveStatus {
127 RESOLVE_STATUS_DNS_SUCCESS = 0,
128 RESOLVE_STATUS_PROC_SUCCESS,
129 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33130 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00131 RESOLVE_STATUS_MAX
132};
133
eroman91dd3602015-03-26 03:46:33134// ICANN uses this localhost address to indicate a name collision.
135//
136// The policy in Chromium is to fail host resolving if it resolves to
137// this special address.
138//
139// Not however that IP literals are exempt from this policy, so it is still
140// possible to navigate to http://127.0.53.53/ directly.
141//
142// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51143const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33144
eroman1efc237c2016-12-14 00:00:45145bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
146 for (const auto& endpoint : addr_list) {
147 const IPAddress& addr = endpoint.address();
148 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
149 return true;
150 }
151 }
152 return false;
153}
154
[email protected]1def74c2012-03-22 20:07:00155void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
156 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
157 result,
158 RESOLVE_STATUS_MAX);
159}
160
[email protected]1d932852012-06-19 19:40:33161bool ResemblesNetBIOSName(const std::string& hostname) {
162 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
163}
164
165// True if |hostname| ends with either ".local" or ".local.".
166bool ResemblesMulticastDNSName(const std::string& hostname) {
167 DCHECK(!hostname.empty());
168 const char kSuffix[] = ".local.";
169 const size_t kSuffixLen = sizeof(kSuffix) - 1;
170 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36171 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33172 return hostname.size() > kSuffixLen &&
173 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
174 }
175 return hostname.size() > kSuffixLenTrimmed &&
176 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
177 kSuffix, kSuffixLenTrimmed);
178}
179
[email protected]51b9a6b2012-06-25 21:50:29180// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21181#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
182 do { \
183 switch (priority) { \
184 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28185 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21186 break; \
187 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28188 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21189 break; \
190 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28191 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21192 break; \
193 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28194 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21195 break; \
196 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28197 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21198 break; \
199 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28200 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21201 break; \
202 } \
203 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29204 } while (0)
205
[email protected]1339a2a22012-10-17 08:39:43206void RecordTTL(base::TimeDelta ttl) {
207 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
208 base::TimeDelta::FromSeconds(1),
209 base::TimeDelta::FromDays(1), 100);
210}
211
[email protected]16c2bd72013-06-28 01:19:22212bool ConfigureAsyncDnsNoFallbackFieldTrial() {
213 const bool kDefault = false;
214
215 // Configure the AsyncDns field trial as follows:
216 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
217 // groups AsyncDnsA and AsyncDnsB: return false,
218 // groups SystemDnsA and SystemDnsB: return false,
219 // otherwise (trial absent): return default.
220 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29221 if (!group_name.empty()) {
222 return base::StartsWith(group_name, "AsyncDnsNoFallback",
223 base::CompareCase::INSENSITIVE_ASCII);
224 }
[email protected]16c2bd72013-06-28 01:19:22225 return kDefault;
226}
227
Maks Orlovich5393c8682018-02-26 16:17:50228const base::FeatureParam<base::TaskPriority>::Option prio_modes[] = {
229 {base::TaskPriority::USER_VISIBLE, "default"},
230 {base::TaskPriority::USER_BLOCKING, "user_blocking"}};
231const base::Feature kSystemResolverPriorityExperiment = {
232 "SystemResolverPriorityExperiment", base::FEATURE_DISABLED_BY_DEFAULT};
233const base::FeatureParam<base::TaskPriority> priority_mode{
234 &kSystemResolverPriorityExperiment, "mode",
235 base::TaskPriority::USER_VISIBLE, &prio_modes};
236
[email protected]d7b9a2b2012-05-31 22:31:19237//-----------------------------------------------------------------------------
238
Eric Orth07ee5f02018-11-29 00:42:03239// Creates a copy of |results| with the port of all address and hostname values
240// set to |port| if the current port is 0. Preserves any non-zero ports.
241HostCache::Entry SetPortOnResults(HostCache::Entry results, uint16_t port) {
242 if (results.addresses() &&
243 std::any_of(results.addresses().value().begin(),
244 results.addresses().value().end(),
245 [](const IPEndPoint& e) { return e.port() == 0; })) {
246 AddressList addresses_with_port;
247 addresses_with_port.set_canonical_name(
248 results.addresses().value().canonical_name());
249 for (const IPEndPoint& endpoint : results.addresses().value()) {
250 if (endpoint.port() == 0)
251 addresses_with_port.push_back(IPEndPoint(endpoint.address(), port));
252 else
253 addresses_with_port.push_back(endpoint);
254 }
255 results.set_addresses(addresses_with_port);
256 }
257
258 if (results.hostnames() &&
259 std::any_of(results.hostnames().value().begin(),
260 results.hostnames().value().end(),
261 [](const HostPortPair& h) { return h.port() == 0; })) {
262 std::vector<HostPortPair> hostnames_with_port;
263 for (const HostPortPair& hostname : results.hostnames().value()) {
264 if (hostname.port() == 0)
265 hostnames_with_port.push_back(HostPortPair(hostname.host(), port));
266 else
267 hostnames_with_port.push_back(hostname);
268 }
269 results.set_hostnames(std::move(hostnames_with_port));
270 }
271
272 return results;
[email protected]7054e78f2012-05-07 21:44:56273}
274
[email protected]ec666ab22013-04-17 20:05:59275// Returns true if |addresses| contains only IPv4 loopback addresses.
276bool IsAllIPv4Loopback(const AddressList& addresses) {
277 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51278 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59279 switch (addresses[i].GetFamily()) {
280 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51281 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59282 return false;
283 break;
284 case ADDRESS_FAMILY_IPV6:
285 return false;
286 default:
287 NOTREACHED();
288 return false;
289 }
290 }
291 return true;
292}
293
tfarinada9e1362017-03-14 16:49:06294// Returns true if it can determine that only loopback addresses are configured.
295// i.e. if only 127.0.0.1 and ::1 are routable.
296// Also returns false if it cannot determine this.
297bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40298 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47299#if defined(OS_WIN)
300 // TODO(wtc): implement with the GetAdaptersAddresses function.
301 NOTIMPLEMENTED();
302 return false;
303#elif defined(OS_ANDROID)
tfarinada9e1362017-03-14 16:49:06304 return android::HaveOnlyLoopbackAddresses();
305#elif defined(OS_NACL)
306 NOTIMPLEMENTED();
307 return false;
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47308#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tfarinada9e1362017-03-14 16:49:06309 struct ifaddrs* interface_addr = NULL;
310 int rv = getifaddrs(&interface_addr);
311 if (rv != 0) {
312 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
313 return false;
314 }
315
316 bool result = true;
317 for (struct ifaddrs* interface = interface_addr;
318 interface != NULL;
319 interface = interface->ifa_next) {
320 if (!(IFF_UP & interface->ifa_flags))
321 continue;
322 if (IFF_LOOPBACK & interface->ifa_flags)
323 continue;
324 const struct sockaddr* addr = interface->ifa_addr;
325 if (!addr)
326 continue;
327 if (addr->sa_family == AF_INET6) {
328 // Safe cast since this is AF_INET6.
329 const struct sockaddr_in6* addr_in6 =
330 reinterpret_cast<const struct sockaddr_in6*>(addr);
331 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
332 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
333 continue;
334 }
335 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
336 continue;
337
338 result = false;
339 break;
340 }
341 freeifaddrs(interface_addr);
342 return result;
tfarinada9e1362017-03-14 16:49:06343#endif // defined(various platforms)
344}
345
[email protected]cd565142012-06-12 16:21:45346// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40347std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46348 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17349 int net_error,
350 int os_error,
351 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40352 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45353 if (attempt_number)
354 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46355
[email protected]cd565142012-06-12 16:21:45356 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16357
[email protected]cd565142012-06-12 16:21:45358 if (os_error) {
359 dict->SetInteger("os_error", os_error);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47360#if defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45361 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04362 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08363 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
364 0, // Use the internal message table.
365 os_error,
366 0, // Use default language.
367 (LPWSTR)&error_string,
368 0, // Buffer size.
369 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01370 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45371 LocalFree(error_string);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47372#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
373 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46374#endif
[email protected]21526002010-05-16 19:42:46375 }
376
dchengc7eeda422015-12-26 03:56:48377 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45378}
[email protected]a9813302012-04-28 09:29:28379
[email protected]cd565142012-06-12 16:21:45380// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40381std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11382 int net_error,
383 int dns_error,
Eric Orth07ee5f02018-11-29 00:42:03384 NetLogParametersCallback results_callback,
385 NetLogCaptureMode capture_mode) {
danakj22f90e72016-04-16 01:55:40386 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45387 dict->SetInteger("net_error", net_error);
388 if (dns_error)
389 dict->SetInteger("dns_error", dns_error);
Eric Orth07ee5f02018-11-29 00:42:03390 if (results_callback)
391 dict->Set("resolve_results", results_callback.Run(capture_mode));
dchengc7eeda422015-12-26 03:56:48392 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36393}
[email protected]ee094b82010-08-24 15:55:51394
[email protected]cd565142012-06-12 16:21:45395// Creates NetLog parameters containing the information in a RequestInfo object,
Eric Orth70992982018-07-24 00:25:00396// along with the associated NetLogSource. Use NetLogRequestCallback() if the
397// request information is not specified via RequestInfo.
danakj22f90e72016-04-16 01:55:40398std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11399 const HostResolver::RequestInfo* info,
400 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40401 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20402
[email protected]cd565142012-06-12 16:21:45403 dict->SetString("host", info->host_port_pair().ToString());
404 dict->SetInteger("address_family",
405 static_cast<int>(info->address_family()));
406 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
407 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48408 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45409}
[email protected]b3601bc22012-02-21 21:23:20410
Eric Orth70992982018-07-24 00:25:00411// Creates NetLog parameters containing the information of the request. Use
412// NetLogRequestInfoCallback if the request is specified via RequestInfo.
413std::unique_ptr<base::Value> NetLogRequestCallback(
414 const HostPortPair& host,
415 NetLogCaptureMode /* capture_mode */) {
416 auto dict = std::make_unique<base::DictionaryValue>();
417
418 dict->SetString("host", host.ToString());
419 dict->SetInteger("address_family",
420 static_cast<int>(ADDRESS_FAMILY_UNSPECIFIED));
421 dict->SetBoolean("allow_cached_response", true);
422 dict->SetBoolean("is_speculative", false);
423 return std::move(dict);
424}
425
[email protected]cd565142012-06-12 16:21:45426// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40427std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19428 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11429 const std::string* host,
430 NetLogCaptureMode /* capture_mode */) {
Eric Orth70992982018-07-24 00:25:00431 auto dict = std::make_unique<base::DictionaryValue>();
estade5e5529d2015-05-21 20:59:11432 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45433 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48434 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45435}
[email protected]a9813302012-04-28 09:29:28436
[email protected]cd565142012-06-12 16:21:45437// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40438std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19439 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11440 RequestPriority priority,
441 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40442 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11443 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56444 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48445 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45446}
[email protected]b3601bc22012-02-21 21:23:20447
[email protected]cd565142012-06-12 16:21:45448// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40449std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11450 const DnsConfig* config,
451 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08452 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45453}
[email protected]b4481b222012-03-16 17:13:11454
danakj22f90e72016-04-16 01:55:40455std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11456 bool ipv6_available,
457 bool cached,
458 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40459 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37460 dict->SetBoolean("ipv6_available", ipv6_available);
461 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48462 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37463}
464
[email protected]0f292de02012-02-01 22:28:20465// The logging routines are defined here because some requests are resolved
466// without a Request object.
467
Eric Orth70992982018-07-24 00:25:00468// Logs when a request has just been started. Overloads for whether or not the
469// request information is specified via a RequestInfo object.
tfarina428341112016-09-22 13:38:20470void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20471 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00472 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
473 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20474}
Eric Orth70992982018-07-24 00:25:00475void LogStartRequest(const NetLogWithSource& source_net_log,
476 const HostPortPair& host) {
477 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
478 base::BindRepeating(&NetLogRequestCallback, host));
479}
[email protected]0f292de02012-02-01 22:28:20480
481// Logs when a request has just completed (before its callback is run).
Eric Orth70992982018-07-24 00:25:00482void LogFinishRequest(const NetLogWithSource& source_net_log, int net_error) {
xunjieli26f90452014-11-10 16:23:02483 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00484 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20485}
486
487// Logs when a request has been cancelled.
Eric Orth70992982018-07-24 00:25:00488void LogCancelRequest(const NetLogWithSource& source_net_log) {
mikecirone8b85c432016-09-08 19:11:00489 source_net_log.AddEvent(NetLogEventType::CANCELLED);
490 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20491}
492
[email protected]b59ff372009-07-15 22:04:32493//-----------------------------------------------------------------------------
494
[email protected]0f292de02012-02-01 22:28:20495// Keeps track of the highest priority.
496class PriorityTracker {
497 public:
[email protected]8c98d002012-07-18 19:02:27498 explicit PriorityTracker(RequestPriority initial_priority)
499 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20500 memset(counts_, 0, sizeof(counts_));
501 }
502
503 RequestPriority highest_priority() const {
504 return highest_priority_;
505 }
506
507 size_t total_count() const {
508 return total_count_;
509 }
510
511 void Add(RequestPriority req_priority) {
512 ++total_count_;
513 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05514 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20515 highest_priority_ = req_priority;
516 }
517
518 void Remove(RequestPriority req_priority) {
519 DCHECK_GT(total_count_, 0u);
520 DCHECK_GT(counts_[req_priority], 0u);
521 --total_count_;
522 --counts_[req_priority];
523 size_t i;
thestiga74ad2b2016-07-11 20:52:36524 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
525 }
[email protected]0f292de02012-02-01 22:28:20526 highest_priority_ = static_cast<RequestPriority>(i);
527
[email protected]31ae7ab2012-04-24 21:09:05528 // In absence of requests, default to MINIMUM_PRIORITY.
529 if (total_count_ == 0)
530 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20531 }
532
533 private:
534 RequestPriority highest_priority_;
535 size_t total_count_;
536 size_t counts_[NUM_PRIORITIES];
537};
538
juliatuttle9fb7aeb2016-06-06 20:16:33539void MakeNotStale(HostCache::EntryStaleness* stale_info) {
540 if (!stale_info)
541 return;
542 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
543 stale_info->network_changes = 0;
544 stale_info->stale_hits = 0;
545}
546
Paul Jensen41dc3e9f2018-11-06 22:10:10547// Is |dns_server| within the list of known DNS servers that also support
548// DNS-over-HTTPS?
549bool DnsServerSupportsDoh(const IPAddress& dns_server) {
Eric Orth192e3bb2018-11-14 19:30:32550 static const base::NoDestructor<std::unordered_set<std::string>>
Raphael Kubo da Costa6e73ad42018-11-28 08:04:57551 upgradable_servers(std::initializer_list<std::string>({
Paul Jensen41dc3e9f2018-11-06 22:10:10552 // Google Public DNS
Raphael Kubo da Costa6e73ad42018-11-28 08:04:57553 "8.8.8.8",
554 "8.8.4.4",
555 "2001:4860:4860::8888",
556 "2001:4860:4860::8844",
Paul Jensen41dc3e9f2018-11-06 22:10:10557 // Cloudflare DNS
Raphael Kubo da Costa6e73ad42018-11-28 08:04:57558 "1.1.1.1",
559 "1.0.0.1",
560 "2606:4700:4700::1111",
561 "2606:4700:4700::1001",
Paul Jensen41dc3e9f2018-11-06 22:10:10562 // Quad9 DNS
Raphael Kubo da Costa6e73ad42018-11-28 08:04:57563 "9.9.9.9",
564 "149.112.112.112",
565 "2620:fe::fe",
566 "2620:fe::9",
567 }));
Paul Jensen41dc3e9f2018-11-06 22:10:10568 return upgradable_servers->find(dns_server.ToString()) !=
569 upgradable_servers->end();
570}
571
[email protected]c54a8912012-10-22 22:09:43572} // namespace
[email protected]0f292de02012-02-01 22:28:20573
574//-----------------------------------------------------------------------------
575
Eric Orth07ee5f02018-11-29 00:42:03576bool ResolveLocalHostname(base::StringPiece host, AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18577 address_list->clear();
578
579 bool is_local6;
580 if (!IsLocalHostname(host, &is_local6))
581 return false;
582
Eric Orth07ee5f02018-11-29 00:42:03583 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), 0));
tfarina9ed7f8c52016-02-19 17:50:18584 if (!is_local6) {
Eric Orth07ee5f02018-11-29 00:42:03585 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), 0));
tfarina9ed7f8c52016-02-19 17:50:18586 }
587
588 return true;
589}
590
[email protected]daae1322013-09-05 18:26:50591const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
592
Eric Roman91aab1e62018-04-24 20:31:32593// Holds the callback and request parameters for an outstanding request.
594//
595// The RequestImpl is owned by the end user of host resolution. Deletion prior
596// to the request having completed means the request was cancelled by the
597// caller.
598//
599// Both the RequestImpl and its associated Job hold non-owning pointers to each
600// other. Care must be taken to clear the corresponding pointer when
601// cancellation is initiated by the Job (OnJobCancelled) vs by the end user
602// (~RequestImpl).
David Benjamina5677192018-04-23 23:25:42603class HostResolverImpl::RequestImpl
Eric Orth70992982018-07-24 00:25:00604 : public HostResolver::ResolveHostRequest,
David Benjamina5677192018-04-23 23:25:42605 public base::LinkNode<HostResolverImpl::RequestImpl> {
[email protected]b59ff372009-07-15 22:04:32606 public:
tfarina428341112016-09-22 13:38:20607 RequestImpl(const NetLogWithSource& source_net_log,
Eric Orth70992982018-07-24 00:25:00608 const HostPortPair& request_host,
Eric Orth00fe5a62018-08-15 22:20:00609 const base::Optional<ResolveHostParameters>& optional_parameters,
Eric Orth70992982018-07-24 00:25:00610 base::WeakPtr<HostResolverImpl> resolver)
[email protected]ee094b82010-08-24 15:55:51611 : source_net_log_(source_net_log),
Eric Orth70992982018-07-24 00:25:00612 request_host_(request_host),
Eric Orth00fe5a62018-08-15 22:20:00613 parameters_(optional_parameters ? optional_parameters.value()
614 : ResolveHostParameters()),
Eric Orthdc35748e2018-08-23 22:41:48615 host_resolver_flags_(ParametersToHostResolverFlags(parameters_)),
Eric Orth00fe5a62018-08-15 22:20:00616 priority_(parameters_.initial_priority),
Eric Orth70992982018-07-24 00:25:00617 job_(nullptr),
618 resolver_(resolver),
619 complete_(false) {}
[email protected]b59ff372009-07-15 22:04:32620
maksim.sisov31452af2016-07-27 06:38:10621 ~RequestImpl() override;
622
Eric Orth70992982018-07-24 00:25:00623 int Start(CompletionOnceCallback callback) override {
624 DCHECK(callback);
625 // Start() may only be called once per request.
626 DCHECK(!job_);
627 DCHECK(!complete_);
628 DCHECK(!callback_);
629 // Parent HostResolver must still be alive to call Start().
630 DCHECK(resolver_);
maksim.sisov31452af2016-07-27 06:38:10631
Eric Orth70992982018-07-24 00:25:00632 int rv = resolver_->Resolve(this);
633 DCHECK(!complete_);
634 if (rv == ERR_IO_PENDING) {
635 DCHECK(job_);
636 callback_ = std::move(callback);
637 } else {
638 DCHECK(!job_);
639 complete_ = true;
640 }
641 resolver_ = nullptr;
642
643 return rv;
644 }
645
646 const base::Optional<AddressList>& GetAddressResults() const override {
647 DCHECK(complete_);
Eric Orth07ee5f02018-11-29 00:42:03648 static const base::NoDestructor<base::Optional<AddressList>> nullopt_result;
649 return results_ ? results_.value().addresses() : *nullopt_result;
Eric Orth70992982018-07-24 00:25:00650 }
651
Eric Orth07ee5f02018-11-29 00:42:03652 const base::Optional<std::vector<std::string>>& GetTextResults()
653 const override {
654 DCHECK(complete_);
655 static const base::NoDestructor<base::Optional<std::vector<std::string>>>
656 nullopt_result;
657 return results_ ? results_.value().text_records() : *nullopt_result;
658 }
659
660 const base::Optional<std::vector<HostPortPair>>& GetHostnameResults()
661 const override {
662 DCHECK(complete_);
663 static const base::NoDestructor<base::Optional<std::vector<HostPortPair>>>
664 nullopt_result;
665 return results_ ? results_.value().hostnames() : *nullopt_result;
666 }
667
668 void set_results(HostCache::Entry results) {
Eric Orth70992982018-07-24 00:25:00669 // Should only be called at most once and before request is marked
670 // completed.
671 DCHECK(!complete_);
Eric Orth07ee5f02018-11-29 00:42:03672 DCHECK(!results_);
Eric Orthb30bc172018-08-17 21:09:57673 DCHECK(!parameters_.is_speculative);
Eric Orth70992982018-07-24 00:25:00674
Eric Orth07ee5f02018-11-29 00:42:03675 results_ = std::move(results);
Eric Orth70992982018-07-24 00:25:00676 }
677
678 void ChangeRequestPriority(RequestPriority priority);
679
680 void AssignJob(Job* job) {
681 DCHECK(job);
682 DCHECK(!job_);
683
684 job_ = job;
685 }
686
687 // Unassigns the Job without calling completion callback.
maksim.sisov31452af2016-07-27 06:38:10688 void OnJobCancelled(Job* job) {
689 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04690 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00691 DCHECK(!complete_);
692 DCHECK(callback_);
[email protected]aa22b242011-11-16 18:58:29693 callback_.Reset();
Eric Orth70992982018-07-24 00:25:00694
695 // No results should be set.
Eric Orth07ee5f02018-11-29 00:42:03696 DCHECK(!results_);
[email protected]b59ff372009-07-15 22:04:32697 }
698
Eric Orth70992982018-07-24 00:25:00699 // Cleans up Job assignment, marks request completed, and calls the completion
700 // callback.
701 void OnJobCompleted(Job* job, int error) {
maksim.sisov31452af2016-07-27 06:38:10702 DCHECK_EQ(job_, job);
maksim.sisov31452af2016-07-27 06:38:10703 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00704
705 DCHECK(!complete_);
706 complete_ = true;
707
708 DCHECK(callback_);
Bence Béky0f26a5812018-06-13 03:18:40709 std::move(callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32710 }
711
Eric Orth70992982018-07-24 00:25:00712 Job* job() const { return job_; }
[email protected]b59ff372009-07-15 22:04:32713
[email protected]0f292de02012-02-01 22:28:20714 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20715 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51716
Eric Orth70992982018-07-24 00:25:00717 const HostPortPair& request_host() const { return request_host_; }
718
Eric Orth00fe5a62018-08-15 22:20:00719 const ResolveHostParameters& parameters() const { return parameters_; }
720
Eric Orth322af3e42018-08-20 18:12:59721 HostResolverFlags host_resolver_flags() const { return host_resolver_flags_; }
722
[email protected]5109c1952013-08-20 18:44:10723 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31724 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10725
Eric Orth70992982018-07-24 00:25:00726 bool complete() const { return complete_; }
727
728 base::TimeTicks request_time() const {
729 DCHECK(!request_time_.is_null());
730 return request_time_;
731 }
732 void set_request_time(base::TimeTicks request_time) {
733 DCHECK(request_time_.is_null());
734 DCHECK(!request_time.is_null());
735 request_time_ = request_time;
736 }
[email protected]51b9a6b2012-06-25 21:50:29737
[email protected]b59ff372009-07-15 22:04:32738 private:
tfarina428341112016-09-22 13:38:20739 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09740
Eric Orth70992982018-07-24 00:25:00741 const HostPortPair request_host_;
Eric Orth00fe5a62018-08-15 22:20:00742 const ResolveHostParameters parameters_;
Eric Orth322af3e42018-08-20 18:12:59743 const HostResolverFlags host_resolver_flags_;
[email protected]5109c1952013-08-20 18:44:10744
juliatuttlec53b19a72016-05-05 13:51:31745 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32746
[email protected]0f292de02012-02-01 22:28:20747 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32748 Job* job_;
Eric Orth70992982018-07-24 00:25:00749 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]b59ff372009-07-15 22:04:32750
751 // The user's callback to invoke when the request completes.
Bence Béky0f26a5812018-06-13 03:18:40752 CompletionOnceCallback callback_;
[email protected]b59ff372009-07-15 22:04:32753
Eric Orth70992982018-07-24 00:25:00754 bool complete_;
Eric Orth07ee5f02018-11-29 00:42:03755 base::Optional<HostCache::Entry> results_;
[email protected]b59ff372009-07-15 22:04:32756
Eric Orth70992982018-07-24 00:25:00757 base::TimeTicks request_time_;
[email protected]51b9a6b2012-06-25 21:50:29758
maksim.sisov31452af2016-07-27 06:38:10759 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32760};
761
Eric Orth70992982018-07-24 00:25:00762// Wraps a RequestImpl to implement Request objects from the legacy Resolve()
763// API. The wrapped request must not yet have been started.
764//
765// TODO(crbug.com/821021): Delete this class once all usage has been
766// converted to the new CreateRequest() API.
767class HostResolverImpl::LegacyRequestImpl : public HostResolver::Request {
768 public:
769 explicit LegacyRequestImpl(std::unique_ptr<RequestImpl> inner_request)
770 : inner_request_(std::move(inner_request)) {
771 DCHECK(!inner_request_->job());
772 DCHECK(!inner_request_->complete());
773 }
774
775 ~LegacyRequestImpl() override {}
776
777 void ChangeRequestPriority(RequestPriority priority) override {
778 inner_request_->ChangeRequestPriority(priority);
779 }
780
781 int Start() {
782 return inner_request_->Start(base::BindOnce(
783 &LegacyRequestImpl::LegacyApiCallback, base::Unretained(this)));
784 }
785
786 // Do not call to assign the callback until we are running an async job (after
787 // Start() returns ERR_IO_PENDING) and before completion. Until then, the
788 // legacy HostResolverImpl::Resolve() needs to hang onto |callback| to ensure
789 // it stays alive for the duration of the method call, as some callers may be
790 // binding objects, eg the AddressList, with the callback.
791 void AssignCallback(CompletionOnceCallback callback,
792 AddressList* addresses_result_ptr) {
793 DCHECK(callback);
794 DCHECK(addresses_result_ptr);
795 DCHECK(inner_request_->job());
796 DCHECK(!inner_request_->complete());
797
798 callback_ = std::move(callback);
799 addresses_result_ptr_ = addresses_result_ptr;
800 }
801
802 const RequestImpl& inner_request() const { return *inner_request_; }
803
804 private:
805 // Result callback to bridge results handled entirely via ResolveHostRequest
806 // to legacy API styles where AddressList was a separate method out parameter.
807 void LegacyApiCallback(int error) {
808 // Must call AssignCallback() before async results.
809 DCHECK(callback_);
810
Eric Orthb30bc172018-08-17 21:09:57811 if (error == OK && !inner_request_->parameters().is_speculative) {
Eric Orth70992982018-07-24 00:25:00812 // Legacy API does not allow non-address results (eg TXT), so AddressList
813 // is always expected to be present on OK.
814 DCHECK(inner_request_->GetAddressResults());
815 *addresses_result_ptr_ = inner_request_->GetAddressResults().value();
816 }
817 addresses_result_ptr_ = nullptr;
818 std::move(callback_).Run(error);
819 }
820
821 const std::unique_ptr<RequestImpl> inner_request_;
822
823 CompletionOnceCallback callback_;
824 // This is a caller-provided pointer and should not be used once |callback_|
825 // is invoked.
826 AddressList* addresses_result_ptr_;
827
828 DISALLOW_COPY_AND_ASSIGN(LegacyRequestImpl);
829};
830
[email protected]1e9bbd22010-10-15 16:42:45831//------------------------------------------------------------------------------
832
Francois Doraya2d01ba2017-09-25 19:17:40833// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20834//
Miriam Gershenson02592182018-03-22 17:42:37835// In non-test code, the HostResolverProc is always SystemHostResolverProc,
836// which calls a platform API that implements host resolution.
837//
[email protected]0f292de02012-02-01 22:28:20838// Whenever we try to resolve the host, we post a delayed task to check if host
839// resolution (OnLookupComplete) is completed or not. If the original attempt
840// hasn't completed, then we start another attempt for host resolution. We take
841// the results from the first attempt that finishes and ignore the results from
842// all other attempts.
843//
844// TODO(szym): Move to separate source file for testing and mocking.
845//
Eric Orth9a037562018-07-03 21:24:38846class HostResolverImpl::ProcTask {
[email protected]b59ff372009-07-15 22:04:32847 public:
Eric Orth9a037562018-07-03 21:24:38848 typedef base::OnceCallback<void(int net_error, const AddressList& addr_list)>
849 Callback;
[email protected]b59ff372009-07-15 22:04:32850
[email protected]0f292de02012-02-01 22:28:20851 ProcTask(const Key& key,
852 const ProcTaskParams& params,
Eric Orth9a037562018-07-03 21:24:38853 Callback callback,
Miriam Gershensone42adb22017-10-16 16:19:38854 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:02855 const NetLogWithSource& job_net_log,
856 const base::TickClock* tick_clock)
[email protected]0f292de02012-02-01 22:28:20857 : key_(key),
858 params_(params),
Eric Orth9a037562018-07-03 21:24:38859 callback_(std::move(callback)),
mmenke91c17162016-06-02 16:03:23860 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38861 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20862 attempt_number_(0),
Misha Efimovb99e7da2018-05-30 16:59:02863 net_log_(job_net_log),
Eric Orth9a037562018-07-03 21:24:38864 tick_clock_(tick_clock),
865 weak_ptr_factory_(this) {
Eric Orth192e3bb2018-11-14 19:30:32866 // ProcTask only supports resolving addresses.
867 DCHECK(IsAddressType(key_.dns_query_type));
868
Eric Orth9a037562018-07-03 21:24:38869 DCHECK(callback_);
[email protected]90499482013-06-01 00:39:50870 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20871 params_.resolver_proc = HostResolverProc::GetDefault();
872 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50873 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06874 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32875 }
876
Eric Orth9a037562018-07-03 21:24:38877 // Cancels this ProcTask. Any outstanding resolve attempts running on worker
878 // thread will continue running, but they will post back to the network thread
879 // before checking their WeakPtrs to find that this task is cancelled.
880 ~ProcTask() {
881 DCHECK(network_task_runner_->BelongsToCurrentThread());
882
883 // If this is cancellation, log the EndEvent (otherwise this was logged in
884 // OnLookupComplete()).
885 if (!was_completed())
886 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
887 }
888
[email protected]b59ff372009-07-15 22:04:32889 void Start() {
mmenke91c17162016-06-02 16:03:23890 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38891 DCHECK(!was_completed());
mikecirone8b85c432016-09-08 19:11:00892 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54893 StartLookupAttempt();
894 }
[email protected]252b699b2010-02-05 21:38:06895
Eric Orth9a037562018-07-03 21:24:38896 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23897 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20898 return callback_.is_null();
899 }
900
[email protected]0f292de02012-02-01 22:28:20901 private:
Eric Orth9a037562018-07-03 21:24:38902 using AttemptCompletionCallback = base::OnceCallback<
903 void(const AddressList& results, int error, const int os_error)>;
[email protected]a9813302012-04-28 09:29:28904
[email protected]189163e2011-05-11 01:48:54905 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23906 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38907 DCHECK(!was_completed());
Misha Efimovb99e7da2018-05-30 16:59:02908 base::TimeTicks start_time = tick_clock_->NowTicks();
[email protected]189163e2011-05-11 01:48:54909 ++attempt_number_;
910 // Dispatch the lookup attempt to a worker thread.
Eric Orth9a037562018-07-03 21:24:38911 AttemptCompletionCallback completion_callback = base::BindOnce(
912 &ProcTask::OnLookupAttemptComplete, weak_ptr_factory_.GetWeakPtr(),
913 start_time, attempt_number_, tick_clock_);
Miriam Gershensone42adb22017-10-16 16:19:38914 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40915 FROM_HERE,
Eric Orth9a037562018-07-03 21:24:38916 base::BindOnce(&ProcTask::DoLookup, key_, params_.resolver_proc,
917 network_task_runner_, std::move(completion_callback)));
[email protected]13024882011-05-18 23:19:16918
mikecirone8b85c432016-09-08 19:11:00919 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28920 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16921
mmenke91c17162016-06-02 16:03:23922 // If the results aren't received within a given time, RetryIfNotComplete
923 // will start a new attempt if none of the outstanding attempts have
924 // completed yet.
Eric Orth9a037562018-07-03 21:24:38925 // Use a WeakPtr to avoid keeping the ProcTask alive after completion or
926 // cancellation.
[email protected]0f292de02012-02-01 22:28:20927 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23928 network_task_runner_->PostDelayedTask(
Eric Orth9a037562018-07-03 21:24:38929 FROM_HERE,
930 base::BindOnce(&ProcTask::StartLookupAttempt,
931 weak_ptr_factory_.GetWeakPtr()),
932 params_.unresponsive_delay *
933 std::pow(params_.retry_factor, attempt_number_ - 1));
[email protected]06ef6d92011-05-19 04:24:58934 }
[email protected]b59ff372009-07-15 22:04:32935 }
936
Francois Doraya2d01ba2017-09-25 19:17:40937 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
938 // shutdown code cannot wait for it to finish, so this code must be very
939 // careful about using other objects (like MessageLoops, Singletons, etc).
Eric Orth9a037562018-07-03 21:24:38940 // During shutdown these objects may no longer exist.
941 static void DoLookup(
942 Key key,
943 scoped_refptr<HostResolverProc> resolver_proc,
944 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
945 AttemptCompletionCallback completion_callback) {
[email protected]189163e2011-05-11 01:48:54946 AddressList results;
947 int os_error = 0;
Eric Orth192e3bb2018-11-14 19:30:32948 int error = resolver_proc->Resolve(
949 key.hostname, DnsQueryTypeToAddressFamily(key.dns_query_type),
950 key.host_resolver_flags, &results, &os_error);
[email protected]b59ff372009-07-15 22:04:32951
Eric Orth9a037562018-07-03 21:24:38952 network_task_runner->PostTask(
953 FROM_HERE, base::BindOnce(std::move(completion_callback), results,
954 error, os_error));
[email protected]189163e2011-05-11 01:48:54955 }
956
Eric Orth9a037562018-07-03 21:24:38957 // Callback for when DoLookup() completes (runs on task runner thread). Now
958 // that we're back in the network thread, checks that |proc_task| is still
959 // valid, and if so, passes back to the object.
960 static void OnLookupAttemptComplete(base::WeakPtr<ProcTask> proc_task,
961 const base::TimeTicks& start_time,
962 const uint32_t attempt_number,
963 const base::TickClock* tick_clock,
964 const AddressList& results,
965 int error,
966 const int os_error) {
Alexandr Ilin33126632018-11-14 14:48:17967 TRACE_EVENT0(NetTracingCategory(), "ProcTask::OnLookupComplete");
Eric Orth9a037562018-07-03 21:24:38968
[email protected]49b70b222013-05-07 21:24:23969 // If results are empty, we should return an error.
970 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23971 if (empty_list_on_ok)
972 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54973
[email protected]2d3b7762010-10-09 00:35:47974 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20975 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23976 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54977 if (error != OK && NetworkChangeNotifier::IsOffline())
978 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47979
Paul Jensenb7352f92018-11-08 00:02:49980 if (!proc_task)
Luciano Pachecob4426082018-07-02 08:04:18981 return;
Eric Orth9a037562018-07-03 21:24:38982
983 proc_task->OnLookupComplete(results, start_time, attempt_number, error,
984 os_error);
985 }
986
987 void OnLookupComplete(const AddressList& results,
988 const base::TimeTicks& start_time,
989 const uint32_t attempt_number,
990 int error,
991 const int os_error) {
992 DCHECK(network_task_runner_->BelongsToCurrentThread());
993 DCHECK(!was_completed());
994
995 // Invalidate WeakPtrs to cancel handling of all outstanding lookup attempts
996 // and retries.
997 weak_ptr_factory_.InvalidateWeakPtrs();
998
Eric Orthcb8862f2018-06-27 18:08:35999 NetLogParametersCallback net_log_callback;
Eric Orth9a037562018-07-03 21:24:381000 NetLogParametersCallback attempt_net_log_callback;
[email protected]0f292de02012-02-01 22:28:201001 if (error != OK) {
Eric Orth70992982018-07-24 00:25:001002 net_log_callback = base::BindRepeating(&NetLogProcTaskFailedCallback, 0,
1003 error, os_error);
1004 attempt_net_log_callback = base::BindRepeating(
1005 &NetLogProcTaskFailedCallback, attempt_number, error, os_error);
[email protected]ee094b82010-08-24 15:55:511006 } else {
Eric Orth9a037562018-07-03 21:24:381007 net_log_callback = results.CreateNetLogCallback();
1008 attempt_net_log_callback =
1009 NetLog::IntCallback("attempt_number", attempt_number);
[email protected]ee094b82010-08-24 15:55:511010 }
mikecirone8b85c432016-09-08 19:11:001011 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:451012 net_log_callback);
Eric Orth9a037562018-07-03 21:24:381013 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
1014 attempt_net_log_callback);
[email protected]ee094b82010-08-24 15:55:511015
Eric Orth9a037562018-07-03 21:24:381016 std::move(callback_).Run(error, results);
[email protected]b59ff372009-07-15 22:04:321017 }
1018
[email protected]123ab1e32009-10-21 19:12:571019 Key key_;
[email protected]b59ff372009-07-15 22:04:321020
[email protected]0f292de02012-02-01 22:28:201021 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:321022 // This may not be the current resolver procedure by the time we call
1023 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
1024 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:201025 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:321026
[email protected]0f292de02012-02-01 22:28:201027 // The listener to the results of this ProcTask.
1028 Callback callback_;
1029
mmenke91c17162016-06-02 16:03:231030 // Used to post events onto the network thread.
1031 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:381032 // Used to post blocking HostResolverProc tasks.
1033 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:541034
1035 // Keeps track of the number of attempts we have made so far to resolve the
1036 // host. Whenever we start an attempt to resolve the host, we increase this
1037 // number.
Avi Drissman13fc8932015-12-20 04:40:461038 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:541039
tfarina428341112016-09-22 13:38:201040 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:511041
Misha Efimovb99e7da2018-05-30 16:59:021042 const base::TickClock* tick_clock_;
1043
Eric Orth9a037562018-07-03 21:24:381044 // Used to loop back from the blocking lookup attempt tasks as well as from
1045 // delayed retry tasks. Invalidate WeakPtrs on completion and cancellation to
1046 // cancel handling of such posted tasks.
1047 base::WeakPtrFactory<ProcTask> weak_ptr_factory_;
1048
[email protected]0f292de02012-02-01 22:28:201049 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:321050};
1051
1052//-----------------------------------------------------------------------------
1053
Miriam Gershenson02592182018-03-22 17:42:371054// Resolves the hostname using DnsTransaction, which is a full implementation of
1055// a DNS stub resolver. One DnsTransaction is created for each resolution
1056// needed, which for AF_UNSPEC resolutions includes both A and AAAA. The
1057// transactions are scheduled separately and started separately.
1058//
[email protected]b3601bc22012-02-21 21:23:201059// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461060class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201061 public:
[email protected]daae1322013-09-05 18:26:501062 class Delegate {
1063 public:
1064 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
Eric Orth07ee5f02018-11-29 00:42:031065 const HostCache::Entry& results) = 0;
[email protected]daae1322013-09-05 18:26:501066
1067 // Called when the first of two jobs succeeds. If the first completed
1068 // transaction fails, this is not called. Also not called when the DnsTask
1069 // only needs to run one transaction.
1070 virtual void OnFirstDnsTransactionComplete() = 0;
1071
Brad Lassey786929ad2018-02-21 20:54:271072 virtual URLRequestContext* url_request_context() = 0;
1073 virtual RequestPriority priority() const = 0;
1074
[email protected]daae1322013-09-05 18:26:501075 protected:
Chris Watkins68b15032017-12-01 03:07:131076 Delegate() = default;
1077 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:501078 };
[email protected]b3601bc22012-02-21 21:23:201079
[email protected]0adcb2b2012-08-15 21:30:461080 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201081 const Key& key,
Eric Orth60931742018-11-05 23:40:571082 bool allow_fallback_resolution,
[email protected]daae1322013-09-05 18:26:501083 Delegate* delegate,
Misha Efimovb99e7da2018-05-30 16:59:021084 const NetLogWithSource& job_net_log,
1085 const base::TickClock* tick_clock)
[email protected]0adcb2b2012-08-15 21:30:461086 : client_(client),
[email protected]daae1322013-09-05 18:26:501087 key_(key),
Eric Orth60931742018-11-05 23:40:571088 allow_fallback_resolution_(allow_fallback_resolution),
[email protected]daae1322013-09-05 18:26:501089 delegate_(delegate),
1090 net_log_(job_net_log),
1091 num_completed_transactions_(0),
Misha Efimovb99e7da2018-05-30 16:59:021092 tick_clock_(tick_clock),
1093 task_start_time_(tick_clock_->NowTicks()) {
[email protected]0adcb2b2012-08-15 21:30:461094 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501095 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501096 }
1097
Eric Orth60931742018-11-05 23:40:571098 bool allow_fallback_resolution() const { return allow_fallback_resolution_; }
1099
[email protected]daae1322013-09-05 18:26:501100 bool needs_two_transactions() const {
Eric Orth192e3bb2018-11-14 19:30:321101 return key_.dns_query_type == DnsQueryType::UNSPECIFIED;
[email protected]daae1322013-09-05 18:26:501102 }
1103
1104 bool needs_another_transaction() const {
Eric Orth192e3bb2018-11-14 19:30:321105 return needs_two_transactions() && !transaction2_;
[email protected]daae1322013-09-05 18:26:501106 }
1107
1108 void StartFirstTransaction() {
1109 DCHECK_EQ(0u, num_completed_transactions_);
Eric Orth192e3bb2018-11-14 19:30:321110 DCHECK(!transaction1_);
1111
mikecirone8b85c432016-09-08 19:11:001112 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
Eric Orth192e3bb2018-11-14 19:30:321113 if (key_.dns_query_type == DnsQueryType::UNSPECIFIED) {
1114 transaction1_ = CreateTransaction(DnsQueryType::A);
[email protected]daae1322013-09-05 18:26:501115 } else {
Eric Orth192e3bb2018-11-14 19:30:321116 transaction1_ = CreateTransaction(key_.dns_query_type);
[email protected]daae1322013-09-05 18:26:501117 }
Eric Orth192e3bb2018-11-14 19:30:321118 transaction1_->Start();
[email protected]daae1322013-09-05 18:26:501119 }
1120
1121 void StartSecondTransaction() {
Eric Orth192e3bb2018-11-14 19:30:321122 DCHECK(needs_another_transaction());
1123 transaction2_ = CreateTransaction(DnsQueryType::AAAA);
1124 transaction2_->Start();
[email protected]70c04ab2013-08-22 16:05:121125 }
1126
[email protected]70c04ab2013-08-22 16:05:121127 private:
Eric Orth192e3bb2018-11-14 19:30:321128 std::unique_ptr<DnsTransaction> CreateTransaction(
1129 DnsQueryType dns_query_type) {
1130 DCHECK_NE(DnsQueryType::UNSPECIFIED, dns_query_type);
Brad Lassey786929ad2018-02-21 20:54:271131 std::unique_ptr<DnsTransaction> trans =
1132 client_->GetTransactionFactory()->CreateTransaction(
Eric Orth192e3bb2018-11-14 19:30:321133 key_.hostname, DnsQueryTypeToQtype(dns_query_type),
Brad Lasseydba0a84b2018-02-23 22:18:531134 base::BindOnce(&DnsTask::OnTransactionComplete,
Eric Orth07ee5f02018-11-29 00:42:031135 base::Unretained(this), tick_clock_->NowTicks(),
1136 dns_query_type),
Brad Lassey786929ad2018-02-21 20:54:271137 net_log_);
1138 trans->SetRequestContext(delegate_->url_request_context());
1139 trans->SetRequestPriority(delegate_->priority());
1140 return trans;
[email protected]daae1322013-09-05 18:26:501141 }
1142
1143 void OnTransactionComplete(const base::TimeTicks& start_time,
Eric Orth07ee5f02018-11-29 00:42:031144 DnsQueryType dns_query_type,
[email protected]1def74c2012-03-22 20:07:001145 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201146 int net_error,
1147 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471148 DCHECK(transaction);
Misha Efimovb99e7da2018-05-30 16:59:021149 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Brad Lassey2e8f185d2018-05-21 22:25:211150 if (net_error != OK && !(net_error == ERR_NAME_NOT_RESOLVED && response &&
1151 response->IsValid())) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211152 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
Eric Orth07ee5f02018-11-29 00:42:031153 OnFailure(net_error, DnsResponse::DNS_PARSE_OK, base::nullopt);
[email protected]0adcb2b2012-08-15 21:30:461154 return;
[email protected]6c411902012-08-14 22:36:361155 }
[email protected]0adcb2b2012-08-15 21:30:461156
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211157 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511158 switch (transaction->GetType()) {
1159 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211160 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511161 break;
1162 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211163 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1164 duration);
[email protected]02cd6982013-01-10 20:12:511165 break;
1166 }
[email protected]daae1322013-09-05 18:26:501167
Eric Orth07ee5f02018-11-29 00:42:031168 DnsResponse::Result parse_result = DnsResponse::DNS_PARSE_RESULT_MAX;
1169 HostCache::Entry results(ERR_FAILED, HostCache::Entry::SOURCE_UNKNOWN);
1170 switch (dns_query_type) {
1171 case DnsQueryType::UNSPECIFIED:
1172 // Should create two separate transactions with specified type.
1173 NOTREACHED();
1174 break;
1175 case DnsQueryType::A:
1176 case DnsQueryType::AAAA:
1177 parse_result = ParseAddressDnsResponse(response, &results);
1178 break;
1179 }
1180 DCHECK_LT(parse_result, DnsResponse::DNS_PARSE_RESULT_MAX);
1181
1182 if (results.error() != OK && results.error() != ERR_NAME_NOT_RESOLVED) {
1183 OnFailure(results.error(), parse_result, results.GetOptionalTtl());
[email protected]0adcb2b2012-08-15 21:30:461184 return;
1185 }
1186
Eric Orth07ee5f02018-11-29 00:42:031187 // Merge results with saved results from previous transactions.
1188 if (saved_results_) {
1189 DCHECK(needs_two_transactions());
1190 DCHECK_GE(1u, num_completed_transactions_);
1191
1192 switch (dns_query_type) {
1193 case DnsQueryType::A:
1194 // A results in |results| go after other results in |saved_results_|,
1195 // so merge |saved_results_| to the front.
1196 results = HostCache::Entry::MergeEntries(
1197 std::move(saved_results_).value(), std::move(results));
1198 break;
1199 case DnsQueryType::AAAA:
1200 // AAAA results in |results| go before other results in
1201 // |saved_results_|, so merge |saved_results_| to the back.
1202 results = HostCache::Entry::MergeEntries(
1203 std::move(results), std::move(saved_results_).value());
1204 break;
1205 default:
1206 // Only expect address query types with multiple transactions.
1207 NOTREACHED();
1208 }
1209 }
1210
1211 // If not all transactions are complete, the task cannot yet be completed
1212 // and the results so far must be saved to merge with additional results.
[email protected]daae1322013-09-05 18:26:501213 ++num_completed_transactions_;
[email protected]daae1322013-09-05 18:26:501214 if (needs_two_transactions() && num_completed_transactions_ == 1) {
Eric Orth07ee5f02018-11-29 00:42:031215 saved_results_ = std::move(results);
[email protected]daae1322013-09-05 18:26:501216 // No need to repeat the suffix search.
1217 key_.hostname = transaction->GetHostname();
1218 delegate_->OnFirstDnsTransactionComplete();
1219 return;
1220 }
1221
[email protected]daae1322013-09-05 18:26:501222 // If there are multiple addresses, and at least one is IPv6, need to sort
1223 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1224 // sufficient to just check the family of the first address.
Eric Orth07ee5f02018-11-29 00:42:031225 if (results.addresses() && results.addresses().value().size() > 1 &&
1226 results.addresses().value()[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]daae1322013-09-05 18:26:501227 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461228 client_->GetAddressSorter()->Sort(
Eric Orth07ee5f02018-11-29 00:42:031229 results.addresses().value(),
1230 base::BindOnce(&DnsTask::OnSortComplete, AsWeakPtr(),
1231 tick_clock_->NowTicks(), std::move(results)));
1232 return;
[email protected]0adcb2b2012-08-15 21:30:461233 }
Eric Orth07ee5f02018-11-29 00:42:031234
1235 OnSuccess(results);
[email protected]0adcb2b2012-08-15 21:30:461236 }
1237
Eric Orth07ee5f02018-11-29 00:42:031238 DnsResponse::Result ParseAddressDnsResponse(const DnsResponse* response,
1239 HostCache::Entry* out_results) {
1240 AddressList addresses;
1241 base::TimeDelta ttl;
1242 DnsResponse::Result parse_result =
1243 response->ParseToAddressList(&addresses, &ttl);
1244 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList", parse_result,
1245 DnsResponse::DNS_PARSE_RESULT_MAX);
1246
1247 if (parse_result != DnsResponse::DNS_PARSE_OK) {
1248 *out_results = HostCache::Entry(ERR_DNS_MALFORMED_RESPONSE, AddressList(),
1249 HostCache::Entry::SOURCE_DNS);
1250 } else if (addresses.empty()) {
1251 *out_results = HostCache::Entry(ERR_NAME_NOT_RESOLVED, AddressList(),
1252 HostCache::Entry::SOURCE_DNS, ttl);
1253 } else {
1254 *out_results = HostCache::Entry(OK, std::move(addresses),
1255 HostCache::Entry::SOURCE_DNS, ttl);
1256 }
1257 return parse_result;
1258 }
1259
1260 void OnSortComplete(base::TimeTicks sort_start_time,
1261 HostCache::Entry results,
[email protected]0adcb2b2012-08-15 21:30:461262 bool success,
1263 const AddressList& addr_list) {
Eric Orth07ee5f02018-11-29 00:42:031264 results.set_addresses(addr_list);
1265
[email protected]0adcb2b2012-08-15 21:30:461266 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211267 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
Eric Orth07ee5f02018-11-29 00:42:031268 tick_clock_->NowTicks() - sort_start_time);
1269 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK,
1270 results.GetOptionalTtl());
[email protected]0adcb2b2012-08-15 21:30:461271 return;
1272 }
1273
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211274 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
Eric Orth07ee5f02018-11-29 00:42:031275 tick_clock_->NowTicks() - sort_start_time);
[email protected]0adcb2b2012-08-15 21:30:461276
1277 // AddressSorter prunes unusable destinations.
Eric Orth07ee5f02018-11-29 00:42:031278 if (addr_list.empty() &&
1279 results.text_records().value_or(std::vector<std::string>()).empty() &&
1280 results.hostnames().value_or(std::vector<HostPortPair>()).empty()) {
[email protected]0adcb2b2012-08-15 21:30:461281 LOG(WARNING) << "Address list empty after RFC3484 sort";
Eric Orth07ee5f02018-11-29 00:42:031282 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK,
1283 results.GetOptionalTtl());
[email protected]0adcb2b2012-08-15 21:30:461284 return;
1285 }
1286
Eric Orth07ee5f02018-11-29 00:42:031287 OnSuccess(results);
[email protected]0adcb2b2012-08-15 21:30:461288 }
1289
Eric Orth07ee5f02018-11-29 00:42:031290 void OnFailure(int net_error,
1291 DnsResponse::Result parse_result,
1292 base::Optional<base::TimeDelta> ttl) {
[email protected]0adcb2b2012-08-15 21:30:461293 DCHECK_NE(OK, net_error);
Eric Orth07ee5f02018-11-29 00:42:031294
1295 HostCache::Entry results(net_error, HostCache::Entry::SOURCE_UNKNOWN);
1296
1297 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
1298 base::Bind(&NetLogDnsTaskFailedCallback, results.error(),
1299 parse_result, results.CreateNetLogCallback()));
1300
1301 // If we have a TTL from a previously completed transaction, use it.
1302 base::TimeDelta previous_transaction_ttl;
1303 if (saved_results_ && saved_results_.value().has_ttl() &&
1304 saved_results_.value().ttl() <
1305 base::TimeDelta::FromSeconds(
1306 std::numeric_limits<uint32_t>::max())) {
1307 previous_transaction_ttl = saved_results_.value().ttl();
1308 if (ttl)
1309 results.set_ttl(std::min(ttl.value(), previous_transaction_ttl));
1310 else
1311 results.set_ttl(previous_transaction_ttl);
1312 } else if (ttl) {
1313 results.set_ttl(ttl.value());
1314 }
1315
1316 delegate_->OnDnsTaskComplete(task_start_time_, results);
[email protected]b3601bc22012-02-21 21:23:201317 }
1318
Eric Orth07ee5f02018-11-29 00:42:031319 void OnSuccess(const HostCache::Entry& results) {
mikecirone8b85c432016-09-08 19:11:001320 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
Eric Orth07ee5f02018-11-29 00:42:031321 results.CreateNetLogCallback());
1322 delegate_->OnDnsTaskComplete(task_start_time_, results);
[email protected]0adcb2b2012-08-15 21:30:461323 }
1324
1325 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501326 Key key_;
1327
Eric Orth60931742018-11-05 23:40:571328 // Whether resolution may fallback to other task types (e.g. ProcTask) on
1329 // failure of this task.
1330 bool allow_fallback_resolution_;
1331
[email protected]b3601bc22012-02-21 21:23:201332 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501333 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201334 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201335
Eric Orth192e3bb2018-11-14 19:30:321336 std::unique_ptr<DnsTransaction> transaction1_;
1337 std::unique_ptr<DnsTransaction> transaction2_;
[email protected]0adcb2b2012-08-15 21:30:461338
[email protected]daae1322013-09-05 18:26:501339 unsigned num_completed_transactions_;
1340
Eric Orth07ee5f02018-11-29 00:42:031341 // Result from previously completed transactions. Only set if a transaction
1342 // has completed while others are still in progress.
1343 base::Optional<HostCache::Entry> saved_results_;
[email protected]daae1322013-09-05 18:26:501344
Misha Efimovb99e7da2018-05-30 16:59:021345 const base::TickClock* tick_clock_;
[email protected]daae1322013-09-05 18:26:501346 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461347
1348 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201349};
1350
1351//-----------------------------------------------------------------------------
1352
[email protected]0f292de02012-02-01 22:28:201353// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501354class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1355 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391356 public:
[email protected]0f292de02012-02-01 22:28:201357 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351358 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181359 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201360 const Key& key,
[email protected]8c98d002012-07-18 19:02:271361 RequestPriority priority,
Miriam Gershensone42adb22017-10-16 16:19:381362 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:021363 const NetLogWithSource& source_net_log,
1364 const base::TickClock* tick_clock)
[email protected]12faa4c2012-11-06 04:44:181365 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201366 key_(key),
[email protected]8c98d002012-07-18 19:02:271367 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381368 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201369 had_non_speculative_request_(false),
[email protected]daae1322013-09-05 18:26:501370 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331371 dns_task_error_(OK),
Misha Efimovb99e7da2018-05-30 16:59:021372 tick_clock_(tick_clock),
tfarina428341112016-09-22 13:38:201373 net_log_(
1374 NetLogWithSource::Make(source_net_log.net_log(),
Eric Orth60931742018-11-05 23:40:571375 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)),
1376 weak_ptr_factory_(this) {
mikecirone8b85c432016-09-08 19:11:001377 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201378
mikecirone8b85c432016-09-08 19:11:001379 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1380 base::Bind(&NetLogJobCreationCallback,
1381 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391382 }
1383
dchengb03027d2014-10-21 12:00:201384 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201385 if (is_running()) {
1386 // |resolver_| was destroyed with this Job still in flight.
1387 // Clean-up, record in the log, but don't run any callbacks.
Eric Orth9a037562018-07-03 21:24:381388 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351389 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501390 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001391 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201392 ERR_ABORTED);
1393 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551394 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351395 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001396 net_log_.AddEvent(NetLogEventType::CANCELLED);
1397 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391398 }
[email protected]b3601bc22012-02-21 21:23:201399 // else CompleteRequests logged EndEvent.
David Benjamina5677192018-04-23 23:25:421400 while (!requests_.empty()) {
maksim.sisov31452af2016-07-27 06:38:101401 // Log any remaining Requests as cancelled.
David Benjamina5677192018-04-23 23:25:421402 RequestImpl* req = requests_.head()->value();
1403 req->RemoveFromList();
1404 DCHECK_EQ(this, req->job());
Eric Orth70992982018-07-24 00:25:001405 LogCancelRequest(req->source_net_log());
David Benjamina5677192018-04-23 23:25:421406 req->OnJobCancelled(this);
[email protected]b3601bc22012-02-21 21:23:201407 }
[email protected]68ad3ee2010-01-30 03:45:391408 }
1409
[email protected]daae1322013-09-05 18:26:501410 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1411 // of the queue.
1412 void Schedule(bool at_head) {
1413 DCHECK(!is_queued());
1414 PrioritizedDispatcher::Handle handle;
1415 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001416 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501417 } else {
[email protected]106ccd2c2014-06-17 09:21:001418 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501419 }
1420 // The dispatcher could have started |this| in the above call to Add, which
1421 // could have called Schedule again. In that case |handle| will be null,
1422 // but |handle_| may have been set by the other nested call to Schedule.
1423 if (!handle.is_null()) {
1424 DCHECK(handle_.is_null());
1425 handle_ = handle;
1426 }
[email protected]16ee26d2012-03-08 03:34:351427 }
1428
maksim.sisov31452af2016-07-27 06:38:101429 void AddRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001430 DCHECK_EQ(key_.hostname, request->request_host().host());
1431
1432 request->AssignJob(this);
[email protected]0f292de02012-02-01 22:28:201433
maksim.sisov31452af2016-07-27 06:38:101434 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201435
maksim.sisov31452af2016-07-27 06:38:101436 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001437 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451438 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201439
1440 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001441 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101442 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451443 priority()));
[email protected]0f292de02012-02-01 22:28:201444
Eric Orthb30bc172018-08-17 21:09:571445 if (!request->parameters().is_speculative)
[email protected]0f292de02012-02-01 22:28:201446 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201447
David Benjamina5677192018-04-23 23:25:421448 requests_.Append(request);
[email protected]b3601bc22012-02-21 21:23:201449
[email protected]51b9a6b2012-06-25 21:50:291450 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391451 }
1452
maksim.sisov31452af2016-07-27 06:38:101453 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
Eric Orth70992982018-07-24 00:25:001454 DCHECK_EQ(key_.hostname, req->request_host().host());
juliatuttlec53b19a72016-05-05 13:51:311455
1456 priority_tracker_.Remove(req->priority());
1457 req->set_priority(priority);
1458 priority_tracker_.Add(req->priority());
1459 UpdatePriority();
1460 }
1461
maksim.sisov31452af2016-07-27 06:38:101462 // Detach cancelled request. If it was the last active Request, also finishes
1463 // this Job.
1464 void CancelRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001465 DCHECK_EQ(key_.hostname, request->request_host().host());
maksim.sisov31452af2016-07-27 06:38:101466 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351467
Eric Orth70992982018-07-24 00:25:001468 LogCancelRequest(request->source_net_log());
[email protected]16ee26d2012-03-08 03:34:351469
maksim.sisov31452af2016-07-27 06:38:101470 priority_tracker_.Remove(request->priority());
1471 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001472 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101473 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1474 priority()));
[email protected]b3601bc22012-02-21 21:23:201475
[email protected]16ee26d2012-03-08 03:34:351476 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291477 UpdatePriority();
David Benjamina5677192018-04-23 23:25:421478 request->RemoveFromList();
[email protected]16ee26d2012-03-08 03:34:351479 } else {
1480 // If we were called from a Request's callback within CompleteRequests,
1481 // that Request could not have been cancelled, so num_active_requests()
1482 // could not be 0. Therefore, we are not in CompleteRequests().
Eric Orth07ee5f02018-11-29 00:42:031483 CompleteRequestsWithError(ERR_FAILED /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201484 }
[email protected]68ad3ee2010-01-30 03:45:391485 }
1486
[email protected]7af985a2012-12-14 22:40:421487 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1488 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111489 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201490 void Abort() {
[email protected]0f292de02012-02-01 22:28:201491 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421492 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201493 }
1494
Eric Orth60931742018-11-05 23:40:571495 // Gets a closure that will abort a DnsTask (see AbortDnsTask()) iff |this| is
1496 // still valid. Useful if aborting a list of Jobs as some may be cancelled
1497 // while aborting others.
1498 base::OnceClosure GetAbortDnsTaskClosure(int error, bool fallback_only) {
1499 return base::BindOnce(&Job::AbortDnsTask, weak_ptr_factory_.GetWeakPtr(),
1500 error, fallback_only);
1501 }
1502
1503 // If DnsTask present, abort it. Depending on task settings, either fall back
1504 // to ProcTask or abort the job entirely. Warning, aborting a job may cause
1505 // other jobs to be aborted, thus |jobs_| may be unpredictably changed by
1506 // calling this method.
1507 //
1508 // |error| is the net error that will be returned to requests if this method
1509 // results in completely aborting the job.
1510 void AbortDnsTask(int error, bool fallback_only) {
[email protected]f0f602bd2012-11-15 18:01:021511 if (dns_task_) {
Eric Orth60931742018-11-05 23:40:571512 if (dns_task_->allow_fallback_resolution()) {
1513 KillDnsTask();
1514 dns_task_error_ = OK;
1515 StartProcTask();
1516 } else if (!fallback_only) {
1517 CompleteRequestsWithError(error);
1518 }
[email protected]f0f602bd2012-11-15 18:01:021519 }
1520 }
1521
[email protected]16ee26d2012-03-08 03:34:351522 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1523 // Completes all requests and destroys the job.
1524 void OnEvicted() {
1525 DCHECK(!is_running());
1526 DCHECK(is_queued());
1527 handle_.Reset();
1528
mikecirone8b85c432016-09-08 19:11:001529 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351530
1531 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431532 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351533 }
1534
[email protected]78eac2a2012-03-14 19:09:271535 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1536 // this Job was destroyed.
1537 bool ServeFromHosts() {
1538 DCHECK_GT(num_active_requests(), 0u);
Eric Orth07ee5f02018-11-29 00:42:031539 base::Optional<HostCache::Entry> results = resolver_->ServeFromHosts(key());
1540 if (results) {
[email protected]78eac2a2012-03-14 19:09:271541 // This will destroy the Job.
Eric Orth07ee5f02018-11-29 00:42:031542 CompleteRequests(results.value(), base::TimeDelta(),
1543 true /* allow_cache */);
[email protected]78eac2a2012-03-14 19:09:271544 return true;
1545 }
1546 return false;
1547 }
1548
tanay.c6ddd5f6f2015-08-25 06:34:571549 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111550
1551 bool is_queued() const {
1552 return !handle_.is_null();
1553 }
1554
1555 bool is_running() const {
Eric Orth9871aafa2018-10-02 19:59:181556 return is_dns_running() || is_mdns_running() || is_proc_running();
[email protected]b4481b222012-03-16 17:13:111557 }
1558
[email protected]16ee26d2012-03-08 03:34:351559 private:
[email protected]daae1322013-09-05 18:26:501560 void KillDnsTask() {
1561 if (dns_task_) {
1562 ReduceToOneJobSlot();
1563 dns_task_.reset();
1564 }
1565 }
1566
1567 // Reduce the number of job slots occupied and queued in the dispatcher
1568 // to one. If the second Job slot is queued in the dispatcher, cancels the
1569 // queued job. Otherwise, the second Job has been started by the
1570 // PrioritizedDispatcher, so signals it is complete.
1571 void ReduceToOneJobSlot() {
1572 DCHECK_GE(num_occupied_job_slots_, 1u);
1573 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001574 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501575 handle_.Reset();
1576 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001577 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501578 --num_occupied_job_slots_;
1579 }
1580 DCHECK_EQ(1u, num_occupied_job_slots_);
1581 }
1582
[email protected]51b9a6b2012-06-25 21:50:291583 void UpdatePriority() {
Paul Jensenb7352f92018-11-08 00:02:491584 if (is_queued())
[email protected]106ccd2c2014-06-17 09:21:001585 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291586 }
1587
[email protected]16ee26d2012-03-08 03:34:351588 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201589 void Start() override {
[email protected]daae1322013-09-05 18:26:501590 DCHECK_LE(num_occupied_job_slots_, 1u);
1591
[email protected]70c04ab2013-08-22 16:05:121592 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501593 ++num_occupied_job_slots_;
1594
1595 if (num_occupied_job_slots_ == 2) {
1596 StartSecondDnsTransaction();
1597 return;
1598 }
1599
1600 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201601
mikecirone8b85c432016-09-08 19:11:001602 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201603
Misha Efimovb99e7da2018-05-30 16:59:021604 start_time_ = tick_clock_->NowTicks();
[email protected]51b9a6b2012-06-25 21:50:291605
Eric Orthdc35748e2018-08-23 22:41:481606 switch (key_.host_resolver_source) {
1607 case HostResolverSource::ANY:
Eric Orth60931742018-11-05 23:40:571608 if (!ResemblesMulticastDNSName(key_.hostname)) {
1609 StartDnsTask(true /* allow_fallback_resolution */);
Eric Orthdc35748e2018-08-23 22:41:481610 } else {
1611 StartProcTask();
1612 }
1613 break;
1614 case HostResolverSource::SYSTEM:
1615 StartProcTask();
1616 break;
1617 case HostResolverSource::DNS:
Eric Orth60931742018-11-05 23:40:571618 StartDnsTask(false /* allow_fallback_resolution */);
Eric Orthdc35748e2018-08-23 22:41:481619 break;
Eric Orth9871aafa2018-10-02 19:59:181620 case HostResolverSource::MULTICAST_DNS:
1621 StartMdnsTask();
1622 break;
Eric Orthdc35748e2018-08-23 22:41:481623 }
[email protected]443714fad2013-09-19 04:52:011624
[email protected]1d932852012-06-19 19:40:331625 // Caution: Job::Start must not complete synchronously.
[email protected]b3601bc22012-02-21 21:23:201626 }
1627
[email protected]b3601bc22012-02-21 21:23:201628 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401629 // the limits on |dispatcher_|. But in order to keep the number of
1630 // TaskScheduler threads low, we will need to use an "inner"
1631 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201632 void StartProcTask() {
Eric Orth9871aafa2018-10-02 19:59:181633 DCHECK(!is_running());
Eric Orth9a037562018-07-03 21:24:381634 proc_task_ = std::make_unique<ProcTask>(
Misha Efimovb99e7da2018-05-30 16:59:021635 key_, resolver_->proc_params_,
Eric Orth70992982018-07-24 00:25:001636 base::BindOnce(&Job::OnProcTaskComplete, base::Unretained(this),
1637 tick_clock_->NowTicks()),
Misha Efimovb99e7da2018-05-30 16:59:021638 proc_task_runner_, net_log_, tick_clock_);
[email protected]0f292de02012-02-01 22:28:201639
[email protected]0f292de02012-02-01 22:28:201640 // Start() could be called from within Resolve(), hence it must NOT directly
1641 // call OnProcTaskComplete, for example, on synchronous failure.
1642 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391643 }
1644
[email protected]0f292de02012-02-01 22:28:201645 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371646 void OnProcTaskComplete(base::TimeTicks start_time,
1647 int net_error,
1648 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201649 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391650
[email protected]1d932852012-06-19 19:40:331651 if (dns_task_error_ != OK) {
Eric Orth60931742018-11-05 23:40:571652 // This ProcTask was a fallback resolution after a failed DnsTask.
Misha Efimovb99e7da2018-05-30 16:59:021653 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]1def74c2012-03-22 20:07:001654 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211655 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331656 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1657 ResemblesNetBIOSName(key_.hostname)) {
1658 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1659 } else {
1660 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1661 }
Ilya Sherman0eb39802017-12-08 20:58:181662 base::UmaHistogramSparse("Net.DNS.DnsTask.Errors",
1663 std::abs(dns_task_error_));
Eric Orth60931742018-11-05 23:40:571664 resolver_->OnFallbackResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001665 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211666 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001667 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1668 }
1669 }
1670
eroman1efc237c2016-12-14 00:00:451671 if (ContainsIcannNameCollisionIp(addr_list))
1672 net_error = ERR_ICANN_NAME_COLLISION;
1673
[email protected]1339a2a22012-10-17 08:39:431674 base::TimeDelta ttl =
1675 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201676 if (net_error == OK)
1677 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391678
Rob Percival94f21ad2017-11-14 10:20:241679 // Source unknown because the system resolver could have gotten it from a
1680 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171681 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241682 CompleteRequests(
Eric Orth07ee5f02018-11-29 00:42:031683 HostCache::Entry(net_error,
1684 net_error == OK
1685 ? AddressList::CopyWithPort(addr_list, 0)
1686 : AddressList(),
1687 HostCache::Entry::SOURCE_UNKNOWN),
Eric Orth9871aafa2018-10-02 19:59:181688 ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201689 }
1690
Eric Orth60931742018-11-05 23:40:571691 void StartDnsTask(bool allow_fallback_resolution) {
1692 if ((!resolver_->HaveDnsConfig() || resolver_->use_proctask_by_default_) &&
1693 allow_fallback_resolution) {
1694 // DnsClient or config is not available, but we're allowed to switch to
1695 // ProcTask instead.
1696 StartProcTask();
1697 return;
1698 }
[email protected]b3601bc22012-02-21 21:23:201699
Eric Orth60931742018-11-05 23:40:571700 // Need to create the task even if we're going to post a failure instead of
1701 // running it, as a "started" job needs a task to be properly cleaned up.
1702 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_,
1703 allow_fallback_resolution, this, net_log_,
1704 tick_clock_));
1705
1706 if (resolver_->HaveDnsConfig()) {
1707 dns_task_->StartFirstTransaction();
1708 // Schedule a second transaction, if needed.
1709 if (dns_task_->needs_two_transactions())
1710 Schedule(true);
1711 } else {
1712 // Cannot start a DNS task when DnsClient or config is not available.
1713 // Since we cannot complete synchronously from here, post a failure.
1714 base::SequencedTaskRunnerHandle::Get()->PostTask(
1715 FROM_HERE,
Eric Orth07ee5f02018-11-29 00:42:031716 base::BindOnce(
1717 &Job::OnDnsTaskFailure, weak_ptr_factory_.GetWeakPtr(),
1718 dns_task_->AsWeakPtr(), base::TimeDelta(),
1719 HostCache::Entry(ERR_FAILED, HostCache::Entry::SOURCE_UNKNOWN)));
Eric Orth60931742018-11-05 23:40:571720 }
[email protected]daae1322013-09-05 18:26:501721 }
1722
1723 void StartSecondDnsTransaction() {
1724 DCHECK(dns_task_->needs_two_transactions());
1725 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221726 }
1727
1728 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1729 // deleted before this callback. In this case dns_task is deleted as well,
1730 // so we use it as indicator whether Job is still valid.
1731 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1732 base::TimeDelta duration,
Eric Orth07ee5f02018-11-29 00:42:031733 const HostCache::Entry& failure_results) {
1734 DCHECK_NE(OK, failure_results.error());
1735
Miriam Gershenson61604662017-09-28 23:51:111736 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221737
wezb9820d42016-06-22 23:41:041738 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221739 return;
1740
Miriam Gershenson19faef812018-02-07 23:56:441741 if (duration < base::TimeDelta::FromMilliseconds(10)) {
1742 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Fast",
Eric Orth07ee5f02018-11-29 00:42:031743 std::abs(failure_results.error()));
Miriam Gershenson19faef812018-02-07 23:56:441744 } else {
1745 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Slow",
Eric Orth07ee5f02018-11-29 00:42:031746 std::abs(failure_results.error()));
Miriam Gershenson19faef812018-02-07 23:56:441747 }
Eric Orth07ee5f02018-11-29 00:42:031748 dns_task_error_ = failure_results.error();
[email protected]16c2bd72013-06-28 01:19:221749
1750 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1751 // http://crbug.com/117655
1752
1753 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1754 // ProcTask in that case is a waste of time.
Eric Orth60931742018-11-05 23:40:571755 if (resolver_->allow_fallback_to_proctask_ &&
1756 dns_task->allow_fallback_resolution()) {
[email protected]daae1322013-09-05 18:26:501757 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221758 StartProcTask();
1759 } else {
1760 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Eric Orth07ee5f02018-11-29 00:42:031761 base::TimeDelta ttl = failure_results.has_ttl()
1762 ? failure_results.ttl()
1763 : base::TimeDelta::FromSeconds(0);
1764 CompleteRequests(failure_results, ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201765 }
1766 }
1767
[email protected]daae1322013-09-05 18:26:501768 // HostResolverImpl::DnsTask::Delegate implementation:
1769
dchengb03027d2014-10-21 12:00:201770 void OnDnsTaskComplete(base::TimeTicks start_time,
Eric Orth07ee5f02018-11-29 00:42:031771 const HostCache::Entry& results) override {
[email protected]b3601bc22012-02-21 21:23:201772 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201773
Misha Efimovb99e7da2018-05-30 16:59:021774 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Eric Orth07ee5f02018-11-29 00:42:031775 if (results.error() != OK) {
1776 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, results);
[email protected]b3601bc22012-02-21 21:23:201777 return;
1778 }
Miriam Gershenson61604662017-09-28 23:51:111779
1780 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201781
[email protected]1def74c2012-03-22 20:07:001782 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
Eric Orth07ee5f02018-11-29 00:42:031783 RecordTTL(results.ttl());
[email protected]0adcb2b2012-08-15 21:30:461784
Eric Orth60931742018-11-05 23:40:571785 resolver_->OnDnsTaskResolve();
[email protected]f0f602bd2012-11-15 18:01:021786
Eric Orth07ee5f02018-11-29 00:42:031787 base::TimeDelta bounded_ttl = std::max(
1788 results.ttl(), base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
[email protected]895123222012-10-25 15:21:171789
Eric Orth07ee5f02018-11-29 00:42:031790 if (results.addresses() &&
1791 ContainsIcannNameCollisionIp(results.addresses().value())) {
eroman0cd87b62016-12-14 19:13:451792 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
Eric Orth07ee5f02018-11-29 00:42:031793 return;
eroman0cd87b62016-12-14 19:13:451794 }
Eric Orth07ee5f02018-11-29 00:42:031795
1796 CompleteRequests(results, bounded_ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201797 }
1798
dchengb03027d2014-10-21 12:00:201799 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501800 DCHECK(dns_task_->needs_two_transactions());
1801 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1802 // No longer need to occupy two dispatcher slots.
1803 ReduceToOneJobSlot();
1804
1805 // We already have a job slot at the dispatcher, so if the second
1806 // transaction hasn't started, reuse it now instead of waiting in the queue
1807 // for the second slot.
1808 if (dns_task_->needs_another_transaction())
1809 dns_task_->StartSecondTransaction();
1810 }
1811
Eric Orth9871aafa2018-10-02 19:59:181812 void StartMdnsTask() {
1813 DCHECK(!is_running());
1814
1815 // No flags are supported for MDNS except
1816 // HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6 (which is not actually an
1817 // input flag).
1818 DCHECK_EQ(0, key_.host_resolver_flags &
1819 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
1820
Eric Orth192e3bb2018-11-14 19:30:321821 std::vector<DnsQueryType> query_types;
1822 if (key_.dns_query_type == DnsQueryType::UNSPECIFIED) {
1823 query_types.push_back(DnsQueryType::A);
1824 query_types.push_back(DnsQueryType::AAAA);
1825 } else {
1826 query_types.push_back(key_.dns_query_type);
Eric Orth9871aafa2018-10-02 19:59:181827 }
1828
1829 mdns_task_ = std::make_unique<HostResolverMdnsTask>(
1830 resolver_->GetOrCreateMdnsClient(), key_.hostname, query_types);
1831 mdns_task_->Start(
1832 base::BindOnce(&Job::OnMdnsTaskComplete, base::Unretained(this)));
1833 }
1834
Eric Orth07ee5f02018-11-29 00:42:031835 void OnMdnsTaskComplete() {
Eric Orth9871aafa2018-10-02 19:59:181836 DCHECK(is_mdns_running());
1837 // TODO(crbug.com/846423): Consider adding MDNS-specific logging.
1838
Eric Orth07ee5f02018-11-29 00:42:031839 HostCache::Entry results = mdns_task_->GetResults();
1840 if (results.addresses() &&
1841 ContainsIcannNameCollisionIp(results.addresses().value())) {
Eric Orth9871aafa2018-10-02 19:59:181842 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1843 } else {
1844 // MDNS uses a separate cache, so skip saving result to cache.
1845 // TODO(crbug.com/846423): Consider merging caches.
Eric Orth07ee5f02018-11-29 00:42:031846 CompleteRequestsWithoutCache(results);
Eric Orth9871aafa2018-10-02 19:59:181847 }
1848 }
1849
Brad Lassey786929ad2018-02-21 20:54:271850 URLRequestContext* url_request_context() override {
1851 return resolver_->url_request_context_;
1852 }
1853
Miriam Gershenson61604662017-09-28 23:51:111854 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581855 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1856 // deprecated values.
1857 enum Category {
1858 RESOLVE_SUCCESS = 0,
1859 RESOLVE_FAIL = 1,
1860 RESOLVE_SPECULATIVE_SUCCESS = 2,
1861 RESOLVE_SPECULATIVE_FAIL = 3,
1862 RESOLVE_ABORT = 4,
1863 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111864 RESOLVE_MAX, // Bounding value.
1865 };
1866 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1867
Misha Efimovb99e7da2018-05-30 16:59:021868 base::TimeDelta duration = tick_clock_->NowTicks() - start_time_;
Miriam Gershenson61604662017-09-28 23:51:111869 if (error == OK) {
1870 if (had_non_speculative_request_) {
1871 category = RESOLVE_SUCCESS;
1872 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
Eric Orth192e3bb2018-11-14 19:30:321873 switch (key_.dns_query_type) {
1874 case DnsQueryType::A:
Miriam Gershenson61604662017-09-28 23:51:111875 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1876 duration);
1877 break;
Eric Orth192e3bb2018-11-14 19:30:321878 case DnsQueryType::AAAA:
Miriam Gershenson61604662017-09-28 23:51:111879 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1880 duration);
1881 break;
Eric Orth192e3bb2018-11-14 19:30:321882 case DnsQueryType::UNSPECIFIED:
Miriam Gershenson61604662017-09-28 23:51:111883 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1884 duration);
1885 break;
Eric Orth192e3bb2018-11-14 19:30:321886 default:
1887 // No histogram for other query types.
1888 break;
Miriam Gershenson61604662017-09-28 23:51:111889 }
1890 } else {
1891 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111892 }
Miriam Gershensonc282ab42017-11-20 23:19:581893 } else if (error == ERR_NETWORK_CHANGED ||
1894 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1895 category = had_non_speculative_request_ ? RESOLVE_ABORT
1896 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111897 } else {
1898 if (had_non_speculative_request_) {
1899 category = RESOLVE_FAIL;
1900 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
Eric Orth192e3bb2018-11-14 19:30:321901 switch (key_.dns_query_type) {
1902 case DnsQueryType::A:
Miriam Gershensonc282ab42017-11-20 23:19:581903 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111904 duration);
1905 break;
Eric Orth192e3bb2018-11-14 19:30:321906 case DnsQueryType::AAAA:
Miriam Gershensonc282ab42017-11-20 23:19:581907 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111908 duration);
1909 break;
Eric Orth192e3bb2018-11-14 19:30:321910 case DnsQueryType::UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581911 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111912 duration);
1913 break;
Eric Orth192e3bb2018-11-14 19:30:321914 default:
1915 // No histogram for other query types.
1916 break;
Miriam Gershenson61604662017-09-28 23:51:111917 }
1918 } else {
1919 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111920 }
1921 }
1922 DCHECK_LT(static_cast<int>(category),
1923 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1924 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061925
1926 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1927 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181928 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061929 else
Ilya Sherman0eb39802017-12-08 20:58:181930 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061931 }
Miriam Gershenson61604662017-09-28 23:51:111932 }
1933
[email protected]16ee26d2012-03-08 03:34:351934 // Performs Job's last rites. Completes all Requests. Deletes this.
Eric Orth9871aafa2018-10-02 19:59:181935 //
1936 // If not |allow_cache|, result will not be stored in the host cache, even if
1937 // result would otherwise allow doing so.
Eric Orth07ee5f02018-11-29 00:42:031938 void CompleteRequests(const HostCache::Entry& results,
Eric Orth9871aafa2018-10-02 19:59:181939 base::TimeDelta ttl,
1940 bool allow_cache) {
[email protected]11fbca0b2013-06-02 23:37:211941 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201942
[email protected]16ee26d2012-03-08 03:34:351943 // This job must be removed from resolver's |jobs_| now to make room for a
1944 // new job with the same key in case one of the OnComplete callbacks decides
Eric Orth18544ae2018-06-11 22:57:161945 // to spawn one. Consequently, if the job was owned by |jobs_|, the job
1946 // deletes itself when CompleteRequests is done.
1947 std::unique_ptr<Job> self_deleter = resolver_->RemoveJob(this);
[email protected]16ee26d2012-03-08 03:34:351948
[email protected]16ee26d2012-03-08 03:34:351949 if (is_running()) {
Eric Orth9a037562018-07-03 21:24:381950 proc_task_ = nullptr;
[email protected]daae1322013-09-05 18:26:501951 KillDnsTask();
Eric Orth9871aafa2018-10-02 19:59:181952 mdns_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351953
1954 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001955 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351956 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001957 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351958 handle_.Reset();
1959 }
1960
1961 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001962 net_log_.AddEvent(NetLogEventType::CANCELLED);
1963 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351964 OK);
1965 return;
1966 }
[email protected]b3601bc22012-02-21 21:23:201967
mikecirone8b85c432016-09-08 19:11:001968 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
Eric Orth07ee5f02018-11-29 00:42:031969 results.error());
[email protected]68ad3ee2010-01-30 03:45:391970
[email protected]78eac2a2012-03-14 19:09:271971 DCHECK(!requests_.empty());
1972
Eric Orth07ee5f02018-11-29 00:42:031973 if (results.error() == OK || results.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191974 // Record this histogram here, when we know the system has a valid DNS
1975 // configuration.
[email protected]539df6c2012-06-19 21:21:291976 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1977 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191978 }
[email protected]16ee26d2012-03-08 03:34:351979
Eric Orth07ee5f02018-11-29 00:42:031980 bool did_complete = (results.error() != ERR_NETWORK_CHANGED) &&
1981 (results.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Eric Orth9871aafa2018-10-02 19:59:181982 if (did_complete && allow_cache)
Eric Orth07ee5f02018-11-29 00:42:031983 resolver_->CacheResult(key_, results, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581984
Eric Orth07ee5f02018-11-29 00:42:031985 RecordJobHistograms(results.error());
[email protected]16ee26d2012-03-08 03:34:351986
maksim.sisov31452af2016-07-27 06:38:101987 // Complete all of the requests that were attached to the job and
1988 // detach them.
1989 while (!requests_.empty()) {
David Benjamina5677192018-04-23 23:25:421990 RequestImpl* req = requests_.head()->value();
1991 req->RemoveFromList();
[email protected]0f292de02012-02-01 22:28:201992 DCHECK_EQ(this, req->job());
1993 // Update the net log and notify registered observers.
Eric Orth07ee5f02018-11-29 00:42:031994 LogFinishRequest(req->source_net_log(), results.error());
[email protected]51b9a6b2012-06-25 21:50:291995 if (did_complete) {
1996 // Record effective total time from creation to completion.
Paul Jensen41dc3e9f2018-11-06 22:10:101997 resolver_->RecordTotalTime(
1998 req->parameters().is_speculative, false /* from_cache */,
1999 tick_clock_->NowTicks() - req->request_time());
[email protected]51b9a6b2012-06-25 21:50:292000 }
Eric Orth07ee5f02018-11-29 00:42:032001 if (results.error() == OK && !req->parameters().is_speculative) {
2002 req->set_results(SetPortOnResults(results, req->request_host().port()));
Eric Orth70992982018-07-24 00:25:002003 }
Eric Orth07ee5f02018-11-29 00:42:032004 req->OnJobCompleted(this, results.error());
[email protected]0f292de02012-02-01 22:28:202005
2006 // Check if the resolver was destroyed as a result of running the
2007 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:212008 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:202009 return;
2010 }
2011 }
2012
Eric Orth07ee5f02018-11-29 00:42:032013 void CompleteRequestsWithoutCache(const HostCache::Entry& results) {
2014 CompleteRequests(results, base::TimeDelta(), false /* allow_cache */);
Eric Orth9871aafa2018-10-02 19:59:182015 }
2016
[email protected]1339a2a22012-10-17 08:39:432017 // Convenience wrapper for CompleteRequests in case of failure.
2018 void CompleteRequestsWithError(int net_error) {
Eric Orth07ee5f02018-11-29 00:42:032019 DCHECK_NE(OK, net_error);
2020 CompleteRequests(
2021 HostCache::Entry(net_error, HostCache::Entry::SOURCE_UNKNOWN),
2022 base::TimeDelta(), true /* allow_cache */);
[email protected]1339a2a22012-10-17 08:39:432023 }
2024
Brad Lassey786929ad2018-02-21 20:54:272025 RequestPriority priority() const override {
[email protected]b4481b222012-03-16 17:13:112026 return priority_tracker_.highest_priority();
2027 }
2028
2029 // Number of non-canceled requests in |requests_|.
2030 size_t num_active_requests() const {
2031 return priority_tracker_.total_count();
2032 }
2033
wezb9820d42016-06-22 23:41:042034 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:112035
Eric Orth9871aafa2018-10-02 19:59:182036 bool is_mdns_running() const { return !!mdns_task_; }
2037
wezb9820d42016-06-22 23:41:042038 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:112039
[email protected]0f292de02012-02-01 22:28:202040 base::WeakPtr<HostResolverImpl> resolver_;
2041
2042 Key key_;
2043
2044 // Tracks the highest priority across |requests_|.
2045 PriorityTracker priority_tracker_;
2046
Miriam Gershensone42adb22017-10-16 16:19:382047 // Task runner used for HostResolverProc.
2048 scoped_refptr<base::TaskRunner> proc_task_runner_;
2049
[email protected]0f292de02012-02-01 22:28:202050 bool had_non_speculative_request_;
2051
[email protected]daae1322013-09-05 18:26:502052 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
2053 unsigned num_occupied_job_slots_;
2054
[email protected]1d932852012-06-19 19:40:332055 // Result of DnsTask.
2056 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:002057
Misha Efimovb99e7da2018-05-30 16:59:022058 const base::TickClock* tick_clock_;
Miriam Gershenson61604662017-09-28 23:51:112059 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:292060
tfarina428341112016-09-22 13:38:202061 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:202062
[email protected]b3601bc22012-02-21 21:23:202063 // Resolves the host using a HostResolverProc.
Eric Orth9a037562018-07-03 21:24:382064 std::unique_ptr<ProcTask> proc_task_;
[email protected]0f292de02012-02-01 22:28:202065
[email protected]b3601bc22012-02-21 21:23:202066 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:402067 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:202068
Eric Orth9871aafa2018-10-02 19:59:182069 // Resolves the host using MDnsClient.
2070 std::unique_ptr<HostResolverMdnsTask> mdns_task_;
2071
[email protected]0f292de02012-02-01 22:28:202072 // All Requests waiting for the result of this Job. Some can be canceled.
David Benjamina5677192018-04-23 23:25:422073 base::LinkedList<RequestImpl> requests_;
[email protected]0f292de02012-02-01 22:28:202074
[email protected]16ee26d2012-03-08 03:34:352075 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:202076 PrioritizedDispatcher::Handle handle_;
Eric Orth60931742018-11-05 23:40:572077
2078 base::WeakPtrFactory<Job> weak_ptr_factory_;
[email protected]68ad3ee2010-01-30 03:45:392079};
2080
2081//-----------------------------------------------------------------------------
2082
[email protected]0f292de02012-02-01 22:28:202083HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:432084 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:202085 size_t max_retry_attempts)
2086 : resolver_proc(resolver_proc),
2087 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:442088 unresponsive_delay(
2089 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:202090 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:002091 // Maximum of 4 retry attempts for host resolution.
2092 static const size_t kDefaultMaxRetryAttempts = 4u;
2093 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
2094 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:202095}
2096
vmpstracd23b72016-02-26 21:08:552097HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
2098 default;
2099
Chris Watkins68b15032017-12-01 03:07:132100HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:202101
Francois Doraya2d01ba2017-09-25 19:17:402102HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:232103 : max_queued_jobs_(0),
2104 proc_params_(NULL, options.max_retry_attempts),
2105 net_log_(net_log),
2106 received_dns_config_(false),
2107 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:032108 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:232109 use_local_ipv6_(false),
2110 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:232111 additional_resolver_flags_(0),
Eric Orth60931742018-11-05 23:40:572112 use_proctask_by_default_(false),
2113 allow_fallback_to_proctask_(true),
Brad Lassey73e67ee2018-05-31 00:11:592114 url_request_context_(nullptr),
Misha Efimovb99e7da2018-05-30 16:59:022115 tick_clock_(base::DefaultTickClock::GetInstance()),
mmenke91c17162016-06-02 16:03:232116 weak_ptr_factory_(this),
2117 probe_weak_ptr_factory_(this) {
2118 if (options.enable_caching)
2119 cache_ = HostCache::CreateDefaultCache();
2120
2121 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2122 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2123 max_queued_jobs_ = job_limits.total_jobs * 100u;
2124
2125 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2126
Miriam Gershensone42adb22017-10-16 16:19:382127 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
Maks Orlovich5393c8682018-02-26 16:17:502128 {base::MayBlock(), priority_mode.Get(),
2129 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
Miriam Gershensone42adb22017-10-16 16:19:382130
mmenke91c17162016-06-02 16:03:232131#if defined(OS_WIN)
2132 EnsureWinsockInit();
2133#endif
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472134#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2135 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232136 RunLoopbackProbeJob();
2137#endif
Paul Jensenf47bbab2018-09-14 16:34:042138 NetworkChangeNotifier::AddIPAddressObserver(this);
2139 NetworkChangeNotifier::AddConnectionTypeObserver(this);
mmenke91c17162016-06-02 16:03:232140 NetworkChangeNotifier::AddDNSObserver(this);
2141#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Fabrice de Gans-Riberi65421f62018-05-22 23:16:182142 !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232143 EnsureDnsReloaderInit();
2144#endif
2145
Paul Jensenf47bbab2018-09-14 16:34:042146 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
mmenke91c17162016-06-02 16:03:232147
2148 {
Eric Orthe366fe62018-10-24 16:38:312149 DnsConfig dns_config = GetBaseDnsConfig();
mmenke91c17162016-06-02 16:03:232150 received_dns_config_ = dns_config.IsValid();
2151 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2152 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
Paul Jensen41dc3e9f2018-11-06 22:10:102153 UpdateModeForHistogram(dns_config);
mmenke91c17162016-06-02 16:03:232154 }
2155
Eric Orth60931742018-11-05 23:40:572156 allow_fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
mmenke91c17162016-06-02 16:03:232157}
2158
Eric Orth70992982018-07-24 00:25:002159HostResolverImpl::~HostResolverImpl() {
2160 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2161 // Prevent the dispatcher from starting new jobs.
2162 dispatcher_->SetLimitsToZero();
2163 // It's now safe for Jobs to call KillDnsTask on destruction, because
2164 // OnJobComplete will not start any new jobs.
2165 jobs_.clear();
2166
Paul Jensenf47bbab2018-09-14 16:34:042167 NetworkChangeNotifier::RemoveIPAddressObserver(this);
2168 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
Eric Orth70992982018-07-24 00:25:002169 NetworkChangeNotifier::RemoveDNSObserver(this);
mmenke91c17162016-06-02 16:03:232170}
2171
Eric Orth70992982018-07-24 00:25:002172void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
2173 // DnsClient and config must be updated before aborting DnsTasks, since doing
2174 // so may start new jobs.
2175 dns_client_ = std::move(dns_client);
2176 if (dns_client_ && !dns_client_->GetConfig() &&
2177 num_dns_failures_ < kMaximumDnsFailures) {
Eric Orthc823a23d2018-10-30 22:12:482178 DnsConfig dns_config;
2179 // Skip retrieving the base config if all values will be overridden.
2180 if (!dns_config_overrides_.OverridesEverything())
2181 dns_config = GetBaseDnsConfig();
Eric Orthc1eb1292018-10-09 22:07:072182 DnsConfig overridden_config =
2183 dns_config_overrides_.ApplyOverrides(dns_config);
2184 dns_client_->SetConfig(overridden_config);
Eric Orth70992982018-07-24 00:25:002185 num_dns_failures_ = 0;
2186 if (dns_client_->GetConfig())
2187 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2188 }
2189
Eric Orth60931742018-11-05 23:40:572190 AbortDnsTasks(ERR_NETWORK_CHANGED, false /* fallback_only */);
Findite5a94e02018-07-13 21:56:212191}
2192
Eric Orth70992982018-07-24 00:25:002193std::unique_ptr<HostResolver::ResolveHostRequest>
Eric Orth00fe5a62018-08-15 22:20:002194HostResolverImpl::CreateRequest(
2195 const HostPortPair& host,
2196 const NetLogWithSource& net_log,
2197 const base::Optional<ResolveHostParameters>& optional_parameters) {
2198 return std::make_unique<RequestImpl>(net_log, host, optional_parameters,
Eric Orth00fe5a62018-08-15 22:20:002199 weak_ptr_factory_.GetWeakPtr());
Eric Orth70992982018-07-24 00:25:002200}
2201
2202int HostResolverImpl::Resolve(const RequestInfo& info,
2203 RequestPriority priority,
2204 AddressList* addresses,
2205 CompletionOnceCallback callback,
2206 std::unique_ptr<Request>* out_req,
2207 const NetLogWithSource& source_net_log) {
2208 DCHECK(addresses);
2209 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2210 DCHECK(callback);
2211 DCHECK(out_req);
2212
2213 auto request = std::make_unique<RequestImpl>(
Eric Orth00fe5a62018-08-15 22:20:002214 source_net_log, info.host_port_pair(),
2215 RequestInfoToResolveHostParameters(info, priority),
Eric Orthb30bc172018-08-17 21:09:572216 weak_ptr_factory_.GetWeakPtr());
Eric Orth70992982018-07-24 00:25:002217 auto wrapped_request =
2218 std::make_unique<LegacyRequestImpl>(std::move(request));
2219
2220 int rv = wrapped_request->Start();
2221
Eric Orthb30bc172018-08-17 21:09:572222 if (rv == OK && !info.is_speculative()) {
Eric Orth70992982018-07-24 00:25:002223 DCHECK(wrapped_request->inner_request().GetAddressResults());
2224 *addresses = wrapped_request->inner_request().GetAddressResults().value();
2225 } else if (rv == ERR_IO_PENDING) {
2226 wrapped_request->AssignCallback(std::move(callback), addresses);
2227 *out_req = std::move(wrapped_request);
Eric Orthfac527992018-07-13 21:11:162228 }
2229
Eric Orth70992982018-07-24 00:25:002230 return rv;
[email protected]95a214c2011-08-04 21:50:402231}
2232
2233int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2234 AddressList* addresses,
tfarina428341112016-09-22 13:38:202235 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432236 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402237 DCHECK(addresses);
2238
[email protected]95a214c2011-08-04 21:50:402239 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022240 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402241
Matt Menke23b4bbf82017-07-20 19:11:292242 Key key;
Eric Orth07ee5f02018-11-29 00:42:032243 HostCache::Entry results = ResolveLocally(
2244 info.host_port_pair().host(),
2245 AddressFamilyToDnsQueryType(info.address_family()),
Eric Orthdc35748e2018-08-23 22:41:482246 FlagsToSource(info.host_resolver_flags()), info.host_resolver_flags(),
2247 info.allow_cached_response(), false /* allow_stale */,
Eric Orth07ee5f02018-11-29 00:42:032248 nullptr /* stale_info */, source_net_log, &key);
[email protected]95a214c2011-08-04 21:50:402249
Eric Orth07ee5f02018-11-29 00:42:032250 if (results.addresses()) {
2251 *addresses = AddressList::CopyWithPort(results.addresses().value(),
2252 info.host_port_pair().port());
2253 }
2254
2255 LogFinishRequest(source_net_log, results.error());
2256 return results.error();
Eric Orth70992982018-07-24 00:25:002257}
2258
2259int HostResolverImpl::ResolveStaleFromCache(
2260 const RequestInfo& info,
2261 AddressList* addresses,
2262 HostCache::EntryStaleness* stale_info,
2263 const NetLogWithSource& source_net_log) {
2264 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2265 DCHECK(addresses);
2266 DCHECK(stale_info);
2267
2268 // Update the net log and notify registered observers.
2269 LogStartRequest(source_net_log, info);
2270
2271 Key key;
Eric Orth07ee5f02018-11-29 00:42:032272 HostCache::Entry results =
2273 ResolveLocally(info.host_port_pair().host(),
2274 AddressFamilyToDnsQueryType(info.address_family()),
2275 FlagsToSource(info.host_resolver_flags()),
2276 info.host_resolver_flags(), info.allow_cached_response(),
2277 true /* allow_stale */, stale_info, source_net_log, &key);
2278
2279 if (results.addresses()) {
2280 *addresses = AddressList::CopyWithPort(results.addresses().value(),
2281 info.host_port_pair().port());
2282 }
2283
2284 LogFinishRequest(source_net_log, results.error());
2285 return results.error();
[email protected]95a214c2011-08-04 21:50:402286}
2287
[email protected]a8883e452012-11-17 05:58:062288void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432289 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062290#if defined(ENABLE_BUILT_IN_DNS)
2291 if (enabled && !dns_client_) {
2292 SetDnsClient(DnsClient::CreateClient(net_log_));
2293 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402294 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062295 }
2296#endif
2297}
2298
[email protected]489d1a82011-10-12 03:09:112299HostCache* HostResolverImpl::GetHostCache() {
2300 return cache_.get();
2301}
[email protected]95a214c2011-08-04 21:50:402302
Rob Percivalbc658a22017-12-13 08:24:422303bool HostResolverImpl::HasCached(base::StringPiece hostname,
2304 HostCache::Entry::Source* source_out,
2305 HostCache::EntryStaleness* stale_out) const {
2306 if (!cache_)
2307 return false;
2308
2309 return cache_->HasEntry(hostname, source_out, stale_out);
2310}
2311
danakj22f90e72016-04-16 01:55:402312std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242313 // Check if async DNS is disabled.
2314 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082315 return nullptr;
[email protected]17e92032012-03-29 00:56:242316
2317 // Check if async DNS is enabled, but we currently have no configuration
2318 // for it.
2319 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042320 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192321 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242322
2323 return dns_config->ToValue();
2324}
2325
Miriam Gershenson2839ef112017-08-30 03:25:372326size_t HostResolverImpl::LastRestoredCacheSize() const {
2327 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2328
2329 return cache_ ? cache_->last_restore_size() : 0;
2330}
2331
2332size_t HostResolverImpl::CacheSize() const {
2333 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2334
2335 return cache_ ? cache_->size() : 0;
2336}
2337
mgershaf9a9232017-04-13 20:19:032338void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432339 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032340 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2341}
2342
2343bool HostResolverImpl::GetNoIPv6OnWifi() {
2344 return assume_ipv6_failure_on_wifi_;
2345}
2346
Eric Orthc1eb1292018-10-09 22:07:072347void HostResolverImpl::SetDnsConfigOverrides(
2348 const DnsConfigOverrides& overrides) {
2349 if (dns_config_overrides_ == overrides)
2350 return;
2351
2352 dns_config_overrides_ = overrides;
Eric Orthc823a23d2018-10-30 22:12:482353 if (dns_client_.get())
Eric Orthc1eb1292018-10-09 22:07:072354 UpdateDNSConfig(true);
2355}
2356
Brad Lassey786929ad2018-02-21 20:54:272357void HostResolverImpl::SetRequestContext(URLRequestContext* context) {
2358 if (context != url_request_context_) {
2359 url_request_context_ = context;
2360 }
2361}
2362
Matt Menkeb67c0a8e2018-06-14 22:41:042363const std::vector<DnsConfig::DnsOverHttpsServerConfig>*
2364HostResolverImpl::GetDnsOverHttpsServersForTesting() const {
Eric Orthc1eb1292018-10-09 22:07:072365 if (!dns_config_overrides_.dns_over_https_servers ||
2366 dns_config_overrides_.dns_over_https_servers.value().empty()) {
Matt Menkeb67c0a8e2018-06-14 22:41:042367 return nullptr;
Eric Orthc1eb1292018-10-09 22:07:072368 }
2369 return &dns_config_overrides_.dns_over_https_servers.value();
Matt Menkeb67c0a8e2018-06-14 22:41:042370}
2371
Eric Orth70992982018-07-24 00:25:002372void HostResolverImpl::SetTickClockForTesting(
2373 const base::TickClock* tick_clock) {
2374 tick_clock_ = tick_clock;
2375 cache_->set_tick_clock_for_testing(tick_clock);
2376}
2377
2378void HostResolverImpl::SetMaxQueuedJobsForTesting(size_t value) {
2379 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
2380 DCHECK_GE(value, 0u);
2381 max_queued_jobs_ = value;
2382}
2383
2384void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2385 if (result) {
2386 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2387 } else {
2388 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2389 }
2390}
2391
Eric Orth9871aafa2018-10-02 19:59:182392void HostResolverImpl::SetMdnsSocketFactoryForTesting(
2393 std::unique_ptr<MDnsSocketFactory> socket_factory) {
2394 DCHECK(!mdns_client_);
2395 mdns_socket_factory_ = std::move(socket_factory);
2396}
2397
2398void HostResolverImpl::SetMdnsClientForTesting(
2399 std::unique_ptr<MDnsClient> client) {
2400 mdns_client_ = std::move(client);
2401}
2402
Eric Orthe366fe62018-10-24 16:38:312403void HostResolverImpl::SetBaseDnsConfigForTesting(
2404 const DnsConfig& base_config) {
2405 test_base_config_ = base_config;
2406 UpdateDNSConfig(true);
2407}
2408
Eric Orth70992982018-07-24 00:25:002409void HostResolverImpl::SetTaskRunnerForTesting(
2410 scoped_refptr<base::TaskRunner> task_runner) {
2411 proc_task_runner_ = std::move(task_runner);
2412}
2413
2414int HostResolverImpl::Resolve(RequestImpl* request) {
2415 // Request should not yet have a scheduled Job.
2416 DCHECK(!request->job());
2417 // Request may only be resolved once.
2418 DCHECK(!request->complete());
Eric Orth9871aafa2018-10-02 19:59:182419 // MDNS requests do not support skipping cache.
2420 // TODO(crbug.com/846423): Either add support for skipping the MDNS cache, or
2421 // merge to use the normal host cache for MDNS requests.
2422 DCHECK(request->parameters().source != HostResolverSource::MULTICAST_DNS ||
2423 request->parameters().allow_cached_response);
Eric Orth70992982018-07-24 00:25:002424
2425 request->set_request_time(tick_clock_->NowTicks());
2426
2427 LogStartRequest(request->source_net_log(), request->request_host());
2428
Eric Orth70992982018-07-24 00:25:002429 Key key;
Eric Orth07ee5f02018-11-29 00:42:032430 HostCache::Entry results = ResolveLocally(
2431 request->request_host().host(), request->parameters().dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482432 request->parameters().source, request->host_resolver_flags(),
2433 request->parameters().allow_cached_response, false /* allow_stale */,
Eric Orth07ee5f02018-11-29 00:42:032434 nullptr /* stale_info */, request->source_net_log(), &key);
2435 if (results.error() == OK && !request->parameters().is_speculative) {
2436 request->set_results(
2437 SetPortOnResults(results, request->request_host().port()));
Eric Orth70992982018-07-24 00:25:002438 }
Eric Orth07ee5f02018-11-29 00:42:032439 if (results.error() != ERR_DNS_CACHE_MISS) {
2440 LogFinishRequest(request->source_net_log(), results.error());
Eric Orthb30bc172018-08-17 21:09:572441 RecordTotalTime(request->parameters().is_speculative, true /* from_cache */,
Eric Orth70992982018-07-24 00:25:002442 base::TimeDelta());
Eric Orth07ee5f02018-11-29 00:42:032443 return results.error();
Eric Orth70992982018-07-24 00:25:002444 }
2445
Eric Orth07ee5f02018-11-29 00:42:032446 int rv = CreateAndStartJob(key, request);
Eric Orth70992982018-07-24 00:25:002447 // At this point, expect only async or errors.
2448 DCHECK_NE(OK, rv);
2449
2450 return rv;
2451}
2452
Eric Orth07ee5f02018-11-29 00:42:032453HostCache::Entry HostResolverImpl::ResolveLocally(
2454 const std::string& hostname,
2455 DnsQueryType dns_query_type,
2456 HostResolverSource source,
2457 HostResolverFlags flags,
2458 bool allow_cache,
2459 bool allow_stale,
2460 HostCache::EntryStaleness* stale_info,
2461 const NetLogWithSource& source_net_log,
2462 Key* out_key) {
Eric Orth70992982018-07-24 00:25:002463 IPAddress ip_address;
2464 IPAddress* ip_address_ptr = nullptr;
Eric Orth07ee5f02018-11-29 00:42:032465 if (ip_address.AssignFromIPLiteral(hostname)) {
Eric Orth70992982018-07-24 00:25:002466 ip_address_ptr = &ip_address;
2467 } else {
2468 // Check that the caller supplied a valid hostname to resolve.
Eric Orth07ee5f02018-11-29 00:42:032469 if (!IsValidDNSDomain(hostname)) {
2470 return HostCache::Entry(ERR_NAME_NOT_RESOLVED,
2471 HostCache::Entry::SOURCE_UNKNOWN);
2472 }
Eric Orth70992982018-07-24 00:25:002473 }
2474
2475 // Build a key that identifies the request in the cache and in the
2476 // outstanding jobs map.
Eric Orth07ee5f02018-11-29 00:42:032477 *out_key = GetEffectiveKeyForRequest(hostname, dns_query_type, source, flags,
2478 ip_address_ptr, source_net_log);
Eric Orth70992982018-07-24 00:25:002479
2480 DCHECK(allow_stale == !!stale_info);
2481 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2482 // On Windows it gives the default interface's address, whereas on Linux it
2483 // gives an error. We will make it fail on all platforms for consistency.
Eric Orth07ee5f02018-11-29 00:42:032484 if (hostname.empty() || hostname.size() > kMaxHostLength) {
Eric Orth70992982018-07-24 00:25:002485 MakeNotStale(stale_info);
Eric Orth07ee5f02018-11-29 00:42:032486 return HostCache::Entry(ERR_NAME_NOT_RESOLVED,
2487 HostCache::Entry::SOURCE_UNKNOWN);
Eric Orth70992982018-07-24 00:25:002488 }
2489
Eric Orth07ee5f02018-11-29 00:42:032490 base::Optional<HostCache::Entry> resolved =
2491 ResolveAsIP(*out_key, ip_address_ptr);
2492 if (resolved) {
Eric Orth70992982018-07-24 00:25:002493 MakeNotStale(stale_info);
Eric Orth07ee5f02018-11-29 00:42:032494 return resolved.value();
Eric Orth70992982018-07-24 00:25:002495 }
2496
2497 // Special-case localhost names, as per the recommendations in
2498 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
Eric Orth07ee5f02018-11-29 00:42:032499 resolved = ServeLocalhost(*out_key);
2500 if (resolved) {
Eric Orth70992982018-07-24 00:25:002501 MakeNotStale(stale_info);
Eric Orth07ee5f02018-11-29 00:42:032502 return resolved.value();
Eric Orth70992982018-07-24 00:25:002503 }
2504
Eric Orth07ee5f02018-11-29 00:42:032505 if (allow_cache) {
2506 resolved = ServeFromCache(*out_key, allow_stale, stale_info);
2507 if (resolved) {
2508 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2509 resolved.value().CreateNetLogCallback());
2510 // |ServeFromCache()| will update |*stale_info| as needed.
2511 return resolved.value();
2512 }
Eric Orth70992982018-07-24 00:25:002513 }
2514
2515 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2516 // http://crbug.com/117655
Eric Orth07ee5f02018-11-29 00:42:032517 resolved = ServeFromHosts(*out_key);
2518 if (resolved) {
Eric Orth70992982018-07-24 00:25:002519 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
Eric Orth07ee5f02018-11-29 00:42:032520 resolved.value().CreateNetLogCallback());
Eric Orth70992982018-07-24 00:25:002521 MakeNotStale(stale_info);
Eric Orth07ee5f02018-11-29 00:42:032522 return resolved.value();
Eric Orth70992982018-07-24 00:25:002523 }
2524
Eric Orth07ee5f02018-11-29 00:42:032525 return HostCache::Entry(ERR_DNS_CACHE_MISS, HostCache::Entry::SOURCE_UNKNOWN);
Eric Orth70992982018-07-24 00:25:002526}
2527
2528int HostResolverImpl::CreateAndStartJob(const Key& key, RequestImpl* request) {
2529 auto jobit = jobs_.find(key);
2530 Job* job;
2531 if (jobit == jobs_.end()) {
2532 auto new_job = std::make_unique<Job>(
2533 weak_ptr_factory_.GetWeakPtr(), key, request->priority(),
2534 proc_task_runner_, request->source_net_log(), tick_clock_);
2535 job = new_job.get();
2536 new_job->Schedule(false);
2537
2538 // Check for queue overflow.
2539 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
2540 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
2541 DCHECK(evicted);
2542 evicted->OnEvicted();
2543 if (evicted == new_job.get()) {
2544 LogFinishRequest(request->source_net_log(),
2545 ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
2546 return ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
2547 }
2548 }
2549 jobs_[key] = std::move(new_job);
2550 } else {
2551 job = jobit->second.get();
2552 }
2553
2554 // Can't complete synchronously. Attach request and job to each other.
2555 job->AddRequest(request);
2556 return ERR_IO_PENDING;
2557}
2558
Eric Orth07ee5f02018-11-29 00:42:032559base::Optional<HostCache::Entry> HostResolverImpl::ResolveAsIP(
2560 const Key& key,
2561 const IPAddress* ip_address) {
Eric Orth192e3bb2018-11-14 19:30:322562 if (ip_address == nullptr || !IsAddressType(key.dns_query_type))
Eric Orth07ee5f02018-11-29 00:42:032563 return base::nullopt;
[email protected]95a214c2011-08-04 21:50:402564
martijna23c8962016-03-04 18:18:512565 AddressFamily family = GetAddressFamily(*ip_address);
Eric Orth192e3bb2018-11-14 19:30:322566 if (key.dns_query_type != DnsQueryType::UNSPECIFIED &&
2567 key.dns_query_type != AddressFamilyToDnsQueryType(family)) {
[email protected]1c7cf3f82014-08-07 21:33:482568 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
Eric Orth07ee5f02018-11-29 00:42:032569 return HostCache::Entry(ERR_NAME_NOT_RESOLVED,
2570 HostCache::Entry::SOURCE_UNKNOWN);
[email protected]95a214c2011-08-04 21:50:402571 }
Eric Orth07ee5f02018-11-29 00:42:032572
2573 AddressList addresses = AddressList::CreateFromIPAddress(*ip_address, 0);
2574 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2575 addresses.SetDefaultCanonicalName();
2576 return HostCache::Entry(OK, std::move(addresses),
2577 HostCache::Entry::SOURCE_UNKNOWN);
[email protected]95a214c2011-08-04 21:50:402578}
2579
Eric Orth07ee5f02018-11-29 00:42:032580base::Optional<HostCache::Entry> HostResolverImpl::ServeFromCache(
2581 const Key& key,
2582 bool allow_stale,
2583 HostCache::EntryStaleness* stale_info) {
juliatuttle9fb7aeb2016-06-06 20:16:332584 DCHECK(allow_stale == !!stale_info);
Eric Orth70992982018-07-24 00:25:002585 if (!cache_.get())
Eric Orth07ee5f02018-11-29 00:42:032586 return base::nullopt;
[email protected]95a214c2011-08-04 21:50:402587
juliatuttle9fb7aeb2016-06-06 20:16:332588 const HostCache::Entry* cache_entry;
2589 if (allow_stale)
Misha Efimovb99e7da2018-05-30 16:59:022590 cache_entry = cache_->LookupStale(key, tick_clock_->NowTicks(), stale_info);
juliatuttle9fb7aeb2016-06-06 20:16:332591 else
Misha Efimovb99e7da2018-05-30 16:59:022592 cache_entry = cache_->Lookup(key, tick_clock_->NowTicks());
[email protected]95a214c2011-08-04 21:50:402593 if (!cache_entry)
Eric Orth07ee5f02018-11-29 00:42:032594 return base::nullopt;
[email protected]95a214c2011-08-04 21:50:402595
Eric Orth07ee5f02018-11-29 00:42:032596 if (cache_entry->error() == OK) {
[email protected]1339a2a22012-10-17 08:39:432597 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222598 RecordTTL(cache_entry->ttl());
[email protected]7054e78f2012-05-07 21:44:562599 }
Eric Orth07ee5f02018-11-29 00:42:032600
2601 return *cache_entry;
[email protected]95a214c2011-08-04 21:50:402602}
2603
Eric Orth07ee5f02018-11-29 00:42:032604base::Optional<HostCache::Entry> HostResolverImpl::ServeFromHosts(
2605 const Key& key) {
2606 if (!HaveDnsConfig() || !IsAddressType(key.dns_query_type))
2607 return base::nullopt;
[email protected]05a79d42013-03-28 07:30:092608
[email protected]cb507622012-03-23 16:17:062609 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222610 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062611
[email protected]05a79d42013-03-28 07:30:092612 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2613
[email protected]78eac2a2012-03-14 19:09:272614 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2615 // (glibc and c-ares) return the first matching line. We have more
2616 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092617 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2618 // necessary.
Eric Orth07ee5f02018-11-29 00:42:032619 AddressList addresses;
Eric Orth192e3bb2018-11-14 19:30:322620 if (key.dns_query_type == DnsQueryType::AAAA ||
2621 key.dns_query_type == DnsQueryType::UNSPECIFIED) {
jdoerrie22a91d8b92018-10-05 08:43:262622 auto it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
[email protected]05a79d42013-03-28 07:30:092623 if (it != hosts.end())
Eric Orth07ee5f02018-11-29 00:42:032624 addresses.push_back(IPEndPoint(it->second, 0));
[email protected]78eac2a2012-03-14 19:09:272625 }
2626
Eric Orth192e3bb2018-11-14 19:30:322627 if (key.dns_query_type == DnsQueryType::A ||
2628 key.dns_query_type == DnsQueryType::UNSPECIFIED) {
jdoerrie22a91d8b92018-10-05 08:43:262629 auto it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
[email protected]05a79d42013-03-28 07:30:092630 if (it != hosts.end())
Eric Orth07ee5f02018-11-29 00:42:032631 addresses.push_back(IPEndPoint(it->second, 0));
[email protected]05a79d42013-03-28 07:30:092632 }
2633
[email protected]ec666ab22013-04-17 20:05:592634 // If got only loopback addresses and the family was restricted, resolve
2635 // again, without restrictions. See SystemHostResolverCall for rationale.
2636 if ((key.host_resolver_flags &
Eric Orth07ee5f02018-11-29 00:42:032637 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2638 IsAllIPv4Loopback(addresses)) {
[email protected]ec666ab22013-04-17 20:05:592639 Key new_key(key);
Eric Orth192e3bb2018-11-14 19:30:322640 new_key.dns_query_type = DnsQueryType::UNSPECIFIED;
[email protected]ec666ab22013-04-17 20:05:592641 new_key.host_resolver_flags &=
2642 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Eric Orth07ee5f02018-11-29 00:42:032643 return ServeFromHosts(new_key);
[email protected]ec666ab22013-04-17 20:05:592644 }
Eric Orth07ee5f02018-11-29 00:42:032645
2646 if (!addresses.empty()) {
2647 return HostCache::Entry(OK, std::move(addresses),
2648 HostCache::Entry::SOURCE_HOSTS);
2649 }
2650
2651 return base::nullopt;
[email protected]78eac2a2012-03-14 19:09:272652}
2653
Eric Orth07ee5f02018-11-29 00:42:032654base::Optional<HostCache::Entry> HostResolverImpl::ServeLocalhost(
2655 const Key& key) {
estarkd1bc206e2015-06-20 00:44:392656 AddressList resolved_addresses;
Eric Orth07ee5f02018-11-29 00:42:032657 if (!IsAddressType(key.dns_query_type) ||
2658 !ResolveLocalHostname(key.hostname, &resolved_addresses)) {
2659 return base::nullopt;
2660 }
estarkd1bc206e2015-06-20 00:44:392661
Eric Orth07ee5f02018-11-29 00:42:032662 AddressList filtered_addresses;
2663 for (const auto& address : resolved_addresses) {
2664 // Include the address if:
2665 // - caller didn't specify an address family, or
2666 // - caller specifically asked for the address family of this address, or
2667 // - this is an IPv6 address and caller specifically asked for IPv4 due
2668 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2669 // rationale).
2670 if (key.dns_query_type == DnsQueryType::UNSPECIFIED ||
2671 DnsQueryTypeToAddressFamily(key.dns_query_type) ==
2672 address.GetFamily() ||
2673 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2674 key.dns_query_type == DnsQueryType::A &&
2675 (key.host_resolver_flags &
2676 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2677 filtered_addresses.push_back(address);
estarkd1bc206e2015-06-20 00:44:392678 }
2679 }
2680
Eric Orth07ee5f02018-11-29 00:42:032681 return HostCache::Entry(OK, std::move(filtered_addresses),
2682 HostCache::Entry::SOURCE_UNKNOWN);
estarkd1bc206e2015-06-20 00:44:392683}
2684
[email protected]16ee26d2012-03-08 03:34:352685void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432686 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352687 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052688 // Don't cache an error unless it has a positive TTL.
2689 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
Misha Efimovb99e7da2018-05-30 16:59:022690 cache_->Set(key, entry, tick_clock_->NowTicks(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032691}
2692
Paul Jensen41dc3e9f2018-11-06 22:10:102693// Record time from Request creation until a valid DNS response.
2694void HostResolverImpl::RecordTotalTime(bool speculative,
2695 bool from_cache,
2696 base::TimeDelta duration) const {
2697 if (!speculative) {
2698 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
2699
2700 switch (mode_for_histogram_) {
2701 case MODE_FOR_HISTOGRAM_SYSTEM:
2702 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.System", duration);
2703 break;
2704 case MODE_FOR_HISTOGRAM_SYSTEM_SUPPORTS_DOH:
2705 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.SystemSupportsDoh",
2706 duration);
2707 break;
2708 case MODE_FOR_HISTOGRAM_SYSTEM_PRIVATE_DNS:
2709 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.SystemPrivate",
2710 duration);
2711 break;
2712 case MODE_FOR_HISTOGRAM_ASYNC_DNS:
2713 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.Async", duration);
2714 break;
2715 case MODE_FOR_HISTOGRAM_ASYNC_DNS_PRIVATE_SUPPORTS_DOH:
2716 UMA_HISTOGRAM_MEDIUM_TIMES(
2717 "Net.DNS.TotalTimeTyped.AsyncPrivateSupportsDoh", duration);
2718 break;
2719 }
2720
2721 if (!from_cache)
2722 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
2723 }
2724}
2725
Eric Orth18544ae2018-06-11 22:57:162726std::unique_ptr<HostResolverImpl::Job> HostResolverImpl::RemoveJob(Job* job) {
[email protected]0f292de02012-02-01 22:28:202727 DCHECK(job);
Eric Orth18544ae2018-06-11 22:57:162728 std::unique_ptr<Job> retval;
avi9e72eb482016-12-09 21:10:542729 auto it = jobs_.find(job->key());
2730 if (it != jobs_.end() && it->second.get() == job) {
Eric Orth18544ae2018-06-11 22:57:162731 it->second.swap(retval);
[email protected]16ee26d2012-03-08 03:34:352732 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542733 }
Eric Orth18544ae2018-06-11 22:57:162734 return retval;
[email protected]b59ff372009-07-15 22:04:322735}
2736
[email protected]137af622010-02-05 02:14:352737HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
Eric Orth70992982018-07-24 00:25:002738 const std::string& hostname,
Eric Orth00fe5a62018-08-15 22:20:002739 DnsQueryType dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482740 HostResolverSource source,
Eric Orth70992982018-07-24 00:25:002741 HostResolverFlags flags,
martijna23c8962016-03-04 18:18:512742 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202743 const NetLogWithSource& net_log) {
Eric Orth70992982018-07-24 00:25:002744 HostResolverFlags effective_flags = flags | additional_resolver_flags_;
Eric Orth00fe5a62018-08-15 22:20:002745
Eric Orth192e3bb2018-11-14 19:30:322746 DnsQueryType effective_query_type = dns_query_type;
[email protected]9db6f702013-04-10 18:10:512747
Eric Orth192e3bb2018-11-14 19:30:322748 if (effective_query_type == DnsQueryType::UNSPECIFIED &&
mgersh3eba057d2017-02-28 18:50:562749 // When resolving IPv4 literals, there's no need to probe for IPv6.
2750 // When resolving IPv6 literals, there's no benefit to artificially
2751 // limiting our resolution based on a probe. Prior logic ensures
Eric Orth192e3bb2018-11-14 19:30:322752 // that this query is UNSPECIFIED (see effective_query_type check above)
2753 // so the code requesting the resolution should be amenable to receiving a
2754 // IPv6 resolution.
mgersh3eba057d2017-02-28 18:50:562755 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
Eric Orth192e3bb2018-11-14 19:30:322756 effective_query_type = DnsQueryType::A;
mgersh3eba057d2017-02-28 18:50:562757 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512758 }
2759
Eric Orth192e3bb2018-11-14 19:30:322760 return Key(hostname, effective_query_type, effective_flags, source);
[email protected]137af622010-02-05 02:14:352761}
2762
tfarina428341112016-09-22 13:38:202763bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032764 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2765 // work on WiFi.
2766 if (assume_ipv6_failure_on_wifi_ &&
2767 NetworkChangeNotifier::GetConnectionType() ==
2768 NetworkChangeNotifier::CONNECTION_WIFI) {
2769 return false;
2770 }
2771
eroman1a17ef32016-12-14 01:06:092772 // Cache the result for kIPv6ProbePeriodMs (measured from after
2773 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372774 bool cached = true;
Misha Efimovb99e7da2018-05-30 16:59:022775 if ((tick_clock_->NowTicks() - last_ipv6_probe_time_).InMilliseconds() >
eroman1a17ef32016-12-14 01:06:092776 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512777 last_ipv6_probe_result_ =
2778 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
Misha Efimovb99e7da2018-05-30 16:59:022779 last_ipv6_probe_time_ = tick_clock_->NowTicks();
sergeyub8cdc212015-05-14 18:50:372780 cached = false;
2781 }
mikecirone8b85c432016-09-08 19:11:002782 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372783 base::Bind(&NetLogIPv6AvailableCallback,
2784 last_ipv6_probe_result_, cached));
2785 return last_ipv6_probe_result_;
2786}
2787
mgershaf9a9232017-04-13 20:19:032788bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2789 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032790 std::unique_ptr<DatagramClientSocket> socket(
2791 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
Sergey Ulanovcbdfc8852018-03-16 20:13:282792 DatagramSocket::DEFAULT_BIND, net_log.net_log(), net_log.source()));
mgershaf9a9232017-04-13 20:19:032793 int rv = socket->Connect(IPEndPoint(dest, 53));
2794 if (rv != OK)
2795 return false;
2796 IPEndPoint endpoint;
2797 rv = socket->GetLocalAddress(&endpoint);
2798 if (rv != OK)
2799 return false;
2800 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2801 const IPAddress& address = endpoint.address();
2802
2803 bool is_link_local =
2804 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2805 if (is_link_local)
2806 return false;
2807
2808 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2809 if (IPAddressStartsWith(address, kTeredoPrefix))
2810 return false;
2811
2812 return true;
2813}
2814
mmenke91c17162016-06-02 16:03:232815void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402816 // Run this asynchronously as it can take 40-100ms and should not block
2817 // initialization.
2818 base::PostTaskWithTraitsAndReplyWithResult(
2819 FROM_HERE,
2820 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2821 base::BindOnce(&HaveOnlyLoopbackAddresses),
2822 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2823 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232824}
2825
[email protected]35ddc282010-09-21 23:42:062826void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202827 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2828 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402829 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542830 for (auto it = jobs_.begin(); it != jobs_.end();) {
2831 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202832 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542833 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202834 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202835 } else {
[email protected]b3601bc22012-02-21 21:23:202836 DCHECK(job->is_queued());
2837 ++it;
[email protected]0f292de02012-02-01 22:28:202838 }
[email protected]ef4c40c2010-09-01 14:42:032839 }
[email protected]b3601bc22012-02-21 21:23:202840
[email protected]daae1322013-09-05 18:26:502841 // Pause the dispatcher so it won't start any new dispatcher jobs while
2842 // aborting the old ones. This is needed so that it won't start the second
2843 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2844 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002845 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2846 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502847 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122848
[email protected]57a48d32012-03-03 00:04:552849 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072850 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552851
[email protected]16ee26d2012-03-08 03:34:352852 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212853 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552854 jobs_to_abort[i]->Abort();
[email protected]b3601bc22012-02-21 21:23:202855 }
[email protected]daae1322013-09-05 18:26:502856
2857 if (self)
[email protected]106ccd2c2014-06-17 09:21:002858 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502859}
2860
Eric Orth60931742018-11-05 23:40:572861void HostResolverImpl::AbortDnsTasks(int error, bool fallback_only) {
2862 // Aborting jobs potentially modifies |jobs_| and may even delete some jobs.
2863 // Create safe closures of all current jobs.
2864 std::vector<base::OnceClosure> job_abort_closures;
2865 for (auto& job : jobs_) {
2866 job_abort_closures.push_back(
2867 job.second->GetAbortDnsTaskClosure(error, fallback_only));
2868 }
2869
[email protected]daae1322013-09-05 18:26:502870 // Pause the dispatcher so it won't start any new dispatcher jobs while
2871 // aborting the old ones. This is needed so that it won't start the second
2872 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002873 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2874 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502875 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2876
Eric Orth60931742018-11-05 23:40:572877 for (base::OnceClosure& closure : job_abort_closures)
2878 std::move(closure).Run();
2879
[email protected]106ccd2c2014-06-17 09:21:002880 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032881}
2882
[email protected]78eac2a2012-03-14 19:09:272883void HostResolverImpl::TryServingAllJobsFromHosts() {
2884 if (!HaveDnsConfig())
2885 return;
2886
2887 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2888 // http://crbug.com/117655
2889
2890 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072891 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272892
avi9e72eb482016-12-09 21:10:542893 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2894 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272895 ++it;
2896 // This could remove |job| from |jobs_|, but iterator will remain valid.
2897 job->ServeFromHosts();
2898 }
2899}
2900
Paul Jensenf47bbab2018-09-14 16:34:042901void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372902 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182903 // Abandon all ProbeJobs.
2904 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172905 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102906 cache_->OnNetworkChange();
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472907#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2908 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232909 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132910#endif
2911 AbortAllInProgressJobs();
2912 // |this| may be deleted inside AbortAllInProgressJobs().
2913}
2914
Paul Jensenf47bbab2018-09-14 16:34:042915void HostResolverImpl::OnConnectionTypeChanged(
ttuttlecf1158bf2016-03-18 16:37:442916 NetworkChangeNotifier::ConnectionType type) {
2917 proc_params_.unresponsive_delay =
2918 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2919 "DnsUnresponsiveDelayMsByConnectionType",
2920 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2921 type);
2922}
2923
pauljensen101ed372015-04-17 00:11:422924void HostResolverImpl::OnInitialDNSConfigRead() {
2925 UpdateDNSConfig(false);
2926}
2927
[email protected]bb0e34542012-08-31 19:52:402928void HostResolverImpl::OnDNSChanged() {
Eric Orthc823a23d2018-10-30 22:12:482929 // Ignore changes if we're using a test config or if we have overriding
2930 // configuration that overrides everything from the base config.
2931 if (test_base_config_ || dns_config_overrides_.OverridesEverything())
Eric Orthe366fe62018-10-24 16:38:312932 return;
2933
pauljensen101ed372015-04-17 00:11:422934 UpdateDNSConfig(true);
2935}
2936
Eric Orthe366fe62018-10-24 16:38:312937DnsConfig HostResolverImpl::GetBaseDnsConfig() const {
[email protected]bb0e34542012-08-31 19:52:402938 DnsConfig dns_config;
Eric Orthe366fe62018-10-24 16:38:312939 if (test_base_config_)
2940 dns_config = test_base_config_.value();
2941 else
2942 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2943 return dns_config;
2944}
2945
2946void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
Eric Orthc823a23d2018-10-30 22:12:482947 DnsConfig dns_config;
[email protected]ec666ab22013-04-17 20:05:592948
Eric Orthc823a23d2018-10-30 22:12:482949 // Skip retrieving the base config if all values will be overridden.
2950 if (!dns_config_overrides_.OverridesEverything()) {
2951 dns_config = GetBaseDnsConfig();
2952
2953 if (net_log_) {
2954 net_log_->AddGlobalEntry(
2955 NetLogEventType::DNS_CONFIG_CHANGED,
2956 base::BindRepeating(&NetLogDnsConfigCallback, &dns_config));
2957 }
2958
2959 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
2960 received_dns_config_ = dns_config.IsValid();
[email protected]b4481b222012-03-16 17:13:112961 }
2962
Eric Orthc1eb1292018-10-09 22:07:072963 dns_config = dns_config_overrides_.ApplyOverrides(dns_config);
2964
[email protected]c9fa8f312013-09-17 12:24:522965 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2966 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272967
[email protected]a8883e452012-11-17 05:58:062968 num_dns_failures_ = 0;
2969
[email protected]01b3b9d2012-08-13 16:18:142970 // We want a new DnsSession in place, before we Abort running Jobs, so that
2971 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022972 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252973 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532974 // wasn't already a DnsConfig or it's the same one.
2975 DCHECK(config_changed || !dns_client_->GetConfig() ||
2976 dns_client_->GetConfig()->Equals(dns_config));
[email protected]d7b9a2b2012-05-31 22:31:192977 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252978 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022979 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022980 }
Eric Orth60931742018-11-05 23:40:572981 use_proctask_by_default_ = false;
[email protected]01b3b9d2012-08-13 16:18:142982
pauljensen101ed372015-04-17 00:11:422983 if (config_changed) {
2984 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232985 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422986 // as NSCD's cache should be dropped automatically by the OS when
2987 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172988 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232989 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142990
pauljensen101ed372015-04-17 00:11:422991 // Life check to bail once |this| is deleted.
2992 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022993
pauljensen101ed372015-04-17 00:11:422994 // Existing jobs will have been sent to the original server so they need to
2995 // be aborted.
2996 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142997
pauljensen101ed372015-04-17 00:11:422998 // |this| may be deleted inside AbortAllInProgressJobs().
2999 if (self.get())
3000 TryServingAllJobsFromHosts();
3001 }
Paul Jensen41dc3e9f2018-11-06 22:10:103002
3003 UpdateModeForHistogram(dns_config);
[email protected]78eac2a2012-03-14 19:09:273004}
3005
3006bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:253007 // Use DnsClient only if it's fully configured and there is no override by
3008 // ScopedDefaultHostResolverProc.
3009 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
3010 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:043011 return dns_client_ && dns_client_->GetConfig() &&
3012 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:203013}
3014
Eric Orth60931742018-11-05 23:40:573015void HostResolverImpl::OnDnsTaskResolve() {
[email protected]f0f602bd2012-11-15 18:01:023016 DCHECK(dns_client_);
Eric Orth60931742018-11-05 23:40:573017 num_dns_failures_ = 0;
3018}
3019
3020void HostResolverImpl::OnFallbackResolve(int dns_task_error) {
3021 DCHECK(dns_client_);
3022 DCHECK_NE(OK, dns_task_error);
3023
[email protected]f0f602bd2012-11-15 18:01:023024 ++num_dns_failures_;
3025 if (num_dns_failures_ < kMaximumDnsFailures)
3026 return;
[email protected]daae1322013-09-05 18:26:503027
Eric Orth60931742018-11-05 23:40:573028 // Force fallback until the next DNS change. Must be done before aborting
3029 // DnsTasks, since doing so may start new jobs. Do not fully clear out or
3030 // disable the DnsClient as some requests (e.g. those specifying DNS source)
3031 // are not allowed to fallback and will continue using DnsTask.
3032 use_proctask_by_default_ = true;
[email protected]daae1322013-09-05 18:26:503033
Eric Orth60931742018-11-05 23:40:573034 // Fallback all fallback-allowed DnsTasks to ProcTasks.
3035 AbortDnsTasks(ERR_FAILED, true /* fallback_only */);
[email protected]daae1322013-09-05 18:26:503036
[email protected]f0f602bd2012-11-15 18:01:023037 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:183038 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
Eric Orth60931742018-11-05 23:40:573039 std::abs(dns_task_error));
[email protected]f0f602bd2012-11-15 18:01:023040}
3041
Eric Orth9871aafa2018-10-02 19:59:183042MDnsClient* HostResolverImpl::GetOrCreateMdnsClient() {
3043#if BUILDFLAG(ENABLE_MDNS)
3044 if (!mdns_client_) {
3045 if (!mdns_socket_factory_)
3046 mdns_socket_factory_ = std::make_unique<MDnsSocketFactoryImpl>(net_log_);
3047
3048 mdns_client_ = MDnsClient::CreateDefault();
3049 mdns_client_->StartListening(mdns_socket_factory_.get());
3050 }
3051
3052 DCHECK(mdns_client_->IsListening());
3053 return mdns_client_.get();
3054#else
3055 // Should not request MDNS resoltuion unless MDNS is enabled.
3056 NOTREACHED();
3057 return nullptr;
3058#endif
3059}
3060
Paul Jensen41dc3e9f2018-11-06 22:10:103061void HostResolverImpl::UpdateModeForHistogram(const DnsConfig& dns_config) {
3062 // Resolving with Async DNS resolver?
3063 if (HaveDnsConfig()) {
3064 mode_for_histogram_ = MODE_FOR_HISTOGRAM_ASYNC_DNS;
3065 for (const auto& dns_server : dns_client_->GetConfig()->nameservers) {
3066 if (DnsServerSupportsDoh(dns_server.address())) {
3067 mode_for_histogram_ = MODE_FOR_HISTOGRAM_ASYNC_DNS_PRIVATE_SUPPORTS_DOH;
3068 break;
3069 }
3070 }
3071 } else {
3072 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM;
3073 for (const auto& dns_server : dns_config.nameservers) {
3074 if (DnsServerSupportsDoh(dns_server.address())) {
3075 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM_SUPPORTS_DOH;
3076 break;
3077 }
3078 }
3079#if defined(OS_ANDROID)
3080 if (base::android::BuildInfo::GetInstance()->sdk_int() >=
3081 base::android::SDK_VERSION_P) {
3082 std::vector<IPEndPoint> dns_servers;
3083 if (net::android::GetDnsServers(&dns_servers) ==
3084 internal::CONFIG_PARSE_POSIX_PRIVATE_DNS_ACTIVE) {
3085 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM_PRIVATE_DNS;
3086 }
3087 }
3088#endif // defined(OS_ANDROID)
3089 }
3090}
3091
maksim.sisov31452af2016-07-27 06:38:103092HostResolverImpl::RequestImpl::~RequestImpl() {
3093 if (job_)
3094 job_->CancelRequest(this);
3095}
3096
3097void HostResolverImpl::RequestImpl::ChangeRequestPriority(
3098 RequestPriority priority) {
3099 job_->ChangeRequestPriority(this, priority);
3100}
3101
[email protected]b59ff372009-07-15 22:04:323102} // namespace net