blob: a76891b1e8bf46097ab940746a530e39b9563c17 [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>
9#elif defined(OS_POSIX)
10#include <netdb.h>
11#endif
12
tfarinada9e1362017-03-14 16:49:0613#if defined(OS_POSIX)
14#include <netinet/in.h>
15#if !defined(OS_NACL)
16#include <net/if.h>
17#if !defined(OS_ANDROID)
18#include <ifaddrs.h>
19#endif // !defined(OS_ANDROID)
20#endif // !defined(OS_NACL)
21#endif // defined(OS_POSIX)
22
[email protected]68ad3ee2010-01-30 03:45:3923#include <cmath>
thestiga74ad2b2016-07-11 20:52:3624#include <memory>
[email protected]0f292de02012-02-01 22:28:2025#include <utility>
[email protected]21526002010-05-16 19:42:4626#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3927
[email protected]33152acc2011-10-20 23:37:1228#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2929#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2030#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1031#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3232#include "base/compiler_specific.h"
Brett Wilsonc6a0c822017-09-12 00:04:2933#include "base/containers/circular_deque.h"
[email protected]58580352010-10-26 04:07:5034#include "base/debug/debugger.h"
[email protected]58580352010-10-26 04:07:5035#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4636#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2337#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4538#include "base/metrics/field_trial.h"
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"
Francois Doraya2d01ba2017-09-25 19:17:4044#include "base/task_scheduler/post_task.h"
45#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3546#include "base/threading/thread_task_runner_handle.h"
[email protected]66e96c42013-06-28 15:20:3147#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5648#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4649#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2050#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3251#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5152#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5153#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4854#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1555#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4856#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1857#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4658#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2759#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2060#include "net/dns/dns_config_service.h"
61#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3562#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2063#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2064#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0365#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5366#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0767#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1968#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0069#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1970#include "net/log/net_log_parameters_callback.h"
71#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0072#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1973#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5174#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2675#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1476#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3277
78#if defined(OS_WIN)
79#include "net/base/winsock_init.h"
80#endif
81
tfarinada9e1362017-03-14 16:49:0682#if defined(OS_ANDROID)
83#include "net/android/network_library.h"
84#endif
85
[email protected]b59ff372009-07-15 22:04:3286namespace net {
87
[email protected]e95d3aca2010-01-11 22:47:4388namespace {
89
ttuttlecf1158bf2016-03-18 16:37:4490// Default delay between calls to the system resolver for the same hostname.
91// (Can be overridden by field trial.)
92const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
93
[email protected]6e78dfb2011-07-28 21:34:4794// Limit the size of hostnames that will be resolved to combat issues in
95// some platform's resolvers.
96const size_t kMaxHostLength = 4096;
97
[email protected]a2730882012-01-21 00:56:2798// Default TTL for successful resolutions with ProcTask.
99const unsigned kCacheEntryTTLSeconds = 60;
100
[email protected]b3601bc22012-02-21 21:23:20101// Default TTL for unsuccessful resolutions with ProcTask.
102const unsigned kNegativeCacheEntryTTLSeconds = 0;
103
[email protected]895123222012-10-25 15:21:17104// Minimum TTL for successful resolutions with DnsTask.
105const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
106
sergeyub8cdc212015-05-14 18:50:37107// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
108// cached.
109const int kIPv6ProbePeriodMs = 1000;
110
111// Google DNS address used for IPv6 probes.
112const uint8_t kIPv6ProbeAddress[] =
113 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
114 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
115
[email protected]24f4bab2010-10-15 01:27:11116// We use a separate histogram name for each platform to facilitate the
117// display of error codes by their symbolic name (since each platform has
118// different mappings).
119const char kOSErrorsForGetAddrinfoHistogramName[] =
120#if defined(OS_WIN)
121 "Net.OSErrorsForGetAddrinfo_Win";
122#elif defined(OS_MACOSX)
123 "Net.OSErrorsForGetAddrinfo_Mac";
124#elif defined(OS_LINUX)
125 "Net.OSErrorsForGetAddrinfo_Linux";
126#else
127 "Net.OSErrorsForGetAddrinfo";
128#endif
129
[email protected]c89b2442011-05-26 14:28:27130// Gets a list of the likely error codes that getaddrinfo() can return
131// (non-exhaustive). These are the error codes that we will track via
132// a histogram.
133std::vector<int> GetAllGetAddrinfoOSErrors() {
134 int os_errors[] = {
135#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51136#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37137#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45138 // EAI_ADDRFAMILY has been declared obsolete in Android's and
139 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27140 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37141#endif
[email protected]c48aef92011-11-22 23:41:45142 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51143 EAI_NODATA,
144#endif
[email protected]c89b2442011-05-26 14:28:27145 EAI_AGAIN,
146 EAI_BADFLAGS,
147 EAI_FAIL,
148 EAI_FAMILY,
149 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27150 EAI_NONAME,
151 EAI_SERVICE,
152 EAI_SOCKTYPE,
153 EAI_SYSTEM,
154#elif defined(OS_WIN)
155 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
156 WSA_NOT_ENOUGH_MEMORY,
157 WSAEAFNOSUPPORT,
158 WSAEINVAL,
159 WSAESOCKTNOSUPPORT,
160 WSAHOST_NOT_FOUND,
161 WSANO_DATA,
162 WSANO_RECOVERY,
163 WSANOTINITIALISED,
164 WSATRY_AGAIN,
165 WSATYPE_NOT_FOUND,
166 // The following are not in doc, but might be to appearing in results :-(.
167 WSA_INVALID_HANDLE,
168#endif
169 };
170
171 // Ensure all errors are positive, as histogram only tracks positive values.
172 for (size_t i = 0; i < arraysize(os_errors); ++i) {
173 os_errors[i] = std::abs(os_errors[i]);
174 }
175
176 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
177 arraysize(os_errors));
178}
179
[email protected]1def74c2012-03-22 20:07:00180enum DnsResolveStatus {
181 RESOLVE_STATUS_DNS_SUCCESS = 0,
182 RESOLVE_STATUS_PROC_SUCCESS,
183 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33184 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00185 RESOLVE_STATUS_MAX
186};
187
eroman91dd3602015-03-26 03:46:33188// ICANN uses this localhost address to indicate a name collision.
189//
190// The policy in Chromium is to fail host resolving if it resolves to
191// this special address.
192//
193// Not however that IP literals are exempt from this policy, so it is still
194// possible to navigate to http://127.0.53.53/ directly.
195//
196// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51197const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33198
eroman1efc237c2016-12-14 00:00:45199bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
200 for (const auto& endpoint : addr_list) {
201 const IPAddress& addr = endpoint.address();
202 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
203 return true;
204 }
205 }
206 return false;
207}
208
[email protected]1def74c2012-03-22 20:07:00209void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
210 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
211 result,
212 RESOLVE_STATUS_MAX);
213}
214
[email protected]1d932852012-06-19 19:40:33215bool ResemblesNetBIOSName(const std::string& hostname) {
216 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
217}
218
219// True if |hostname| ends with either ".local" or ".local.".
220bool ResemblesMulticastDNSName(const std::string& hostname) {
221 DCHECK(!hostname.empty());
222 const char kSuffix[] = ".local.";
223 const size_t kSuffixLen = sizeof(kSuffix) - 1;
224 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36225 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33226 return hostname.size() > kSuffixLen &&
227 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
228 }
229 return hostname.size() > kSuffixLenTrimmed &&
230 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
231 kSuffix, kSuffixLenTrimmed);
232}
233
[email protected]51b9a6b2012-06-25 21:50:29234// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21235#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
236 do { \
237 switch (priority) { \
238 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28239 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21240 break; \
241 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28242 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21243 break; \
244 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28245 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21246 break; \
247 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28248 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21249 break; \
250 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28251 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21252 break; \
253 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28254 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21255 break; \
256 } \
257 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29258 } while (0)
259
260// Record time from Request creation until a valid DNS response.
Miriam Gershenson90d05e02017-09-28 19:29:28261void RecordTotalTime(bool speculative,
262 bool from_cache,
[email protected]51b9a6b2012-06-25 21:50:29263 base::TimeDelta duration) {
Miriam Gershenson90d05e02017-09-28 19:29:28264 if (speculative) {
265 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime.Speculative", duration);
[email protected]51b9a6b2012-06-25 21:50:29266 } else {
Miriam Gershenson90d05e02017-09-28 19:29:28267 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
268 }
269
270 if (!from_cache) {
[email protected]51b9a6b2012-06-25 21:50:29271 if (speculative) {
Miriam Gershenson90d05e02017-09-28 19:29:28272 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached.Speculative",
273 duration);
[email protected]51b9a6b2012-06-25 21:50:29274 } else {
Miriam Gershenson90d05e02017-09-28 19:29:28275 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
[email protected]51b9a6b2012-06-25 21:50:29276 }
277 }
278}
279
[email protected]1339a2a22012-10-17 08:39:43280void RecordTTL(base::TimeDelta ttl) {
281 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
282 base::TimeDelta::FromSeconds(1),
283 base::TimeDelta::FromDays(1), 100);
284}
285
[email protected]16c2bd72013-06-28 01:19:22286bool ConfigureAsyncDnsNoFallbackFieldTrial() {
287 const bool kDefault = false;
288
289 // Configure the AsyncDns field trial as follows:
290 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
291 // groups AsyncDnsA and AsyncDnsB: return false,
292 // groups SystemDnsA and SystemDnsB: return false,
293 // otherwise (trial absent): return default.
294 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29295 if (!group_name.empty()) {
296 return base::StartsWith(group_name, "AsyncDnsNoFallback",
297 base::CompareCase::INSENSITIVE_ASCII);
298 }
[email protected]16c2bd72013-06-28 01:19:22299 return kDefault;
300}
301
[email protected]d7b9a2b2012-05-31 22:31:19302//-----------------------------------------------------------------------------
303
Avi Drissman13fc8932015-12-20 04:40:46304AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17305 if (list.empty() || list.front().port() == port)
306 return list;
307 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56308}
309
[email protected]ec666ab22013-04-17 20:05:59310// Returns true if |addresses| contains only IPv4 loopback addresses.
311bool IsAllIPv4Loopback(const AddressList& addresses) {
312 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51313 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59314 switch (addresses[i].GetFamily()) {
315 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51316 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59317 return false;
318 break;
319 case ADDRESS_FAMILY_IPV6:
320 return false;
321 default:
322 NOTREACHED();
323 return false;
324 }
325 }
326 return true;
327}
328
tfarinada9e1362017-03-14 16:49:06329// Returns true if it can determine that only loopback addresses are configured.
330// i.e. if only 127.0.0.1 and ::1 are routable.
331// Also returns false if it cannot determine this.
332bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40333 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
tfarinada9e1362017-03-14 16:49:06334#if defined(OS_ANDROID)
335 return android::HaveOnlyLoopbackAddresses();
336#elif defined(OS_NACL)
337 NOTIMPLEMENTED();
338 return false;
339#elif defined(OS_POSIX)
340 struct ifaddrs* interface_addr = NULL;
341 int rv = getifaddrs(&interface_addr);
342 if (rv != 0) {
343 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
344 return false;
345 }
346
347 bool result = true;
348 for (struct ifaddrs* interface = interface_addr;
349 interface != NULL;
350 interface = interface->ifa_next) {
351 if (!(IFF_UP & interface->ifa_flags))
352 continue;
353 if (IFF_LOOPBACK & interface->ifa_flags)
354 continue;
355 const struct sockaddr* addr = interface->ifa_addr;
356 if (!addr)
357 continue;
358 if (addr->sa_family == AF_INET6) {
359 // Safe cast since this is AF_INET6.
360 const struct sockaddr_in6* addr_in6 =
361 reinterpret_cast<const struct sockaddr_in6*>(addr);
362 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
363 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
364 continue;
365 }
366 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
367 continue;
368
369 result = false;
370 break;
371 }
372 freeifaddrs(interface_addr);
373 return result;
374#elif defined(OS_WIN)
375 // TODO(wtc): implement with the GetAdaptersAddresses function.
376 NOTIMPLEMENTED();
377 return false;
378#else
379 NOTIMPLEMENTED();
380 return false;
381#endif // defined(various platforms)
382}
383
[email protected]cd565142012-06-12 16:21:45384// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40385std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46386 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17387 int net_error,
388 int os_error,
389 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40390 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45391 if (attempt_number)
392 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46393
[email protected]cd565142012-06-12 16:21:45394 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16395
[email protected]cd565142012-06-12 16:21:45396 if (os_error) {
397 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46398#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45399 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46400#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45401 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04402 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08403 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
404 0, // Use the internal message table.
405 os_error,
406 0, // Use default language.
407 (LPWSTR)&error_string,
408 0, // Buffer size.
409 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01410 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45411 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46412#endif
[email protected]21526002010-05-16 19:42:46413 }
414
dchengc7eeda422015-12-26 03:56:48415 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45416}
[email protected]a9813302012-04-28 09:29:28417
[email protected]cd565142012-06-12 16:21:45418// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40419std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11420 int net_error,
421 int dns_error,
422 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40423 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45424 dict->SetInteger("net_error", net_error);
425 if (dns_error)
426 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48427 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36428}
[email protected]ee094b82010-08-24 15:55:51429
[email protected]cd565142012-06-12 16:21:45430// Creates NetLog parameters containing the information in a RequestInfo object,
mikecironef22f9812016-10-04 03:40:19431// along with the associated NetLogSource.
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
[email protected]cd565142012-06-12 16:21:45445// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40446std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19447 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11448 const std::string* host,
449 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40450 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11451 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45452 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48453 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45454}
[email protected]a9813302012-04-28 09:29:28455
[email protected]cd565142012-06-12 16:21:45456// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40457std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19458 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11459 RequestPriority priority,
460 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40461 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11462 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56463 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48464 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45465}
[email protected]b3601bc22012-02-21 21:23:20466
[email protected]cd565142012-06-12 16:21:45467// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40468std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11469 const DnsConfig* config,
470 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08471 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45472}
[email protected]b4481b222012-03-16 17:13:11473
danakj22f90e72016-04-16 01:55:40474std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11475 bool ipv6_available,
476 bool cached,
477 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40478 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37479 dict->SetBoolean("ipv6_available", ipv6_available);
480 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48481 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37482}
483
[email protected]0f292de02012-02-01 22:28:20484// The logging routines are defined here because some requests are resolved
485// without a Request object.
486
487// Logs when a request has just been started.
tfarina428341112016-09-22 13:38:20488void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20489 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00490 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
491 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20492}
493
494// Logs when a request has just completed (before its callback is run).
tfarina428341112016-09-22 13:38:20495void LogFinishRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20496 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20497 int net_error) {
xunjieli26f90452014-11-10 16:23:02498 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00499 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20500}
501
502// Logs when a request has been cancelled.
tfarina428341112016-09-22 13:38:20503void LogCancelRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20504 const HostResolverImpl::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00505 source_net_log.AddEvent(NetLogEventType::CANCELLED);
506 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20507}
508
[email protected]b59ff372009-07-15 22:04:32509//-----------------------------------------------------------------------------
510
[email protected]0f292de02012-02-01 22:28:20511// Keeps track of the highest priority.
512class PriorityTracker {
513 public:
[email protected]8c98d002012-07-18 19:02:27514 explicit PriorityTracker(RequestPriority initial_priority)
515 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20516 memset(counts_, 0, sizeof(counts_));
517 }
518
519 RequestPriority highest_priority() const {
520 return highest_priority_;
521 }
522
523 size_t total_count() const {
524 return total_count_;
525 }
526
527 void Add(RequestPriority req_priority) {
528 ++total_count_;
529 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05530 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20531 highest_priority_ = req_priority;
532 }
533
534 void Remove(RequestPriority req_priority) {
535 DCHECK_GT(total_count_, 0u);
536 DCHECK_GT(counts_[req_priority], 0u);
537 --total_count_;
538 --counts_[req_priority];
539 size_t i;
thestiga74ad2b2016-07-11 20:52:36540 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
541 }
[email protected]0f292de02012-02-01 22:28:20542 highest_priority_ = static_cast<RequestPriority>(i);
543
[email protected]31ae7ab2012-04-24 21:09:05544 // In absence of requests, default to MINIMUM_PRIORITY.
545 if (total_count_ == 0)
546 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20547 }
548
549 private:
550 RequestPriority highest_priority_;
551 size_t total_count_;
552 size_t counts_[NUM_PRIORITIES];
553};
554
juliatuttle9fb7aeb2016-06-06 20:16:33555void MakeNotStale(HostCache::EntryStaleness* stale_info) {
556 if (!stale_info)
557 return;
558 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
559 stale_info->network_changes = 0;
560 stale_info->stale_hits = 0;
561}
562
juliatuttled7fa5852016-07-29 13:16:57563// Persist data every five minutes (potentially, cache and learned RTT).
564const int64_t kPersistDelaySec = 300;
565
[email protected]c54a8912012-10-22 22:09:43566} // namespace
[email protected]0f292de02012-02-01 22:28:20567
568//-----------------------------------------------------------------------------
569
tfarina9ed7f8c52016-02-19 17:50:18570bool ResolveLocalHostname(base::StringPiece host,
571 uint16_t port,
572 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18573 address_list->clear();
574
575 bool is_local6;
576 if (!IsLocalHostname(host, &is_local6))
577 return false;
578
martijna23c8962016-03-04 18:18:51579 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18580 if (!is_local6) {
martijna23c8962016-03-04 18:18:51581 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18582 }
583
584 return true;
585}
586
[email protected]daae1322013-09-05 18:26:50587const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
588
[email protected]0f292de02012-02-01 22:28:20589// Holds the data for a request that could not be completed synchronously.
590// It is owned by a Job. Canceled Requests are only marked as canceled rather
591// than removed from the Job's |requests_| list.
maksim.sisov31452af2016-07-27 06:38:10592class HostResolverImpl::RequestImpl : public HostResolver::Request {
[email protected]b59ff372009-07-15 22:04:32593 public:
tfarina428341112016-09-22 13:38:20594 RequestImpl(const NetLogWithSource& source_net_log,
maksim.sisov31452af2016-07-27 06:38:10595 const RequestInfo& info,
596 RequestPriority priority,
597 const CompletionCallback& callback,
598 AddressList* addresses,
599 Job* job)
[email protected]ee094b82010-08-24 15:55:51600 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09601 info_(info),
[email protected]5109c1952013-08-20 18:44:10602 priority_(priority),
maksim.sisov31452af2016-07-27 06:38:10603 job_(job),
[email protected]54e13772009-08-14 03:01:09604 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29605 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10606 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32607
maksim.sisov31452af2016-07-27 06:38:10608 ~RequestImpl() override;
609
610 void ChangeRequestPriority(RequestPriority priority) override;
611
612 void OnJobCancelled(Job* job) {
613 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04614 job_ = nullptr;
615 addresses_ = nullptr;
[email protected]aa22b242011-11-16 18:58:29616 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32617 }
618
[email protected]0f292de02012-02-01 22:28:20619 // Prepare final AddressList and call completion callback.
maksim.sisov31452af2016-07-27 06:38:10620 void OnJobCompleted(Job* job, int error, const AddressList& addr_list) {
621 DCHECK_EQ(job_, job);
[email protected]895123222012-10-25 15:21:17622 if (error == OK)
623 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
maksim.sisov31452af2016-07-27 06:38:10624 job_ = nullptr;
625 addresses_ = nullptr;
626 base::ResetAndReturn(&callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32627 }
628
[email protected]b59ff372009-07-15 22:04:32629 Job* job() const {
630 return job_;
631 }
632
[email protected]0f292de02012-02-01 22:28:20633 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20634 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51635
[email protected]b59ff372009-07-15 22:04:32636 const RequestInfo& info() const {
637 return info_;
638 }
639
[email protected]5109c1952013-08-20 18:44:10640 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31641 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10642
643 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29644
[email protected]b59ff372009-07-15 22:04:32645 private:
tfarina428341112016-09-22 13:38:20646 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09647
[email protected]b59ff372009-07-15 22:04:32648 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10649 const RequestInfo info_;
650
juliatuttlec53b19a72016-05-05 13:51:31651 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32652
[email protected]0f292de02012-02-01 22:28:20653 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32654 Job* job_;
655
656 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29657 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32658
659 // The address list to save result into.
660 AddressList* addresses_;
661
[email protected]51b9a6b2012-06-25 21:50:29662 const base::TimeTicks request_time_;
663
maksim.sisov31452af2016-07-27 06:38:10664 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32665};
666
[email protected]1e9bbd22010-10-15 16:42:45667//------------------------------------------------------------------------------
668
Francois Doraya2d01ba2017-09-25 19:17:40669// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20670//
671// Whenever we try to resolve the host, we post a delayed task to check if host
672// resolution (OnLookupComplete) is completed or not. If the original attempt
673// hasn't completed, then we start another attempt for host resolution. We take
674// the results from the first attempt that finishes and ignore the results from
675// all other attempts.
676//
677// TODO(szym): Move to separate source file for testing and mocking.
678//
679class HostResolverImpl::ProcTask
680 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32681 public:
[email protected]b3601bc22012-02-21 21:23:20682 typedef base::Callback<void(int net_error,
683 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32684
[email protected]0f292de02012-02-01 22:28:20685 ProcTask(const Key& key,
686 const ProcTaskParams& params,
687 const Callback& callback,
Miriam Gershensone42adb22017-10-16 16:19:38688 scoped_refptr<base::TaskRunner> proc_task_runner,
tfarina428341112016-09-22 13:38:20689 const NetLogWithSource& job_net_log)
[email protected]0f292de02012-02-01 22:28:20690 : key_(key),
691 params_(params),
692 callback_(callback),
mmenke91c17162016-06-02 16:03:23693 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38694 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20695 attempt_number_(0),
696 completed_attempt_number_(0),
697 completed_attempt_error_(ERR_UNEXPECTED),
[email protected]b3601bc22012-02-21 21:23:20698 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50699 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20700 params_.resolver_proc = HostResolverProc::GetDefault();
701 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50702 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06703 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32704 }
705
[email protected]b59ff372009-07-15 22:04:32706 void Start() {
mmenke91c17162016-06-02 16:03:23707 DCHECK(network_task_runner_->BelongsToCurrentThread());
mikecirone8b85c432016-09-08 19:11:00708 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54709 StartLookupAttempt();
710 }
[email protected]252b699b2010-02-05 21:38:06711
[email protected]0f292de02012-02-01 22:28:20712 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23713 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20714 // attempts complete will the final reference to this ProcTask be released.
715 void Cancel() {
mmenke91c17162016-06-02 16:03:23716 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20717
[email protected]0adcb2b2012-08-15 21:30:46718 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20719 return;
720
[email protected]0f292de02012-02-01 22:28:20721 callback_.Reset();
mikecirone8b85c432016-09-08 19:11:00722 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20723 }
724
[email protected]0f292de02012-02-01 22:28:20725 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23726 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20727 return callback_.is_null();
728 }
729
730 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23731 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20732 return completed_attempt_number_ > 0;
733 }
734
735 private:
[email protected]a9813302012-04-28 09:29:28736 friend class base::RefCountedThreadSafe<ProcTask>;
Chris Watkins68b15032017-12-01 03:07:13737 ~ProcTask() = default;
[email protected]a9813302012-04-28 09:29:28738
[email protected]189163e2011-05-11 01:48:54739 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23740 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54741 base::TimeTicks start_time = base::TimeTicks::Now();
742 ++attempt_number_;
743 // Dispatch the lookup attempt to a worker thread.
Miriam Gershensone42adb22017-10-16 16:19:38744 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40745 FROM_HERE,
Francois Doraya2d01ba2017-09-25 19:17:40746 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_));
[email protected]13024882011-05-18 23:19:16747
mikecirone8b85c432016-09-08 19:11:00748 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28749 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16750
mmenke91c17162016-06-02 16:03:23751 // If the results aren't received within a given time, RetryIfNotComplete
752 // will start a new attempt if none of the outstanding attempts have
753 // completed yet.
[email protected]0f292de02012-02-01 22:28:20754 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23755 network_task_runner_->PostDelayedTask(
756 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42757 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58758 }
[email protected]b59ff372009-07-15 22:04:32759 }
760
Francois Doraya2d01ba2017-09-25 19:17:40761 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
762 // shutdown code cannot wait for it to finish, so this code must be very
763 // careful about using other objects (like MessageLoops, Singletons, etc).
764 // During shutdown these objects may no longer exist. Multiple DoLookups()
765 // could be running in parallel, so any state inside of |this| must not
766 // mutate.
[email protected]189163e2011-05-11 01:48:54767 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46768 const uint32_t attempt_number) {
Miriam Gershenson1ac86662017-10-09 20:50:57769 TRACE_HEAP_PROFILER_API_SCOPED_TASK_EXECUTION scoped_heap_context(
770 "net/dns/proctask");
[email protected]189163e2011-05-11 01:48:54771 AddressList results;
772 int os_error = 0;
[email protected]0f292de02012-02-01 22:28:20773 int error = params_.resolver_proc->Resolve(key_.hostname,
774 key_.address_family,
775 key_.host_resolver_flags,
776 &results,
777 &os_error);
[email protected]b59ff372009-07-15 22:04:32778
mmenke91c17162016-06-02 16:03:23779 network_task_runner_->PostTask(
780 FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
781 start_time, attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54782 }
783
mmenke91c17162016-06-02 16:03:23784 // Makes next attempt if DoLookup() has not finished.
[email protected]0f292de02012-02-01 22:28:20785 void RetryIfNotComplete() {
mmenke91c17162016-06-02 16:03:23786 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54787
[email protected]0f292de02012-02-01 22:28:20788 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54789 return;
790
[email protected]0f292de02012-02-01 22:28:20791 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54792 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32793 }
794
anujk.sharma7c907f02015-05-29 02:55:44795 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54796 void OnLookupComplete(const AddressList& results,
797 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46798 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54799 int error,
800 const int os_error) {
xunjieli0b7f5b62016-12-06 20:43:48801 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
mmenke91c17162016-06-02 16:03:23802 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23803 // If results are empty, we should return an error.
804 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23805 if (empty_list_on_ok)
806 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54807
808 bool was_retry_attempt = attempt_number > 1;
809
[email protected]2d3b7762010-10-09 00:35:47810 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20811 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23812 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54813 if (error != OK && NetworkChangeNotifier::IsOffline())
814 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47815
[email protected]189163e2011-05-11 01:48:54816 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35817
[email protected]0f292de02012-02-01 22:28:20818 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32819 return;
820
mikecironef22f9812016-10-04 03:40:19821 NetLogParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20822 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45823 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
824 attempt_number,
825 error,
826 os_error);
[email protected]0f292de02012-02-01 22:28:20827 } else {
tfarina5e24b242015-10-27 13:11:28828 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20829 }
mikecirone8b85c432016-09-08 19:11:00830 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
[email protected]cd565142012-06-12 16:21:45831 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20832
833 if (was_completed())
834 return;
835
Miriam Gershenson61604662017-09-28 23:51:11836 RecordTaskHistograms(start_time, error, os_error);
837
[email protected]0f292de02012-02-01 22:28:20838 // Copy the results from the first worker thread that resolves the host.
839 results_ = results;
840 completed_attempt_number_ = attempt_number;
841 completed_attempt_error_ = error;
842
[email protected]e87b8b512011-06-14 22:12:52843 if (was_retry_attempt) {
844 // If retry attempt finishes before 1st attempt, then get stats on how
845 // much time is saved by having spawned an extra attempt.
846 retry_attempt_finished_time_ = base::TimeTicks::Now();
847 }
848
[email protected]189163e2011-05-11 01:48:54849 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45850 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
851 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51852 } else {
[email protected]cd565142012-06-12 16:21:45853 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51854 }
mikecirone8b85c432016-09-08 19:11:00855 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45856 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51857
[email protected]b3601bc22012-02-21 21:23:20858 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32859 }
860
Miriam Gershenson61604662017-09-28 23:51:11861 void RecordTaskHistograms(const base::TimeTicks& start_time,
862 const int error,
863 const int os_error) const {
mmenke91c17162016-06-02 16:03:23864 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54865 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
Miriam Gershenson61604662017-09-28 23:51:11866 if (error == OK)
867 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.SuccessTime", duration);
868 else
869 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.FailureTime", duration);
[email protected]7e96d792011-06-10 17:08:23870
Miriam Gershenson61604662017-09-28 23:51:11871 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
872 std::abs(os_error),
873 GetAllGetAddrinfoOSErrors());
[email protected]1e9bbd22010-10-15 16:42:45874 }
875
[email protected]189163e2011-05-11 01:48:54876 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46877 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54878 const int error,
879 const int os_error) const {
mmenke91c17162016-06-02 16:03:23880 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54881 bool first_attempt_to_complete =
882 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52883 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45884
[email protected]189163e2011-05-11 01:48:54885 if (first_attempt_to_complete) {
886 // If this was first attempt to complete, then record the resolution
887 // status of the attempt.
888 if (completed_attempt_error_ == OK) {
889 UMA_HISTOGRAM_ENUMERATION(
890 "DNS.AttemptFirstSuccess", attempt_number, 100);
891 } else {
892 UMA_HISTOGRAM_ENUMERATION(
893 "DNS.AttemptFirstFailure", attempt_number, 100);
894 }
895 }
896
897 if (error == OK)
898 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
899 else
900 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
901
[email protected]e87b8b512011-06-14 22:12:52902 // If first attempt didn't finish before retry attempt, then calculate stats
903 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20904 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21905 UMA_HISTOGRAM_LONG_TIMES_100(
906 "DNS.AttemptTimeSavedByRetry",
907 base::TimeTicks::Now() - retry_attempt_finished_time_);
[email protected]e87b8b512011-06-14 22:12:52908 }
909
[email protected]0f292de02012-02-01 22:28:20910 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54911 // Count those attempts which completed after the job was already canceled
912 // OR after the job was already completed by an earlier attempt (so in
913 // effect).
914 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
915
[email protected]0f292de02012-02-01 22:28:20916 // Record if job is canceled.
917 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54918 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
919 }
920
921 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
922 if (error == OK)
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21923 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptSuccessDuration", duration);
[email protected]189163e2011-05-11 01:48:54924 else
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21925 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptFailDuration", duration);
[email protected]189163e2011-05-11 01:48:54926 }
[email protected]1e9bbd22010-10-15 16:42:45927
anujk.sharma7c907f02015-05-29 02:55:44928 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57929 Key key_;
[email protected]b59ff372009-07-15 22:04:32930
[email protected]0f292de02012-02-01 22:28:20931 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32932 // This may not be the current resolver procedure by the time we call
933 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
934 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20935 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32936
[email protected]0f292de02012-02-01 22:28:20937 // The listener to the results of this ProcTask.
938 Callback callback_;
939
mmenke91c17162016-06-02 16:03:23940 // Used to post events onto the network thread.
941 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:38942 // Used to post blocking HostResolverProc tasks.
943 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:54944
945 // Keeps track of the number of attempts we have made so far to resolve the
946 // host. Whenever we start an attempt to resolve the host, we increase this
947 // number.
Avi Drissman13fc8932015-12-20 04:40:46948 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54949
950 // The index of the attempt which finished first (or 0 if the job is still in
951 // progress).
Avi Drissman13fc8932015-12-20 04:40:46952 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:54953
954 // The result (a net error code) from the first attempt to complete.
955 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06956
[email protected]e87b8b512011-06-14 22:12:52957 // The time when retry attempt was finished.
958 base::TimeTicks retry_attempt_finished_time_;
959
[email protected]b59ff372009-07-15 22:04:32960 AddressList results_;
961
tfarina428341112016-09-22 13:38:20962 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51963
[email protected]0f292de02012-02-01 22:28:20964 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32965};
966
967//-----------------------------------------------------------------------------
968
[email protected]b3601bc22012-02-21 21:23:20969// Resolves the hostname using DnsTransaction.
970// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46971class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20972 public:
[email protected]daae1322013-09-05 18:26:50973 class Delegate {
974 public:
975 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
976 int net_error,
977 const AddressList& addr_list,
978 base::TimeDelta ttl) = 0;
979
980 // Called when the first of two jobs succeeds. If the first completed
981 // transaction fails, this is not called. Also not called when the DnsTask
982 // only needs to run one transaction.
983 virtual void OnFirstDnsTransactionComplete() = 0;
984
985 protected:
Chris Watkins68b15032017-12-01 03:07:13986 Delegate() = default;
987 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:50988 };
[email protected]b3601bc22012-02-21 21:23:20989
[email protected]0adcb2b2012-08-15 21:30:46990 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:20991 const Key& key,
[email protected]daae1322013-09-05 18:26:50992 Delegate* delegate,
tfarina428341112016-09-22 13:38:20993 const NetLogWithSource& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:46994 : client_(client),
[email protected]daae1322013-09-05 18:26:50995 key_(key),
996 delegate_(delegate),
997 net_log_(job_net_log),
998 num_completed_transactions_(0),
999 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461000 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501001 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501002 }
1003
[email protected]daae1322013-09-05 18:26:501004 bool needs_two_transactions() const {
1005 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1006 }
1007
1008 bool needs_another_transaction() const {
1009 return needs_two_transactions() && !transaction_aaaa_;
1010 }
1011
1012 void StartFirstTransaction() {
1013 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001014 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501015 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1016 StartAAAA();
1017 } else {
1018 StartA();
1019 }
1020 }
1021
1022 void StartSecondTransaction() {
1023 DCHECK(needs_two_transactions());
1024 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121025 }
1026
1027 private:
[email protected]daae1322013-09-05 18:26:501028 void StartA() {
1029 DCHECK(!transaction_a_);
1030 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1031 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1032 transaction_a_->Start();
1033 }
1034
1035 void StartAAAA() {
1036 DCHECK(!transaction_aaaa_);
1037 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1038 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1039 transaction_aaaa_->Start();
1040 }
1041
danakj22f90e72016-04-16 01:55:401042 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501043 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1044 return client_->GetTransactionFactory()->CreateTransaction(
1045 key_.hostname,
1046 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1047 dns_protocol::kTypeA,
1048 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1049 base::TimeTicks::Now()),
1050 net_log_);
1051 }
1052
1053 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001054 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201055 int net_error,
1056 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471057 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511058 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
Miriam Gershenson66024d72017-12-05 04:30:321059 if (net_error != OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211060 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461061 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1062 return;
[email protected]6c411902012-08-14 22:36:361063 }
[email protected]0adcb2b2012-08-15 21:30:461064
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211065 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511066 switch (transaction->GetType()) {
1067 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211068 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511069 break;
1070 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211071 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1072 duration);
[email protected]02cd6982013-01-10 20:12:511073 break;
1074 }
[email protected]daae1322013-09-05 18:26:501075
[email protected]0adcb2b2012-08-15 21:30:461076 AddressList addr_list;
1077 base::TimeDelta ttl;
1078 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1079 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1080 result,
1081 DnsResponse::DNS_PARSE_RESULT_MAX);
1082 if (result != DnsResponse::DNS_PARSE_OK) {
1083 // Fail even if the other query succeeds.
1084 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1085 return;
1086 }
1087
[email protected]daae1322013-09-05 18:26:501088 ++num_completed_transactions_;
1089 if (num_completed_transactions_ == 1) {
1090 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461091 } else {
[email protected]daae1322013-09-05 18:26:501092 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461093 }
1094
[email protected]daae1322013-09-05 18:26:501095 if (transaction->GetType() == dns_protocol::kTypeA) {
1096 DCHECK_EQ(transaction_a_.get(), transaction);
1097 // Place IPv4 addresses after IPv6.
1098 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1099 } else {
1100 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1101 // Place IPv6 addresses before IPv4.
1102 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1103 }
1104
1105 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1106 // No need to repeat the suffix search.
1107 key_.hostname = transaction->GetHostname();
1108 delegate_->OnFirstDnsTransactionComplete();
1109 return;
1110 }
1111
1112 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121113 // TODO(szym): Don't fallback to ProcTask in this case.
1114 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461115 return;
1116 }
1117
[email protected]daae1322013-09-05 18:26:501118 // If there are multiple addresses, and at least one is IPv6, need to sort
1119 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1120 // sufficient to just check the family of the first address.
1121 if (addr_list_.size() > 1 &&
1122 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1123 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461124 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501125 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071126 base::Bind(&DnsTask::OnSortComplete,
1127 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501128 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461129 } else {
[email protected]daae1322013-09-05 18:26:501130 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461131 }
1132 }
1133
1134 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461135 bool success,
1136 const AddressList& addr_list) {
1137 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211138 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
1139 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461140 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1141 return;
1142 }
1143
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211144 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
1145 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461146
1147 // AddressSorter prunes unusable destinations.
1148 if (addr_list.empty()) {
1149 LOG(WARNING) << "Address list empty after RFC3484 sort";
1150 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1151 return;
1152 }
1153
[email protected]daae1322013-09-05 18:26:501154 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461155 }
1156
1157 void OnFailure(int net_error, DnsResponse::Result result) {
1158 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451159 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001160 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451161 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
Miriam Gershenson66024d72017-12-05 04:30:321162 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1163 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201164 }
1165
[email protected]daae1322013-09-05 18:26:501166 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001167 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461168 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501169 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461170 }
1171
1172 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501173 Key key_;
1174
[email protected]b3601bc22012-02-21 21:23:201175 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501176 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201177 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201178
danakj22f90e72016-04-16 01:55:401179 std::unique_ptr<DnsTransaction> transaction_a_;
1180 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461181
[email protected]daae1322013-09-05 18:26:501182 unsigned num_completed_transactions_;
1183
1184 // These are updated as each transaction completes.
1185 base::TimeDelta ttl_;
1186 // IPv6 addresses must appear first in the list.
1187 AddressList addr_list_;
1188
1189 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461190
1191 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201192};
1193
1194//-----------------------------------------------------------------------------
1195
[email protected]0f292de02012-02-01 22:28:201196// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501197class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1198 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391199 public:
[email protected]0f292de02012-02-01 22:28:201200 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351201 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181202 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201203 const Key& key,
[email protected]8c98d002012-07-18 19:02:271204 RequestPriority priority,
Miriam Gershensone42adb22017-10-16 16:19:381205 scoped_refptr<base::TaskRunner> proc_task_runner,
tfarina428341112016-09-22 13:38:201206 const NetLogWithSource& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181207 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201208 key_(key),
[email protected]8c98d002012-07-18 19:02:271209 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381210 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201211 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291212 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501213 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331214 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291215 creation_time_(base::TimeTicks::Now()),
1216 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201217 net_log_(
1218 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001219 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1220 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201221
mikecirone8b85c432016-09-08 19:11:001222 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1223 base::Bind(&NetLogJobCreationCallback,
1224 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391225 }
1226
dchengb03027d2014-10-21 12:00:201227 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201228 if (is_running()) {
1229 // |resolver_| was destroyed with this Job still in flight.
1230 // Clean-up, record in the log, but don't run any callbacks.
1231 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201232 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041233 proc_task_ = nullptr;
[email protected]0f292de02012-02-01 22:28:201234 }
[email protected]16ee26d2012-03-08 03:34:351235 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501236 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001237 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201238 ERR_ABORTED);
1239 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551240 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351241 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001242 net_log_.AddEvent(NetLogEventType::CANCELLED);
1243 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391244 }
[email protected]b3601bc22012-02-21 21:23:201245 // else CompleteRequests logged EndEvent.
maksim.sisov31452af2016-07-27 06:38:101246 if (!requests_.empty()) {
1247 // Log any remaining Requests as cancelled.
1248 for (RequestImpl* req : requests_) {
1249 DCHECK_EQ(this, req->job());
maksim.sisov31452af2016-07-27 06:38:101250 LogCancelRequest(req->source_net_log(), req->info());
maksim.sisov320d5962016-08-15 18:02:511251 req->OnJobCancelled(this);
maksim.sisov31452af2016-07-27 06:38:101252 }
1253 requests_.clear();
[email protected]b3601bc22012-02-21 21:23:201254 }
[email protected]68ad3ee2010-01-30 03:45:391255 }
1256
[email protected]daae1322013-09-05 18:26:501257 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1258 // of the queue.
1259 void Schedule(bool at_head) {
1260 DCHECK(!is_queued());
1261 PrioritizedDispatcher::Handle handle;
1262 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001263 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501264 } else {
[email protected]106ccd2c2014-06-17 09:21:001265 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501266 }
1267 // The dispatcher could have started |this| in the above call to Add, which
1268 // could have called Schedule again. In that case |handle| will be null,
1269 // but |handle_| may have been set by the other nested call to Schedule.
1270 if (!handle.is_null()) {
1271 DCHECK(handle_.is_null());
1272 handle_ = handle;
1273 }
[email protected]16ee26d2012-03-08 03:34:351274 }
1275
maksim.sisov31452af2016-07-27 06:38:101276 void AddRequest(RequestImpl* request) {
1277 DCHECK_EQ(key_.hostname, request->info().hostname());
[email protected]0f292de02012-02-01 22:28:201278
maksim.sisov31452af2016-07-27 06:38:101279 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201280
maksim.sisov31452af2016-07-27 06:38:101281 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001282 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451283 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201284
1285 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001286 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101287 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451288 priority()));
[email protected]0f292de02012-02-01 22:28:201289
Miriam Gershenson61604662017-09-28 23:51:111290 if (!request->info().is_speculative())
[email protected]0f292de02012-02-01 22:28:201291 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201292
maksim.sisov31452af2016-07-27 06:38:101293 requests_.push_back(request);
[email protected]b3601bc22012-02-21 21:23:201294
[email protected]51b9a6b2012-06-25 21:50:291295 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391296 }
1297
maksim.sisov31452af2016-07-27 06:38:101298 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
juliatuttlec53b19a72016-05-05 13:51:311299 DCHECK_EQ(key_.hostname, req->info().hostname());
juliatuttlec53b19a72016-05-05 13:51:311300
1301 priority_tracker_.Remove(req->priority());
1302 req->set_priority(priority);
1303 priority_tracker_.Add(req->priority());
1304 UpdatePriority();
1305 }
1306
maksim.sisov31452af2016-07-27 06:38:101307 // Detach cancelled request. If it was the last active Request, also finishes
1308 // this Job.
1309 void CancelRequest(RequestImpl* request) {
1310 DCHECK_EQ(key_.hostname, request->info().hostname());
1311 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351312
maksim.sisov31452af2016-07-27 06:38:101313 LogCancelRequest(request->source_net_log(), request->info());
[email protected]16ee26d2012-03-08 03:34:351314
maksim.sisov31452af2016-07-27 06:38:101315 priority_tracker_.Remove(request->priority());
1316 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001317 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101318 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1319 priority()));
[email protected]b3601bc22012-02-21 21:23:201320
[email protected]16ee26d2012-03-08 03:34:351321 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291322 UpdatePriority();
maksim.sisov31452af2016-07-27 06:38:101323 RemoveRequest(request);
[email protected]16ee26d2012-03-08 03:34:351324 } else {
1325 // If we were called from a Request's callback within CompleteRequests,
1326 // that Request could not have been cancelled, so num_active_requests()
1327 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431328 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201329 }
[email protected]68ad3ee2010-01-30 03:45:391330 }
1331
maksim.sisov31452af2016-07-27 06:38:101332 void RemoveRequest(RequestImpl* request) {
1333 auto it = std::find(requests_.begin(), requests_.end(), request);
1334 DCHECK(it != requests_.end());
1335 requests_.erase(it);
1336 }
1337
[email protected]7af985a2012-12-14 22:40:421338 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1339 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111340 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201341 void Abort() {
[email protected]0f292de02012-02-01 22:28:201342 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421343 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201344 }
1345
[email protected]f0f602bd2012-11-15 18:01:021346 // If DnsTask present, abort it and fall back to ProcTask.
1347 void AbortDnsTask() {
1348 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501349 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021350 dns_task_error_ = OK;
1351 StartProcTask();
1352 }
1353 }
1354
[email protected]16ee26d2012-03-08 03:34:351355 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1356 // Completes all requests and destroys the job.
1357 void OnEvicted() {
1358 DCHECK(!is_running());
1359 DCHECK(is_queued());
1360 handle_.Reset();
1361
mikecirone8b85c432016-09-08 19:11:001362 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351363
1364 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431365 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351366 }
1367
[email protected]78eac2a2012-03-14 19:09:271368 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1369 // this Job was destroyed.
1370 bool ServeFromHosts() {
1371 DCHECK_GT(num_active_requests(), 0u);
1372 AddressList addr_list;
1373 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031374 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271375 &addr_list)) {
1376 // This will destroy the Job.
Rob Percival94f21ad2017-11-14 10:20:241377 CompleteRequests(
1378 MakeCacheEntry(OK, addr_list, HostCache::Entry::SOURCE_HOSTS),
1379 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271380 return true;
1381 }
1382 return false;
1383 }
1384
tanay.c6ddd5f6f2015-08-25 06:34:571385 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111386
1387 bool is_queued() const {
1388 return !handle_.is_null();
1389 }
1390
1391 bool is_running() const {
1392 return is_dns_running() || is_proc_running();
1393 }
1394
[email protected]16ee26d2012-03-08 03:34:351395 private:
[email protected]daae1322013-09-05 18:26:501396 void KillDnsTask() {
1397 if (dns_task_) {
1398 ReduceToOneJobSlot();
1399 dns_task_.reset();
1400 }
1401 }
1402
1403 // Reduce the number of job slots occupied and queued in the dispatcher
1404 // to one. If the second Job slot is queued in the dispatcher, cancels the
1405 // queued job. Otherwise, the second Job has been started by the
1406 // PrioritizedDispatcher, so signals it is complete.
1407 void ReduceToOneJobSlot() {
1408 DCHECK_GE(num_occupied_job_slots_, 1u);
1409 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001410 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501411 handle_.Reset();
1412 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001413 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501414 --num_occupied_job_slots_;
1415 }
1416 DCHECK_EQ(1u, num_occupied_job_slots_);
1417 }
1418
eroman0cd87b62016-12-14 19:13:451419 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1420 // HostCache::Entry(). The address list is omited from the cache entry
1421 // for errors.
1422 HostCache::Entry MakeCacheEntry(int net_error,
Rob Percival94f21ad2017-11-14 10:20:241423 const AddressList& addr_list,
1424 HostCache::Entry::Source source) const {
eroman0cd87b62016-12-14 19:13:451425 return HostCache::Entry(
1426 net_error,
Rob Percival94f21ad2017-11-14 10:20:241427 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1428 source);
eroman0cd87b62016-12-14 19:13:451429 }
1430
1431 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1432 const AddressList& addr_list,
Rob Percival94f21ad2017-11-14 10:20:241433 HostCache::Entry::Source source,
eroman0cd87b62016-12-14 19:13:451434 base::TimeDelta ttl) const {
1435 return HostCache::Entry(
1436 net_error,
1437 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
Rob Percival94f21ad2017-11-14 10:20:241438 source, ttl);
eroman0cd87b62016-12-14 19:13:451439 }
1440
juliatuttlec53b19a72016-05-05 13:51:311441 AddressList MakeAddressListForRequest(const AddressList& list) const {
1442 if (requests_.empty())
1443 return list;
1444 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1445 }
1446
[email protected]51b9a6b2012-06-25 21:50:291447 void UpdatePriority() {
1448 if (is_queued()) {
1449 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1450 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001451 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291452 }
1453 }
1454
[email protected]16ee26d2012-03-08 03:34:351455 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201456 void Start() override {
[email protected]daae1322013-09-05 18:26:501457 DCHECK_LE(num_occupied_job_slots_, 1u);
1458
[email protected]70c04ab2013-08-22 16:05:121459 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501460 ++num_occupied_job_slots_;
1461
1462 if (num_occupied_job_slots_ == 2) {
1463 StartSecondDnsTransaction();
1464 return;
1465 }
1466
1467 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201468
mikecirone8b85c432016-09-08 19:11:001469 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201470
[email protected]51b9a6b2012-06-25 21:50:291471 had_dns_config_ = resolver_->HaveDnsConfig();
1472
Miriam Gershenson61604662017-09-28 23:51:111473 start_time_ = base::TimeTicks::Now();
1474 base::TimeDelta queue_time = start_time_ - creation_time_;
1475 base::TimeDelta queue_time_after_change =
1476 start_time_ - priority_change_time_;
[email protected]51b9a6b2012-06-25 21:50:291477
Miriam Gershenson90d05e02017-09-28 19:29:281478 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTime", priority(), queue_time);
1479 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTimeAfterChange", priority(),
1480 queue_time_after_change);
[email protected]51b9a6b2012-06-25 21:50:291481
[email protected]443714fad2013-09-19 04:52:011482 bool system_only =
1483 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1484
[email protected]1d932852012-06-19 19:40:331485 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011486 if (!system_only && had_dns_config_ &&
1487 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201488 StartDnsTask();
1489 } else {
1490 StartProcTask();
1491 }
1492 }
1493
[email protected]b3601bc22012-02-21 21:23:201494 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401495 // the limits on |dispatcher_|. But in order to keep the number of
1496 // TaskScheduler threads low, we will need to use an "inner"
1497 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201498 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351499 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231500 proc_task_ =
1501 new ProcTask(key_, resolver_->proc_params_,
1502 base::Bind(&Job::OnProcTaskComplete,
1503 base::Unretained(this), base::TimeTicks::Now()),
Miriam Gershensone42adb22017-10-16 16:19:381504 proc_task_runner_, net_log_);
[email protected]0f292de02012-02-01 22:28:201505
[email protected]0f292de02012-02-01 22:28:201506 // Start() could be called from within Resolve(), hence it must NOT directly
1507 // call OnProcTaskComplete, for example, on synchronous failure.
1508 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391509 }
1510
[email protected]0f292de02012-02-01 22:28:201511 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371512 void OnProcTaskComplete(base::TimeTicks start_time,
1513 int net_error,
1514 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201515 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391516
[email protected]1d932852012-06-19 19:40:331517 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371518 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001519 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211520 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331521 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1522 ResemblesNetBIOSName(key_.hostname)) {
1523 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1524 } else {
1525 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1526 }
Ilya Sherman0eb39802017-12-08 20:58:181527 base::UmaHistogramSparse("Net.DNS.DnsTask.Errors",
1528 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221529 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001530 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211531 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001532 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1533 }
1534 }
1535
eroman1efc237c2016-12-14 00:00:451536 if (ContainsIcannNameCollisionIp(addr_list))
1537 net_error = ERR_ICANN_NAME_COLLISION;
1538
[email protected]1339a2a22012-10-17 08:39:431539 base::TimeDelta ttl =
1540 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201541 if (net_error == OK)
1542 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391543
Rob Percival94f21ad2017-11-14 10:20:241544 // Source unknown because the system resolver could have gotten it from a
1545 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171546 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241547 CompleteRequests(
1548 MakeCacheEntry(net_error, addr_list, HostCache::Entry::SOURCE_UNKNOWN),
1549 ttl);
[email protected]b3601bc22012-02-21 21:23:201550 }
1551
1552 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271553 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501554 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1555 net_log_));
[email protected]b3601bc22012-02-21 21:23:201556
[email protected]daae1322013-09-05 18:26:501557 dns_task_->StartFirstTransaction();
1558 // Schedule a second transaction, if needed.
1559 if (dns_task_->needs_two_transactions())
1560 Schedule(true);
1561 }
1562
1563 void StartSecondDnsTransaction() {
1564 DCHECK(dns_task_->needs_two_transactions());
1565 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221566 }
1567
1568 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1569 // deleted before this callback. In this case dns_task is deleted as well,
1570 // so we use it as indicator whether Job is still valid.
1571 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1572 base::TimeDelta duration,
1573 int net_error) {
Miriam Gershenson61604662017-09-28 23:51:111574 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221575
wezb9820d42016-06-22 23:41:041576 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221577 return;
1578
1579 dns_task_error_ = net_error;
1580
1581 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1582 // http://crbug.com/117655
1583
1584 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1585 // ProcTask in that case is a waste of time.
1586 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501587 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221588 StartProcTask();
1589 } else {
1590 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Miriam Gershenson66024d72017-12-05 04:30:321591 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201592 }
1593 }
1594
[email protected]daae1322013-09-05 18:26:501595
1596 // HostResolverImpl::DnsTask::Delegate implementation:
1597
dchengb03027d2014-10-21 12:00:201598 void OnDnsTaskComplete(base::TimeTicks start_time,
1599 int net_error,
1600 const AddressList& addr_list,
1601 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201602 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201603
[email protected]e3bd4822012-10-23 18:01:371604 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201605 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221606 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201607 return;
1608 }
Miriam Gershenson61604662017-09-28 23:51:111609
1610 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201611
[email protected]1def74c2012-03-22 20:07:001612 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431613 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461614
[email protected]1ffdda82012-12-12 23:04:221615 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021616
[email protected]895123222012-10-25 15:21:171617 base::TimeDelta bounded_ttl =
1618 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1619
eroman0cd87b62016-12-14 19:13:451620 if (ContainsIcannNameCollisionIp(addr_list)) {
1621 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1622 } else {
Rob Percival94f21ad2017-11-14 10:20:241623 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list,
1624 HostCache::Entry::SOURCE_DNS, ttl),
eroman0cd87b62016-12-14 19:13:451625 bounded_ttl);
1626 }
[email protected]b3601bc22012-02-21 21:23:201627 }
1628
dchengb03027d2014-10-21 12:00:201629 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501630 DCHECK(dns_task_->needs_two_transactions());
1631 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1632 // No longer need to occupy two dispatcher slots.
1633 ReduceToOneJobSlot();
1634
1635 // We already have a job slot at the dispatcher, so if the second
1636 // transaction hasn't started, reuse it now instead of waiting in the queue
1637 // for the second slot.
1638 if (dns_task_->needs_another_transaction())
1639 dns_task_->StartSecondTransaction();
1640 }
1641
Miriam Gershenson61604662017-09-28 23:51:111642 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581643 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1644 // deprecated values.
1645 enum Category {
1646 RESOLVE_SUCCESS = 0,
1647 RESOLVE_FAIL = 1,
1648 RESOLVE_SPECULATIVE_SUCCESS = 2,
1649 RESOLVE_SPECULATIVE_FAIL = 3,
1650 RESOLVE_ABORT = 4,
1651 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111652 RESOLVE_MAX, // Bounding value.
1653 };
1654 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1655
1656 base::TimeDelta duration = base::TimeTicks::Now() - start_time_;
1657 if (error == OK) {
1658 if (had_non_speculative_request_) {
1659 category = RESOLVE_SUCCESS;
1660 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
1661 switch (key_.address_family) {
1662 case ADDRESS_FAMILY_IPV4:
1663 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1664 duration);
1665 break;
1666 case ADDRESS_FAMILY_IPV6:
1667 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1668 duration);
1669 break;
1670 case ADDRESS_FAMILY_UNSPECIFIED:
1671 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1672 duration);
1673 break;
1674 }
1675 } else {
1676 category = RESOLVE_SPECULATIVE_SUCCESS;
1677 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.Speculative",
1678 duration);
1679 }
Miriam Gershensonc282ab42017-11-20 23:19:581680 } else if (error == ERR_NETWORK_CHANGED ||
1681 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1682 category = had_non_speculative_request_ ? RESOLVE_ABORT
1683 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111684 } else {
1685 if (had_non_speculative_request_) {
1686 category = RESOLVE_FAIL;
1687 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
1688 switch (key_.address_family) {
1689 case ADDRESS_FAMILY_IPV4:
Miriam Gershensonc282ab42017-11-20 23:19:581690 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111691 duration);
1692 break;
1693 case ADDRESS_FAMILY_IPV6:
Miriam Gershensonc282ab42017-11-20 23:19:581694 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111695 duration);
1696 break;
1697 case ADDRESS_FAMILY_UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581698 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111699 duration);
1700 break;
1701 }
1702 } else {
1703 category = RESOLVE_SPECULATIVE_FAIL;
1704 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.Speculative",
1705 duration);
1706 }
1707 }
1708 DCHECK_LT(static_cast<int>(category),
1709 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1710 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061711
1712 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1713 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181714 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061715 else
Ilya Sherman0eb39802017-12-08 20:58:181716 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061717 }
Miriam Gershenson61604662017-09-28 23:51:111718 }
1719
[email protected]16ee26d2012-03-08 03:34:351720 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171721 void CompleteRequests(const HostCache::Entry& entry,
1722 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211723 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201724
[email protected]16ee26d2012-03-08 03:34:351725 // This job must be removed from resolver's |jobs_| now to make room for a
1726 // new job with the same key in case one of the OnComplete callbacks decides
1727 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1728 // is done.
danakj22f90e72016-04-16 01:55:401729 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351730
1731 resolver_->RemoveJob(this);
1732
[email protected]16ee26d2012-03-08 03:34:351733 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351734 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501735 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351736 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041737 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351738 }
[email protected]daae1322013-09-05 18:26:501739 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351740
1741 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001742 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351743 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001744 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351745 handle_.Reset();
1746 }
1747
1748 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001749 net_log_.AddEvent(NetLogEventType::CANCELLED);
1750 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351751 OK);
1752 return;
1753 }
[email protected]b3601bc22012-02-21 21:23:201754
mikecirone8b85c432016-09-08 19:11:001755 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221756 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391757
juliatuttled7fa5852016-07-29 13:16:571758 resolver_->SchedulePersist();
1759
[email protected]78eac2a2012-03-14 19:09:271760 DCHECK(!requests_.empty());
1761
eroman1efc237c2016-12-14 00:00:451762 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191763 // Record this histogram here, when we know the system has a valid DNS
1764 // configuration.
[email protected]539df6c2012-06-19 21:21:291765 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1766 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191767 }
[email protected]16ee26d2012-03-08 03:34:351768
juliatuttle317860e2016-05-12 14:47:221769 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1770 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Miriam Gershensonc282ab42017-11-20 23:19:581771 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431772 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581773
1774 RecordJobHistograms(entry.error());
[email protected]16ee26d2012-03-08 03:34:351775
maksim.sisov31452af2016-07-27 06:38:101776 // Complete all of the requests that were attached to the job and
1777 // detach them.
1778 while (!requests_.empty()) {
1779 RequestImpl* req = requests_.front();
1780 requests_.pop_front();
[email protected]0f292de02012-02-01 22:28:201781 DCHECK_EQ(this, req->job());
1782 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221783 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291784 if (did_complete) {
[email protected]51b9a6b2012-06-25 21:50:291785 // Record effective total time from creation to completion.
Miriam Gershenson90d05e02017-09-28 19:29:281786 RecordTotalTime(req->info().is_speculative(), false,
[email protected]51b9a6b2012-06-25 21:50:291787 base::TimeTicks::Now() - req->request_time());
1788 }
maksim.sisov31452af2016-07-27 06:38:101789 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201790
1791 // Check if the resolver was destroyed as a result of running the
1792 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211793 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201794 return;
1795 }
1796 }
1797
[email protected]1339a2a22012-10-17 08:39:431798 // Convenience wrapper for CompleteRequests in case of failure.
1799 void CompleteRequestsWithError(int net_error) {
Rob Percival94f21ad2017-11-14 10:20:241800 CompleteRequests(HostCache::Entry(net_error, AddressList(),
1801 HostCache::Entry::SOURCE_UNKNOWN),
[email protected]895123222012-10-25 15:21:171802 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431803 }
1804
[email protected]b4481b222012-03-16 17:13:111805 RequestPriority priority() const {
1806 return priority_tracker_.highest_priority();
1807 }
1808
1809 // Number of non-canceled requests in |requests_|.
1810 size_t num_active_requests() const {
1811 return priority_tracker_.total_count();
1812 }
1813
wezb9820d42016-06-22 23:41:041814 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111815
wezb9820d42016-06-22 23:41:041816 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111817
[email protected]0f292de02012-02-01 22:28:201818 base::WeakPtr<HostResolverImpl> resolver_;
1819
1820 Key key_;
1821
1822 // Tracks the highest priority across |requests_|.
1823 PriorityTracker priority_tracker_;
1824
Miriam Gershensone42adb22017-10-16 16:19:381825 // Task runner used for HostResolverProc.
1826 scoped_refptr<base::TaskRunner> proc_task_runner_;
1827
[email protected]0f292de02012-02-01 22:28:201828 bool had_non_speculative_request_;
1829
[email protected]51b9a6b2012-06-25 21:50:291830 // Distinguishes measurements taken while DnsClient was fully configured.
1831 bool had_dns_config_;
1832
[email protected]daae1322013-09-05 18:26:501833 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1834 unsigned num_occupied_job_slots_;
1835
[email protected]1d932852012-06-19 19:40:331836 // Result of DnsTask.
1837 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001838
[email protected]51b9a6b2012-06-25 21:50:291839 const base::TimeTicks creation_time_;
1840 base::TimeTicks priority_change_time_;
Miriam Gershenson61604662017-09-28 23:51:111841 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:291842
tfarina428341112016-09-22 13:38:201843 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201844
[email protected]b3601bc22012-02-21 21:23:201845 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201846 scoped_refptr<ProcTask> proc_task_;
1847
[email protected]b3601bc22012-02-21 21:23:201848 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401849 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201850
[email protected]0f292de02012-02-01 22:28:201851 // All Requests waiting for the result of this Job. Some can be canceled.
Brett Wilsonc6a0c822017-09-12 00:04:291852 base::circular_deque<RequestImpl*> requests_;
[email protected]0f292de02012-02-01 22:28:201853
[email protected]16ee26d2012-03-08 03:34:351854 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201855 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391856};
1857
1858//-----------------------------------------------------------------------------
1859
[email protected]0f292de02012-02-01 22:28:201860HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431861 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201862 size_t max_retry_attempts)
1863 : resolver_proc(resolver_proc),
1864 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441865 unresponsive_delay(
1866 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201867 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001868 // Maximum of 4 retry attempts for host resolution.
1869 static const size_t kDefaultMaxRetryAttempts = 4u;
1870 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1871 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201872}
1873
vmpstracd23b72016-02-26 21:08:551874HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1875 default;
1876
Chris Watkins68b15032017-12-01 03:07:131877HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:201878
[email protected]b59ff372009-07-15 22:04:321879HostResolverImpl::~HostResolverImpl() {
gab47aa7da2017-06-02 16:09:431880 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]daae1322013-09-05 18:26:501881 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001882 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541883 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501884 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541885 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431886
[email protected]232a5812011-03-04 22:42:081887 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441888 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401889 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321890}
1891
[email protected]0f292de02012-02-01 22:28:201892void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001893 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201894 DCHECK_GT(value, 0u);
1895 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131896}
1897
[email protected]684970b2009-08-14 04:54:461898int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101899 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321900 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291901 const CompletionCallback& callback,
maksim.sisov31452af2016-07-27 06:38:101902 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:201903 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401904 DCHECK(addresses);
gab47aa7da2017-06-02 16:09:431905 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]aa22b242011-11-16 18:58:291906 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:101907 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:141908
Chris Palmer9cbf4212017-07-19 01:54:551909 LogStartRequest(source_net_log, info);
pauljensen19eb73422015-04-15 23:20:061910
Matt Menke23b4bbf82017-07-20 19:11:291911 Key key;
1912 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:401913 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021914 LogFinishRequest(source_net_log, info, rv);
Miriam Gershenson90d05e02017-09-28 19:29:281915 RecordTotalTime(info.is_speculative(), true, base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401916 return rv;
[email protected]38368712011-03-02 08:09:401917 }
1918
[email protected]0f292de02012-02-01 22:28:201919 // Next we need to attach our request to a "job". This job is responsible for
1920 // calling "getaddrinfo(hostname)" on a worker thread.
1921
avi9e72eb482016-12-09 21:10:541922 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:201923 Job* job;
1924 if (jobit == jobs_.end()) {
Miriam Gershensone42adb22017-10-16 16:19:381925 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
1926 proc_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:501927 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201928
1929 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001930 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1931 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201932 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351933 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201934 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201935 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021936 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201937 return rv;
1938 }
[email protected]0f292de02012-02-01 22:28:201939 }
avi9e72eb482016-12-09 21:10:541940 jobs_[key] = base::WrapUnique(job);
[email protected]0f292de02012-02-01 22:28:201941 } else {
avi9e72eb482016-12-09 21:10:541942 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:201943 }
1944
1945 // Can't complete synchronously. Create and attach request.
Jeremy Roman0579ed62017-08-29 15:56:191946 auto req = std::make_unique<RequestImpl>(source_net_log, info, priority,
avi9e72eb482016-12-09 21:10:541947 callback, addresses, job);
maksim.sisov31452af2016-07-27 06:38:101948 job->AddRequest(req.get());
1949 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:321950
[email protected]0f292de02012-02-01 22:28:201951 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321952 return ERR_IO_PENDING;
1953}
1954
Francois Doraya2d01ba2017-09-25 19:17:401955HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231956 : max_queued_jobs_(0),
1957 proc_params_(NULL, options.max_retry_attempts),
1958 net_log_(net_log),
1959 received_dns_config_(false),
1960 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:031961 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:231962 use_local_ipv6_(false),
1963 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:231964 additional_resolver_flags_(0),
1965 fallback_to_proctask_(true),
juliatuttled7fa5852016-07-29 13:16:571966 persist_initialized_(false),
mmenke91c17162016-06-02 16:03:231967 weak_ptr_factory_(this),
1968 probe_weak_ptr_factory_(this) {
1969 if (options.enable_caching)
1970 cache_ = HostCache::CreateDefaultCache();
1971
1972 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1973 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1974 max_queued_jobs_ = job_limits.total_jobs * 100u;
1975
1976 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
1977
Miriam Gershensone42adb22017-10-16 16:19:381978 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
1979 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
1980
mmenke91c17162016-06-02 16:03:231981#if defined(OS_WIN)
1982 EnsureWinsockInit();
1983#endif
1984#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
1985 RunLoopbackProbeJob();
1986#endif
1987 NetworkChangeNotifier::AddIPAddressObserver(this);
1988 NetworkChangeNotifier::AddConnectionTypeObserver(this);
1989 NetworkChangeNotifier::AddDNSObserver(this);
1990#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Sergey Ulanov49085572017-07-10 23:25:461991 !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:231992 EnsureDnsReloaderInit();
1993#endif
1994
1995 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
1996
1997 {
1998 DnsConfig dns_config;
1999 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2000 received_dns_config_ = dns_config.IsValid();
2001 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2002 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2003 }
2004
2005 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2006}
2007
2008void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2009 if (result) {
2010 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2011 } else {
2012 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2013 }
2014}
2015
Miriam Gershensone42adb22017-10-16 16:19:382016void HostResolverImpl::SetTaskRunnerForTesting(
2017 scoped_refptr<base::TaskRunner> task_runner) {
2018 proc_task_runner_ = std::move(task_runner);
2019}
2020
Matt Menke23b4bbf82017-07-20 19:11:292021int HostResolverImpl::ResolveHelper(const RequestInfo& info,
juliatuttle9fb7aeb2016-06-06 20:16:332022 bool allow_stale,
2023 HostCache::EntryStaleness* stale_info,
Matt Menke23b4bbf82017-07-20 19:11:292024 const NetLogWithSource& source_net_log,
2025 AddressList* addresses,
2026 Key* key) {
2027 IPAddress ip_address;
2028 IPAddress* ip_address_ptr = nullptr;
2029 if (ip_address.AssignFromIPLiteral(info.hostname())) {
2030 ip_address_ptr = &ip_address;
2031 } else {
2032 // Check that the caller supplied a valid hostname to resolve.
2033 if (!IsValidDNSDomain(info.hostname()))
2034 return ERR_NAME_NOT_RESOLVED;
2035 }
2036
2037 // Build a key that identifies the request in the cache and in the
2038 // outstanding jobs map.
2039 *key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2040
juliatuttle9fb7aeb2016-06-06 20:16:332041 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402042 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2043 // On Windows it gives the default interface's address, whereas on Linux it
2044 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332045 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2046 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402047 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332048 }
[email protected]95a214c2011-08-04 21:50:402049
2050 int net_error = ERR_UNEXPECTED;
Matt Menke23b4bbf82017-07-20 19:11:292051 if (ResolveAsIP(*key, info, ip_address_ptr, &net_error, addresses)) {
juliatuttle9fb7aeb2016-06-06 20:16:332052 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402053 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332054 }
Mike Westda1c690e2017-08-12 05:57:162055
2056 // Special-case localhost names, as per the recommendations in
2057 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2058 if (ServeLocalhost(*key, info, addresses)) {
2059 MakeNotStale(stale_info);
2060 return OK;
2061 }
2062
Matt Menke23b4bbf82017-07-20 19:11:292063 if (ServeFromCache(*key, info, &net_error, addresses, allow_stale,
juliatuttle9fb7aeb2016-06-06 20:16:332064 stale_info)) {
mgersh33d23c02017-03-29 20:24:252065 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2066 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332067 // |ServeFromCache()| will set |*stale_info| as needed.
[email protected]78eac2a2012-03-14 19:09:272068 return net_error;
2069 }
Mike Westda1c690e2017-08-12 05:57:162070
[email protected]78eac2a2012-03-14 19:09:272071 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2072 // http://crbug.com/117655
Matt Menke23b4bbf82017-07-20 19:11:292073 if (ServeFromHosts(*key, info, addresses)) {
mgersh33d23c02017-03-29 20:24:252074 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2075 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332076 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272077 return OK;
2078 }
estarkd1bc206e2015-06-20 00:44:392079
[email protected]78eac2a2012-03-14 19:09:272080 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402081}
2082
2083int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2084 AddressList* addresses,
tfarina428341112016-09-22 13:38:202085 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432086 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402087 DCHECK(addresses);
2088
[email protected]95a214c2011-08-04 21:50:402089 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022090 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402091
Matt Menke23b4bbf82017-07-20 19:11:292092 Key key;
2093 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402094
xunjieli26f90452014-11-10 16:23:022095 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402096 return rv;
2097}
2098
[email protected]a8883e452012-11-17 05:58:062099void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432100 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062101#if defined(ENABLE_BUILT_IN_DNS)
2102 if (enabled && !dns_client_) {
2103 SetDnsClient(DnsClient::CreateClient(net_log_));
2104 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402105 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062106 }
2107#endif
2108}
2109
[email protected]489d1a82011-10-12 03:09:112110HostCache* HostResolverImpl::GetHostCache() {
2111 return cache_.get();
2112}
[email protected]95a214c2011-08-04 21:50:402113
danakj22f90e72016-04-16 01:55:402114std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242115 // Check if async DNS is disabled.
2116 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082117 return nullptr;
[email protected]17e92032012-03-29 00:56:242118
2119 // Check if async DNS is enabled, but we currently have no configuration
2120 // for it.
2121 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042122 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192123 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242124
2125 return dns_config->ToValue();
2126}
2127
juliatuttle9fb7aeb2016-06-06 20:16:332128int HostResolverImpl::ResolveStaleFromCache(
2129 const RequestInfo& info,
2130 AddressList* addresses,
2131 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202132 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432133 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
juliatuttle9fb7aeb2016-06-06 20:16:332134 DCHECK(addresses);
2135 DCHECK(stale_info);
2136
2137 // Update the net log and notify registered observers.
2138 LogStartRequest(source_net_log, info);
2139
Matt Menke23b4bbf82017-07-20 19:11:292140 Key key;
2141 int rv =
2142 ResolveHelper(info, true, stale_info, source_net_log, addresses, &key);
juliatuttle9fb7aeb2016-06-06 20:16:332143 LogFinishRequest(source_net_log, info, rv);
2144 return rv;
2145}
2146
Miriam Gershenson2839ef112017-08-30 03:25:372147size_t HostResolverImpl::LastRestoredCacheSize() const {
2148 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2149
2150 return cache_ ? cache_->last_restore_size() : 0;
2151}
2152
2153size_t HostResolverImpl::CacheSize() const {
2154 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2155
2156 return cache_ ? cache_->size() : 0;
2157}
2158
mgershaf9a9232017-04-13 20:19:032159void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432160 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032161 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2162}
2163
2164bool HostResolverImpl::GetNoIPv6OnWifi() {
2165 return assume_ipv6_failure_on_wifi_;
2166}
2167
[email protected]95a214c2011-08-04 21:50:402168bool HostResolverImpl::ResolveAsIP(const Key& key,
2169 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512170 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402171 int* net_error,
2172 AddressList* addresses) {
2173 DCHECK(addresses);
2174 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512175 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402176 return false;
2177
[email protected]95a214c2011-08-04 21:50:402178 *net_error = OK;
martijna23c8962016-03-04 18:18:512179 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252180 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2181 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482182 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402183 *net_error = ERR_NAME_NOT_RESOLVED;
2184 } else {
martijna23c8962016-03-04 18:18:512185 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562186 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2187 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402188 }
2189 return true;
2190}
2191
2192bool HostResolverImpl::ServeFromCache(const Key& key,
2193 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402194 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332195 AddressList* addresses,
2196 bool allow_stale,
2197 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402198 DCHECK(addresses);
2199 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332200 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402201 if (!info.allow_cached_response() || !cache_.get())
2202 return false;
2203
juliatuttle9fb7aeb2016-06-06 20:16:332204 const HostCache::Entry* cache_entry;
2205 if (allow_stale)
2206 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2207 else
2208 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402209 if (!cache_entry)
2210 return false;
2211
juliatuttle317860e2016-05-12 14:47:222212 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562213 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432214 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222215 RecordTTL(cache_entry->ttl());
2216 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562217 }
[email protected]95a214c2011-08-04 21:50:402218 return true;
2219}
2220
[email protected]78eac2a2012-03-14 19:09:272221bool HostResolverImpl::ServeFromHosts(const Key& key,
2222 const RequestInfo& info,
2223 AddressList* addresses) {
2224 DCHECK(addresses);
2225 if (!HaveDnsConfig())
2226 return false;
[email protected]05a79d42013-03-28 07:30:092227 addresses->clear();
2228
[email protected]cb507622012-03-23 16:17:062229 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222230 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062231
[email protected]05a79d42013-03-28 07:30:092232 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2233
[email protected]78eac2a2012-03-14 19:09:272234 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2235 // (glibc and c-ares) return the first matching line. We have more
2236 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092237 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2238 // necessary.
2239 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2240 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2241 DnsHosts::const_iterator it = hosts.find(
2242 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2243 if (it != hosts.end())
2244 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272245 }
2246
[email protected]05a79d42013-03-28 07:30:092247 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2248 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2249 DnsHosts::const_iterator it = hosts.find(
2250 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2251 if (it != hosts.end())
2252 addresses->push_back(IPEndPoint(it->second, info.port()));
2253 }
2254
[email protected]ec666ab22013-04-17 20:05:592255 // If got only loopback addresses and the family was restricted, resolve
2256 // again, without restrictions. See SystemHostResolverCall for rationale.
2257 if ((key.host_resolver_flags &
2258 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2259 IsAllIPv4Loopback(*addresses)) {
2260 Key new_key(key);
2261 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2262 new_key.host_resolver_flags &=
2263 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2264 return ServeFromHosts(new_key, info, addresses);
2265 }
[email protected]05a79d42013-03-28 07:30:092266 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272267}
2268
estarkd1bc206e2015-06-20 00:44:392269bool HostResolverImpl::ServeLocalhost(const Key& key,
2270 const RequestInfo& info,
2271 AddressList* addresses) {
2272 AddressList resolved_addresses;
2273 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2274 return false;
2275
2276 addresses->clear();
2277
2278 for (const auto& address : resolved_addresses) {
2279 // Include the address if:
2280 // - caller didn't specify an address family, or
2281 // - caller specifically asked for the address family of this address, or
2282 // - this is an IPv6 address and caller specifically asked for IPv4 due
2283 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2284 // rationale).
2285 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2286 key.address_family == address.GetFamily() ||
2287 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2288 key.address_family == ADDRESS_FAMILY_IPV4 &&
2289 (key.host_resolver_flags &
2290 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2291 addresses->push_back(address);
2292 }
2293 }
2294
2295 return true;
2296}
2297
[email protected]16ee26d2012-03-08 03:34:352298void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432299 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352300 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052301 // Don't cache an error unless it has a positive TTL.
2302 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
[email protected]1339a2a22012-10-17 08:39:432303 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032304}
2305
[email protected]0f292de02012-02-01 22:28:202306void HostResolverImpl::RemoveJob(Job* job) {
2307 DCHECK(job);
avi9e72eb482016-12-09 21:10:542308 auto it = jobs_.find(job->key());
2309 if (it != jobs_.end() && it->second.get() == job) {
2310 it->second.release();
[email protected]16ee26d2012-03-08 03:34:352311 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542312 }
[email protected]b59ff372009-07-15 22:04:322313}
2314
[email protected]137af622010-02-05 02:14:352315HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062316 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512317 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202318 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272319 HostResolverFlags effective_flags =
2320 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352321 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512322
mgersh3eba057d2017-02-28 18:50:562323 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2324 // When resolving IPv4 literals, there's no need to probe for IPv6.
2325 // When resolving IPv6 literals, there's no benefit to artificially
2326 // limiting our resolution based on a probe. Prior logic ensures
2327 // that this query is UNSPECIFIED (see effective_address_family
2328 // check above) so the code requesting the resolution should be amenable
2329 // to receiving a IPv6 resolution.
2330 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2331 effective_address_family = ADDRESS_FAMILY_IPV4;
2332 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512333 }
2334
estarkd1bc206e2015-06-20 00:44:392335 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352336}
2337
tfarina428341112016-09-22 13:38:202338bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032339 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2340 // work on WiFi.
2341 if (assume_ipv6_failure_on_wifi_ &&
2342 NetworkChangeNotifier::GetConnectionType() ==
2343 NetworkChangeNotifier::CONNECTION_WIFI) {
2344 return false;
2345 }
2346
eroman1a17ef32016-12-14 01:06:092347 // Cache the result for kIPv6ProbePeriodMs (measured from after
2348 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372349 bool cached = true;
eroman1a17ef32016-12-14 01:06:092350 if ((base::TimeTicks::Now() - last_ipv6_probe_time_).InMilliseconds() >
2351 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512352 last_ipv6_probe_result_ =
2353 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
eroman1a17ef32016-12-14 01:06:092354 last_ipv6_probe_time_ = base::TimeTicks::Now();
sergeyub8cdc212015-05-14 18:50:372355 cached = false;
2356 }
mikecirone8b85c432016-09-08 19:11:002357 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372358 base::Bind(&NetLogIPv6AvailableCallback,
2359 last_ipv6_probe_result_, cached));
2360 return last_ipv6_probe_result_;
2361}
2362
mgershaf9a9232017-04-13 20:19:032363bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2364 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032365 std::unique_ptr<DatagramClientSocket> socket(
2366 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
2367 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
2368 net_log.source()));
2369 int rv = socket->Connect(IPEndPoint(dest, 53));
2370 if (rv != OK)
2371 return false;
2372 IPEndPoint endpoint;
2373 rv = socket->GetLocalAddress(&endpoint);
2374 if (rv != OK)
2375 return false;
2376 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2377 const IPAddress& address = endpoint.address();
2378
2379 bool is_link_local =
2380 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2381 if (is_link_local)
2382 return false;
2383
2384 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2385 if (IPAddressStartsWith(address, kTeredoPrefix))
2386 return false;
2387
2388 return true;
2389}
2390
mmenke91c17162016-06-02 16:03:232391void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402392 // Run this asynchronously as it can take 40-100ms and should not block
2393 // initialization.
2394 base::PostTaskWithTraitsAndReplyWithResult(
2395 FROM_HERE,
2396 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2397 base::BindOnce(&HaveOnlyLoopbackAddresses),
2398 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2399 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232400}
2401
[email protected]35ddc282010-09-21 23:42:062402void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202403 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2404 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402405 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542406 for (auto it = jobs_.begin(); it != jobs_.end();) {
2407 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202408 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542409 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202410 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202411 } else {
[email protected]b3601bc22012-02-21 21:23:202412 DCHECK(job->is_queued());
2413 ++it;
[email protected]0f292de02012-02-01 22:28:202414 }
[email protected]ef4c40c2010-09-01 14:42:032415 }
[email protected]b3601bc22012-02-21 21:23:202416
[email protected]daae1322013-09-05 18:26:502417 // Pause the dispatcher so it won't start any new dispatcher jobs while
2418 // aborting the old ones. This is needed so that it won't start the second
2419 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2420 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002421 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2422 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502423 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122424
[email protected]57a48d32012-03-03 00:04:552425 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072426 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552427
[email protected]16ee26d2012-03-08 03:34:352428 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212429 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552430 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112431 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202432 }
[email protected]daae1322013-09-05 18:26:502433
2434 if (self)
[email protected]106ccd2c2014-06-17 09:21:002435 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502436}
2437
2438void HostResolverImpl::AbortDnsTasks() {
2439 // Pause the dispatcher so it won't start any new dispatcher jobs while
2440 // aborting the old ones. This is needed so that it won't start the second
2441 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002442 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2443 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502444 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2445
avi9e72eb482016-12-09 21:10:542446 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502447 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002448 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032449}
2450
[email protected]78eac2a2012-03-14 19:09:272451void HostResolverImpl::TryServingAllJobsFromHosts() {
2452 if (!HaveDnsConfig())
2453 return;
2454
2455 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2456 // http://crbug.com/117655
2457
2458 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072459 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272460
avi9e72eb482016-12-09 21:10:542461 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2462 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272463 ++it;
2464 // This could remove |job| from |jobs_|, but iterator will remain valid.
2465 job->ServeFromHosts();
2466 }
2467}
2468
[email protected]be1a48b2011-01-20 00:12:132469void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372470 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182471 // Abandon all ProbeJobs.
2472 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172473 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102474 cache_->OnNetworkChange();
[email protected]7c466e92013-07-20 01:44:482475#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232476 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132477#endif
2478 AbortAllInProgressJobs();
2479 // |this| may be deleted inside AbortAllInProgressJobs().
2480}
2481
ttuttlecf1158bf2016-03-18 16:37:442482void HostResolverImpl::OnConnectionTypeChanged(
2483 NetworkChangeNotifier::ConnectionType type) {
2484 proc_params_.unresponsive_delay =
2485 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2486 "DnsUnresponsiveDelayMsByConnectionType",
2487 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2488 type);
2489}
2490
pauljensen101ed372015-04-17 00:11:422491void HostResolverImpl::OnInitialDNSConfigRead() {
2492 UpdateDNSConfig(false);
2493}
2494
[email protected]bb0e34542012-08-31 19:52:402495void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422496 UpdateDNSConfig(true);
2497}
2498
2499void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402500 DnsConfig dns_config;
2501 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592502
[email protected]b4481b222012-03-16 17:13:112503 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002504 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2505 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112506 }
2507
[email protected]01b3b9d2012-08-13 16:18:142508 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192509 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522510 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2511 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272512
[email protected]a8883e452012-11-17 05:58:062513 num_dns_failures_ = 0;
2514
[email protected]01b3b9d2012-08-13 16:18:142515 // We want a new DnsSession in place, before we Abort running Jobs, so that
2516 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022517 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252518 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532519 // wasn't already a DnsConfig or it's the same one.
2520 DCHECK(config_changed || !dns_client_->GetConfig() ||
2521 dns_client_->GetConfig()->Equals(dns_config));
[email protected]d7b9a2b2012-05-31 22:31:192522 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252523 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022524 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022525 }
[email protected]01b3b9d2012-08-13 16:18:142526
pauljensen101ed372015-04-17 00:11:422527 if (config_changed) {
2528 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232529 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422530 // as NSCD's cache should be dropped automatically by the OS when
2531 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172532 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232533 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142534
pauljensen101ed372015-04-17 00:11:422535 // Life check to bail once |this| is deleted.
2536 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022537
pauljensen101ed372015-04-17 00:11:422538 // Existing jobs will have been sent to the original server so they need to
2539 // be aborted.
2540 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142541
pauljensen101ed372015-04-17 00:11:422542 // |this| may be deleted inside AbortAllInProgressJobs().
2543 if (self.get())
2544 TryServingAllJobsFromHosts();
2545 }
[email protected]78eac2a2012-03-14 19:09:272546}
2547
2548bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252549 // Use DnsClient only if it's fully configured and there is no override by
2550 // ScopedDefaultHostResolverProc.
2551 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2552 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042553 return dns_client_ && dns_client_->GetConfig() &&
2554 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202555}
2556
[email protected]1ffdda82012-12-12 23:04:222557void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022558 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222559 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022560 num_dns_failures_ = 0;
2561 return;
2562 }
2563 ++num_dns_failures_;
2564 if (num_dns_failures_ < kMaximumDnsFailures)
2565 return;
[email protected]daae1322013-09-05 18:26:502566
2567 // Disable DnsClient until the next DNS change. Must be done before aborting
2568 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022569 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502570
2571 // Switch jobs with active DnsTasks over to using ProcTasks.
2572 AbortDnsTasks();
2573
[email protected]f0f602bd2012-11-15 18:01:022574 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:182575 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
2576 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022577}
2578
danakj22f90e72016-04-16 01:55:402579void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502580 // DnsClient and config must be updated before aborting DnsTasks, since doing
2581 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482582 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502583 if (dns_client_ && !dns_client_->GetConfig() &&
2584 num_dns_failures_ < kMaximumDnsFailures) {
2585 DnsConfig dns_config;
2586 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2587 dns_client_->SetConfig(dns_config);
2588 num_dns_failures_ = 0;
2589 if (dns_client_->GetConfig())
2590 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062591 }
[email protected]daae1322013-09-05 18:26:502592
2593 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062594}
2595
juliatuttled7fa5852016-07-29 13:16:572596void HostResolverImpl::InitializePersistence(
2597 const PersistCallback& persist_callback,
2598 std::unique_ptr<const base::Value> old_data) {
2599 DCHECK(!persist_initialized_);
2600 persist_callback_ = persist_callback;
2601 persist_initialized_ = true;
2602 if (old_data)
2603 ApplyPersistentData(std::move(old_data));
2604}
2605
juliatuttle7e8bf1c2016-08-02 19:09:092606void HostResolverImpl::ApplyPersistentData(
2607 std::unique_ptr<const base::Value> data) {}
2608
2609std::unique_ptr<const base::Value> HostResolverImpl::GetPersistentData() {
2610 return std::unique_ptr<const base::Value>();
2611}
2612
juliatuttled7fa5852016-07-29 13:16:572613void HostResolverImpl::SchedulePersist() {
2614 if (!persist_initialized_ || persist_timer_.IsRunning())
2615 return;
2616 persist_timer_.Start(
2617 FROM_HERE, base::TimeDelta::FromSeconds(kPersistDelaySec),
2618 base::Bind(&HostResolverImpl::DoPersist, weak_ptr_factory_.GetWeakPtr()));
2619}
2620
2621void HostResolverImpl::DoPersist() {
2622 DCHECK(persist_initialized_);
2623 persist_callback_.Run(GetPersistentData());
2624}
2625
maksim.sisov31452af2016-07-27 06:38:102626HostResolverImpl::RequestImpl::~RequestImpl() {
2627 if (job_)
2628 job_->CancelRequest(this);
2629}
2630
2631void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2632 RequestPriority priority) {
2633 job_->ChangeRequestPriority(this, priority);
2634}
2635
[email protected]b59ff372009-07-15 22:04:322636} // namespace net