blob: 6b71265395f6e63a197b691befab1aa7f8e86355 [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>
[email protected]0f292de02012-02-01 22:28:2024#include <utility>
[email protected]21526002010-05-16 19:42:4625#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3926
[email protected]33152acc2011-10-20 23:37:1227#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2928#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2029#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1030#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3231#include "base/compiler_specific.h"
David Benjamina5677192018-04-23 23:25:4232#include "base/containers/linked_list.h"
[email protected]58580352010-10-26 04:07:5033#include "base/debug/debugger.h"
34#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4635#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2336#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4537#include "base/metrics/field_trial.h"
Maks Orlovich5393c8682018-02-26 16:17:5038#include "base/metrics/field_trial_params.h"
Ilya Sherman0eb39802017-12-08 20:58:1839#include "base/metrics/histogram_functions.h"
davidbenad6fc442015-05-18 20:59:1340#include "base/metrics/histogram_macros.h"
anujk.sharma7c907f02015-05-29 02:55:4441#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4842#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0543#include "base/strings/utf_string_conversions.h"
Gabriel Charette44db1422018-08-06 11:19:3344#include "base/task/post_task.h"
Francois Doraya2d01ba2017-09-25 19:17:4045#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3546#include "base/threading/thread_task_runner_handle.h"
Misha Efimovb99e7da2018-05-30 16:59:0247#include "base/time/default_tick_clock.h"
[email protected]66e96c42013-06-28 15:20:3148#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5649#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4650#include "base/values.h"
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4751#include "build/build_config.h"
[email protected]b3601bc22012-02-21 21:23:2052#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3253#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5154#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5155#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4856#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1557#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4858#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1859#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4660#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2761#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2062#include "net/dns/dns_config_service.h"
63#include "net/dns/dns_protocol.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"
[email protected]f2cb3cf2013-03-21 01:40:5368#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0769#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1970#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0071#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1972#include "net/log/net_log_parameters_callback.h"
73#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0074#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1975#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5176#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2677#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1478#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3279
80#if defined(OS_WIN)
81#include "net/base/winsock_init.h"
82#endif
83
tfarinada9e1362017-03-14 16:49:0684#if defined(OS_ANDROID)
85#include "net/android/network_library.h"
86#endif
87
[email protected]b59ff372009-07-15 22:04:3288namespace net {
89
[email protected]e95d3aca2010-01-11 22:47:4390namespace {
91
ttuttlecf1158bf2016-03-18 16:37:4492// Default delay between calls to the system resolver for the same hostname.
93// (Can be overridden by field trial.)
94const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
95
[email protected]6e78dfb2011-07-28 21:34:4796// Limit the size of hostnames that will be resolved to combat issues in
97// some platform's resolvers.
98const size_t kMaxHostLength = 4096;
99
[email protected]a2730882012-01-21 00:56:27100// Default TTL for successful resolutions with ProcTask.
101const unsigned kCacheEntryTTLSeconds = 60;
102
[email protected]b3601bc22012-02-21 21:23:20103// Default TTL for unsuccessful resolutions with ProcTask.
104const unsigned kNegativeCacheEntryTTLSeconds = 0;
105
[email protected]895123222012-10-25 15:21:17106// Minimum TTL for successful resolutions with DnsTask.
107const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
108
sergeyub8cdc212015-05-14 18:50:37109// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
110// cached.
111const int kIPv6ProbePeriodMs = 1000;
112
113// Google DNS address used for IPv6 probes.
114const uint8_t kIPv6ProbeAddress[] =
115 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
116 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
117
[email protected]24f4bab2010-10-15 01:27:11118// We use a separate histogram name for each platform to facilitate the
119// display of error codes by their symbolic name (since each platform has
120// different mappings).
121const char kOSErrorsForGetAddrinfoHistogramName[] =
122#if defined(OS_WIN)
123 "Net.OSErrorsForGetAddrinfo_Win";
124#elif defined(OS_MACOSX)
125 "Net.OSErrorsForGetAddrinfo_Mac";
126#elif defined(OS_LINUX)
127 "Net.OSErrorsForGetAddrinfo_Linux";
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47128#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]24f4bab2010-10-15 01:27:11129 "Net.OSErrorsForGetAddrinfo";
130#endif
131
[email protected]c89b2442011-05-26 14:28:27132// Gets a list of the likely error codes that getaddrinfo() can return
133// (non-exhaustive). These are the error codes that we will track via
134// a histogram.
135std::vector<int> GetAllGetAddrinfoOSErrors() {
136 int os_errors[] = {
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47137#if defined(OS_WIN)
138 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
139 WSA_NOT_ENOUGH_MEMORY,
140 WSAEAFNOSUPPORT,
141 WSAEINVAL,
142 WSAESOCKTNOSUPPORT,
143 WSAHOST_NOT_FOUND,
144 WSANO_DATA,
145 WSANO_RECOVERY,
146 WSANOTINITIALISED,
147 WSATRY_AGAIN,
148 WSATYPE_NOT_FOUND,
149 // The following are not in doc, but might be to appearing in results :-(.
150 WSA_INVALID_HANDLE,
151#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]23f771162011-06-02 18:37:51152#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37153#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45154 // EAI_ADDRFAMILY has been declared obsolete in Android's and
155 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27156 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37157#endif
[email protected]c48aef92011-11-22 23:41:45158 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51159 EAI_NODATA,
160#endif
[email protected]c89b2442011-05-26 14:28:27161 EAI_AGAIN,
162 EAI_BADFLAGS,
163 EAI_FAIL,
164 EAI_FAMILY,
165 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27166 EAI_NONAME,
167 EAI_SERVICE,
168 EAI_SOCKTYPE,
169 EAI_SYSTEM,
[email protected]c89b2442011-05-26 14:28:27170#endif
171 };
172
173 // Ensure all errors are positive, as histogram only tracks positive values.
174 for (size_t i = 0; i < arraysize(os_errors); ++i) {
175 os_errors[i] = std::abs(os_errors[i]);
176 }
177
Ryan Sleevi9c79c3542018-05-12 01:38:09178 return base::CustomHistogram::ArrayToCustomEnumRanges(os_errors);
[email protected]c89b2442011-05-26 14:28:27179}
180
[email protected]1def74c2012-03-22 20:07:00181enum DnsResolveStatus {
182 RESOLVE_STATUS_DNS_SUCCESS = 0,
183 RESOLVE_STATUS_PROC_SUCCESS,
184 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33185 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00186 RESOLVE_STATUS_MAX
187};
188
eroman91dd3602015-03-26 03:46:33189// ICANN uses this localhost address to indicate a name collision.
190//
191// The policy in Chromium is to fail host resolving if it resolves to
192// this special address.
193//
194// Not however that IP literals are exempt from this policy, so it is still
195// possible to navigate to http://127.0.53.53/ directly.
196//
197// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51198const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33199
eroman1efc237c2016-12-14 00:00:45200bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
201 for (const auto& endpoint : addr_list) {
202 const IPAddress& addr = endpoint.address();
203 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
204 return true;
205 }
206 }
207 return false;
208}
209
[email protected]1def74c2012-03-22 20:07:00210void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
211 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
212 result,
213 RESOLVE_STATUS_MAX);
214}
215
[email protected]1d932852012-06-19 19:40:33216bool ResemblesNetBIOSName(const std::string& hostname) {
217 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
218}
219
220// True if |hostname| ends with either ".local" or ".local.".
221bool ResemblesMulticastDNSName(const std::string& hostname) {
222 DCHECK(!hostname.empty());
223 const char kSuffix[] = ".local.";
224 const size_t kSuffixLen = sizeof(kSuffix) - 1;
225 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36226 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33227 return hostname.size() > kSuffixLen &&
228 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
229 }
230 return hostname.size() > kSuffixLenTrimmed &&
231 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
232 kSuffix, kSuffixLenTrimmed);
233}
234
[email protected]51b9a6b2012-06-25 21:50:29235// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21236#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
237 do { \
238 switch (priority) { \
239 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28240 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21241 break; \
242 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28243 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21244 break; \
245 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28246 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21247 break; \
248 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28249 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21250 break; \
251 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28252 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21253 break; \
254 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28255 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21256 break; \
257 } \
258 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29259 } while (0)
260
261// Record time from Request creation until a valid DNS response.
Miriam Gershenson90d05e02017-09-28 19:29:28262void RecordTotalTime(bool speculative,
263 bool from_cache,
[email protected]51b9a6b2012-06-25 21:50:29264 base::TimeDelta duration) {
Miriam Gershenson7ba03e12018-02-07 22:48:24265 if (!speculative) {
Miriam Gershenson90d05e02017-09-28 19:29:28266 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
Miriam Gershenson90d05e02017-09-28 19:29:28267
Miriam Gershenson7ba03e12018-02-07 22:48:24268 if (!from_cache)
Miriam Gershenson90d05e02017-09-28 19:29:28269 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
[email protected]51b9a6b2012-06-25 21:50:29270 }
271}
272
[email protected]1339a2a22012-10-17 08:39:43273void RecordTTL(base::TimeDelta ttl) {
274 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
275 base::TimeDelta::FromSeconds(1),
276 base::TimeDelta::FromDays(1), 100);
277}
278
[email protected]16c2bd72013-06-28 01:19:22279bool ConfigureAsyncDnsNoFallbackFieldTrial() {
280 const bool kDefault = false;
281
282 // Configure the AsyncDns field trial as follows:
283 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
284 // groups AsyncDnsA and AsyncDnsB: return false,
285 // groups SystemDnsA and SystemDnsB: return false,
286 // otherwise (trial absent): return default.
287 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29288 if (!group_name.empty()) {
289 return base::StartsWith(group_name, "AsyncDnsNoFallback",
290 base::CompareCase::INSENSITIVE_ASCII);
291 }
[email protected]16c2bd72013-06-28 01:19:22292 return kDefault;
293}
294
Maks Orlovich5393c8682018-02-26 16:17:50295const base::FeatureParam<base::TaskPriority>::Option prio_modes[] = {
296 {base::TaskPriority::USER_VISIBLE, "default"},
297 {base::TaskPriority::USER_BLOCKING, "user_blocking"}};
298const base::Feature kSystemResolverPriorityExperiment = {
299 "SystemResolverPriorityExperiment", base::FEATURE_DISABLED_BY_DEFAULT};
300const base::FeatureParam<base::TaskPriority> priority_mode{
301 &kSystemResolverPriorityExperiment, "mode",
302 base::TaskPriority::USER_VISIBLE, &prio_modes};
303
[email protected]d7b9a2b2012-05-31 22:31:19304//-----------------------------------------------------------------------------
305
Avi Drissman13fc8932015-12-20 04:40:46306AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17307 if (list.empty() || list.front().port() == port)
308 return list;
309 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56310}
311
[email protected]ec666ab22013-04-17 20:05:59312// Returns true if |addresses| contains only IPv4 loopback addresses.
313bool IsAllIPv4Loopback(const AddressList& addresses) {
314 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51315 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59316 switch (addresses[i].GetFamily()) {
317 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51318 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59319 return false;
320 break;
321 case ADDRESS_FAMILY_IPV6:
322 return false;
323 default:
324 NOTREACHED();
325 return false;
326 }
327 }
328 return true;
329}
330
tfarinada9e1362017-03-14 16:49:06331// Returns true if it can determine that only loopback addresses are configured.
332// i.e. if only 127.0.0.1 and ::1 are routable.
333// Also returns false if it cannot determine this.
334bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40335 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47336#if defined(OS_WIN)
337 // TODO(wtc): implement with the GetAdaptersAddresses function.
338 NOTIMPLEMENTED();
339 return false;
340#elif defined(OS_ANDROID)
tfarinada9e1362017-03-14 16:49:06341 return android::HaveOnlyLoopbackAddresses();
342#elif defined(OS_NACL)
343 NOTIMPLEMENTED();
344 return false;
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47345#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tfarinada9e1362017-03-14 16:49:06346 struct ifaddrs* interface_addr = NULL;
347 int rv = getifaddrs(&interface_addr);
348 if (rv != 0) {
349 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
350 return false;
351 }
352
353 bool result = true;
354 for (struct ifaddrs* interface = interface_addr;
355 interface != NULL;
356 interface = interface->ifa_next) {
357 if (!(IFF_UP & interface->ifa_flags))
358 continue;
359 if (IFF_LOOPBACK & interface->ifa_flags)
360 continue;
361 const struct sockaddr* addr = interface->ifa_addr;
362 if (!addr)
363 continue;
364 if (addr->sa_family == AF_INET6) {
365 // Safe cast since this is AF_INET6.
366 const struct sockaddr_in6* addr_in6 =
367 reinterpret_cast<const struct sockaddr_in6*>(addr);
368 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
369 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
370 continue;
371 }
372 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
373 continue;
374
375 result = false;
376 break;
377 }
378 freeifaddrs(interface_addr);
379 return result;
tfarinada9e1362017-03-14 16:49:06380#endif // defined(various platforms)
381}
382
[email protected]cd565142012-06-12 16:21:45383// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40384std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46385 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17386 int net_error,
387 int os_error,
388 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40389 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45390 if (attempt_number)
391 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46392
[email protected]cd565142012-06-12 16:21:45393 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16394
[email protected]cd565142012-06-12 16:21:45395 if (os_error) {
396 dict->SetInteger("os_error", os_error);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47397#if defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45398 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04399 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08400 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
401 0, // Use the internal message table.
402 os_error,
403 0, // Use default language.
404 (LPWSTR)&error_string,
405 0, // Buffer size.
406 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01407 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45408 LocalFree(error_string);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47409#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
410 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46411#endif
[email protected]21526002010-05-16 19:42:46412 }
413
dchengc7eeda422015-12-26 03:56:48414 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45415}
[email protected]a9813302012-04-28 09:29:28416
[email protected]cd565142012-06-12 16:21:45417// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40418std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11419 int net_error,
420 int dns_error,
421 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40422 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45423 dict->SetInteger("net_error", net_error);
424 if (dns_error)
425 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48426 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36427}
[email protected]ee094b82010-08-24 15:55:51428
[email protected]cd565142012-06-12 16:21:45429// Creates NetLog parameters containing the information in a RequestInfo object,
Eric Orth70992982018-07-24 00:25:00430// along with the associated NetLogSource. Use NetLogRequestCallback() if the
431// request information is not specified via RequestInfo.
danakj22f90e72016-04-16 01:55:40432std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11433 const HostResolver::RequestInfo* info,
434 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40435 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20436
[email protected]cd565142012-06-12 16:21:45437 dict->SetString("host", info->host_port_pair().ToString());
438 dict->SetInteger("address_family",
439 static_cast<int>(info->address_family()));
440 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
441 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48442 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45443}
[email protected]b3601bc22012-02-21 21:23:20444
Eric Orth70992982018-07-24 00:25:00445// Creates NetLog parameters containing the information of the request. Use
446// NetLogRequestInfoCallback if the request is specified via RequestInfo.
447std::unique_ptr<base::Value> NetLogRequestCallback(
448 const HostPortPair& host,
449 NetLogCaptureMode /* capture_mode */) {
450 auto dict = std::make_unique<base::DictionaryValue>();
451
452 dict->SetString("host", host.ToString());
453 dict->SetInteger("address_family",
454 static_cast<int>(ADDRESS_FAMILY_UNSPECIFIED));
455 dict->SetBoolean("allow_cached_response", true);
456 dict->SetBoolean("is_speculative", false);
457 return std::move(dict);
458}
459
[email protected]cd565142012-06-12 16:21:45460// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40461std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19462 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11463 const std::string* host,
464 NetLogCaptureMode /* capture_mode */) {
Eric Orth70992982018-07-24 00:25:00465 auto dict = std::make_unique<base::DictionaryValue>();
estade5e5529d2015-05-21 20:59:11466 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45467 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48468 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45469}
[email protected]a9813302012-04-28 09:29:28470
[email protected]cd565142012-06-12 16:21:45471// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40472std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19473 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11474 RequestPriority priority,
475 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40476 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11477 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56478 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48479 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45480}
[email protected]b3601bc22012-02-21 21:23:20481
[email protected]cd565142012-06-12 16:21:45482// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40483std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11484 const DnsConfig* config,
485 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08486 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45487}
[email protected]b4481b222012-03-16 17:13:11488
danakj22f90e72016-04-16 01:55:40489std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11490 bool ipv6_available,
491 bool cached,
492 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40493 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37494 dict->SetBoolean("ipv6_available", ipv6_available);
495 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48496 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37497}
498
[email protected]0f292de02012-02-01 22:28:20499// The logging routines are defined here because some requests are resolved
500// without a Request object.
501
Eric Orth70992982018-07-24 00:25:00502// Logs when a request has just been started. Overloads for whether or not the
503// request information is specified via a RequestInfo object.
tfarina428341112016-09-22 13:38:20504void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20505 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00506 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
507 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20508}
Eric Orth70992982018-07-24 00:25:00509void LogStartRequest(const NetLogWithSource& source_net_log,
510 const HostPortPair& host) {
511 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
512 base::BindRepeating(&NetLogRequestCallback, host));
513}
[email protected]0f292de02012-02-01 22:28:20514
515// Logs when a request has just completed (before its callback is run).
Eric Orth70992982018-07-24 00:25:00516void LogFinishRequest(const NetLogWithSource& source_net_log, int net_error) {
xunjieli26f90452014-11-10 16:23:02517 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00518 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20519}
520
521// Logs when a request has been cancelled.
Eric Orth70992982018-07-24 00:25:00522void LogCancelRequest(const NetLogWithSource& source_net_log) {
mikecirone8b85c432016-09-08 19:11:00523 source_net_log.AddEvent(NetLogEventType::CANCELLED);
524 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20525}
526
[email protected]b59ff372009-07-15 22:04:32527//-----------------------------------------------------------------------------
528
[email protected]0f292de02012-02-01 22:28:20529// Keeps track of the highest priority.
530class PriorityTracker {
531 public:
[email protected]8c98d002012-07-18 19:02:27532 explicit PriorityTracker(RequestPriority initial_priority)
533 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20534 memset(counts_, 0, sizeof(counts_));
535 }
536
537 RequestPriority highest_priority() const {
538 return highest_priority_;
539 }
540
541 size_t total_count() const {
542 return total_count_;
543 }
544
545 void Add(RequestPriority req_priority) {
546 ++total_count_;
547 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05548 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20549 highest_priority_ = req_priority;
550 }
551
552 void Remove(RequestPriority req_priority) {
553 DCHECK_GT(total_count_, 0u);
554 DCHECK_GT(counts_[req_priority], 0u);
555 --total_count_;
556 --counts_[req_priority];
557 size_t i;
thestiga74ad2b2016-07-11 20:52:36558 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
559 }
[email protected]0f292de02012-02-01 22:28:20560 highest_priority_ = static_cast<RequestPriority>(i);
561
[email protected]31ae7ab2012-04-24 21:09:05562 // In absence of requests, default to MINIMUM_PRIORITY.
563 if (total_count_ == 0)
564 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20565 }
566
567 private:
568 RequestPriority highest_priority_;
569 size_t total_count_;
570 size_t counts_[NUM_PRIORITIES];
571};
572
juliatuttle9fb7aeb2016-06-06 20:16:33573void MakeNotStale(HostCache::EntryStaleness* stale_info) {
574 if (!stale_info)
575 return;
576 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
577 stale_info->network_changes = 0;
578 stale_info->stale_hits = 0;
579}
580
[email protected]c54a8912012-10-22 22:09:43581} // namespace
[email protected]0f292de02012-02-01 22:28:20582
583//-----------------------------------------------------------------------------
584
tfarina9ed7f8c52016-02-19 17:50:18585bool ResolveLocalHostname(base::StringPiece host,
586 uint16_t port,
587 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18588 address_list->clear();
589
590 bool is_local6;
591 if (!IsLocalHostname(host, &is_local6))
592 return false;
593
martijna23c8962016-03-04 18:18:51594 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18595 if (!is_local6) {
martijna23c8962016-03-04 18:18:51596 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18597 }
598
599 return true;
600}
601
[email protected]daae1322013-09-05 18:26:50602const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
603
Eric Roman91aab1e62018-04-24 20:31:32604// Holds the callback and request parameters for an outstanding request.
605//
606// The RequestImpl is owned by the end user of host resolution. Deletion prior
607// to the request having completed means the request was cancelled by the
608// caller.
609//
610// Both the RequestImpl and its associated Job hold non-owning pointers to each
611// other. Care must be taken to clear the corresponding pointer when
612// cancellation is initiated by the Job (OnJobCancelled) vs by the end user
613// (~RequestImpl).
David Benjamina5677192018-04-23 23:25:42614class HostResolverImpl::RequestImpl
Eric Orth70992982018-07-24 00:25:00615 : public HostResolver::ResolveHostRequest,
David Benjamina5677192018-04-23 23:25:42616 public base::LinkNode<HostResolverImpl::RequestImpl> {
[email protected]b59ff372009-07-15 22:04:32617 public:
tfarina428341112016-09-22 13:38:20618 RequestImpl(const NetLogWithSource& source_net_log,
Eric Orth70992982018-07-24 00:25:00619 const HostPortPair& request_host,
620 bool is_speculative,
maksim.sisov31452af2016-07-27 06:38:10621 RequestPriority priority,
Eric Orth70992982018-07-24 00:25:00622 base::WeakPtr<HostResolverImpl> resolver)
623 : RequestImpl(source_net_log,
624 request_host,
625 ADDRESS_FAMILY_UNSPECIFIED,
626 0 /* host_resolver_flags */,
627 true /* allow_cached_response */,
628 is_speculative,
629 priority,
630 resolver) {}
631
632 // Overload for use by the legacy Resolve() API. Has more advanced parameters
633 // not yet supported by the CreateRequest() API.
634 RequestImpl(const NetLogWithSource& source_net_log,
635 const HostPortPair& request_host,
636 AddressFamily address_family,
637 HostResolverFlags host_resolver_flags,
638 bool allow_cached_response,
639 bool is_speculative,
640 RequestPriority priority,
641 base::WeakPtr<HostResolverImpl> resolver)
[email protected]ee094b82010-08-24 15:55:51642 : source_net_log_(source_net_log),
Eric Orth70992982018-07-24 00:25:00643 request_host_(request_host),
644 address_family_(address_family),
645 host_resolver_flags_(host_resolver_flags),
646 allow_cached_response_(allow_cached_response),
647 is_speculative_(is_speculative),
[email protected]5109c1952013-08-20 18:44:10648 priority_(priority),
Eric Orth70992982018-07-24 00:25:00649 job_(nullptr),
650 resolver_(resolver),
651 complete_(false) {}
[email protected]b59ff372009-07-15 22:04:32652
maksim.sisov31452af2016-07-27 06:38:10653 ~RequestImpl() override;
654
Eric Orth70992982018-07-24 00:25:00655 int Start(CompletionOnceCallback callback) override {
656 DCHECK(callback);
657 // Start() may only be called once per request.
658 DCHECK(!job_);
659 DCHECK(!complete_);
660 DCHECK(!callback_);
661 // Parent HostResolver must still be alive to call Start().
662 DCHECK(resolver_);
maksim.sisov31452af2016-07-27 06:38:10663
Eric Orth70992982018-07-24 00:25:00664 int rv = resolver_->Resolve(this);
665 DCHECK(!complete_);
666 if (rv == ERR_IO_PENDING) {
667 DCHECK(job_);
668 callback_ = std::move(callback);
669 } else {
670 DCHECK(!job_);
671 complete_ = true;
672 }
673 resolver_ = nullptr;
674
675 return rv;
676 }
677
678 const base::Optional<AddressList>& GetAddressResults() const override {
679 DCHECK(complete_);
680 return address_results_;
681 }
682
683 void set_address_results(const AddressList& address_results) {
684 // Should only be called at most once and before request is marked
685 // completed.
686 DCHECK(!complete_);
687 DCHECK(!address_results_);
688
689 address_results_ = address_results;
690 }
691
692 void ChangeRequestPriority(RequestPriority priority);
693
694 void AssignJob(Job* job) {
695 DCHECK(job);
696 DCHECK(!job_);
697
698 job_ = job;
699 }
700
701 // Unassigns the Job without calling completion callback.
maksim.sisov31452af2016-07-27 06:38:10702 void OnJobCancelled(Job* job) {
703 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04704 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00705 DCHECK(!complete_);
706 DCHECK(callback_);
[email protected]aa22b242011-11-16 18:58:29707 callback_.Reset();
Eric Orth70992982018-07-24 00:25:00708
709 // No results should be set.
710 DCHECK(!address_results_);
[email protected]b59ff372009-07-15 22:04:32711 }
712
Eric Orth70992982018-07-24 00:25:00713 // Cleans up Job assignment, marks request completed, and calls the completion
714 // callback.
715 void OnJobCompleted(Job* job, int error) {
maksim.sisov31452af2016-07-27 06:38:10716 DCHECK_EQ(job_, job);
maksim.sisov31452af2016-07-27 06:38:10717 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00718
719 DCHECK(!complete_);
720 complete_ = true;
721
722 DCHECK(callback_);
Bence Béky0f26a5812018-06-13 03:18:40723 std::move(callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32724 }
725
Eric Orth70992982018-07-24 00:25:00726 Job* job() const { return job_; }
[email protected]b59ff372009-07-15 22:04:32727
[email protected]0f292de02012-02-01 22:28:20728 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20729 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51730
Eric Orth70992982018-07-24 00:25:00731 const HostPortPair& request_host() const { return request_host_; }
732
733 AddressFamily address_family() const { return address_family_; }
734
735 HostResolverFlags host_resolver_flags() const { return host_resolver_flags_; }
736
737 bool allow_cached_response() const { return allow_cached_response_; }
738
739 bool is_speculative() const { return is_speculative_; }
[email protected]b59ff372009-07-15 22:04:32740
[email protected]5109c1952013-08-20 18:44:10741 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31742 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10743
Eric Orth70992982018-07-24 00:25:00744 bool complete() const { return complete_; }
745
746 base::TimeTicks request_time() const {
747 DCHECK(!request_time_.is_null());
748 return request_time_;
749 }
750 void set_request_time(base::TimeTicks request_time) {
751 DCHECK(request_time_.is_null());
752 DCHECK(!request_time.is_null());
753 request_time_ = request_time;
754 }
[email protected]51b9a6b2012-06-25 21:50:29755
[email protected]b59ff372009-07-15 22:04:32756 private:
tfarina428341112016-09-22 13:38:20757 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09758
Eric Orth70992982018-07-24 00:25:00759 const HostPortPair request_host_;
760 const AddressFamily address_family_;
761 const HostResolverFlags host_resolver_flags_;
762 const bool allow_cached_response_;
763 const bool is_speculative_;
[email protected]5109c1952013-08-20 18:44:10764
juliatuttlec53b19a72016-05-05 13:51:31765 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32766
[email protected]0f292de02012-02-01 22:28:20767 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32768 Job* job_;
Eric Orth70992982018-07-24 00:25:00769 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]b59ff372009-07-15 22:04:32770
771 // The user's callback to invoke when the request completes.
Bence Béky0f26a5812018-06-13 03:18:40772 CompletionOnceCallback callback_;
[email protected]b59ff372009-07-15 22:04:32773
Eric Orth70992982018-07-24 00:25:00774 bool complete_;
775 base::Optional<AddressList> address_results_;
[email protected]b59ff372009-07-15 22:04:32776
Eric Orth70992982018-07-24 00:25:00777 base::TimeTicks request_time_;
[email protected]51b9a6b2012-06-25 21:50:29778
maksim.sisov31452af2016-07-27 06:38:10779 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32780};
781
Eric Orth70992982018-07-24 00:25:00782// Wraps a RequestImpl to implement Request objects from the legacy Resolve()
783// API. The wrapped request must not yet have been started.
784//
785// TODO(crbug.com/821021): Delete this class once all usage has been
786// converted to the new CreateRequest() API.
787class HostResolverImpl::LegacyRequestImpl : public HostResolver::Request {
788 public:
789 explicit LegacyRequestImpl(std::unique_ptr<RequestImpl> inner_request)
790 : inner_request_(std::move(inner_request)) {
791 DCHECK(!inner_request_->job());
792 DCHECK(!inner_request_->complete());
793 }
794
795 ~LegacyRequestImpl() override {}
796
797 void ChangeRequestPriority(RequestPriority priority) override {
798 inner_request_->ChangeRequestPriority(priority);
799 }
800
801 int Start() {
802 return inner_request_->Start(base::BindOnce(
803 &LegacyRequestImpl::LegacyApiCallback, base::Unretained(this)));
804 }
805
806 // Do not call to assign the callback until we are running an async job (after
807 // Start() returns ERR_IO_PENDING) and before completion. Until then, the
808 // legacy HostResolverImpl::Resolve() needs to hang onto |callback| to ensure
809 // it stays alive for the duration of the method call, as some callers may be
810 // binding objects, eg the AddressList, with the callback.
811 void AssignCallback(CompletionOnceCallback callback,
812 AddressList* addresses_result_ptr) {
813 DCHECK(callback);
814 DCHECK(addresses_result_ptr);
815 DCHECK(inner_request_->job());
816 DCHECK(!inner_request_->complete());
817
818 callback_ = std::move(callback);
819 addresses_result_ptr_ = addresses_result_ptr;
820 }
821
822 const RequestImpl& inner_request() const { return *inner_request_; }
823
824 private:
825 // Result callback to bridge results handled entirely via ResolveHostRequest
826 // to legacy API styles where AddressList was a separate method out parameter.
827 void LegacyApiCallback(int error) {
828 // Must call AssignCallback() before async results.
829 DCHECK(callback_);
830
831 if (error == OK) {
832 // Legacy API does not allow non-address results (eg TXT), so AddressList
833 // is always expected to be present on OK.
834 DCHECK(inner_request_->GetAddressResults());
835 *addresses_result_ptr_ = inner_request_->GetAddressResults().value();
836 }
837 addresses_result_ptr_ = nullptr;
838 std::move(callback_).Run(error);
839 }
840
841 const std::unique_ptr<RequestImpl> inner_request_;
842
843 CompletionOnceCallback callback_;
844 // This is a caller-provided pointer and should not be used once |callback_|
845 // is invoked.
846 AddressList* addresses_result_ptr_;
847
848 DISALLOW_COPY_AND_ASSIGN(LegacyRequestImpl);
849};
850
[email protected]1e9bbd22010-10-15 16:42:45851//------------------------------------------------------------------------------
852
Francois Doraya2d01ba2017-09-25 19:17:40853// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20854//
Miriam Gershenson02592182018-03-22 17:42:37855// In non-test code, the HostResolverProc is always SystemHostResolverProc,
856// which calls a platform API that implements host resolution.
857//
[email protected]0f292de02012-02-01 22:28:20858// Whenever we try to resolve the host, we post a delayed task to check if host
859// resolution (OnLookupComplete) is completed or not. If the original attempt
860// hasn't completed, then we start another attempt for host resolution. We take
861// the results from the first attempt that finishes and ignore the results from
862// all other attempts.
863//
864// TODO(szym): Move to separate source file for testing and mocking.
865//
Eric Orth9a037562018-07-03 21:24:38866class HostResolverImpl::ProcTask {
[email protected]b59ff372009-07-15 22:04:32867 public:
Eric Orth9a037562018-07-03 21:24:38868 typedef base::OnceCallback<void(int net_error, const AddressList& addr_list)>
869 Callback;
[email protected]b59ff372009-07-15 22:04:32870
[email protected]0f292de02012-02-01 22:28:20871 ProcTask(const Key& key,
872 const ProcTaskParams& params,
Eric Orth9a037562018-07-03 21:24:38873 Callback callback,
Miriam Gershensone42adb22017-10-16 16:19:38874 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:02875 const NetLogWithSource& job_net_log,
876 const base::TickClock* tick_clock)
[email protected]0f292de02012-02-01 22:28:20877 : key_(key),
878 params_(params),
Eric Orth9a037562018-07-03 21:24:38879 callback_(std::move(callback)),
mmenke91c17162016-06-02 16:03:23880 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38881 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20882 attempt_number_(0),
Misha Efimovb99e7da2018-05-30 16:59:02883 net_log_(job_net_log),
Eric Orth9a037562018-07-03 21:24:38884 tick_clock_(tick_clock),
885 weak_ptr_factory_(this) {
886 DCHECK(callback_);
[email protected]90499482013-06-01 00:39:50887 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20888 params_.resolver_proc = HostResolverProc::GetDefault();
889 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50890 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06891 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32892 }
893
Eric Orth9a037562018-07-03 21:24:38894 // Cancels this ProcTask. Any outstanding resolve attempts running on worker
895 // thread will continue running, but they will post back to the network thread
896 // before checking their WeakPtrs to find that this task is cancelled.
897 ~ProcTask() {
898 DCHECK(network_task_runner_->BelongsToCurrentThread());
899
900 // If this is cancellation, log the EndEvent (otherwise this was logged in
901 // OnLookupComplete()).
902 if (!was_completed())
903 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
904 }
905
[email protected]b59ff372009-07-15 22:04:32906 void Start() {
mmenke91c17162016-06-02 16:03:23907 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38908 DCHECK(!was_completed());
mikecirone8b85c432016-09-08 19:11:00909 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54910 StartLookupAttempt();
911 }
[email protected]252b699b2010-02-05 21:38:06912
Eric Orth9a037562018-07-03 21:24:38913 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23914 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20915 return callback_.is_null();
916 }
917
[email protected]0f292de02012-02-01 22:28:20918 private:
Eric Orth9a037562018-07-03 21:24:38919 using AttemptCompletionCallback = base::OnceCallback<
920 void(const AddressList& results, int error, const int os_error)>;
[email protected]a9813302012-04-28 09:29:28921
[email protected]189163e2011-05-11 01:48:54922 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23923 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38924 DCHECK(!was_completed());
Misha Efimovb99e7da2018-05-30 16:59:02925 base::TimeTicks start_time = tick_clock_->NowTicks();
[email protected]189163e2011-05-11 01:48:54926 ++attempt_number_;
927 // Dispatch the lookup attempt to a worker thread.
Eric Orth9a037562018-07-03 21:24:38928 AttemptCompletionCallback completion_callback = base::BindOnce(
929 &ProcTask::OnLookupAttemptComplete, weak_ptr_factory_.GetWeakPtr(),
930 start_time, attempt_number_, tick_clock_);
Miriam Gershensone42adb22017-10-16 16:19:38931 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40932 FROM_HERE,
Eric Orth9a037562018-07-03 21:24:38933 base::BindOnce(&ProcTask::DoLookup, key_, params_.resolver_proc,
934 network_task_runner_, std::move(completion_callback)));
[email protected]13024882011-05-18 23:19:16935
mikecirone8b85c432016-09-08 19:11:00936 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28937 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16938
mmenke91c17162016-06-02 16:03:23939 // If the results aren't received within a given time, RetryIfNotComplete
940 // will start a new attempt if none of the outstanding attempts have
941 // completed yet.
Eric Orth9a037562018-07-03 21:24:38942 // Use a WeakPtr to avoid keeping the ProcTask alive after completion or
943 // cancellation.
[email protected]0f292de02012-02-01 22:28:20944 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23945 network_task_runner_->PostDelayedTask(
Eric Orth9a037562018-07-03 21:24:38946 FROM_HERE,
947 base::BindOnce(&ProcTask::StartLookupAttempt,
948 weak_ptr_factory_.GetWeakPtr()),
949 params_.unresponsive_delay *
950 std::pow(params_.retry_factor, attempt_number_ - 1));
[email protected]06ef6d92011-05-19 04:24:58951 }
[email protected]b59ff372009-07-15 22:04:32952 }
953
Francois Doraya2d01ba2017-09-25 19:17:40954 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
955 // shutdown code cannot wait for it to finish, so this code must be very
956 // careful about using other objects (like MessageLoops, Singletons, etc).
Eric Orth9a037562018-07-03 21:24:38957 // During shutdown these objects may no longer exist.
958 static void DoLookup(
959 Key key,
960 scoped_refptr<HostResolverProc> resolver_proc,
961 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
962 AttemptCompletionCallback completion_callback) {
[email protected]189163e2011-05-11 01:48:54963 AddressList results;
964 int os_error = 0;
Eric Orth9a037562018-07-03 21:24:38965 int error =
966 resolver_proc->Resolve(key.hostname, key.address_family,
967 key.host_resolver_flags, &results, &os_error);
[email protected]b59ff372009-07-15 22:04:32968
Eric Orth9a037562018-07-03 21:24:38969 network_task_runner->PostTask(
970 FROM_HERE, base::BindOnce(std::move(completion_callback), results,
971 error, os_error));
[email protected]189163e2011-05-11 01:48:54972 }
973
Eric Orth9a037562018-07-03 21:24:38974 // Callback for when DoLookup() completes (runs on task runner thread). Now
975 // that we're back in the network thread, checks that |proc_task| is still
976 // valid, and if so, passes back to the object.
977 static void OnLookupAttemptComplete(base::WeakPtr<ProcTask> proc_task,
978 const base::TimeTicks& start_time,
979 const uint32_t attempt_number,
980 const base::TickClock* tick_clock,
981 const AddressList& results,
982 int error,
983 const int os_error) {
Luciano Pachecob4426082018-07-02 08:04:18984 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
Eric Orth9a037562018-07-03 21:24:38985
[email protected]49b70b222013-05-07 21:24:23986 // If results are empty, we should return an error.
987 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23988 if (empty_list_on_ok)
989 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54990
[email protected]2d3b7762010-10-09 00:35:47991 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20992 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23993 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54994 if (error != OK && NetworkChangeNotifier::IsOffline())
995 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47996
Eric Orth9a037562018-07-03 21:24:38997 RecordAttemptHistograms(start_time, attempt_number, error, os_error,
998 tick_clock);
Luciano Pachecob4426082018-07-02 08:04:18999
Eric Orth9a037562018-07-03 21:24:381000 if (!proc_task) {
1001 RecordDiscardedAttemptHistograms(attempt_number);
Luciano Pachecob4426082018-07-02 08:04:181002 return;
Eric Orth9a037562018-07-03 21:24:381003 }
1004
1005 proc_task->OnLookupComplete(results, start_time, attempt_number, error,
1006 os_error);
1007 }
1008
1009 void OnLookupComplete(const AddressList& results,
1010 const base::TimeTicks& start_time,
1011 const uint32_t attempt_number,
1012 int error,
1013 const int os_error) {
1014 DCHECK(network_task_runner_->BelongsToCurrentThread());
1015 DCHECK(!was_completed());
1016
1017 // Invalidate WeakPtrs to cancel handling of all outstanding lookup attempts
1018 // and retries.
1019 weak_ptr_factory_.InvalidateWeakPtrs();
1020
1021 RecordTaskHistograms(start_time, error, os_error, attempt_number);
Luciano Pachecob4426082018-07-02 08:04:181022
Eric Orthcb8862f2018-06-27 18:08:351023 NetLogParametersCallback net_log_callback;
Eric Orth9a037562018-07-03 21:24:381024 NetLogParametersCallback attempt_net_log_callback;
[email protected]0f292de02012-02-01 22:28:201025 if (error != OK) {
Eric Orth70992982018-07-24 00:25:001026 net_log_callback = base::BindRepeating(&NetLogProcTaskFailedCallback, 0,
1027 error, os_error);
1028 attempt_net_log_callback = base::BindRepeating(
1029 &NetLogProcTaskFailedCallback, attempt_number, error, os_error);
[email protected]ee094b82010-08-24 15:55:511030 } else {
Eric Orth9a037562018-07-03 21:24:381031 net_log_callback = results.CreateNetLogCallback();
1032 attempt_net_log_callback =
1033 NetLog::IntCallback("attempt_number", attempt_number);
[email protected]ee094b82010-08-24 15:55:511034 }
mikecirone8b85c432016-09-08 19:11:001035 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:451036 net_log_callback);
Eric Orth9a037562018-07-03 21:24:381037 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
1038 attempt_net_log_callback);
[email protected]ee094b82010-08-24 15:55:511039
Eric Orth9a037562018-07-03 21:24:381040 std::move(callback_).Run(error, results);
[email protected]b59ff372009-07-15 22:04:321041 }
1042
Miriam Gershenson61604662017-09-28 23:51:111043 void RecordTaskHistograms(const base::TimeTicks& start_time,
1044 const int error,
Eric Orth9a037562018-07-03 21:24:381045 const int os_error,
1046 const uint32_t attempt_number) const {
mmenke91c17162016-06-02 16:03:231047 DCHECK(network_task_runner_->BelongsToCurrentThread());
Misha Efimovb99e7da2018-05-30 16:59:021048 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Eric Orth9a037562018-07-03 21:24:381049 if (error == OK) {
Miriam Gershenson61604662017-09-28 23:51:111050 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.SuccessTime", duration);
Eric Orth9a037562018-07-03 21:24:381051 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFirstSuccess", attempt_number, 100);
1052 } else {
Miriam Gershenson61604662017-09-28 23:51:111053 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.FailureTime", duration);
Eric Orth9a037562018-07-03 21:24:381054 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFirstFailure", attempt_number, 100);
1055 }
[email protected]7e96d792011-06-10 17:08:231056
Miriam Gershenson61604662017-09-28 23:51:111057 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
1058 std::abs(os_error),
1059 GetAllGetAddrinfoOSErrors());
[email protected]1e9bbd22010-10-15 16:42:451060 }
1061
Eric Orth9a037562018-07-03 21:24:381062 static void RecordAttemptHistograms(const base::TimeTicks& start_time,
1063 const uint32_t attempt_number,
1064 const int error,
1065 const int os_error,
1066 const base::TickClock* tick_clock) {
1067 base::TimeDelta duration = tick_clock->NowTicks() - start_time;
1068 if (error == OK) {
Luciano Pachecob4426082018-07-02 08:04:181069 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
Luciano Pachecob4426082018-07-02 08:04:181070 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptSuccessDuration", duration);
Eric Orth9a037562018-07-03 21:24:381071 } else {
1072 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
Luciano Pachecob4426082018-07-02 08:04:181073 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptFailDuration", duration);
Eric Orth9a037562018-07-03 21:24:381074 }
[email protected]189163e2011-05-11 01:48:541075 }
[email protected]1e9bbd22010-10-15 16:42:451076
Eric Orth9a037562018-07-03 21:24:381077 static void RecordDiscardedAttemptHistograms(const uint32_t attempt_number) {
1078 // Count those attempts which completed after the job was already canceled
1079 // OR after the job was already completed by an earlier attempt (so
1080 // cancelled in effect).
1081 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
1082 }
1083
[email protected]123ab1e32009-10-21 19:12:571084 Key key_;
[email protected]b59ff372009-07-15 22:04:321085
[email protected]0f292de02012-02-01 22:28:201086 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:321087 // This may not be the current resolver procedure by the time we call
1088 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
1089 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:201090 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:321091
[email protected]0f292de02012-02-01 22:28:201092 // The listener to the results of this ProcTask.
1093 Callback callback_;
1094
mmenke91c17162016-06-02 16:03:231095 // Used to post events onto the network thread.
1096 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:381097 // Used to post blocking HostResolverProc tasks.
1098 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:541099
1100 // Keeps track of the number of attempts we have made so far to resolve the
1101 // host. Whenever we start an attempt to resolve the host, we increase this
1102 // number.
Avi Drissman13fc8932015-12-20 04:40:461103 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:541104
tfarina428341112016-09-22 13:38:201105 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:511106
Misha Efimovb99e7da2018-05-30 16:59:021107 const base::TickClock* tick_clock_;
1108
Eric Orth9a037562018-07-03 21:24:381109 // Used to loop back from the blocking lookup attempt tasks as well as from
1110 // delayed retry tasks. Invalidate WeakPtrs on completion and cancellation to
1111 // cancel handling of such posted tasks.
1112 base::WeakPtrFactory<ProcTask> weak_ptr_factory_;
1113
[email protected]0f292de02012-02-01 22:28:201114 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:321115};
1116
1117//-----------------------------------------------------------------------------
1118
Miriam Gershenson02592182018-03-22 17:42:371119// Resolves the hostname using DnsTransaction, which is a full implementation of
1120// a DNS stub resolver. One DnsTransaction is created for each resolution
1121// needed, which for AF_UNSPEC resolutions includes both A and AAAA. The
1122// transactions are scheduled separately and started separately.
1123//
[email protected]b3601bc22012-02-21 21:23:201124// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461125class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201126 public:
[email protected]daae1322013-09-05 18:26:501127 class Delegate {
1128 public:
1129 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1130 int net_error,
1131 const AddressList& addr_list,
1132 base::TimeDelta ttl) = 0;
1133
1134 // Called when the first of two jobs succeeds. If the first completed
1135 // transaction fails, this is not called. Also not called when the DnsTask
1136 // only needs to run one transaction.
1137 virtual void OnFirstDnsTransactionComplete() = 0;
1138
Brad Lassey786929ad2018-02-21 20:54:271139 virtual URLRequestContext* url_request_context() = 0;
1140 virtual RequestPriority priority() const = 0;
1141
[email protected]daae1322013-09-05 18:26:501142 protected:
Chris Watkins68b15032017-12-01 03:07:131143 Delegate() = default;
1144 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:501145 };
[email protected]b3601bc22012-02-21 21:23:201146
[email protected]0adcb2b2012-08-15 21:30:461147 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201148 const Key& key,
[email protected]daae1322013-09-05 18:26:501149 Delegate* delegate,
Misha Efimovb99e7da2018-05-30 16:59:021150 const NetLogWithSource& job_net_log,
1151 const base::TickClock* tick_clock)
[email protected]0adcb2b2012-08-15 21:30:461152 : client_(client),
[email protected]daae1322013-09-05 18:26:501153 key_(key),
1154 delegate_(delegate),
1155 net_log_(job_net_log),
1156 num_completed_transactions_(0),
Misha Efimovb99e7da2018-05-30 16:59:021157 tick_clock_(tick_clock),
1158 task_start_time_(tick_clock_->NowTicks()) {
[email protected]0adcb2b2012-08-15 21:30:461159 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501160 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501161 }
1162
[email protected]daae1322013-09-05 18:26:501163 bool needs_two_transactions() const {
1164 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1165 }
1166
1167 bool needs_another_transaction() const {
1168 return needs_two_transactions() && !transaction_aaaa_;
1169 }
1170
1171 void StartFirstTransaction() {
1172 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001173 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501174 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1175 StartAAAA();
1176 } else {
1177 StartA();
1178 }
1179 }
1180
1181 void StartSecondTransaction() {
1182 DCHECK(needs_two_transactions());
1183 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121184 }
1185
Brad Lassey2e8f185d2018-05-21 22:25:211186 base::TimeDelta ttl() { return ttl_; }
1187
[email protected]70c04ab2013-08-22 16:05:121188 private:
[email protected]daae1322013-09-05 18:26:501189 void StartA() {
1190 DCHECK(!transaction_a_);
1191 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1192 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1193 transaction_a_->Start();
1194 }
1195
1196 void StartAAAA() {
1197 DCHECK(!transaction_aaaa_);
1198 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1199 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1200 transaction_aaaa_->Start();
1201 }
1202
danakj22f90e72016-04-16 01:55:401203 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501204 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
Brad Lassey786929ad2018-02-21 20:54:271205 std::unique_ptr<DnsTransaction> trans =
1206 client_->GetTransactionFactory()->CreateTransaction(
1207 key_.hostname,
1208 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA
1209 : dns_protocol::kTypeA,
Brad Lasseydba0a84b2018-02-23 22:18:531210 base::BindOnce(&DnsTask::OnTransactionComplete,
Misha Efimovb99e7da2018-05-30 16:59:021211 base::Unretained(this), tick_clock_->NowTicks()),
Brad Lassey786929ad2018-02-21 20:54:271212 net_log_);
1213 trans->SetRequestContext(delegate_->url_request_context());
1214 trans->SetRequestPriority(delegate_->priority());
1215 return trans;
[email protected]daae1322013-09-05 18:26:501216 }
1217
1218 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001219 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201220 int net_error,
1221 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471222 DCHECK(transaction);
Misha Efimovb99e7da2018-05-30 16:59:021223 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Brad Lassey2e8f185d2018-05-21 22:25:211224 if (net_error != OK && !(net_error == ERR_NAME_NOT_RESOLVED && response &&
1225 response->IsValid())) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211226 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461227 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1228 return;
[email protected]6c411902012-08-14 22:36:361229 }
[email protected]0adcb2b2012-08-15 21:30:461230
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211231 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511232 switch (transaction->GetType()) {
1233 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211234 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511235 break;
1236 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211237 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1238 duration);
[email protected]02cd6982013-01-10 20:12:511239 break;
1240 }
[email protected]daae1322013-09-05 18:26:501241
[email protected]0adcb2b2012-08-15 21:30:461242 AddressList addr_list;
1243 base::TimeDelta ttl;
1244 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1245 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1246 result,
1247 DnsResponse::DNS_PARSE_RESULT_MAX);
1248 if (result != DnsResponse::DNS_PARSE_OK) {
1249 // Fail even if the other query succeeds.
1250 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1251 return;
1252 }
1253
[email protected]daae1322013-09-05 18:26:501254 ++num_completed_transactions_;
1255 if (num_completed_transactions_ == 1) {
1256 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461257 } else {
[email protected]daae1322013-09-05 18:26:501258 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461259 }
1260
[email protected]daae1322013-09-05 18:26:501261 if (transaction->GetType() == dns_protocol::kTypeA) {
1262 DCHECK_EQ(transaction_a_.get(), transaction);
1263 // Place IPv4 addresses after IPv6.
1264 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1265 } else {
1266 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1267 // Place IPv6 addresses before IPv4.
1268 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1269 }
1270
1271 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1272 // No need to repeat the suffix search.
1273 key_.hostname = transaction->GetHostname();
1274 delegate_->OnFirstDnsTransactionComplete();
1275 return;
1276 }
1277
1278 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121279 // TODO(szym): Don't fallback to ProcTask in this case.
1280 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461281 return;
1282 }
1283
[email protected]daae1322013-09-05 18:26:501284 // If there are multiple addresses, and at least one is IPv6, need to sort
1285 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1286 // sufficient to just check the family of the first address.
1287 if (addr_list_.size() > 1 &&
1288 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1289 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461290 client_->GetAddressSorter()->Sort(
Bence Békyd5e474c2018-08-02 18:45:081291 addr_list_, base::BindOnce(&DnsTask::OnSortComplete, AsWeakPtr(),
1292 tick_clock_->NowTicks()));
[email protected]0adcb2b2012-08-15 21:30:461293 } else {
[email protected]daae1322013-09-05 18:26:501294 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461295 }
1296 }
1297
1298 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461299 bool success,
1300 const AddressList& addr_list) {
1301 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211302 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
Misha Efimovb99e7da2018-05-30 16:59:021303 tick_clock_->NowTicks() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461304 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1305 return;
1306 }
1307
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211308 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
Misha Efimovb99e7da2018-05-30 16:59:021309 tick_clock_->NowTicks() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461310
1311 // AddressSorter prunes unusable destinations.
1312 if (addr_list.empty()) {
1313 LOG(WARNING) << "Address list empty after RFC3484 sort";
1314 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1315 return;
1316 }
1317
[email protected]daae1322013-09-05 18:26:501318 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461319 }
1320
1321 void OnFailure(int net_error, DnsResponse::Result result) {
1322 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451323 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001324 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451325 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
Brad Lassey2e8f185d2018-05-21 22:25:211326 base::TimeDelta ttl = ttl_ < base::TimeDelta::FromSeconds(
1327 std::numeric_limits<uint32_t>::max()) &&
1328 num_completed_transactions_ > 0
1329 ? ttl_
1330 : base::TimeDelta::FromSeconds(0);
Miriam Gershenson66024d72017-12-05 04:30:321331 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
Brad Lassey2e8f185d2018-05-21 22:25:211332 ttl);
[email protected]b3601bc22012-02-21 21:23:201333 }
1334
[email protected]daae1322013-09-05 18:26:501335 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001336 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461337 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501338 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461339 }
1340
1341 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501342 Key key_;
1343
[email protected]b3601bc22012-02-21 21:23:201344 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501345 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201346 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201347
danakj22f90e72016-04-16 01:55:401348 std::unique_ptr<DnsTransaction> transaction_a_;
1349 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461350
[email protected]daae1322013-09-05 18:26:501351 unsigned num_completed_transactions_;
1352
1353 // These are updated as each transaction completes.
1354 base::TimeDelta ttl_;
1355 // IPv6 addresses must appear first in the list.
1356 AddressList addr_list_;
1357
Misha Efimovb99e7da2018-05-30 16:59:021358 const base::TickClock* tick_clock_;
[email protected]daae1322013-09-05 18:26:501359 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461360
1361 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201362};
1363
1364//-----------------------------------------------------------------------------
1365
[email protected]0f292de02012-02-01 22:28:201366// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501367class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1368 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391369 public:
[email protected]0f292de02012-02-01 22:28:201370 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351371 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181372 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201373 const Key& key,
[email protected]8c98d002012-07-18 19:02:271374 RequestPriority priority,
Miriam Gershensone42adb22017-10-16 16:19:381375 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:021376 const NetLogWithSource& source_net_log,
1377 const base::TickClock* tick_clock)
[email protected]12faa4c2012-11-06 04:44:181378 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201379 key_(key),
[email protected]8c98d002012-07-18 19:02:271380 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381381 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201382 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291383 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501384 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331385 dns_task_error_(OK),
Misha Efimovb99e7da2018-05-30 16:59:021386 tick_clock_(tick_clock),
1387 creation_time_(tick_clock_->NowTicks()),
[email protected]51b9a6b2012-06-25 21:50:291388 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201389 net_log_(
1390 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001391 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1392 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201393
mikecirone8b85c432016-09-08 19:11:001394 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1395 base::Bind(&NetLogJobCreationCallback,
1396 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391397 }
1398
dchengb03027d2014-10-21 12:00:201399 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201400 if (is_running()) {
1401 // |resolver_| was destroyed with this Job still in flight.
1402 // Clean-up, record in the log, but don't run any callbacks.
Eric Orth9a037562018-07-03 21:24:381403 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351404 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501405 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001406 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201407 ERR_ABORTED);
1408 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551409 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351410 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001411 net_log_.AddEvent(NetLogEventType::CANCELLED);
1412 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391413 }
[email protected]b3601bc22012-02-21 21:23:201414 // else CompleteRequests logged EndEvent.
David Benjamina5677192018-04-23 23:25:421415 while (!requests_.empty()) {
maksim.sisov31452af2016-07-27 06:38:101416 // Log any remaining Requests as cancelled.
David Benjamina5677192018-04-23 23:25:421417 RequestImpl* req = requests_.head()->value();
1418 req->RemoveFromList();
1419 DCHECK_EQ(this, req->job());
Eric Orth70992982018-07-24 00:25:001420 LogCancelRequest(req->source_net_log());
David Benjamina5677192018-04-23 23:25:421421 req->OnJobCancelled(this);
[email protected]b3601bc22012-02-21 21:23:201422 }
[email protected]68ad3ee2010-01-30 03:45:391423 }
1424
[email protected]daae1322013-09-05 18:26:501425 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1426 // of the queue.
1427 void Schedule(bool at_head) {
1428 DCHECK(!is_queued());
1429 PrioritizedDispatcher::Handle handle;
1430 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001431 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501432 } else {
[email protected]106ccd2c2014-06-17 09:21:001433 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501434 }
1435 // The dispatcher could have started |this| in the above call to Add, which
1436 // could have called Schedule again. In that case |handle| will be null,
1437 // but |handle_| may have been set by the other nested call to Schedule.
1438 if (!handle.is_null()) {
1439 DCHECK(handle_.is_null());
1440 handle_ = handle;
1441 }
[email protected]16ee26d2012-03-08 03:34:351442 }
1443
maksim.sisov31452af2016-07-27 06:38:101444 void AddRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001445 DCHECK_EQ(key_.hostname, request->request_host().host());
1446
1447 request->AssignJob(this);
[email protected]0f292de02012-02-01 22:28:201448
maksim.sisov31452af2016-07-27 06:38:101449 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201450
maksim.sisov31452af2016-07-27 06:38:101451 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001452 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451453 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201454
1455 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001456 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101457 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451458 priority()));
[email protected]0f292de02012-02-01 22:28:201459
Eric Orth70992982018-07-24 00:25:001460 if (!request->is_speculative())
[email protected]0f292de02012-02-01 22:28:201461 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201462
David Benjamina5677192018-04-23 23:25:421463 requests_.Append(request);
[email protected]b3601bc22012-02-21 21:23:201464
[email protected]51b9a6b2012-06-25 21:50:291465 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391466 }
1467
maksim.sisov31452af2016-07-27 06:38:101468 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
Eric Orth70992982018-07-24 00:25:001469 DCHECK_EQ(key_.hostname, req->request_host().host());
juliatuttlec53b19a72016-05-05 13:51:311470
1471 priority_tracker_.Remove(req->priority());
1472 req->set_priority(priority);
1473 priority_tracker_.Add(req->priority());
1474 UpdatePriority();
1475 }
1476
maksim.sisov31452af2016-07-27 06:38:101477 // Detach cancelled request. If it was the last active Request, also finishes
1478 // this Job.
1479 void CancelRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001480 DCHECK_EQ(key_.hostname, request->request_host().host());
maksim.sisov31452af2016-07-27 06:38:101481 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351482
Eric Orth70992982018-07-24 00:25:001483 LogCancelRequest(request->source_net_log());
[email protected]16ee26d2012-03-08 03:34:351484
maksim.sisov31452af2016-07-27 06:38:101485 priority_tracker_.Remove(request->priority());
1486 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001487 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101488 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1489 priority()));
[email protected]b3601bc22012-02-21 21:23:201490
[email protected]16ee26d2012-03-08 03:34:351491 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291492 UpdatePriority();
David Benjamina5677192018-04-23 23:25:421493 request->RemoveFromList();
[email protected]16ee26d2012-03-08 03:34:351494 } else {
1495 // If we were called from a Request's callback within CompleteRequests,
1496 // that Request could not have been cancelled, so num_active_requests()
1497 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431498 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201499 }
[email protected]68ad3ee2010-01-30 03:45:391500 }
1501
[email protected]7af985a2012-12-14 22:40:421502 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1503 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111504 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201505 void Abort() {
[email protected]0f292de02012-02-01 22:28:201506 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421507 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201508 }
1509
[email protected]f0f602bd2012-11-15 18:01:021510 // If DnsTask present, abort it and fall back to ProcTask.
1511 void AbortDnsTask() {
1512 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501513 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021514 dns_task_error_ = OK;
1515 StartProcTask();
1516 }
1517 }
1518
[email protected]16ee26d2012-03-08 03:34:351519 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1520 // Completes all requests and destroys the job.
1521 void OnEvicted() {
1522 DCHECK(!is_running());
1523 DCHECK(is_queued());
1524 handle_.Reset();
1525
mikecirone8b85c432016-09-08 19:11:001526 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351527
1528 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431529 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351530 }
1531
[email protected]78eac2a2012-03-14 19:09:271532 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1533 // this Job was destroyed.
1534 bool ServeFromHosts() {
1535 DCHECK_GT(num_active_requests(), 0u);
1536 AddressList addr_list;
Eric Orth70992982018-07-24 00:25:001537 if (resolver_->ServeFromHosts(
1538 key(), requests_.head()->value()->request_host().port(),
1539 &addr_list)) {
[email protected]78eac2a2012-03-14 19:09:271540 // This will destroy the Job.
Rob Percival94f21ad2017-11-14 10:20:241541 CompleteRequests(
1542 MakeCacheEntry(OK, addr_list, HostCache::Entry::SOURCE_HOSTS),
1543 base::TimeDelta());
[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 {
1556 return is_dns_running() || is_proc_running();
1557 }
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
eroman0cd87b62016-12-14 19:13:451583 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1584 // HostCache::Entry(). The address list is omited from the cache entry
1585 // for errors.
1586 HostCache::Entry MakeCacheEntry(int net_error,
Rob Percival94f21ad2017-11-14 10:20:241587 const AddressList& addr_list,
1588 HostCache::Entry::Source source) const {
eroman0cd87b62016-12-14 19:13:451589 return HostCache::Entry(
1590 net_error,
Rob Percival94f21ad2017-11-14 10:20:241591 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1592 source);
eroman0cd87b62016-12-14 19:13:451593 }
1594
1595 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1596 const AddressList& addr_list,
Rob Percival94f21ad2017-11-14 10:20:241597 HostCache::Entry::Source source,
eroman0cd87b62016-12-14 19:13:451598 base::TimeDelta ttl) const {
1599 return HostCache::Entry(
1600 net_error,
1601 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
Rob Percival94f21ad2017-11-14 10:20:241602 source, ttl);
eroman0cd87b62016-12-14 19:13:451603 }
1604
juliatuttlec53b19a72016-05-05 13:51:311605 AddressList MakeAddressListForRequest(const AddressList& list) const {
1606 if (requests_.empty())
1607 return list;
Eric Orth70992982018-07-24 00:25:001608 return AddressList::CopyWithPort(
1609 list, requests_.head()->value()->request_host().port());
juliatuttlec53b19a72016-05-05 13:51:311610 }
1611
[email protected]51b9a6b2012-06-25 21:50:291612 void UpdatePriority() {
1613 if (is_queued()) {
1614 if (priority() != static_cast<RequestPriority>(handle_.priority()))
Misha Efimovb99e7da2018-05-30 16:59:021615 priority_change_time_ = tick_clock_->NowTicks();
[email protected]106ccd2c2014-06-17 09:21:001616 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291617 }
1618 }
1619
[email protected]16ee26d2012-03-08 03:34:351620 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201621 void Start() override {
[email protected]daae1322013-09-05 18:26:501622 DCHECK_LE(num_occupied_job_slots_, 1u);
1623
[email protected]70c04ab2013-08-22 16:05:121624 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501625 ++num_occupied_job_slots_;
1626
1627 if (num_occupied_job_slots_ == 2) {
1628 StartSecondDnsTransaction();
1629 return;
1630 }
1631
1632 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201633
mikecirone8b85c432016-09-08 19:11:001634 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201635
[email protected]51b9a6b2012-06-25 21:50:291636 had_dns_config_ = resolver_->HaveDnsConfig();
1637
Misha Efimovb99e7da2018-05-30 16:59:021638 start_time_ = tick_clock_->NowTicks();
Miriam Gershenson61604662017-09-28 23:51:111639 base::TimeDelta queue_time = start_time_ - creation_time_;
1640 base::TimeDelta queue_time_after_change =
1641 start_time_ - priority_change_time_;
[email protected]51b9a6b2012-06-25 21:50:291642
Miriam Gershenson90d05e02017-09-28 19:29:281643 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTime", priority(), queue_time);
1644 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTimeAfterChange", priority(),
1645 queue_time_after_change);
[email protected]51b9a6b2012-06-25 21:50:291646
[email protected]443714fad2013-09-19 04:52:011647 bool system_only =
1648 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1649
[email protected]1d932852012-06-19 19:40:331650 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011651 if (!system_only && had_dns_config_ &&
1652 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201653 StartDnsTask();
1654 } else {
1655 StartProcTask();
1656 }
1657 }
1658
[email protected]b3601bc22012-02-21 21:23:201659 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401660 // the limits on |dispatcher_|. But in order to keep the number of
1661 // TaskScheduler threads low, we will need to use an "inner"
1662 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201663 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351664 DCHECK(!is_dns_running());
Eric Orth9a037562018-07-03 21:24:381665 proc_task_ = std::make_unique<ProcTask>(
Misha Efimovb99e7da2018-05-30 16:59:021666 key_, resolver_->proc_params_,
Eric Orth70992982018-07-24 00:25:001667 base::BindOnce(&Job::OnProcTaskComplete, base::Unretained(this),
1668 tick_clock_->NowTicks()),
Misha Efimovb99e7da2018-05-30 16:59:021669 proc_task_runner_, net_log_, tick_clock_);
[email protected]0f292de02012-02-01 22:28:201670
[email protected]0f292de02012-02-01 22:28:201671 // Start() could be called from within Resolve(), hence it must NOT directly
1672 // call OnProcTaskComplete, for example, on synchronous failure.
1673 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391674 }
1675
[email protected]0f292de02012-02-01 22:28:201676 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371677 void OnProcTaskComplete(base::TimeTicks start_time,
1678 int net_error,
1679 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201680 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391681
[email protected]1d932852012-06-19 19:40:331682 if (dns_task_error_ != OK) {
Misha Efimovb99e7da2018-05-30 16:59:021683 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]1def74c2012-03-22 20:07:001684 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211685 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331686 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1687 ResemblesNetBIOSName(key_.hostname)) {
1688 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1689 } else {
1690 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1691 }
Ilya Sherman0eb39802017-12-08 20:58:181692 base::UmaHistogramSparse("Net.DNS.DnsTask.Errors",
1693 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221694 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001695 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211696 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001697 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1698 }
1699 }
1700
eroman1efc237c2016-12-14 00:00:451701 if (ContainsIcannNameCollisionIp(addr_list))
1702 net_error = ERR_ICANN_NAME_COLLISION;
1703
[email protected]1339a2a22012-10-17 08:39:431704 base::TimeDelta ttl =
1705 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201706 if (net_error == OK)
1707 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391708
Rob Percival94f21ad2017-11-14 10:20:241709 // Source unknown because the system resolver could have gotten it from a
1710 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171711 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241712 CompleteRequests(
1713 MakeCacheEntry(net_error, addr_list, HostCache::Entry::SOURCE_UNKNOWN),
1714 ttl);
[email protected]b3601bc22012-02-21 21:23:201715 }
1716
1717 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271718 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501719 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
Misha Efimovb99e7da2018-05-30 16:59:021720 net_log_, tick_clock_));
[email protected]b3601bc22012-02-21 21:23:201721
[email protected]daae1322013-09-05 18:26:501722 dns_task_->StartFirstTransaction();
1723 // Schedule a second transaction, if needed.
1724 if (dns_task_->needs_two_transactions())
1725 Schedule(true);
1726 }
1727
1728 void StartSecondDnsTransaction() {
1729 DCHECK(dns_task_->needs_two_transactions());
1730 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221731 }
1732
1733 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1734 // deleted before this callback. In this case dns_task is deleted as well,
1735 // so we use it as indicator whether Job is still valid.
1736 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1737 base::TimeDelta duration,
1738 int net_error) {
Miriam Gershenson61604662017-09-28 23:51:111739 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221740
wezb9820d42016-06-22 23:41:041741 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221742 return;
1743
Miriam Gershenson19faef812018-02-07 23:56:441744 if (duration < base::TimeDelta::FromMilliseconds(10)) {
1745 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Fast",
1746 std::abs(net_error));
1747 } else {
1748 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Slow",
1749 std::abs(net_error));
1750 }
[email protected]16c2bd72013-06-28 01:19:221751 dns_task_error_ = net_error;
1752
1753 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1754 // http://crbug.com/117655
1755
1756 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1757 // ProcTask in that case is a waste of time.
1758 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501759 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221760 StartProcTask();
1761 } else {
1762 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Brad Lassey2e8f185d2018-05-21 22:25:211763 // If the ttl is max, we didn't get one from the record, so set it to 0
1764 base::TimeDelta ttl =
1765 dns_task->ttl() < base::TimeDelta::FromSeconds(
1766 std::numeric_limits<uint32_t>::max())
1767 ? dns_task->ttl()
1768 : base::TimeDelta::FromSeconds(0);
1769 CompleteRequests(
1770 HostCache::Entry(net_error, AddressList(),
1771 HostCache::Entry::Source::SOURCE_UNKNOWN, ttl),
1772 ttl);
[email protected]b3601bc22012-02-21 21:23:201773 }
1774 }
1775
[email protected]daae1322013-09-05 18:26:501776 // HostResolverImpl::DnsTask::Delegate implementation:
1777
dchengb03027d2014-10-21 12:00:201778 void OnDnsTaskComplete(base::TimeTicks start_time,
1779 int net_error,
1780 const AddressList& addr_list,
1781 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201782 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201783
Misha Efimovb99e7da2018-05-30 16:59:021784 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]b3601bc22012-02-21 21:23:201785 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221786 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201787 return;
1788 }
Miriam Gershenson61604662017-09-28 23:51:111789
1790 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201791
[email protected]1def74c2012-03-22 20:07:001792 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431793 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461794
[email protected]1ffdda82012-12-12 23:04:221795 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021796
[email protected]895123222012-10-25 15:21:171797 base::TimeDelta bounded_ttl =
1798 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1799
eroman0cd87b62016-12-14 19:13:451800 if (ContainsIcannNameCollisionIp(addr_list)) {
1801 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1802 } else {
Rob Percival94f21ad2017-11-14 10:20:241803 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list,
1804 HostCache::Entry::SOURCE_DNS, ttl),
eroman0cd87b62016-12-14 19:13:451805 bounded_ttl);
1806 }
[email protected]b3601bc22012-02-21 21:23:201807 }
1808
dchengb03027d2014-10-21 12:00:201809 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501810 DCHECK(dns_task_->needs_two_transactions());
1811 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1812 // No longer need to occupy two dispatcher slots.
1813 ReduceToOneJobSlot();
1814
1815 // We already have a job slot at the dispatcher, so if the second
1816 // transaction hasn't started, reuse it now instead of waiting in the queue
1817 // for the second slot.
1818 if (dns_task_->needs_another_transaction())
1819 dns_task_->StartSecondTransaction();
1820 }
1821
Brad Lassey786929ad2018-02-21 20:54:271822 URLRequestContext* url_request_context() override {
1823 return resolver_->url_request_context_;
1824 }
1825
Miriam Gershenson61604662017-09-28 23:51:111826 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581827 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1828 // deprecated values.
1829 enum Category {
1830 RESOLVE_SUCCESS = 0,
1831 RESOLVE_FAIL = 1,
1832 RESOLVE_SPECULATIVE_SUCCESS = 2,
1833 RESOLVE_SPECULATIVE_FAIL = 3,
1834 RESOLVE_ABORT = 4,
1835 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111836 RESOLVE_MAX, // Bounding value.
1837 };
1838 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1839
Misha Efimovb99e7da2018-05-30 16:59:021840 base::TimeDelta duration = tick_clock_->NowTicks() - start_time_;
Miriam Gershenson61604662017-09-28 23:51:111841 if (error == OK) {
1842 if (had_non_speculative_request_) {
1843 category = RESOLVE_SUCCESS;
1844 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
1845 switch (key_.address_family) {
1846 case ADDRESS_FAMILY_IPV4:
1847 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1848 duration);
1849 break;
1850 case ADDRESS_FAMILY_IPV6:
1851 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1852 duration);
1853 break;
1854 case ADDRESS_FAMILY_UNSPECIFIED:
1855 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1856 duration);
1857 break;
1858 }
1859 } else {
1860 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111861 }
Miriam Gershensonc282ab42017-11-20 23:19:581862 } else if (error == ERR_NETWORK_CHANGED ||
1863 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1864 category = had_non_speculative_request_ ? RESOLVE_ABORT
1865 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111866 } else {
1867 if (had_non_speculative_request_) {
1868 category = RESOLVE_FAIL;
1869 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
1870 switch (key_.address_family) {
1871 case ADDRESS_FAMILY_IPV4:
Miriam Gershensonc282ab42017-11-20 23:19:581872 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111873 duration);
1874 break;
1875 case ADDRESS_FAMILY_IPV6:
Miriam Gershensonc282ab42017-11-20 23:19:581876 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111877 duration);
1878 break;
1879 case ADDRESS_FAMILY_UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581880 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111881 duration);
1882 break;
1883 }
1884 } else {
1885 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111886 }
1887 }
1888 DCHECK_LT(static_cast<int>(category),
1889 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1890 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061891
1892 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1893 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181894 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061895 else
Ilya Sherman0eb39802017-12-08 20:58:181896 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061897 }
Miriam Gershenson61604662017-09-28 23:51:111898 }
1899
[email protected]16ee26d2012-03-08 03:34:351900 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171901 void CompleteRequests(const HostCache::Entry& entry,
1902 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211903 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201904
[email protected]16ee26d2012-03-08 03:34:351905 // This job must be removed from resolver's |jobs_| now to make room for a
1906 // new job with the same key in case one of the OnComplete callbacks decides
Eric Orth18544ae2018-06-11 22:57:161907 // to spawn one. Consequently, if the job was owned by |jobs_|, the job
1908 // deletes itself when CompleteRequests is done.
1909 std::unique_ptr<Job> self_deleter = resolver_->RemoveJob(this);
[email protected]16ee26d2012-03-08 03:34:351910
[email protected]16ee26d2012-03-08 03:34:351911 if (is_running()) {
Eric Orth9a037562018-07-03 21:24:381912 proc_task_ = nullptr;
[email protected]daae1322013-09-05 18:26:501913 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351914
1915 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001916 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351917 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001918 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351919 handle_.Reset();
1920 }
1921
1922 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001923 net_log_.AddEvent(NetLogEventType::CANCELLED);
1924 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351925 OK);
1926 return;
1927 }
[email protected]b3601bc22012-02-21 21:23:201928
mikecirone8b85c432016-09-08 19:11:001929 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221930 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391931
[email protected]78eac2a2012-03-14 19:09:271932 DCHECK(!requests_.empty());
1933
eroman1efc237c2016-12-14 00:00:451934 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191935 // Record this histogram here, when we know the system has a valid DNS
1936 // configuration.
[email protected]539df6c2012-06-19 21:21:291937 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1938 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191939 }
[email protected]16ee26d2012-03-08 03:34:351940
juliatuttle317860e2016-05-12 14:47:221941 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1942 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Miriam Gershensonc282ab42017-11-20 23:19:581943 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431944 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581945
1946 RecordJobHistograms(entry.error());
[email protected]16ee26d2012-03-08 03:34:351947
maksim.sisov31452af2016-07-27 06:38:101948 // Complete all of the requests that were attached to the job and
1949 // detach them.
1950 while (!requests_.empty()) {
David Benjamina5677192018-04-23 23:25:421951 RequestImpl* req = requests_.head()->value();
1952 req->RemoveFromList();
[email protected]0f292de02012-02-01 22:28:201953 DCHECK_EQ(this, req->job());
1954 // Update the net log and notify registered observers.
Eric Orth70992982018-07-24 00:25:001955 LogFinishRequest(req->source_net_log(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291956 if (did_complete) {
1957 // Record effective total time from creation to completion.
Eric Orth70992982018-07-24 00:25:001958 RecordTotalTime(req->is_speculative(), false /* from_cache */,
Misha Efimovb99e7da2018-05-30 16:59:021959 tick_clock_->NowTicks() - req->request_time());
[email protected]51b9a6b2012-06-25 21:50:291960 }
Eric Orth70992982018-07-24 00:25:001961 if (entry.error() == OK) {
1962 req->set_address_results(EnsurePortOnAddressList(
1963 entry.addresses(), req->request_host().port()));
1964 }
1965 req->OnJobCompleted(this, entry.error());
[email protected]0f292de02012-02-01 22:28:201966
1967 // Check if the resolver was destroyed as a result of running the
1968 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211969 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201970 return;
1971 }
1972 }
1973
[email protected]1339a2a22012-10-17 08:39:431974 // Convenience wrapper for CompleteRequests in case of failure.
1975 void CompleteRequestsWithError(int net_error) {
Rob Percival94f21ad2017-11-14 10:20:241976 CompleteRequests(HostCache::Entry(net_error, AddressList(),
1977 HostCache::Entry::SOURCE_UNKNOWN),
[email protected]895123222012-10-25 15:21:171978 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431979 }
1980
Brad Lassey786929ad2018-02-21 20:54:271981 RequestPriority priority() const override {
[email protected]b4481b222012-03-16 17:13:111982 return priority_tracker_.highest_priority();
1983 }
1984
1985 // Number of non-canceled requests in |requests_|.
1986 size_t num_active_requests() const {
1987 return priority_tracker_.total_count();
1988 }
1989
wezb9820d42016-06-22 23:41:041990 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111991
wezb9820d42016-06-22 23:41:041992 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111993
[email protected]0f292de02012-02-01 22:28:201994 base::WeakPtr<HostResolverImpl> resolver_;
1995
1996 Key key_;
1997
1998 // Tracks the highest priority across |requests_|.
1999 PriorityTracker priority_tracker_;
2000
Miriam Gershensone42adb22017-10-16 16:19:382001 // Task runner used for HostResolverProc.
2002 scoped_refptr<base::TaskRunner> proc_task_runner_;
2003
[email protected]0f292de02012-02-01 22:28:202004 bool had_non_speculative_request_;
2005
[email protected]51b9a6b2012-06-25 21:50:292006 // Distinguishes measurements taken while DnsClient was fully configured.
2007 bool had_dns_config_;
2008
[email protected]daae1322013-09-05 18:26:502009 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
2010 unsigned num_occupied_job_slots_;
2011
[email protected]1d932852012-06-19 19:40:332012 // Result of DnsTask.
2013 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:002014
Misha Efimovb99e7da2018-05-30 16:59:022015 const base::TickClock* tick_clock_;
[email protected]51b9a6b2012-06-25 21:50:292016 const base::TimeTicks creation_time_;
2017 base::TimeTicks priority_change_time_;
Miriam Gershenson61604662017-09-28 23:51:112018 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:292019
tfarina428341112016-09-22 13:38:202020 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:202021
[email protected]b3601bc22012-02-21 21:23:202022 // Resolves the host using a HostResolverProc.
Eric Orth9a037562018-07-03 21:24:382023 std::unique_ptr<ProcTask> proc_task_;
[email protected]0f292de02012-02-01 22:28:202024
[email protected]b3601bc22012-02-21 21:23:202025 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:402026 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:202027
[email protected]0f292de02012-02-01 22:28:202028 // All Requests waiting for the result of this Job. Some can be canceled.
David Benjamina5677192018-04-23 23:25:422029 base::LinkedList<RequestImpl> requests_;
[email protected]0f292de02012-02-01 22:28:202030
[email protected]16ee26d2012-03-08 03:34:352031 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:202032 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:392033};
2034
2035//-----------------------------------------------------------------------------
2036
[email protected]0f292de02012-02-01 22:28:202037HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:432038 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:202039 size_t max_retry_attempts)
2040 : resolver_proc(resolver_proc),
2041 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:442042 unresponsive_delay(
2043 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:202044 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:002045 // Maximum of 4 retry attempts for host resolution.
2046 static const size_t kDefaultMaxRetryAttempts = 4u;
2047 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
2048 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:202049}
2050
vmpstracd23b72016-02-26 21:08:552051HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
2052 default;
2053
Chris Watkins68b15032017-12-01 03:07:132054HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:202055
Francois Doraya2d01ba2017-09-25 19:17:402056HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:232057 : max_queued_jobs_(0),
2058 proc_params_(NULL, options.max_retry_attempts),
2059 net_log_(net_log),
2060 received_dns_config_(false),
2061 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:032062 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:232063 use_local_ipv6_(false),
2064 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:232065 additional_resolver_flags_(0),
2066 fallback_to_proctask_(true),
Brad Lassey73e67ee2018-05-31 00:11:592067 url_request_context_(nullptr),
Misha Efimovb99e7da2018-05-30 16:59:022068 tick_clock_(base::DefaultTickClock::GetInstance()),
mmenke91c17162016-06-02 16:03:232069 weak_ptr_factory_(this),
2070 probe_weak_ptr_factory_(this) {
2071 if (options.enable_caching)
2072 cache_ = HostCache::CreateDefaultCache();
2073
2074 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2075 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2076 max_queued_jobs_ = job_limits.total_jobs * 100u;
2077
2078 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2079
Miriam Gershensone42adb22017-10-16 16:19:382080 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
Maks Orlovich5393c8682018-02-26 16:17:502081 {base::MayBlock(), priority_mode.Get(),
2082 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
Miriam Gershensone42adb22017-10-16 16:19:382083
mmenke91c17162016-06-02 16:03:232084#if defined(OS_WIN)
2085 EnsureWinsockInit();
2086#endif
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472087#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2088 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232089 RunLoopbackProbeJob();
2090#endif
2091 NetworkChangeNotifier::AddIPAddressObserver(this);
2092 NetworkChangeNotifier::AddConnectionTypeObserver(this);
2093 NetworkChangeNotifier::AddDNSObserver(this);
2094#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Fabrice de Gans-Riberi65421f62018-05-22 23:16:182095 !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232096 EnsureDnsReloaderInit();
2097#endif
2098
2099 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
2100
2101 {
2102 DnsConfig dns_config;
2103 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2104 received_dns_config_ = dns_config.IsValid();
2105 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2106 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2107 }
2108
2109 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2110}
2111
Eric Orth70992982018-07-24 00:25:002112HostResolverImpl::~HostResolverImpl() {
2113 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2114 // Prevent the dispatcher from starting new jobs.
2115 dispatcher_->SetLimitsToZero();
2116 // It's now safe for Jobs to call KillDnsTask on destruction, because
2117 // OnJobComplete will not start any new jobs.
2118 jobs_.clear();
2119
2120 NetworkChangeNotifier::RemoveIPAddressObserver(this);
2121 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
2122 NetworkChangeNotifier::RemoveDNSObserver(this);
mmenke91c17162016-06-02 16:03:232123}
2124
Eric Orth70992982018-07-24 00:25:002125void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
2126 // DnsClient and config must be updated before aborting DnsTasks, since doing
2127 // so may start new jobs.
2128 dns_client_ = std::move(dns_client);
2129 if (dns_client_ && !dns_client_->GetConfig() &&
2130 num_dns_failures_ < kMaximumDnsFailures) {
2131 DnsConfig dns_config;
2132 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2133 dns_config.dns_over_https_servers = dns_over_https_servers_;
2134 dns_client_->SetConfig(dns_config);
2135 num_dns_failures_ = 0;
2136 if (dns_client_->GetConfig())
2137 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2138 }
2139
2140 AbortDnsTasks();
Findite5a94e02018-07-13 21:56:212141}
2142
Eric Orth70992982018-07-24 00:25:002143std::unique_ptr<HostResolver::ResolveHostRequest>
2144HostResolverImpl::CreateRequest(const HostPortPair& host,
2145 const NetLogWithSource& net_log) {
2146 return std::make_unique<RequestImpl>(
2147 net_log, host, false /* is_speculative */,
2148 RequestPriority::DEFAULT_PRIORITY, weak_ptr_factory_.GetWeakPtr());
2149}
2150
2151int HostResolverImpl::Resolve(const RequestInfo& info,
2152 RequestPriority priority,
2153 AddressList* addresses,
2154 CompletionOnceCallback callback,
2155 std::unique_ptr<Request>* out_req,
2156 const NetLogWithSource& source_net_log) {
2157 DCHECK(addresses);
2158 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2159 DCHECK(callback);
2160 DCHECK(out_req);
2161
2162 auto request = std::make_unique<RequestImpl>(
2163 source_net_log, info.host_port_pair(), info.address_family(),
2164 info.host_resolver_flags(), info.allow_cached_response(),
2165 info.is_speculative(), priority, weak_ptr_factory_.GetWeakPtr());
2166 auto wrapped_request =
2167 std::make_unique<LegacyRequestImpl>(std::move(request));
2168
2169 int rv = wrapped_request->Start();
2170
2171 if (rv == OK) {
2172 DCHECK(wrapped_request->inner_request().GetAddressResults());
2173 *addresses = wrapped_request->inner_request().GetAddressResults().value();
2174 } else if (rv == ERR_IO_PENDING) {
2175 wrapped_request->AssignCallback(std::move(callback), addresses);
2176 *out_req = std::move(wrapped_request);
Eric Orthfac527992018-07-13 21:11:162177 }
2178
Eric Orth70992982018-07-24 00:25:002179 return rv;
[email protected]95a214c2011-08-04 21:50:402180}
2181
2182int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2183 AddressList* addresses,
tfarina428341112016-09-22 13:38:202184 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432185 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402186 DCHECK(addresses);
2187
[email protected]95a214c2011-08-04 21:50:402188 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022189 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402190
Matt Menke23b4bbf82017-07-20 19:11:292191 Key key;
Eric Orth70992982018-07-24 00:25:002192 int rv = ResolveLocally(
2193 info.host_port_pair(), info.address_family(), info.host_resolver_flags(),
2194 info.allow_cached_response(), false /* allow_stale */,
2195 nullptr /* stale_info */, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402196
Eric Orth70992982018-07-24 00:25:002197 LogFinishRequest(source_net_log, rv);
2198 return rv;
2199}
2200
2201int HostResolverImpl::ResolveStaleFromCache(
2202 const RequestInfo& info,
2203 AddressList* addresses,
2204 HostCache::EntryStaleness* stale_info,
2205 const NetLogWithSource& source_net_log) {
2206 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2207 DCHECK(addresses);
2208 DCHECK(stale_info);
2209
2210 // Update the net log and notify registered observers.
2211 LogStartRequest(source_net_log, info);
2212
2213 Key key;
2214 int rv = ResolveLocally(info.host_port_pair(), info.address_family(),
2215 info.host_resolver_flags(),
2216 info.allow_cached_response(), true /* allow_stale */,
2217 stale_info, source_net_log, addresses, &key);
2218 LogFinishRequest(source_net_log, rv);
[email protected]95a214c2011-08-04 21:50:402219 return rv;
2220}
2221
[email protected]a8883e452012-11-17 05:58:062222void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432223 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062224#if defined(ENABLE_BUILT_IN_DNS)
2225 if (enabled && !dns_client_) {
2226 SetDnsClient(DnsClient::CreateClient(net_log_));
2227 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402228 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062229 }
2230#endif
2231}
2232
[email protected]489d1a82011-10-12 03:09:112233HostCache* HostResolverImpl::GetHostCache() {
2234 return cache_.get();
2235}
[email protected]95a214c2011-08-04 21:50:402236
Rob Percivalbc658a22017-12-13 08:24:422237bool HostResolverImpl::HasCached(base::StringPiece hostname,
2238 HostCache::Entry::Source* source_out,
2239 HostCache::EntryStaleness* stale_out) const {
2240 if (!cache_)
2241 return false;
2242
2243 return cache_->HasEntry(hostname, source_out, stale_out);
2244}
2245
danakj22f90e72016-04-16 01:55:402246std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242247 // Check if async DNS is disabled.
2248 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082249 return nullptr;
[email protected]17e92032012-03-29 00:56:242250
2251 // Check if async DNS is enabled, but we currently have no configuration
2252 // for it.
2253 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042254 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192255 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242256
2257 return dns_config->ToValue();
2258}
2259
Miriam Gershenson2839ef112017-08-30 03:25:372260size_t HostResolverImpl::LastRestoredCacheSize() const {
2261 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2262
2263 return cache_ ? cache_->last_restore_size() : 0;
2264}
2265
2266size_t HostResolverImpl::CacheSize() const {
2267 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2268
2269 return cache_ ? cache_->size() : 0;
2270}
2271
mgershaf9a9232017-04-13 20:19:032272void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432273 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032274 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2275}
2276
2277bool HostResolverImpl::GetNoIPv6OnWifi() {
2278 return assume_ipv6_failure_on_wifi_;
2279}
2280
Brad Lassey786929ad2018-02-21 20:54:272281void HostResolverImpl::SetRequestContext(URLRequestContext* context) {
2282 if (context != url_request_context_) {
2283 url_request_context_ = context;
2284 }
2285}
2286
Eric Orth70992982018-07-24 00:25:002287void HostResolverImpl::AddDnsOverHttpsServer(std::string spec, bool use_post) {
2288 GURL url(spec);
2289 if (!url.SchemeIs("https"))
2290 return;
2291
2292 dns_over_https_servers_.emplace_back(url, use_post);
2293
2294 if (dns_client_.get() && dns_client_->GetConfig())
2295 UpdateDNSConfig(true);
Misha Efimovb99e7da2018-05-30 16:59:022296}
2297
Brad Lassey786929ad2018-02-21 20:54:272298void HostResolverImpl::ClearDnsOverHttpsServers() {
2299 if (dns_over_https_servers_.size() == 0)
2300 return;
2301
2302 dns_over_https_servers_.clear();
2303
2304 if (dns_client_.get() && dns_client_->GetConfig())
2305 UpdateDNSConfig(true);
2306}
2307
Matt Menkeb67c0a8e2018-06-14 22:41:042308const std::vector<DnsConfig::DnsOverHttpsServerConfig>*
2309HostResolverImpl::GetDnsOverHttpsServersForTesting() const {
2310 if (dns_over_https_servers_.empty())
2311 return nullptr;
2312 return &dns_over_https_servers_;
2313}
2314
Eric Orth70992982018-07-24 00:25:002315void HostResolverImpl::SetTickClockForTesting(
2316 const base::TickClock* tick_clock) {
2317 tick_clock_ = tick_clock;
2318 cache_->set_tick_clock_for_testing(tick_clock);
2319}
2320
2321void HostResolverImpl::SetMaxQueuedJobsForTesting(size_t value) {
2322 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
2323 DCHECK_GE(value, 0u);
2324 max_queued_jobs_ = value;
2325}
2326
2327void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2328 if (result) {
2329 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2330 } else {
2331 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2332 }
2333}
2334
2335void HostResolverImpl::SetTaskRunnerForTesting(
2336 scoped_refptr<base::TaskRunner> task_runner) {
2337 proc_task_runner_ = std::move(task_runner);
2338}
2339
2340int HostResolverImpl::Resolve(RequestImpl* request) {
2341 // Request should not yet have a scheduled Job.
2342 DCHECK(!request->job());
2343 // Request may only be resolved once.
2344 DCHECK(!request->complete());
2345
2346 request->set_request_time(tick_clock_->NowTicks());
2347
2348 LogStartRequest(request->source_net_log(), request->request_host());
2349
2350 AddressList addresses;
2351 Key key;
2352 int rv = ResolveLocally(request->request_host(), request->address_family(),
2353 request->host_resolver_flags(),
2354 request->allow_cached_response(),
2355 false /* allow_stale */, nullptr /* stale_info */,
2356 request->source_net_log(), &addresses, &key);
2357 if (rv == OK) {
2358 request->set_address_results(
2359 EnsurePortOnAddressList(addresses, request->request_host().port()));
2360 }
2361 if (rv != ERR_DNS_CACHE_MISS) {
2362 LogFinishRequest(request->source_net_log(), rv);
2363 RecordTotalTime(request->is_speculative(), true /* from_cache */,
2364 base::TimeDelta());
2365 return rv;
2366 }
2367
2368 rv = CreateAndStartJob(key, request);
2369 // At this point, expect only async or errors.
2370 DCHECK_NE(OK, rv);
2371
2372 return rv;
2373}
2374
2375int HostResolverImpl::ResolveLocally(const HostPortPair& host,
2376 AddressFamily requested_address_family,
2377 HostResolverFlags flags,
2378 bool allow_cache,
2379 bool allow_stale,
2380 HostCache::EntryStaleness* stale_info,
2381 const NetLogWithSource& source_net_log,
2382 AddressList* addresses,
2383 Key* key) {
2384 IPAddress ip_address;
2385 IPAddress* ip_address_ptr = nullptr;
2386 if (ip_address.AssignFromIPLiteral(host.host())) {
2387 ip_address_ptr = &ip_address;
2388 } else {
2389 // Check that the caller supplied a valid hostname to resolve.
2390 if (!IsValidDNSDomain(host.host()))
2391 return ERR_NAME_NOT_RESOLVED;
2392 }
2393
2394 // Build a key that identifies the request in the cache and in the
2395 // outstanding jobs map.
2396 *key = GetEffectiveKeyForRequest(host.host(), requested_address_family, flags,
2397 ip_address_ptr, source_net_log);
2398
2399 DCHECK(allow_stale == !!stale_info);
2400 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2401 // On Windows it gives the default interface's address, whereas on Linux it
2402 // gives an error. We will make it fail on all platforms for consistency.
2403 if (host.host().empty() || host.host().size() > kMaxHostLength) {
2404 MakeNotStale(stale_info);
2405 return ERR_NAME_NOT_RESOLVED;
2406 }
2407
2408 int net_error = ERR_UNEXPECTED;
2409 if (ResolveAsIP(*key, host.port(), ip_address_ptr, &net_error, addresses)) {
2410 MakeNotStale(stale_info);
2411 return net_error;
2412 }
2413
2414 // Special-case localhost names, as per the recommendations in
2415 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2416 if (ServeLocalhost(*key, host.port(), addresses)) {
2417 MakeNotStale(stale_info);
2418 return OK;
2419 }
2420
2421 if (allow_cache && ServeFromCache(*key, host.port(), &net_error, addresses,
2422 allow_stale, stale_info)) {
2423 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2424 addresses->CreateNetLogCallback());
2425 // |ServeFromCache()| will set |*stale_info| as needed.
2426 return net_error;
2427 }
2428
2429 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2430 // http://crbug.com/117655
2431 if (ServeFromHosts(*key, host.port(), addresses)) {
2432 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2433 addresses->CreateNetLogCallback());
2434 MakeNotStale(stale_info);
2435 return OK;
2436 }
2437
2438 return ERR_DNS_CACHE_MISS;
2439}
2440
2441int HostResolverImpl::CreateAndStartJob(const Key& key, RequestImpl* request) {
2442 auto jobit = jobs_.find(key);
2443 Job* job;
2444 if (jobit == jobs_.end()) {
2445 auto new_job = std::make_unique<Job>(
2446 weak_ptr_factory_.GetWeakPtr(), key, request->priority(),
2447 proc_task_runner_, request->source_net_log(), tick_clock_);
2448 job = new_job.get();
2449 new_job->Schedule(false);
2450
2451 // Check for queue overflow.
2452 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
2453 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
2454 DCHECK(evicted);
2455 evicted->OnEvicted();
2456 if (evicted == new_job.get()) {
2457 LogFinishRequest(request->source_net_log(),
2458 ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
2459 return ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
2460 }
2461 }
2462 jobs_[key] = std::move(new_job);
2463 } else {
2464 job = jobit->second.get();
2465 }
2466
2467 // Can't complete synchronously. Attach request and job to each other.
2468 job->AddRequest(request);
2469 return ERR_IO_PENDING;
2470}
2471
[email protected]95a214c2011-08-04 21:50:402472bool HostResolverImpl::ResolveAsIP(const Key& key,
Eric Orth70992982018-07-24 00:25:002473 uint16_t host_port,
martijna23c8962016-03-04 18:18:512474 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402475 int* net_error,
2476 AddressList* addresses) {
2477 DCHECK(addresses);
2478 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512479 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402480 return false;
2481
[email protected]95a214c2011-08-04 21:50:402482 *net_error = OK;
martijna23c8962016-03-04 18:18:512483 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252484 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2485 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482486 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402487 *net_error = ERR_NAME_NOT_RESOLVED;
2488 } else {
Eric Orth70992982018-07-24 00:25:002489 *addresses = AddressList::CreateFromIPAddress(*ip_address, host_port);
[email protected]7054e78f2012-05-07 21:44:562490 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2491 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402492 }
2493 return true;
2494}
2495
2496bool HostResolverImpl::ServeFromCache(const Key& key,
Eric Orth70992982018-07-24 00:25:002497 uint16_t host_port,
[email protected]95a214c2011-08-04 21:50:402498 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332499 AddressList* addresses,
2500 bool allow_stale,
2501 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402502 DCHECK(addresses);
2503 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332504 DCHECK(allow_stale == !!stale_info);
Eric Orth70992982018-07-24 00:25:002505 if (!cache_.get())
[email protected]95a214c2011-08-04 21:50:402506 return false;
2507
juliatuttle9fb7aeb2016-06-06 20:16:332508 const HostCache::Entry* cache_entry;
2509 if (allow_stale)
Misha Efimovb99e7da2018-05-30 16:59:022510 cache_entry = cache_->LookupStale(key, tick_clock_->NowTicks(), stale_info);
juliatuttle9fb7aeb2016-06-06 20:16:332511 else
Misha Efimovb99e7da2018-05-30 16:59:022512 cache_entry = cache_->Lookup(key, tick_clock_->NowTicks());
[email protected]95a214c2011-08-04 21:50:402513 if (!cache_entry)
2514 return false;
2515
juliatuttle317860e2016-05-12 14:47:222516 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562517 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432518 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222519 RecordTTL(cache_entry->ttl());
Eric Orth70992982018-07-24 00:25:002520 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), host_port);
[email protected]7054e78f2012-05-07 21:44:562521 }
[email protected]95a214c2011-08-04 21:50:402522 return true;
2523}
2524
[email protected]78eac2a2012-03-14 19:09:272525bool HostResolverImpl::ServeFromHosts(const Key& key,
Eric Orth70992982018-07-24 00:25:002526 uint16_t host_port,
[email protected]78eac2a2012-03-14 19:09:272527 AddressList* addresses) {
2528 DCHECK(addresses);
2529 if (!HaveDnsConfig())
2530 return false;
[email protected]05a79d42013-03-28 07:30:092531 addresses->clear();
2532
[email protected]cb507622012-03-23 16:17:062533 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222534 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062535
[email protected]05a79d42013-03-28 07:30:092536 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2537
[email protected]78eac2a2012-03-14 19:09:272538 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2539 // (glibc and c-ares) return the first matching line. We have more
2540 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092541 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2542 // necessary.
2543 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2544 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2545 DnsHosts::const_iterator it = hosts.find(
2546 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2547 if (it != hosts.end())
Eric Orth70992982018-07-24 00:25:002548 addresses->push_back(IPEndPoint(it->second, host_port));
[email protected]78eac2a2012-03-14 19:09:272549 }
2550
[email protected]05a79d42013-03-28 07:30:092551 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2552 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2553 DnsHosts::const_iterator it = hosts.find(
2554 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2555 if (it != hosts.end())
Eric Orth70992982018-07-24 00:25:002556 addresses->push_back(IPEndPoint(it->second, host_port));
[email protected]05a79d42013-03-28 07:30:092557 }
2558
[email protected]ec666ab22013-04-17 20:05:592559 // If got only loopback addresses and the family was restricted, resolve
2560 // again, without restrictions. See SystemHostResolverCall for rationale.
2561 if ((key.host_resolver_flags &
2562 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2563 IsAllIPv4Loopback(*addresses)) {
2564 Key new_key(key);
2565 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2566 new_key.host_resolver_flags &=
2567 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Eric Orth70992982018-07-24 00:25:002568 return ServeFromHosts(new_key, host_port, addresses);
[email protected]ec666ab22013-04-17 20:05:592569 }
[email protected]05a79d42013-03-28 07:30:092570 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272571}
2572
estarkd1bc206e2015-06-20 00:44:392573bool HostResolverImpl::ServeLocalhost(const Key& key,
Eric Orth70992982018-07-24 00:25:002574 uint16_t host_port,
estarkd1bc206e2015-06-20 00:44:392575 AddressList* addresses) {
2576 AddressList resolved_addresses;
Eric Orth70992982018-07-24 00:25:002577 if (!ResolveLocalHostname(key.hostname, host_port, &resolved_addresses))
estarkd1bc206e2015-06-20 00:44:392578 return false;
2579
2580 addresses->clear();
2581
2582 for (const auto& address : resolved_addresses) {
2583 // Include the address if:
2584 // - caller didn't specify an address family, or
2585 // - caller specifically asked for the address family of this address, or
2586 // - this is an IPv6 address and caller specifically asked for IPv4 due
2587 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2588 // rationale).
2589 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2590 key.address_family == address.GetFamily() ||
2591 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2592 key.address_family == ADDRESS_FAMILY_IPV4 &&
2593 (key.host_resolver_flags &
2594 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2595 addresses->push_back(address);
2596 }
2597 }
2598
2599 return true;
2600}
2601
[email protected]16ee26d2012-03-08 03:34:352602void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432603 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352604 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052605 // Don't cache an error unless it has a positive TTL.
2606 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
Misha Efimovb99e7da2018-05-30 16:59:022607 cache_->Set(key, entry, tick_clock_->NowTicks(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032608}
2609
Eric Orth18544ae2018-06-11 22:57:162610std::unique_ptr<HostResolverImpl::Job> HostResolverImpl::RemoveJob(Job* job) {
[email protected]0f292de02012-02-01 22:28:202611 DCHECK(job);
Eric Orth18544ae2018-06-11 22:57:162612 std::unique_ptr<Job> retval;
avi9e72eb482016-12-09 21:10:542613 auto it = jobs_.find(job->key());
2614 if (it != jobs_.end() && it->second.get() == job) {
Eric Orth18544ae2018-06-11 22:57:162615 it->second.swap(retval);
[email protected]16ee26d2012-03-08 03:34:352616 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542617 }
Eric Orth18544ae2018-06-11 22:57:162618 return retval;
[email protected]b59ff372009-07-15 22:04:322619}
2620
[email protected]137af622010-02-05 02:14:352621HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
Eric Orth70992982018-07-24 00:25:002622 const std::string& hostname,
2623 AddressFamily requested_address_family,
2624 HostResolverFlags flags,
martijna23c8962016-03-04 18:18:512625 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202626 const NetLogWithSource& net_log) {
Eric Orth70992982018-07-24 00:25:002627 HostResolverFlags effective_flags = flags | additional_resolver_flags_;
2628 AddressFamily effective_address_family = requested_address_family;
[email protected]9db6f702013-04-10 18:10:512629
mgersh3eba057d2017-02-28 18:50:562630 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2631 // When resolving IPv4 literals, there's no need to probe for IPv6.
2632 // When resolving IPv6 literals, there's no benefit to artificially
2633 // limiting our resolution based on a probe. Prior logic ensures
2634 // that this query is UNSPECIFIED (see effective_address_family
2635 // check above) so the code requesting the resolution should be amenable
2636 // to receiving a IPv6 resolution.
2637 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2638 effective_address_family = ADDRESS_FAMILY_IPV4;
2639 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512640 }
2641
Eric Orth70992982018-07-24 00:25:002642 return Key(hostname, effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352643}
2644
tfarina428341112016-09-22 13:38:202645bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032646 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2647 // work on WiFi.
2648 if (assume_ipv6_failure_on_wifi_ &&
2649 NetworkChangeNotifier::GetConnectionType() ==
2650 NetworkChangeNotifier::CONNECTION_WIFI) {
2651 return false;
2652 }
2653
eroman1a17ef32016-12-14 01:06:092654 // Cache the result for kIPv6ProbePeriodMs (measured from after
2655 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372656 bool cached = true;
Misha Efimovb99e7da2018-05-30 16:59:022657 if ((tick_clock_->NowTicks() - last_ipv6_probe_time_).InMilliseconds() >
eroman1a17ef32016-12-14 01:06:092658 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512659 last_ipv6_probe_result_ =
2660 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
Misha Efimovb99e7da2018-05-30 16:59:022661 last_ipv6_probe_time_ = tick_clock_->NowTicks();
sergeyub8cdc212015-05-14 18:50:372662 cached = false;
2663 }
mikecirone8b85c432016-09-08 19:11:002664 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372665 base::Bind(&NetLogIPv6AvailableCallback,
2666 last_ipv6_probe_result_, cached));
2667 return last_ipv6_probe_result_;
2668}
2669
mgershaf9a9232017-04-13 20:19:032670bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2671 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032672 std::unique_ptr<DatagramClientSocket> socket(
2673 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
Sergey Ulanovcbdfc8852018-03-16 20:13:282674 DatagramSocket::DEFAULT_BIND, net_log.net_log(), net_log.source()));
mgershaf9a9232017-04-13 20:19:032675 int rv = socket->Connect(IPEndPoint(dest, 53));
2676 if (rv != OK)
2677 return false;
2678 IPEndPoint endpoint;
2679 rv = socket->GetLocalAddress(&endpoint);
2680 if (rv != OK)
2681 return false;
2682 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2683 const IPAddress& address = endpoint.address();
2684
2685 bool is_link_local =
2686 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2687 if (is_link_local)
2688 return false;
2689
2690 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2691 if (IPAddressStartsWith(address, kTeredoPrefix))
2692 return false;
2693
2694 return true;
2695}
2696
mmenke91c17162016-06-02 16:03:232697void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402698 // Run this asynchronously as it can take 40-100ms and should not block
2699 // initialization.
2700 base::PostTaskWithTraitsAndReplyWithResult(
2701 FROM_HERE,
2702 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2703 base::BindOnce(&HaveOnlyLoopbackAddresses),
2704 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2705 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232706}
2707
[email protected]35ddc282010-09-21 23:42:062708void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202709 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2710 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402711 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542712 for (auto it = jobs_.begin(); it != jobs_.end();) {
2713 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202714 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542715 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202716 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202717 } else {
[email protected]b3601bc22012-02-21 21:23:202718 DCHECK(job->is_queued());
2719 ++it;
[email protected]0f292de02012-02-01 22:28:202720 }
[email protected]ef4c40c2010-09-01 14:42:032721 }
[email protected]b3601bc22012-02-21 21:23:202722
[email protected]daae1322013-09-05 18:26:502723 // Pause the dispatcher so it won't start any new dispatcher jobs while
2724 // aborting the old ones. This is needed so that it won't start the second
2725 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2726 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002727 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2728 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502729 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122730
[email protected]57a48d32012-03-03 00:04:552731 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072732 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552733
[email protected]16ee26d2012-03-08 03:34:352734 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212735 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552736 jobs_to_abort[i]->Abort();
[email protected]b3601bc22012-02-21 21:23:202737 }
[email protected]daae1322013-09-05 18:26:502738
2739 if (self)
[email protected]106ccd2c2014-06-17 09:21:002740 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502741}
2742
2743void HostResolverImpl::AbortDnsTasks() {
2744 // Pause the dispatcher so it won't start any new dispatcher jobs while
2745 // aborting the old ones. This is needed so that it won't start the second
2746 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002747 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2748 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502749 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2750
avi9e72eb482016-12-09 21:10:542751 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502752 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002753 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032754}
2755
[email protected]78eac2a2012-03-14 19:09:272756void HostResolverImpl::TryServingAllJobsFromHosts() {
2757 if (!HaveDnsConfig())
2758 return;
2759
2760 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2761 // http://crbug.com/117655
2762
2763 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072764 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272765
avi9e72eb482016-12-09 21:10:542766 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2767 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272768 ++it;
2769 // This could remove |job| from |jobs_|, but iterator will remain valid.
2770 job->ServeFromHosts();
2771 }
2772}
2773
[email protected]be1a48b2011-01-20 00:12:132774void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372775 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182776 // Abandon all ProbeJobs.
2777 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172778 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102779 cache_->OnNetworkChange();
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472780#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2781 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232782 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132783#endif
2784 AbortAllInProgressJobs();
2785 // |this| may be deleted inside AbortAllInProgressJobs().
2786}
2787
ttuttlecf1158bf2016-03-18 16:37:442788void HostResolverImpl::OnConnectionTypeChanged(
2789 NetworkChangeNotifier::ConnectionType type) {
2790 proc_params_.unresponsive_delay =
2791 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2792 "DnsUnresponsiveDelayMsByConnectionType",
2793 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2794 type);
2795}
2796
pauljensen101ed372015-04-17 00:11:422797void HostResolverImpl::OnInitialDNSConfigRead() {
2798 UpdateDNSConfig(false);
2799}
2800
[email protected]bb0e34542012-08-31 19:52:402801void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422802 UpdateDNSConfig(true);
2803}
2804
2805void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402806 DnsConfig dns_config;
2807 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592808
[email protected]b4481b222012-03-16 17:13:112809 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002810 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2811 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112812 }
2813
[email protected]01b3b9d2012-08-13 16:18:142814 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192815 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522816 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2817 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272818
[email protected]a8883e452012-11-17 05:58:062819 num_dns_failures_ = 0;
2820
[email protected]01b3b9d2012-08-13 16:18:142821 // We want a new DnsSession in place, before we Abort running Jobs, so that
2822 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022823 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252824 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532825 // wasn't already a DnsConfig or it's the same one.
2826 DCHECK(config_changed || !dns_client_->GetConfig() ||
2827 dns_client_->GetConfig()->Equals(dns_config));
Brad Lassey786929ad2018-02-21 20:54:272828 dns_config.dns_over_https_servers = dns_over_https_servers_;
[email protected]d7b9a2b2012-05-31 22:31:192829 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252830 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022831 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022832 }
[email protected]01b3b9d2012-08-13 16:18:142833
pauljensen101ed372015-04-17 00:11:422834 if (config_changed) {
2835 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232836 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422837 // as NSCD's cache should be dropped automatically by the OS when
2838 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172839 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232840 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142841
pauljensen101ed372015-04-17 00:11:422842 // Life check to bail once |this| is deleted.
2843 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022844
pauljensen101ed372015-04-17 00:11:422845 // Existing jobs will have been sent to the original server so they need to
2846 // be aborted.
2847 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142848
pauljensen101ed372015-04-17 00:11:422849 // |this| may be deleted inside AbortAllInProgressJobs().
2850 if (self.get())
2851 TryServingAllJobsFromHosts();
2852 }
[email protected]78eac2a2012-03-14 19:09:272853}
2854
2855bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252856 // Use DnsClient only if it's fully configured and there is no override by
2857 // ScopedDefaultHostResolverProc.
2858 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2859 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042860 return dns_client_ && dns_client_->GetConfig() &&
2861 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202862}
2863
[email protected]1ffdda82012-12-12 23:04:222864void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022865 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222866 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022867 num_dns_failures_ = 0;
2868 return;
2869 }
2870 ++num_dns_failures_;
2871 if (num_dns_failures_ < kMaximumDnsFailures)
2872 return;
[email protected]daae1322013-09-05 18:26:502873
2874 // Disable DnsClient until the next DNS change. Must be done before aborting
2875 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022876 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502877
2878 // Switch jobs with active DnsTasks over to using ProcTasks.
2879 AbortDnsTasks();
2880
[email protected]f0f602bd2012-11-15 18:01:022881 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:182882 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
2883 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022884}
2885
maksim.sisov31452af2016-07-27 06:38:102886HostResolverImpl::RequestImpl::~RequestImpl() {
2887 if (job_)
2888 job_->CancelRequest(this);
2889}
2890
2891void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2892 RequestPriority priority) {
2893 job_->ChangeRequestPriority(this, priority);
2894}
2895
[email protected]b59ff372009-07-15 22:04:322896} // namespace net