blob: 161f740b21de0d1192267b95e42e3c6e90280bc2 [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"
[email protected]58580352010-10-26 04:07:5033#include "base/debug/debugger.h"
[email protected]58580352010-10-26 04:07:5034#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4635#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2336#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4537#include "base/metrics/field_trial.h"
davidbenad6fc442015-05-18 20:59:1338#include "base/metrics/histogram_macros.h"
39#include "base/metrics/sparse_histogram.h"
eromane1867242015-04-23 23:07:4440#include "base/profiler/scoped_tracker.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"
gabf767595f2016-05-11 18:50:3544#include "base/threading/thread_task_runner_handle.h"
[email protected]ac9ba8fe2010-12-30 18:08:3645#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3146#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5647#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4648#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2049#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3250#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5151#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5152#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4853#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1554#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4855#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1856#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4657#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2758#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2059#include "net/dns/dns_config_service.h"
60#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3561#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2062#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2063#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0364#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5365#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0766#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1967#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0068#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1969#include "net/log/net_log_parameters_callback.h"
70#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0071#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1972#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5173#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2674#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1475#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3276
77#if defined(OS_WIN)
78#include "net/base/winsock_init.h"
79#endif
80
tfarinada9e1362017-03-14 16:49:0681#if defined(OS_ANDROID)
82#include "net/android/network_library.h"
83#endif
84
[email protected]b59ff372009-07-15 22:04:3285namespace net {
86
[email protected]e95d3aca2010-01-11 22:47:4387namespace {
88
ttuttlecf1158bf2016-03-18 16:37:4489// Default delay between calls to the system resolver for the same hostname.
90// (Can be overridden by field trial.)
91const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
92
[email protected]6e78dfb2011-07-28 21:34:4793// Limit the size of hostnames that will be resolved to combat issues in
94// some platform's resolvers.
95const size_t kMaxHostLength = 4096;
96
[email protected]a2730882012-01-21 00:56:2797// Default TTL for successful resolutions with ProcTask.
98const unsigned kCacheEntryTTLSeconds = 60;
99
[email protected]b3601bc22012-02-21 21:23:20100// Default TTL for unsuccessful resolutions with ProcTask.
101const unsigned kNegativeCacheEntryTTLSeconds = 0;
102
[email protected]895123222012-10-25 15:21:17103// Minimum TTL for successful resolutions with DnsTask.
104const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
105
sergeyub8cdc212015-05-14 18:50:37106// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
107// cached.
108const int kIPv6ProbePeriodMs = 1000;
109
110// Google DNS address used for IPv6 probes.
111const uint8_t kIPv6ProbeAddress[] =
112 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
113 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
114
[email protected]24f4bab2010-10-15 01:27:11115// We use a separate histogram name for each platform to facilitate the
116// display of error codes by their symbolic name (since each platform has
117// different mappings).
118const char kOSErrorsForGetAddrinfoHistogramName[] =
119#if defined(OS_WIN)
120 "Net.OSErrorsForGetAddrinfo_Win";
121#elif defined(OS_MACOSX)
122 "Net.OSErrorsForGetAddrinfo_Mac";
123#elif defined(OS_LINUX)
124 "Net.OSErrorsForGetAddrinfo_Linux";
125#else
126 "Net.OSErrorsForGetAddrinfo";
127#endif
128
[email protected]c89b2442011-05-26 14:28:27129// Gets a list of the likely error codes that getaddrinfo() can return
130// (non-exhaustive). These are the error codes that we will track via
131// a histogram.
132std::vector<int> GetAllGetAddrinfoOSErrors() {
133 int os_errors[] = {
134#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51135#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37136#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45137 // EAI_ADDRFAMILY has been declared obsolete in Android's and
138 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27139 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37140#endif
[email protected]c48aef92011-11-22 23:41:45141 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51142 EAI_NODATA,
143#endif
[email protected]c89b2442011-05-26 14:28:27144 EAI_AGAIN,
145 EAI_BADFLAGS,
146 EAI_FAIL,
147 EAI_FAMILY,
148 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27149 EAI_NONAME,
150 EAI_SERVICE,
151 EAI_SOCKTYPE,
152 EAI_SYSTEM,
153#elif defined(OS_WIN)
154 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
155 WSA_NOT_ENOUGH_MEMORY,
156 WSAEAFNOSUPPORT,
157 WSAEINVAL,
158 WSAESOCKTNOSUPPORT,
159 WSAHOST_NOT_FOUND,
160 WSANO_DATA,
161 WSANO_RECOVERY,
162 WSANOTINITIALISED,
163 WSATRY_AGAIN,
164 WSATYPE_NOT_FOUND,
165 // The following are not in doc, but might be to appearing in results :-(.
166 WSA_INVALID_HANDLE,
167#endif
168 };
169
170 // Ensure all errors are positive, as histogram only tracks positive values.
171 for (size_t i = 0; i < arraysize(os_errors); ++i) {
172 os_errors[i] = std::abs(os_errors[i]);
173 }
174
175 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
176 arraysize(os_errors));
177}
178
[email protected]1def74c2012-03-22 20:07:00179enum DnsResolveStatus {
180 RESOLVE_STATUS_DNS_SUCCESS = 0,
181 RESOLVE_STATUS_PROC_SUCCESS,
182 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33183 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00184 RESOLVE_STATUS_MAX
185};
186
eroman91dd3602015-03-26 03:46:33187// ICANN uses this localhost address to indicate a name collision.
188//
189// The policy in Chromium is to fail host resolving if it resolves to
190// this special address.
191//
192// Not however that IP literals are exempt from this policy, so it is still
193// possible to navigate to http://127.0.53.53/ directly.
194//
195// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51196const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33197
eroman1efc237c2016-12-14 00:00:45198bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
199 for (const auto& endpoint : addr_list) {
200 const IPAddress& addr = endpoint.address();
201 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
202 return true;
203 }
204 }
205 return false;
206}
207
[email protected]1def74c2012-03-22 20:07:00208void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
209 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
210 result,
211 RESOLVE_STATUS_MAX);
212}
213
[email protected]1d932852012-06-19 19:40:33214bool ResemblesNetBIOSName(const std::string& hostname) {
215 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
216}
217
218// True if |hostname| ends with either ".local" or ".local.".
219bool ResemblesMulticastDNSName(const std::string& hostname) {
220 DCHECK(!hostname.empty());
221 const char kSuffix[] = ".local.";
222 const size_t kSuffixLen = sizeof(kSuffix) - 1;
223 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36224 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33225 return hostname.size() > kSuffixLen &&
226 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
227 }
228 return hostname.size() > kSuffixLenTrimmed &&
229 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
230 kSuffix, kSuffixLenTrimmed);
231}
232
[email protected]51b9a6b2012-06-25 21:50:29233// Provide a common macro to simplify code and readability. We must use a
234// macro as the underlying HISTOGRAM macro creates static variables.
235#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
236 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
237
238// A macro to simplify code and readability.
239#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
240 do { \
241 switch (priority) { \
242 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
243 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
244 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
245 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
246 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
mmenke2f23b70292016-10-26 23:26:42247 case THROTTLED: DNS_HISTOGRAM(basename "_THROTTLED", time); break; \
[email protected]51b9a6b2012-06-25 21:50:29248 } \
249 DNS_HISTOGRAM(basename, time); \
250 } while (0)
251
252// Record time from Request creation until a valid DNS response.
253void RecordTotalTime(bool had_dns_config,
254 bool speculative,
255 base::TimeDelta duration) {
256 if (had_dns_config) {
257 if (speculative) {
258 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
259 } else {
260 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
261 }
262 } else {
263 if (speculative) {
264 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
265 } else {
266 DNS_HISTOGRAM("DNS.TotalTime", duration);
267 }
268 }
269}
270
[email protected]1339a2a22012-10-17 08:39:43271void RecordTTL(base::TimeDelta ttl) {
272 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
273 base::TimeDelta::FromSeconds(1),
274 base::TimeDelta::FromDays(1), 100);
275}
276
[email protected]16c2bd72013-06-28 01:19:22277bool ConfigureAsyncDnsNoFallbackFieldTrial() {
278 const bool kDefault = false;
279
280 // Configure the AsyncDns field trial as follows:
281 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
282 // groups AsyncDnsA and AsyncDnsB: return false,
283 // groups SystemDnsA and SystemDnsB: return false,
284 // otherwise (trial absent): return default.
285 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29286 if (!group_name.empty()) {
287 return base::StartsWith(group_name, "AsyncDnsNoFallback",
288 base::CompareCase::INSENSITIVE_ASCII);
289 }
[email protected]16c2bd72013-06-28 01:19:22290 return kDefault;
291}
292
[email protected]d7b9a2b2012-05-31 22:31:19293//-----------------------------------------------------------------------------
294
Avi Drissman13fc8932015-12-20 04:40:46295AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17296 if (list.empty() || list.front().port() == port)
297 return list;
298 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56299}
300
[email protected]ec666ab22013-04-17 20:05:59301// Returns true if |addresses| contains only IPv4 loopback addresses.
302bool IsAllIPv4Loopback(const AddressList& addresses) {
303 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51304 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59305 switch (addresses[i].GetFamily()) {
306 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51307 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59308 return false;
309 break;
310 case ADDRESS_FAMILY_IPV6:
311 return false;
312 default:
313 NOTREACHED();
314 return false;
315 }
316 }
317 return true;
318}
319
tfarinada9e1362017-03-14 16:49:06320// Returns true if it can determine that only loopback addresses are configured.
321// i.e. if only 127.0.0.1 and ::1 are routable.
322// Also returns false if it cannot determine this.
323bool HaveOnlyLoopbackAddresses() {
324#if defined(OS_ANDROID)
325 return android::HaveOnlyLoopbackAddresses();
326#elif defined(OS_NACL)
327 NOTIMPLEMENTED();
328 return false;
329#elif defined(OS_POSIX)
330 struct ifaddrs* interface_addr = NULL;
331 int rv = getifaddrs(&interface_addr);
332 if (rv != 0) {
333 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
334 return false;
335 }
336
337 bool result = true;
338 for (struct ifaddrs* interface = interface_addr;
339 interface != NULL;
340 interface = interface->ifa_next) {
341 if (!(IFF_UP & interface->ifa_flags))
342 continue;
343 if (IFF_LOOPBACK & interface->ifa_flags)
344 continue;
345 const struct sockaddr* addr = interface->ifa_addr;
346 if (!addr)
347 continue;
348 if (addr->sa_family == AF_INET6) {
349 // Safe cast since this is AF_INET6.
350 const struct sockaddr_in6* addr_in6 =
351 reinterpret_cast<const struct sockaddr_in6*>(addr);
352 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
353 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
354 continue;
355 }
356 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
357 continue;
358
359 result = false;
360 break;
361 }
362 freeifaddrs(interface_addr);
363 return result;
364#elif defined(OS_WIN)
365 // TODO(wtc): implement with the GetAdaptersAddresses function.
366 NOTIMPLEMENTED();
367 return false;
368#else
369 NOTIMPLEMENTED();
370 return false;
371#endif // defined(various platforms)
372}
373
[email protected]cd565142012-06-12 16:21:45374// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40375std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46376 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17377 int net_error,
378 int os_error,
379 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40380 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45381 if (attempt_number)
382 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46383
[email protected]cd565142012-06-12 16:21:45384 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16385
[email protected]cd565142012-06-12 16:21:45386 if (os_error) {
387 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46388#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45389 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46390#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45391 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04392 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08393 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
394 0, // Use the internal message table.
395 os_error,
396 0, // Use default language.
397 (LPWSTR)&error_string,
398 0, // Buffer size.
399 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01400 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45401 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46402#endif
[email protected]21526002010-05-16 19:42:46403 }
404
dchengc7eeda422015-12-26 03:56:48405 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45406}
[email protected]a9813302012-04-28 09:29:28407
[email protected]cd565142012-06-12 16:21:45408// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40409std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11410 int net_error,
411 int dns_error,
412 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40413 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45414 dict->SetInteger("net_error", net_error);
415 if (dns_error)
416 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48417 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36418}
[email protected]ee094b82010-08-24 15:55:51419
[email protected]cd565142012-06-12 16:21:45420// Creates NetLog parameters containing the information in a RequestInfo object,
mikecironef22f9812016-10-04 03:40:19421// along with the associated NetLogSource.
danakj22f90e72016-04-16 01:55:40422std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11423 const HostResolver::RequestInfo* info,
424 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40425 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20426
[email protected]cd565142012-06-12 16:21:45427 dict->SetString("host", info->host_port_pair().ToString());
428 dict->SetInteger("address_family",
429 static_cast<int>(info->address_family()));
430 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
431 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48432 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45433}
[email protected]b3601bc22012-02-21 21:23:20434
[email protected]cd565142012-06-12 16:21:45435// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40436std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19437 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11438 const std::string* host,
439 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40440 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11441 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45442 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48443 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45444}
[email protected]a9813302012-04-28 09:29:28445
[email protected]cd565142012-06-12 16:21:45446// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40447std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19448 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11449 RequestPriority priority,
450 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40451 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11452 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56453 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48454 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45455}
[email protected]b3601bc22012-02-21 21:23:20456
[email protected]cd565142012-06-12 16:21:45457// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40458std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11459 const DnsConfig* config,
460 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08461 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45462}
[email protected]b4481b222012-03-16 17:13:11463
danakj22f90e72016-04-16 01:55:40464std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11465 bool ipv6_available,
466 bool cached,
467 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40468 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37469 dict->SetBoolean("ipv6_available", ipv6_available);
470 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48471 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37472}
473
[email protected]0f292de02012-02-01 22:28:20474// The logging routines are defined here because some requests are resolved
475// without a Request object.
476
477// Logs when a request has just been started.
tfarina428341112016-09-22 13:38:20478void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20479 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00480 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
481 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20482}
483
484// Logs when a request has just completed (before its callback is run).
tfarina428341112016-09-22 13:38:20485void LogFinishRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20486 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20487 int net_error) {
xunjieli26f90452014-11-10 16:23:02488 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00489 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20490}
491
492// Logs when a request has been cancelled.
tfarina428341112016-09-22 13:38:20493void LogCancelRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20494 const HostResolverImpl::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00495 source_net_log.AddEvent(NetLogEventType::CANCELLED);
496 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20497}
498
[email protected]b59ff372009-07-15 22:04:32499//-----------------------------------------------------------------------------
500
[email protected]0f292de02012-02-01 22:28:20501// Keeps track of the highest priority.
502class PriorityTracker {
503 public:
[email protected]8c98d002012-07-18 19:02:27504 explicit PriorityTracker(RequestPriority initial_priority)
505 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20506 memset(counts_, 0, sizeof(counts_));
507 }
508
509 RequestPriority highest_priority() const {
510 return highest_priority_;
511 }
512
513 size_t total_count() const {
514 return total_count_;
515 }
516
517 void Add(RequestPriority req_priority) {
518 ++total_count_;
519 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05520 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20521 highest_priority_ = req_priority;
522 }
523
524 void Remove(RequestPriority req_priority) {
525 DCHECK_GT(total_count_, 0u);
526 DCHECK_GT(counts_[req_priority], 0u);
527 --total_count_;
528 --counts_[req_priority];
529 size_t i;
thestiga74ad2b2016-07-11 20:52:36530 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
531 }
[email protected]0f292de02012-02-01 22:28:20532 highest_priority_ = static_cast<RequestPriority>(i);
533
[email protected]31ae7ab2012-04-24 21:09:05534 // In absence of requests, default to MINIMUM_PRIORITY.
535 if (total_count_ == 0)
536 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20537 }
538
539 private:
540 RequestPriority highest_priority_;
541 size_t total_count_;
542 size_t counts_[NUM_PRIORITIES];
543};
544
juliatuttle9fb7aeb2016-06-06 20:16:33545void MakeNotStale(HostCache::EntryStaleness* stale_info) {
546 if (!stale_info)
547 return;
548 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
549 stale_info->network_changes = 0;
550 stale_info->stale_hits = 0;
551}
552
juliatuttled7fa5852016-07-29 13:16:57553// Persist data every five minutes (potentially, cache and learned RTT).
554const int64_t kPersistDelaySec = 300;
555
[email protected]c54a8912012-10-22 22:09:43556} // namespace
[email protected]0f292de02012-02-01 22:28:20557
558//-----------------------------------------------------------------------------
559
tfarina9ed7f8c52016-02-19 17:50:18560bool ResolveLocalHostname(base::StringPiece host,
561 uint16_t port,
562 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18563 address_list->clear();
564
565 bool is_local6;
566 if (!IsLocalHostname(host, &is_local6))
567 return false;
568
martijna23c8962016-03-04 18:18:51569 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18570 if (!is_local6) {
martijna23c8962016-03-04 18:18:51571 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18572 }
573
574 return true;
575}
576
[email protected]daae1322013-09-05 18:26:50577const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
578
[email protected]0f292de02012-02-01 22:28:20579// Holds the data for a request that could not be completed synchronously.
580// It is owned by a Job. Canceled Requests are only marked as canceled rather
581// than removed from the Job's |requests_| list.
maksim.sisov31452af2016-07-27 06:38:10582class HostResolverImpl::RequestImpl : public HostResolver::Request {
[email protected]b59ff372009-07-15 22:04:32583 public:
tfarina428341112016-09-22 13:38:20584 RequestImpl(const NetLogWithSource& source_net_log,
maksim.sisov31452af2016-07-27 06:38:10585 const RequestInfo& info,
586 RequestPriority priority,
587 const CompletionCallback& callback,
588 AddressList* addresses,
589 Job* job)
[email protected]ee094b82010-08-24 15:55:51590 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09591 info_(info),
[email protected]5109c1952013-08-20 18:44:10592 priority_(priority),
maksim.sisov31452af2016-07-27 06:38:10593 job_(job),
[email protected]54e13772009-08-14 03:01:09594 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29595 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10596 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32597
maksim.sisov31452af2016-07-27 06:38:10598 ~RequestImpl() override;
599
600 void ChangeRequestPriority(RequestPriority priority) override;
601
602 void OnJobCancelled(Job* job) {
603 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04604 job_ = nullptr;
605 addresses_ = nullptr;
[email protected]aa22b242011-11-16 18:58:29606 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32607 }
608
[email protected]0f292de02012-02-01 22:28:20609 // Prepare final AddressList and call completion callback.
maksim.sisov31452af2016-07-27 06:38:10610 void OnJobCompleted(Job* job, int error, const AddressList& addr_list) {
611 DCHECK_EQ(job_, job);
[email protected]895123222012-10-25 15:21:17612 if (error == OK)
613 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
maksim.sisov31452af2016-07-27 06:38:10614 job_ = nullptr;
615 addresses_ = nullptr;
616 base::ResetAndReturn(&callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32617 }
618
[email protected]b59ff372009-07-15 22:04:32619 Job* job() const {
620 return job_;
621 }
622
[email protected]0f292de02012-02-01 22:28:20623 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20624 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51625
[email protected]b59ff372009-07-15 22:04:32626 const RequestInfo& info() const {
627 return info_;
628 }
629
[email protected]5109c1952013-08-20 18:44:10630 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31631 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10632
633 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29634
[email protected]b59ff372009-07-15 22:04:32635 private:
tfarina428341112016-09-22 13:38:20636 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09637
[email protected]b59ff372009-07-15 22:04:32638 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10639 const RequestInfo info_;
640
juliatuttlec53b19a72016-05-05 13:51:31641 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32642
[email protected]0f292de02012-02-01 22:28:20643 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32644 Job* job_;
645
646 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29647 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32648
649 // The address list to save result into.
650 AddressList* addresses_;
651
[email protected]51b9a6b2012-06-25 21:50:29652 const base::TimeTicks request_time_;
653
maksim.sisov31452af2016-07-27 06:38:10654 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32655};
656
[email protected]1e9bbd22010-10-15 16:42:45657//------------------------------------------------------------------------------
658
mmenke91c17162016-06-02 16:03:23659// Calls HostResolverProc using a worker task runner. Performs retries if
660// necessary.
[email protected]0f292de02012-02-01 22:28:20661//
662// Whenever we try to resolve the host, we post a delayed task to check if host
663// resolution (OnLookupComplete) is completed or not. If the original attempt
664// hasn't completed, then we start another attempt for host resolution. We take
665// the results from the first attempt that finishes and ignore the results from
666// all other attempts.
667//
668// TODO(szym): Move to separate source file for testing and mocking.
669//
670class HostResolverImpl::ProcTask
671 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32672 public:
[email protected]b3601bc22012-02-21 21:23:20673 typedef base::Callback<void(int net_error,
674 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32675
[email protected]0f292de02012-02-01 22:28:20676 ProcTask(const Key& key,
677 const ProcTaskParams& params,
678 const Callback& callback,
mmenke91c17162016-06-02 16:03:23679 scoped_refptr<base::TaskRunner> worker_task_runner,
tfarina428341112016-09-22 13:38:20680 const NetLogWithSource& job_net_log)
[email protected]0f292de02012-02-01 22:28:20681 : key_(key),
682 params_(params),
683 callback_(callback),
mmenke91c17162016-06-02 16:03:23684 worker_task_runner_(std::move(worker_task_runner)),
685 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
[email protected]0f292de02012-02-01 22:28:20686 attempt_number_(0),
687 completed_attempt_number_(0),
688 completed_attempt_error_(ERR_UNEXPECTED),
689 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20690 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50691 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20692 params_.resolver_proc = HostResolverProc::GetDefault();
693 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50694 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06695 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32696 }
697
[email protected]b59ff372009-07-15 22:04:32698 void Start() {
mmenke91c17162016-06-02 16:03:23699 DCHECK(network_task_runner_->BelongsToCurrentThread());
mikecirone8b85c432016-09-08 19:11:00700 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54701 StartLookupAttempt();
702 }
[email protected]252b699b2010-02-05 21:38:06703
[email protected]0f292de02012-02-01 22:28:20704 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23705 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20706 // attempts complete will the final reference to this ProcTask be released.
707 void Cancel() {
mmenke91c17162016-06-02 16:03:23708 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20709
[email protected]0adcb2b2012-08-15 21:30:46710 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20711 return;
712
[email protected]0f292de02012-02-01 22:28:20713 callback_.Reset();
mikecirone8b85c432016-09-08 19:11:00714 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20715 }
716
717 void set_had_non_speculative_request() {
mmenke91c17162016-06-02 16:03:23718 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20719 had_non_speculative_request_ = true;
720 }
721
722 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23723 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20724 return callback_.is_null();
725 }
726
727 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23728 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20729 return completed_attempt_number_ > 0;
730 }
731
732 private:
[email protected]a9813302012-04-28 09:29:28733 friend class base::RefCountedThreadSafe<ProcTask>;
734 ~ProcTask() {}
735
[email protected]189163e2011-05-11 01:48:54736 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23737 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54738 base::TimeTicks start_time = base::TimeTicks::Now();
739 ++attempt_number_;
740 // Dispatch the lookup attempt to a worker thread.
mmenke91c17162016-06-02 16:03:23741 if (!worker_task_runner_->PostTask(
742 FROM_HERE, base::Bind(&ProcTask::DoLookup, this, start_time,
743 attempt_number_))) {
[email protected]b59ff372009-07-15 22:04:32744 NOTREACHED();
745
mmenke91c17162016-06-02 16:03:23746 // Since this method may have been called from Resolve(), can't just call
747 // OnLookupComplete(). Instead, must wait until Resolve() has returned
748 // (IO_PENDING).
749 network_task_runner_->PostTask(
750 FROM_HERE,
751 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
752 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54753 return;
[email protected]b59ff372009-07-15 22:04:32754 }
[email protected]13024882011-05-18 23:19:16755
mikecirone8b85c432016-09-08 19:11:00756 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28757 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16758
mmenke91c17162016-06-02 16:03:23759 // If the results aren't received within a given time, RetryIfNotComplete
760 // will start a new attempt if none of the outstanding attempts have
761 // completed yet.
[email protected]0f292de02012-02-01 22:28:20762 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23763 network_task_runner_->PostDelayedTask(
764 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42765 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58766 }
[email protected]b59ff372009-07-15 22:04:32767 }
768
mmenke91c17162016-06-02 16:03:23769 // WARNING: In production, this code runs on a worker pool. The shutdown code
770 // cannot wait for it to finish, so this code must be very careful about using
771 // other objects (like MessageLoops, Singletons, etc). During shutdown these
772 // objects may no longer exist. Multiple DoLookups() could be running in
773 // parallel, so any state inside of |this| must not mutate .
[email protected]189163e2011-05-11 01:48:54774 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46775 const uint32_t attempt_number) {
[email protected]189163e2011-05-11 01:48:54776 AddressList results;
777 int os_error = 0;
mmenke91c17162016-06-02 16:03:23778 // Running on a worker task runner.
[email protected]0f292de02012-02-01 22:28:20779 int error = params_.resolver_proc->Resolve(key_.hostname,
780 key_.address_family,
781 key_.host_resolver_flags,
782 &results,
783 &os_error);
[email protected]b59ff372009-07-15 22:04:32784
mmenke91c17162016-06-02 16:03:23785 network_task_runner_->PostTask(
786 FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
787 start_time, attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54788 }
789
mmenke91c17162016-06-02 16:03:23790 // Makes next attempt if DoLookup() has not finished.
[email protected]0f292de02012-02-01 22:28:20791 void RetryIfNotComplete() {
mmenke91c17162016-06-02 16:03:23792 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54793
[email protected]0f292de02012-02-01 22:28:20794 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54795 return;
796
[email protected]0f292de02012-02-01 22:28:20797 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54798 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32799 }
800
anujk.sharma7c907f02015-05-29 02:55:44801 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54802 void OnLookupComplete(const AddressList& results,
803 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46804 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54805 int error,
806 const int os_error) {
xunjieli0b7f5b62016-12-06 20:43:48807 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
mmenke91c17162016-06-02 16:03:23808 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23809 // If results are empty, we should return an error.
810 bool empty_list_on_ok = (error == OK && results.empty());
811 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
812 if (empty_list_on_ok)
813 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54814
815 bool was_retry_attempt = attempt_number > 1;
816
[email protected]2d3b7762010-10-09 00:35:47817 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20818 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23819 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54820 if (error != OK && NetworkChangeNotifier::IsOffline())
821 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47822
[email protected]b3601bc22012-02-21 21:23:20823 // If this is the first attempt that is finishing later, then record data
824 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54825 if (!was_retry_attempt)
826 RecordPerformanceHistograms(start_time, error, os_error);
827
828 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35829
[email protected]0f292de02012-02-01 22:28:20830 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32831 return;
832
mikecironef22f9812016-10-04 03:40:19833 NetLogParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20834 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45835 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
836 attempt_number,
837 error,
838 os_error);
[email protected]0f292de02012-02-01 22:28:20839 } else {
tfarina5e24b242015-10-27 13:11:28840 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20841 }
mikecirone8b85c432016-09-08 19:11:00842 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
[email protected]cd565142012-06-12 16:21:45843 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20844
845 if (was_completed())
846 return;
847
848 // Copy the results from the first worker thread that resolves the host.
849 results_ = results;
850 completed_attempt_number_ = attempt_number;
851 completed_attempt_error_ = error;
852
[email protected]e87b8b512011-06-14 22:12:52853 if (was_retry_attempt) {
854 // If retry attempt finishes before 1st attempt, then get stats on how
855 // much time is saved by having spawned an extra attempt.
856 retry_attempt_finished_time_ = base::TimeTicks::Now();
857 }
858
[email protected]189163e2011-05-11 01:48:54859 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45860 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
861 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51862 } else {
[email protected]cd565142012-06-12 16:21:45863 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51864 }
mikecirone8b85c432016-09-08 19:11:00865 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45866 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51867
[email protected]b3601bc22012-02-21 21:23:20868 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32869 }
870
[email protected]189163e2011-05-11 01:48:54871 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
872 const int error,
873 const int os_error) const {
mmenke91c17162016-06-02 16:03:23874 DCHECK(network_task_runner_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35875 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45876 RESOLVE_SUCCESS,
877 RESOLVE_FAIL,
878 RESOLVE_SPECULATIVE_SUCCESS,
879 RESOLVE_SPECULATIVE_FAIL,
880 RESOLVE_MAX, // Bounding value.
881 };
Wei-Yin Chen (陳威尹)223326c2017-07-21 02:08:28882 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
[email protected]1e9bbd22010-10-15 16:42:45883
[email protected]189163e2011-05-11 01:48:54884 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
885 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45886 if (had_non_speculative_request_) {
887 category = RESOLVE_SUCCESS;
888 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
889 } else {
890 category = RESOLVE_SPECULATIVE_SUCCESS;
891 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
892 }
[email protected]7e96d792011-06-10 17:08:23893
[email protected]78eac2a2012-03-14 19:09:27894 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23895 // if IPv4 or IPv4/6 lookups are faster or slower.
thestiga74ad2b2016-07-11 20:52:36896 switch (key_.address_family) {
[email protected]7e96d792011-06-10 17:08:23897 case ADDRESS_FAMILY_IPV4:
898 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
899 break;
900 case ADDRESS_FAMILY_IPV6:
901 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
902 break;
903 case ADDRESS_FAMILY_UNSPECIFIED:
904 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
905 break;
906 }
[email protected]1e9bbd22010-10-15 16:42:45907 } else {
908 if (had_non_speculative_request_) {
909 category = RESOLVE_FAIL;
910 DNS_HISTOGRAM("DNS.ResolveFail", duration);
911 } else {
912 category = RESOLVE_SPECULATIVE_FAIL;
913 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
914 }
[email protected]78eac2a2012-03-14 19:09:27915 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23916 // if IPv4 or IPv4/6 lookups are faster or slower.
thestiga74ad2b2016-07-11 20:52:36917 switch (key_.address_family) {
[email protected]7e96d792011-06-10 17:08:23918 case ADDRESS_FAMILY_IPV4:
919 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
920 break;
921 case ADDRESS_FAMILY_IPV6:
922 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
923 break;
924 case ADDRESS_FAMILY_UNSPECIFIED:
925 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
926 break;
927 }
[email protected]c833e322010-10-16 23:51:36928 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54929 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45930 GetAllGetAddrinfoOSErrors());
931 }
[email protected]051b6ab2010-10-18 16:50:46932 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45933
934 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45935 }
936
[email protected]189163e2011-05-11 01:48:54937 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46938 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54939 const int error,
940 const int os_error) const {
mmenke91c17162016-06-02 16:03:23941 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54942 bool first_attempt_to_complete =
943 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52944 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45945
[email protected]189163e2011-05-11 01:48:54946 if (first_attempt_to_complete) {
947 // If this was first attempt to complete, then record the resolution
948 // status of the attempt.
949 if (completed_attempt_error_ == OK) {
950 UMA_HISTOGRAM_ENUMERATION(
951 "DNS.AttemptFirstSuccess", attempt_number, 100);
952 } else {
953 UMA_HISTOGRAM_ENUMERATION(
954 "DNS.AttemptFirstFailure", attempt_number, 100);
955 }
956 }
957
958 if (error == OK)
959 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
960 else
961 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
962
[email protected]e87b8b512011-06-14 22:12:52963 // If first attempt didn't finish before retry attempt, then calculate stats
964 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20965 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52966 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
967 base::TimeTicks::Now() - retry_attempt_finished_time_);
968 }
969
[email protected]0f292de02012-02-01 22:28:20970 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54971 // Count those attempts which completed after the job was already canceled
972 // OR after the job was already completed by an earlier attempt (so in
973 // effect).
974 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
975
[email protected]0f292de02012-02-01 22:28:20976 // Record if job is canceled.
977 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54978 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
979 }
980
981 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
982 if (error == OK)
983 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
984 else
985 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
986 }
[email protected]1e9bbd22010-10-15 16:42:45987
anujk.sharma7c907f02015-05-29 02:55:44988 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57989 Key key_;
[email protected]b59ff372009-07-15 22:04:32990
[email protected]0f292de02012-02-01 22:28:20991 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32992 // This may not be the current resolver procedure by the time we call
993 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
994 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20995 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32996
[email protected]0f292de02012-02-01 22:28:20997 // The listener to the results of this ProcTask.
998 Callback callback_;
999
mmenke91c17162016-06-02 16:03:231000 // Task runner for the call to the HostResolverProc.
1001 scoped_refptr<base::TaskRunner> worker_task_runner_;
1002
1003 // Used to post events onto the network thread.
1004 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
[email protected]189163e2011-05-11 01:48:541005
1006 // Keeps track of the number of attempts we have made so far to resolve the
1007 // host. Whenever we start an attempt to resolve the host, we increase this
1008 // number.
Avi Drissman13fc8932015-12-20 04:40:461009 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:541010
1011 // The index of the attempt which finished first (or 0 if the job is still in
1012 // progress).
Avi Drissman13fc8932015-12-20 04:40:461013 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:541014
1015 // The result (a net error code) from the first attempt to complete.
1016 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:061017
[email protected]e87b8b512011-06-14 22:12:521018 // The time when retry attempt was finished.
1019 base::TimeTicks retry_attempt_finished_time_;
1020
[email protected]252b699b2010-02-05 21:38:061021 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:201022 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:061023 // This boolean is used for histogramming the duration of jobs used to
1024 // service non-speculative requests.
1025 bool had_non_speculative_request_;
1026
[email protected]b59ff372009-07-15 22:04:321027 AddressList results_;
1028
tfarina428341112016-09-22 13:38:201029 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:511030
[email protected]0f292de02012-02-01 22:28:201031 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:321032};
1033
1034//-----------------------------------------------------------------------------
1035
mmenke91c17162016-06-02 16:03:231036// Wraps a call to HaveOnlyLoopbackAddresses to be executed on a
1037// |worker_task_runner|, as it takes 40-100ms and should not block
1038// initialization.
[email protected]12faa4c2012-11-06 04:44:181039class HostResolverImpl::LoopbackProbeJob {
1040 public:
mmenke91c17162016-06-02 16:03:231041 LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver,
1042 base::TaskRunner* worker_task_runner)
1043 : resolver_(resolver), result_(false) {
[email protected]11fbca0b2013-06-02 23:37:211044 DCHECK(resolver.get());
mmenke91c17162016-06-02 16:03:231045
mmenke91c17162016-06-02 16:03:231046 worker_task_runner->PostTaskAndReply(
[email protected]12faa4c2012-11-06 04:44:181047 FROM_HERE,
1048 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
mmenke91c17162016-06-02 16:03:231049 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)));
[email protected]12faa4c2012-11-06 04:44:181050 }
1051
1052 virtual ~LoopbackProbeJob() {}
1053
1054 private:
1055 // Runs on worker thread.
1056 void DoProbe() {
1057 result_ = HaveOnlyLoopbackAddresses();
1058 }
1059
1060 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:211061 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:181062 return;
1063 resolver_->SetHaveOnlyLoopbackAddresses(result_);
1064 }
1065
anujk.sharma7c907f02015-05-29 02:55:441066 // Used/set only on task runner thread.
[email protected]12faa4c2012-11-06 04:44:181067 base::WeakPtr<HostResolverImpl> resolver_;
1068
1069 bool result_;
1070
1071 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
1072};
1073
[email protected]0f8f1b432010-03-16 19:06:031074//-----------------------------------------------------------------------------
1075
[email protected]b3601bc22012-02-21 21:23:201076// Resolves the hostname using DnsTransaction.
1077// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461078class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201079 public:
[email protected]daae1322013-09-05 18:26:501080 class Delegate {
1081 public:
1082 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1083 int net_error,
1084 const AddressList& addr_list,
1085 base::TimeDelta ttl) = 0;
1086
1087 // Called when the first of two jobs succeeds. If the first completed
1088 // transaction fails, this is not called. Also not called when the DnsTask
1089 // only needs to run one transaction.
1090 virtual void OnFirstDnsTransactionComplete() = 0;
1091
1092 protected:
1093 Delegate() {}
1094 virtual ~Delegate() {}
1095 };
[email protected]b3601bc22012-02-21 21:23:201096
[email protected]0adcb2b2012-08-15 21:30:461097 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201098 const Key& key,
[email protected]daae1322013-09-05 18:26:501099 Delegate* delegate,
tfarina428341112016-09-22 13:38:201100 const NetLogWithSource& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461101 : client_(client),
[email protected]daae1322013-09-05 18:26:501102 key_(key),
1103 delegate_(delegate),
1104 net_log_(job_net_log),
1105 num_completed_transactions_(0),
1106 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461107 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501108 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501109 }
1110
[email protected]daae1322013-09-05 18:26:501111 bool needs_two_transactions() const {
1112 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1113 }
1114
1115 bool needs_another_transaction() const {
1116 return needs_two_transactions() && !transaction_aaaa_;
1117 }
1118
1119 void StartFirstTransaction() {
1120 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001121 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501122 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1123 StartAAAA();
1124 } else {
1125 StartA();
1126 }
1127 }
1128
1129 void StartSecondTransaction() {
1130 DCHECK(needs_two_transactions());
1131 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121132 }
1133
1134 private:
[email protected]daae1322013-09-05 18:26:501135 void StartA() {
1136 DCHECK(!transaction_a_);
1137 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1138 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1139 transaction_a_->Start();
1140 }
1141
1142 void StartAAAA() {
1143 DCHECK(!transaction_aaaa_);
1144 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1145 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1146 transaction_aaaa_->Start();
1147 }
1148
danakj22f90e72016-04-16 01:55:401149 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501150 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1151 return client_->GetTransactionFactory()->CreateTransaction(
1152 key_.hostname,
1153 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1154 dns_protocol::kTypeA,
1155 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1156 base::TimeTicks::Now()),
1157 net_log_);
1158 }
1159
1160 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001161 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201162 int net_error,
1163 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471164 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511165 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461166 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511167 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461168 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1169 return;
[email protected]6c411902012-08-14 22:36:361170 }
[email protected]0adcb2b2012-08-15 21:30:461171
[email protected]02cd6982013-01-10 20:12:511172 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1173 switch (transaction->GetType()) {
1174 case dns_protocol::kTypeA:
1175 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1176 break;
1177 case dns_protocol::kTypeAAAA:
1178 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1179 break;
1180 }
[email protected]daae1322013-09-05 18:26:501181
[email protected]0adcb2b2012-08-15 21:30:461182 AddressList addr_list;
1183 base::TimeDelta ttl;
1184 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1185 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1186 result,
1187 DnsResponse::DNS_PARSE_RESULT_MAX);
1188 if (result != DnsResponse::DNS_PARSE_OK) {
1189 // Fail even if the other query succeeds.
1190 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1191 return;
1192 }
1193
[email protected]daae1322013-09-05 18:26:501194 ++num_completed_transactions_;
1195 if (num_completed_transactions_ == 1) {
1196 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461197 } else {
[email protected]daae1322013-09-05 18:26:501198 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461199 }
1200
[email protected]daae1322013-09-05 18:26:501201 if (transaction->GetType() == dns_protocol::kTypeA) {
1202 DCHECK_EQ(transaction_a_.get(), transaction);
1203 // Place IPv4 addresses after IPv6.
1204 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1205 } else {
1206 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1207 // Place IPv6 addresses before IPv4.
1208 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1209 }
1210
1211 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1212 // No need to repeat the suffix search.
1213 key_.hostname = transaction->GetHostname();
1214 delegate_->OnFirstDnsTransactionComplete();
1215 return;
1216 }
1217
1218 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121219 // TODO(szym): Don't fallback to ProcTask in this case.
1220 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461221 return;
1222 }
1223
[email protected]daae1322013-09-05 18:26:501224 // If there are multiple addresses, and at least one is IPv6, need to sort
1225 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1226 // sufficient to just check the family of the first address.
1227 if (addr_list_.size() > 1 &&
1228 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1229 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461230 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501231 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071232 base::Bind(&DnsTask::OnSortComplete,
1233 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501234 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461235 } else {
[email protected]daae1322013-09-05 18:26:501236 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461237 }
1238 }
1239
1240 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461241 bool success,
1242 const AddressList& addr_list) {
1243 if (!success) {
1244 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1245 base::TimeTicks::Now() - start_time);
1246 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1247 return;
1248 }
1249
1250 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1251 base::TimeTicks::Now() - start_time);
1252
1253 // AddressSorter prunes unusable destinations.
1254 if (addr_list.empty()) {
1255 LOG(WARNING) << "Address list empty after RFC3484 sort";
1256 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1257 return;
1258 }
1259
[email protected]daae1322013-09-05 18:26:501260 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461261 }
1262
1263 void OnFailure(int net_error, DnsResponse::Result result) {
1264 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451265 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001266 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451267 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501268 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1269 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201270 }
1271
[email protected]daae1322013-09-05 18:26:501272 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001273 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461274 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501275 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461276 }
1277
1278 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501279 Key key_;
1280
[email protected]b3601bc22012-02-21 21:23:201281 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501282 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201283 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201284
danakj22f90e72016-04-16 01:55:401285 std::unique_ptr<DnsTransaction> transaction_a_;
1286 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461287
[email protected]daae1322013-09-05 18:26:501288 unsigned num_completed_transactions_;
1289
1290 // These are updated as each transaction completes.
1291 base::TimeDelta ttl_;
1292 // IPv6 addresses must appear first in the list.
1293 AddressList addr_list_;
1294
1295 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461296
1297 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201298};
1299
1300//-----------------------------------------------------------------------------
1301
[email protected]0f292de02012-02-01 22:28:201302// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501303class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1304 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391305 public:
[email protected]0f292de02012-02-01 22:28:201306 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351307 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181308 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201309 const Key& key,
[email protected]8c98d002012-07-18 19:02:271310 RequestPriority priority,
mmenke91c17162016-06-02 16:03:231311 scoped_refptr<base::TaskRunner> worker_task_runner,
tfarina428341112016-09-22 13:38:201312 const NetLogWithSource& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181313 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201314 key_(key),
[email protected]8c98d002012-07-18 19:02:271315 priority_tracker_(priority),
mmenke91c17162016-06-02 16:03:231316 worker_task_runner_(std::move(worker_task_runner)),
[email protected]0f292de02012-02-01 22:28:201317 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291318 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501319 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331320 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291321 creation_time_(base::TimeTicks::Now()),
1322 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201323 net_log_(
1324 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001325 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1326 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201327
mikecirone8b85c432016-09-08 19:11:001328 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1329 base::Bind(&NetLogJobCreationCallback,
1330 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391331 }
1332
dchengb03027d2014-10-21 12:00:201333 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201334 if (is_running()) {
1335 // |resolver_| was destroyed with this Job still in flight.
1336 // Clean-up, record in the log, but don't run any callbacks.
1337 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201338 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041339 proc_task_ = nullptr;
[email protected]0f292de02012-02-01 22:28:201340 }
[email protected]16ee26d2012-03-08 03:34:351341 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501342 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001343 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201344 ERR_ABORTED);
1345 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551346 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351347 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001348 net_log_.AddEvent(NetLogEventType::CANCELLED);
1349 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391350 }
[email protected]b3601bc22012-02-21 21:23:201351 // else CompleteRequests logged EndEvent.
maksim.sisov31452af2016-07-27 06:38:101352 if (!requests_.empty()) {
1353 // Log any remaining Requests as cancelled.
1354 for (RequestImpl* req : requests_) {
1355 DCHECK_EQ(this, req->job());
maksim.sisov31452af2016-07-27 06:38:101356 LogCancelRequest(req->source_net_log(), req->info());
maksim.sisov320d5962016-08-15 18:02:511357 req->OnJobCancelled(this);
maksim.sisov31452af2016-07-27 06:38:101358 }
1359 requests_.clear();
[email protected]b3601bc22012-02-21 21:23:201360 }
[email protected]68ad3ee2010-01-30 03:45:391361 }
1362
[email protected]daae1322013-09-05 18:26:501363 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1364 // of the queue.
1365 void Schedule(bool at_head) {
1366 DCHECK(!is_queued());
1367 PrioritizedDispatcher::Handle handle;
1368 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001369 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501370 } else {
[email protected]106ccd2c2014-06-17 09:21:001371 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501372 }
1373 // The dispatcher could have started |this| in the above call to Add, which
1374 // could have called Schedule again. In that case |handle| will be null,
1375 // but |handle_| may have been set by the other nested call to Schedule.
1376 if (!handle.is_null()) {
1377 DCHECK(handle_.is_null());
1378 handle_ = handle;
1379 }
[email protected]16ee26d2012-03-08 03:34:351380 }
1381
maksim.sisov31452af2016-07-27 06:38:101382 void AddRequest(RequestImpl* request) {
1383 DCHECK_EQ(key_.hostname, request->info().hostname());
[email protected]0f292de02012-02-01 22:28:201384
maksim.sisov31452af2016-07-27 06:38:101385 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201386
maksim.sisov31452af2016-07-27 06:38:101387 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001388 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451389 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201390
1391 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001392 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101393 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451394 priority()));
[email protected]0f292de02012-02-01 22:28:201395
1396 // TODO(szym): Check if this is still needed.
maksim.sisov31452af2016-07-27 06:38:101397 if (!request->info().is_speculative()) {
[email protected]0f292de02012-02-01 22:28:201398 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501399 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201400 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391401 }
[email protected]b3601bc22012-02-21 21:23:201402
maksim.sisov31452af2016-07-27 06:38:101403 requests_.push_back(request);
[email protected]b3601bc22012-02-21 21:23:201404
[email protected]51b9a6b2012-06-25 21:50:291405 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391406 }
1407
maksim.sisov31452af2016-07-27 06:38:101408 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
juliatuttlec53b19a72016-05-05 13:51:311409 DCHECK_EQ(key_.hostname, req->info().hostname());
juliatuttlec53b19a72016-05-05 13:51:311410
1411 priority_tracker_.Remove(req->priority());
1412 req->set_priority(priority);
1413 priority_tracker_.Add(req->priority());
1414 UpdatePriority();
1415 }
1416
maksim.sisov31452af2016-07-27 06:38:101417 // Detach cancelled request. If it was the last active Request, also finishes
1418 // this Job.
1419 void CancelRequest(RequestImpl* request) {
1420 DCHECK_EQ(key_.hostname, request->info().hostname());
1421 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351422
maksim.sisov31452af2016-07-27 06:38:101423 LogCancelRequest(request->source_net_log(), request->info());
[email protected]16ee26d2012-03-08 03:34:351424
maksim.sisov31452af2016-07-27 06:38:101425 priority_tracker_.Remove(request->priority());
1426 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001427 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101428 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1429 priority()));
[email protected]b3601bc22012-02-21 21:23:201430
[email protected]16ee26d2012-03-08 03:34:351431 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291432 UpdatePriority();
maksim.sisov31452af2016-07-27 06:38:101433 RemoveRequest(request);
[email protected]16ee26d2012-03-08 03:34:351434 } else {
1435 // If we were called from a Request's callback within CompleteRequests,
1436 // that Request could not have been cancelled, so num_active_requests()
1437 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431438 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201439 }
[email protected]68ad3ee2010-01-30 03:45:391440 }
1441
maksim.sisov31452af2016-07-27 06:38:101442 void RemoveRequest(RequestImpl* request) {
1443 auto it = std::find(requests_.begin(), requests_.end(), request);
1444 DCHECK(it != requests_.end());
1445 requests_.erase(it);
1446 }
1447
[email protected]7af985a2012-12-14 22:40:421448 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1449 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111450 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201451 void Abort() {
[email protected]0f292de02012-02-01 22:28:201452 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421453 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201454 }
1455
[email protected]f0f602bd2012-11-15 18:01:021456 // If DnsTask present, abort it and fall back to ProcTask.
1457 void AbortDnsTask() {
1458 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501459 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021460 dns_task_error_ = OK;
1461 StartProcTask();
1462 }
1463 }
1464
[email protected]16ee26d2012-03-08 03:34:351465 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1466 // Completes all requests and destroys the job.
1467 void OnEvicted() {
1468 DCHECK(!is_running());
1469 DCHECK(is_queued());
1470 handle_.Reset();
1471
mikecirone8b85c432016-09-08 19:11:001472 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351473
1474 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431475 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351476 }
1477
[email protected]78eac2a2012-03-14 19:09:271478 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1479 // this Job was destroyed.
1480 bool ServeFromHosts() {
1481 DCHECK_GT(num_active_requests(), 0u);
1482 AddressList addr_list;
1483 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031484 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271485 &addr_list)) {
1486 // This will destroy the Job.
eroman0cd87b62016-12-14 19:13:451487 CompleteRequests(MakeCacheEntry(OK, addr_list), base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271488 return true;
1489 }
1490 return false;
1491 }
1492
tanay.c6ddd5f6f2015-08-25 06:34:571493 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111494
1495 bool is_queued() const {
1496 return !handle_.is_null();
1497 }
1498
1499 bool is_running() const {
1500 return is_dns_running() || is_proc_running();
1501 }
1502
[email protected]16ee26d2012-03-08 03:34:351503 private:
[email protected]daae1322013-09-05 18:26:501504 void KillDnsTask() {
1505 if (dns_task_) {
1506 ReduceToOneJobSlot();
1507 dns_task_.reset();
1508 }
1509 }
1510
1511 // Reduce the number of job slots occupied and queued in the dispatcher
1512 // to one. If the second Job slot is queued in the dispatcher, cancels the
1513 // queued job. Otherwise, the second Job has been started by the
1514 // PrioritizedDispatcher, so signals it is complete.
1515 void ReduceToOneJobSlot() {
1516 DCHECK_GE(num_occupied_job_slots_, 1u);
1517 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001518 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501519 handle_.Reset();
1520 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001521 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501522 --num_occupied_job_slots_;
1523 }
1524 DCHECK_EQ(1u, num_occupied_job_slots_);
1525 }
1526
eroman0cd87b62016-12-14 19:13:451527 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1528 // HostCache::Entry(). The address list is omited from the cache entry
1529 // for errors.
1530 HostCache::Entry MakeCacheEntry(int net_error,
1531 const AddressList& addr_list) const {
1532 return HostCache::Entry(
1533 net_error,
1534 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList());
1535 }
1536
1537 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1538 const AddressList& addr_list,
1539 base::TimeDelta ttl) const {
1540 return HostCache::Entry(
1541 net_error,
1542 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1543 ttl);
1544 }
1545
juliatuttlec53b19a72016-05-05 13:51:311546 AddressList MakeAddressListForRequest(const AddressList& list) const {
1547 if (requests_.empty())
1548 return list;
1549 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1550 }
1551
[email protected]51b9a6b2012-06-25 21:50:291552 void UpdatePriority() {
1553 if (is_queued()) {
1554 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1555 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001556 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291557 }
1558 }
1559
[email protected]16ee26d2012-03-08 03:34:351560 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201561 void Start() override {
[email protected]daae1322013-09-05 18:26:501562 DCHECK_LE(num_occupied_job_slots_, 1u);
1563
[email protected]70c04ab2013-08-22 16:05:121564 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501565 ++num_occupied_job_slots_;
1566
1567 if (num_occupied_job_slots_ == 2) {
1568 StartSecondDnsTransaction();
1569 return;
1570 }
1571
1572 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201573
mikecirone8b85c432016-09-08 19:11:001574 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201575
[email protected]51b9a6b2012-06-25 21:50:291576 had_dns_config_ = resolver_->HaveDnsConfig();
1577
1578 base::TimeTicks now = base::TimeTicks::Now();
1579 base::TimeDelta queue_time = now - creation_time_;
1580 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1581
1582 if (had_dns_config_) {
1583 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1584 queue_time);
1585 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1586 queue_time_after_change);
1587 } else {
1588 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1589 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1590 queue_time_after_change);
1591 }
1592
[email protected]443714fad2013-09-19 04:52:011593 bool system_only =
1594 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1595
[email protected]1d932852012-06-19 19:40:331596 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011597 if (!system_only && had_dns_config_ &&
1598 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201599 StartDnsTask();
1600 } else {
1601 StartProcTask();
1602 }
1603 }
1604
[email protected]b3601bc22012-02-21 21:23:201605 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1606 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1607 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1608 // tighter limits.
1609 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351610 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231611 proc_task_ =
1612 new ProcTask(key_, resolver_->proc_params_,
1613 base::Bind(&Job::OnProcTaskComplete,
1614 base::Unretained(this), base::TimeTicks::Now()),
1615 worker_task_runner_, net_log_);
[email protected]0f292de02012-02-01 22:28:201616
1617 if (had_non_speculative_request_)
1618 proc_task_->set_had_non_speculative_request();
1619 // Start() could be called from within Resolve(), hence it must NOT directly
1620 // call OnProcTaskComplete, for example, on synchronous failure.
1621 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391622 }
1623
[email protected]0f292de02012-02-01 22:28:201624 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371625 void OnProcTaskComplete(base::TimeTicks start_time,
1626 int net_error,
1627 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201628 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391629
[email protected]1d932852012-06-19 19:40:331630 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371631 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001632 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371633 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331634 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1635 ResemblesNetBIOSName(key_.hostname)) {
1636 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1637 } else {
1638 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1639 }
davidbenad6fc442015-05-18 20:59:131640 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1641 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221642 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001643 } else {
[email protected]e3bd4822012-10-23 18:01:371644 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001645 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1646 }
1647 }
1648
eroman1efc237c2016-12-14 00:00:451649 if (ContainsIcannNameCollisionIp(addr_list))
1650 net_error = ERR_ICANN_NAME_COLLISION;
1651
[email protected]1339a2a22012-10-17 08:39:431652 base::TimeDelta ttl =
1653 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201654 if (net_error == OK)
1655 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391656
[email protected]895123222012-10-25 15:21:171657 // Don't store the |ttl| in cache since it's not obtained from the server.
eroman0cd87b62016-12-14 19:13:451658 CompleteRequests(MakeCacheEntry(net_error, addr_list), ttl);
[email protected]b3601bc22012-02-21 21:23:201659 }
1660
1661 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271662 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501663 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1664 net_log_));
[email protected]b3601bc22012-02-21 21:23:201665
[email protected]daae1322013-09-05 18:26:501666 dns_task_->StartFirstTransaction();
1667 // Schedule a second transaction, if needed.
1668 if (dns_task_->needs_two_transactions())
1669 Schedule(true);
1670 }
1671
1672 void StartSecondDnsTransaction() {
1673 DCHECK(dns_task_->needs_two_transactions());
1674 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221675 }
1676
1677 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1678 // deleted before this callback. In this case dns_task is deleted as well,
1679 // so we use it as indicator whether Job is still valid.
1680 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1681 base::TimeDelta duration,
1682 int net_error) {
1683 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1684
wezb9820d42016-06-22 23:41:041685 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221686 return;
1687
1688 dns_task_error_ = net_error;
1689
1690 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1691 // http://crbug.com/117655
1692
1693 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1694 // ProcTask in that case is a waste of time.
1695 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501696 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221697 StartProcTask();
1698 } else {
1699 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1700 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201701 }
1702 }
1703
[email protected]daae1322013-09-05 18:26:501704
1705 // HostResolverImpl::DnsTask::Delegate implementation:
1706
dchengb03027d2014-10-21 12:00:201707 void OnDnsTaskComplete(base::TimeTicks start_time,
1708 int net_error,
1709 const AddressList& addr_list,
1710 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201711 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201712
[email protected]e3bd4822012-10-23 18:01:371713 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201714 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221715 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201716 return;
1717 }
[email protected]e3bd4822012-10-23 18:01:371718 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511719 // Log DNS lookups based on |address_family|.
thestiga74ad2b2016-07-11 20:52:361720 switch (key_.address_family) {
[email protected]02cd6982013-01-10 20:12:511721 case ADDRESS_FAMILY_IPV4:
1722 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1723 break;
1724 case ADDRESS_FAMILY_IPV6:
1725 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1726 break;
1727 case ADDRESS_FAMILY_UNSPECIFIED:
1728 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1729 break;
1730 }
[email protected]b3601bc22012-02-21 21:23:201731
[email protected]1def74c2012-03-22 20:07:001732 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431733 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461734
[email protected]1ffdda82012-12-12 23:04:221735 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021736
[email protected]895123222012-10-25 15:21:171737 base::TimeDelta bounded_ttl =
1738 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1739
eroman0cd87b62016-12-14 19:13:451740 if (ContainsIcannNameCollisionIp(addr_list)) {
1741 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1742 } else {
1743 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list, ttl),
1744 bounded_ttl);
1745 }
[email protected]b3601bc22012-02-21 21:23:201746 }
1747
dchengb03027d2014-10-21 12:00:201748 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501749 DCHECK(dns_task_->needs_two_transactions());
1750 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1751 // No longer need to occupy two dispatcher slots.
1752 ReduceToOneJobSlot();
1753
1754 // We already have a job slot at the dispatcher, so if the second
1755 // transaction hasn't started, reuse it now instead of waiting in the queue
1756 // for the second slot.
1757 if (dns_task_->needs_another_transaction())
1758 dns_task_->StartSecondTransaction();
1759 }
1760
[email protected]16ee26d2012-03-08 03:34:351761 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171762 void CompleteRequests(const HostCache::Entry& entry,
1763 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211764 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201765
[email protected]16ee26d2012-03-08 03:34:351766 // This job must be removed from resolver's |jobs_| now to make room for a
1767 // new job with the same key in case one of the OnComplete callbacks decides
1768 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1769 // is done.
danakj22f90e72016-04-16 01:55:401770 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351771
1772 resolver_->RemoveJob(this);
1773
[email protected]16ee26d2012-03-08 03:34:351774 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351775 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501776 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351777 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041778 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351779 }
[email protected]daae1322013-09-05 18:26:501780 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351781
1782 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001783 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351784 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001785 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351786 handle_.Reset();
1787 }
1788
1789 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001790 net_log_.AddEvent(NetLogEventType::CANCELLED);
1791 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351792 OK);
1793 return;
1794 }
[email protected]b3601bc22012-02-21 21:23:201795
mikecirone8b85c432016-09-08 19:11:001796 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221797 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391798
juliatuttled7fa5852016-07-29 13:16:571799 resolver_->SchedulePersist();
1800
[email protected]78eac2a2012-03-14 19:09:271801 DCHECK(!requests_.empty());
1802
eroman1efc237c2016-12-14 00:00:451803 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191804 // Record this histogram here, when we know the system has a valid DNS
1805 // configuration.
[email protected]539df6c2012-06-19 21:21:291806 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1807 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191808 }
[email protected]16ee26d2012-03-08 03:34:351809
juliatuttle317860e2016-05-12 14:47:221810 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1811 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Matt Menkeef8f5cf82017-07-20 22:50:171812 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431813 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351814
maksim.sisov31452af2016-07-27 06:38:101815 // Complete all of the requests that were attached to the job and
1816 // detach them.
1817 while (!requests_.empty()) {
1818 RequestImpl* req = requests_.front();
1819 requests_.pop_front();
[email protected]0f292de02012-02-01 22:28:201820 DCHECK_EQ(this, req->job());
1821 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221822 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291823 if (did_complete) {
[email protected]51b9a6b2012-06-25 21:50:291824 // Record effective total time from creation to completion.
1825 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1826 base::TimeTicks::Now() - req->request_time());
1827 }
maksim.sisov31452af2016-07-27 06:38:101828 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201829
1830 // Check if the resolver was destroyed as a result of running the
1831 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211832 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201833 return;
1834 }
1835 }
1836
[email protected]1339a2a22012-10-17 08:39:431837 // Convenience wrapper for CompleteRequests in case of failure.
1838 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171839 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1840 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431841 }
1842
[email protected]b4481b222012-03-16 17:13:111843 RequestPriority priority() const {
1844 return priority_tracker_.highest_priority();
1845 }
1846
1847 // Number of non-canceled requests in |requests_|.
1848 size_t num_active_requests() const {
1849 return priority_tracker_.total_count();
1850 }
1851
wezb9820d42016-06-22 23:41:041852 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111853
wezb9820d42016-06-22 23:41:041854 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111855
[email protected]0f292de02012-02-01 22:28:201856 base::WeakPtr<HostResolverImpl> resolver_;
1857
1858 Key key_;
1859
1860 // Tracks the highest priority across |requests_|.
1861 PriorityTracker priority_tracker_;
1862
mmenke91c17162016-06-02 16:03:231863 // Task runner where the HostResolverProc is invoked.
1864 scoped_refptr<base::TaskRunner> worker_task_runner_;
1865
[email protected]0f292de02012-02-01 22:28:201866 bool had_non_speculative_request_;
1867
[email protected]51b9a6b2012-06-25 21:50:291868 // Distinguishes measurements taken while DnsClient was fully configured.
1869 bool had_dns_config_;
1870
[email protected]daae1322013-09-05 18:26:501871 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1872 unsigned num_occupied_job_slots_;
1873
[email protected]1d932852012-06-19 19:40:331874 // Result of DnsTask.
1875 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001876
[email protected]51b9a6b2012-06-25 21:50:291877 const base::TimeTicks creation_time_;
1878 base::TimeTicks priority_change_time_;
1879
tfarina428341112016-09-22 13:38:201880 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201881
[email protected]b3601bc22012-02-21 21:23:201882 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201883 scoped_refptr<ProcTask> proc_task_;
1884
[email protected]b3601bc22012-02-21 21:23:201885 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401886 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201887
[email protected]0f292de02012-02-01 22:28:201888 // All Requests waiting for the result of this Job. Some can be canceled.
maksim.sisov31452af2016-07-27 06:38:101889 std::deque<RequestImpl*> requests_;
[email protected]0f292de02012-02-01 22:28:201890
[email protected]16ee26d2012-03-08 03:34:351891 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201892 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391893};
1894
1895//-----------------------------------------------------------------------------
1896
[email protected]0f292de02012-02-01 22:28:201897HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431898 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201899 size_t max_retry_attempts)
1900 : resolver_proc(resolver_proc),
1901 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441902 unresponsive_delay(
1903 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201904 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001905 // Maximum of 4 retry attempts for host resolution.
1906 static const size_t kDefaultMaxRetryAttempts = 4u;
1907 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1908 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201909}
1910
vmpstracd23b72016-02-26 21:08:551911HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1912 default;
1913
[email protected]0f292de02012-02-01 22:28:201914HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1915
[email protected]106ccd2c2014-06-17 09:21:001916HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231917 : HostResolverImpl(
1918 options,
1919 net_log,
1920 base::WorkerPool::GetTaskRunner(true /* task_is_slow */)) {}
[email protected]b59ff372009-07-15 22:04:321921
1922HostResolverImpl::~HostResolverImpl() {
gab47aa7da2017-06-02 16:09:431923 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]daae1322013-09-05 18:26:501924 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001925 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541926 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501927 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541928 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431929
[email protected]232a5812011-03-04 22:42:081930 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441931 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401932 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321933}
1934
[email protected]0f292de02012-02-01 22:28:201935void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001936 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201937 DCHECK_GT(value, 0u);
1938 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131939}
1940
[email protected]684970b2009-08-14 04:54:461941int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101942 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321943 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291944 const CompletionCallback& callback,
maksim.sisov31452af2016-07-27 06:38:101945 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:201946 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401947 DCHECK(addresses);
gab47aa7da2017-06-02 16:09:431948 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]aa22b242011-11-16 18:58:291949 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:101950 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:141951
Chris Palmer9cbf4212017-07-19 01:54:551952 LogStartRequest(source_net_log, info);
pauljensen19eb73422015-04-15 23:20:061953
Matt Menke23b4bbf82017-07-20 19:11:291954 Key key;
1955 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:401956 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021957 LogFinishRequest(source_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291958 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401959 return rv;
[email protected]38368712011-03-02 08:09:401960 }
1961
[email protected]0f292de02012-02-01 22:28:201962 // Next we need to attach our request to a "job". This job is responsible for
1963 // calling "getaddrinfo(hostname)" on a worker thread.
1964
avi9e72eb482016-12-09 21:10:541965 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:201966 Job* job;
1967 if (jobit == jobs_.end()) {
mmenke91c17162016-06-02 16:03:231968 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
1969 worker_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:501970 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201971
1972 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001973 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1974 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201975 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351976 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201977 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201978 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021979 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201980 return rv;
1981 }
[email protected]0f292de02012-02-01 22:28:201982 }
avi9e72eb482016-12-09 21:10:541983 jobs_[key] = base::WrapUnique(job);
[email protected]0f292de02012-02-01 22:28:201984 } else {
avi9e72eb482016-12-09 21:10:541985 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:201986 }
1987
1988 // Can't complete synchronously. Create and attach request.
Jeremy Roman0579ed62017-08-29 15:56:191989 auto req = std::make_unique<RequestImpl>(source_net_log, info, priority,
avi9e72eb482016-12-09 21:10:541990 callback, addresses, job);
maksim.sisov31452af2016-07-27 06:38:101991 job->AddRequest(req.get());
1992 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:321993
[email protected]0f292de02012-02-01 22:28:201994 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321995 return ERR_IO_PENDING;
1996}
1997
mmenke91c17162016-06-02 16:03:231998HostResolverImpl::HostResolverImpl(
1999 const Options& options,
2000 NetLog* net_log,
2001 scoped_refptr<base::TaskRunner> worker_task_runner)
2002 : max_queued_jobs_(0),
2003 proc_params_(NULL, options.max_retry_attempts),
2004 net_log_(net_log),
2005 received_dns_config_(false),
2006 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:032007 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:232008 use_local_ipv6_(false),
2009 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:232010 additional_resolver_flags_(0),
2011 fallback_to_proctask_(true),
2012 worker_task_runner_(std::move(worker_task_runner)),
juliatuttled7fa5852016-07-29 13:16:572013 persist_initialized_(false),
mmenke91c17162016-06-02 16:03:232014 weak_ptr_factory_(this),
2015 probe_weak_ptr_factory_(this) {
2016 if (options.enable_caching)
2017 cache_ = HostCache::CreateDefaultCache();
2018
2019 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2020 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2021 max_queued_jobs_ = job_limits.total_jobs * 100u;
2022
2023 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2024
2025#if defined(OS_WIN)
2026 EnsureWinsockInit();
2027#endif
2028#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2029 RunLoopbackProbeJob();
2030#endif
2031 NetworkChangeNotifier::AddIPAddressObserver(this);
2032 NetworkChangeNotifier::AddConnectionTypeObserver(this);
2033 NetworkChangeNotifier::AddDNSObserver(this);
2034#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Sergey Ulanov49085572017-07-10 23:25:462035 !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232036 EnsureDnsReloaderInit();
2037#endif
2038
2039 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
2040
2041 {
2042 DnsConfig dns_config;
2043 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2044 received_dns_config_ = dns_config.IsValid();
2045 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2046 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2047 }
2048
2049 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2050}
2051
2052void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2053 if (result) {
2054 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2055 } else {
2056 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2057 }
2058}
2059
Matt Menke23b4bbf82017-07-20 19:11:292060int HostResolverImpl::ResolveHelper(const RequestInfo& info,
juliatuttle9fb7aeb2016-06-06 20:16:332061 bool allow_stale,
2062 HostCache::EntryStaleness* stale_info,
Matt Menke23b4bbf82017-07-20 19:11:292063 const NetLogWithSource& source_net_log,
2064 AddressList* addresses,
2065 Key* key) {
2066 IPAddress ip_address;
2067 IPAddress* ip_address_ptr = nullptr;
2068 if (ip_address.AssignFromIPLiteral(info.hostname())) {
2069 ip_address_ptr = &ip_address;
2070 } else {
2071 // Check that the caller supplied a valid hostname to resolve.
2072 if (!IsValidDNSDomain(info.hostname()))
2073 return ERR_NAME_NOT_RESOLVED;
2074 }
2075
2076 // Build a key that identifies the request in the cache and in the
2077 // outstanding jobs map.
2078 *key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2079
juliatuttle9fb7aeb2016-06-06 20:16:332080 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402081 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2082 // On Windows it gives the default interface's address, whereas on Linux it
2083 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332084 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2085 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402086 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332087 }
[email protected]95a214c2011-08-04 21:50:402088
2089 int net_error = ERR_UNEXPECTED;
Matt Menke23b4bbf82017-07-20 19:11:292090 if (ResolveAsIP(*key, info, ip_address_ptr, &net_error, addresses)) {
juliatuttle9fb7aeb2016-06-06 20:16:332091 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402092 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332093 }
Mike Westda1c690e2017-08-12 05:57:162094
2095 // Special-case localhost names, as per the recommendations in
2096 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2097 if (ServeLocalhost(*key, info, addresses)) {
2098 MakeNotStale(stale_info);
2099 return OK;
2100 }
2101
Matt Menke23b4bbf82017-07-20 19:11:292102 if (ServeFromCache(*key, info, &net_error, addresses, allow_stale,
juliatuttle9fb7aeb2016-06-06 20:16:332103 stale_info)) {
mgersh33d23c02017-03-29 20:24:252104 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2105 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332106 // |ServeFromCache()| will set |*stale_info| as needed.
[email protected]78eac2a2012-03-14 19:09:272107 return net_error;
2108 }
Mike Westda1c690e2017-08-12 05:57:162109
[email protected]78eac2a2012-03-14 19:09:272110 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2111 // http://crbug.com/117655
Matt Menke23b4bbf82017-07-20 19:11:292112 if (ServeFromHosts(*key, info, addresses)) {
mgersh33d23c02017-03-29 20:24:252113 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2114 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332115 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272116 return OK;
2117 }
estarkd1bc206e2015-06-20 00:44:392118
[email protected]78eac2a2012-03-14 19:09:272119 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402120}
2121
2122int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2123 AddressList* addresses,
tfarina428341112016-09-22 13:38:202124 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432125 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402126 DCHECK(addresses);
2127
[email protected]95a214c2011-08-04 21:50:402128 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022129 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402130
Matt Menke23b4bbf82017-07-20 19:11:292131 Key key;
2132 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402133
xunjieli26f90452014-11-10 16:23:022134 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402135 return rv;
2136}
2137
[email protected]a8883e452012-11-17 05:58:062138void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432139 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062140#if defined(ENABLE_BUILT_IN_DNS)
2141 if (enabled && !dns_client_) {
2142 SetDnsClient(DnsClient::CreateClient(net_log_));
2143 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402144 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062145 }
2146#endif
2147}
2148
[email protected]489d1a82011-10-12 03:09:112149HostCache* HostResolverImpl::GetHostCache() {
2150 return cache_.get();
2151}
[email protected]95a214c2011-08-04 21:50:402152
danakj22f90e72016-04-16 01:55:402153std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242154 // Check if async DNS is disabled.
2155 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082156 return nullptr;
[email protected]17e92032012-03-29 00:56:242157
2158 // Check if async DNS is enabled, but we currently have no configuration
2159 // for it.
2160 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042161 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192162 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242163
2164 return dns_config->ToValue();
2165}
2166
juliatuttle9fb7aeb2016-06-06 20:16:332167int HostResolverImpl::ResolveStaleFromCache(
2168 const RequestInfo& info,
2169 AddressList* addresses,
2170 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202171 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432172 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
juliatuttle9fb7aeb2016-06-06 20:16:332173 DCHECK(addresses);
2174 DCHECK(stale_info);
2175
2176 // Update the net log and notify registered observers.
2177 LogStartRequest(source_net_log, info);
2178
Matt Menke23b4bbf82017-07-20 19:11:292179 Key key;
2180 int rv =
2181 ResolveHelper(info, true, stale_info, source_net_log, addresses, &key);
juliatuttle9fb7aeb2016-06-06 20:16:332182 LogFinishRequest(source_net_log, info, rv);
2183 return rv;
2184}
2185
mgershaf9a9232017-04-13 20:19:032186void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432187 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032188 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2189}
2190
2191bool HostResolverImpl::GetNoIPv6OnWifi() {
2192 return assume_ipv6_failure_on_wifi_;
2193}
2194
[email protected]95a214c2011-08-04 21:50:402195bool HostResolverImpl::ResolveAsIP(const Key& key,
2196 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512197 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402198 int* net_error,
2199 AddressList* addresses) {
2200 DCHECK(addresses);
2201 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512202 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402203 return false;
2204
[email protected]95a214c2011-08-04 21:50:402205 *net_error = OK;
martijna23c8962016-03-04 18:18:512206 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252207 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2208 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482209 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402210 *net_error = ERR_NAME_NOT_RESOLVED;
2211 } else {
martijna23c8962016-03-04 18:18:512212 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562213 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2214 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402215 }
2216 return true;
2217}
2218
2219bool HostResolverImpl::ServeFromCache(const Key& key,
2220 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402221 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332222 AddressList* addresses,
2223 bool allow_stale,
2224 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402225 DCHECK(addresses);
2226 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332227 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402228 if (!info.allow_cached_response() || !cache_.get())
2229 return false;
2230
juliatuttle9fb7aeb2016-06-06 20:16:332231 const HostCache::Entry* cache_entry;
2232 if (allow_stale)
2233 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2234 else
2235 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402236 if (!cache_entry)
2237 return false;
2238
juliatuttle317860e2016-05-12 14:47:222239 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562240 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432241 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222242 RecordTTL(cache_entry->ttl());
2243 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562244 }
[email protected]95a214c2011-08-04 21:50:402245 return true;
2246}
2247
[email protected]78eac2a2012-03-14 19:09:272248bool HostResolverImpl::ServeFromHosts(const Key& key,
2249 const RequestInfo& info,
2250 AddressList* addresses) {
2251 DCHECK(addresses);
2252 if (!HaveDnsConfig())
2253 return false;
[email protected]05a79d42013-03-28 07:30:092254 addresses->clear();
2255
[email protected]cb507622012-03-23 16:17:062256 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222257 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062258
[email protected]05a79d42013-03-28 07:30:092259 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2260
[email protected]78eac2a2012-03-14 19:09:272261 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2262 // (glibc and c-ares) return the first matching line. We have more
2263 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092264 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2265 // necessary.
2266 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2267 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2268 DnsHosts::const_iterator it = hosts.find(
2269 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2270 if (it != hosts.end())
2271 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272272 }
2273
[email protected]05a79d42013-03-28 07:30:092274 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2275 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2276 DnsHosts::const_iterator it = hosts.find(
2277 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2278 if (it != hosts.end())
2279 addresses->push_back(IPEndPoint(it->second, info.port()));
2280 }
2281
[email protected]ec666ab22013-04-17 20:05:592282 // If got only loopback addresses and the family was restricted, resolve
2283 // again, without restrictions. See SystemHostResolverCall for rationale.
2284 if ((key.host_resolver_flags &
2285 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2286 IsAllIPv4Loopback(*addresses)) {
2287 Key new_key(key);
2288 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2289 new_key.host_resolver_flags &=
2290 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2291 return ServeFromHosts(new_key, info, addresses);
2292 }
[email protected]05a79d42013-03-28 07:30:092293 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272294}
2295
estarkd1bc206e2015-06-20 00:44:392296bool HostResolverImpl::ServeLocalhost(const Key& key,
2297 const RequestInfo& info,
2298 AddressList* addresses) {
2299 AddressList resolved_addresses;
2300 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2301 return false;
2302
2303 addresses->clear();
2304
2305 for (const auto& address : resolved_addresses) {
2306 // Include the address if:
2307 // - caller didn't specify an address family, or
2308 // - caller specifically asked for the address family of this address, or
2309 // - this is an IPv6 address and caller specifically asked for IPv4 due
2310 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2311 // rationale).
2312 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2313 key.address_family == address.GetFamily() ||
2314 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2315 key.address_family == ADDRESS_FAMILY_IPV4 &&
2316 (key.host_resolver_flags &
2317 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2318 addresses->push_back(address);
2319 }
2320 }
2321
2322 return true;
2323}
2324
[email protected]16ee26d2012-03-08 03:34:352325void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432326 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352327 base::TimeDelta ttl) {
2328 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432329 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032330}
2331
[email protected]0f292de02012-02-01 22:28:202332void HostResolverImpl::RemoveJob(Job* job) {
2333 DCHECK(job);
avi9e72eb482016-12-09 21:10:542334 auto it = jobs_.find(job->key());
2335 if (it != jobs_.end() && it->second.get() == job) {
2336 it->second.release();
[email protected]16ee26d2012-03-08 03:34:352337 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542338 }
[email protected]b59ff372009-07-15 22:04:322339}
2340
[email protected]137af622010-02-05 02:14:352341HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062342 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512343 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202344 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272345 HostResolverFlags effective_flags =
2346 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352347 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512348
mgersh3eba057d2017-02-28 18:50:562349 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2350 // When resolving IPv4 literals, there's no need to probe for IPv6.
2351 // When resolving IPv6 literals, there's no benefit to artificially
2352 // limiting our resolution based on a probe. Prior logic ensures
2353 // that this query is UNSPECIFIED (see effective_address_family
2354 // check above) so the code requesting the resolution should be amenable
2355 // to receiving a IPv6 resolution.
2356 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2357 effective_address_family = ADDRESS_FAMILY_IPV4;
2358 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512359 }
2360
estarkd1bc206e2015-06-20 00:44:392361 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352362}
2363
tfarina428341112016-09-22 13:38:202364bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032365 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2366 // work on WiFi.
2367 if (assume_ipv6_failure_on_wifi_ &&
2368 NetworkChangeNotifier::GetConnectionType() ==
2369 NetworkChangeNotifier::CONNECTION_WIFI) {
2370 return false;
2371 }
2372
eroman1a17ef32016-12-14 01:06:092373 // Cache the result for kIPv6ProbePeriodMs (measured from after
2374 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372375 bool cached = true;
eroman1a17ef32016-12-14 01:06:092376 if ((base::TimeTicks::Now() - last_ipv6_probe_time_).InMilliseconds() >
2377 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512378 last_ipv6_probe_result_ =
2379 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
eroman1a17ef32016-12-14 01:06:092380 last_ipv6_probe_time_ = base::TimeTicks::Now();
sergeyub8cdc212015-05-14 18:50:372381 cached = false;
2382 }
mikecirone8b85c432016-09-08 19:11:002383 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372384 base::Bind(&NetLogIPv6AvailableCallback,
2385 last_ipv6_probe_result_, cached));
2386 return last_ipv6_probe_result_;
2387}
2388
mgershaf9a9232017-04-13 20:19:032389bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2390 const NetLogWithSource& net_log) {
2391 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
2392 tracked_objects::ScopedTracker tracking_profile_1(
2393 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
2394
2395 std::unique_ptr<DatagramClientSocket> socket(
2396 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
2397 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
2398 net_log.source()));
2399 int rv = socket->Connect(IPEndPoint(dest, 53));
2400 if (rv != OK)
2401 return false;
2402 IPEndPoint endpoint;
2403 rv = socket->GetLocalAddress(&endpoint);
2404 if (rv != OK)
2405 return false;
2406 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2407 const IPAddress& address = endpoint.address();
2408
2409 bool is_link_local =
2410 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2411 if (is_link_local)
2412 return false;
2413
2414 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2415 if (IPAddressStartsWith(address, kTeredoPrefix))
2416 return false;
2417
2418 return true;
2419}
2420
mmenke91c17162016-06-02 16:03:232421void HostResolverImpl::RunLoopbackProbeJob() {
2422 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr(),
2423 worker_task_runner_.get());
2424}
2425
[email protected]35ddc282010-09-21 23:42:062426void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202427 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2428 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402429 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542430 for (auto it = jobs_.begin(); it != jobs_.end();) {
2431 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202432 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542433 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202434 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202435 } else {
[email protected]b3601bc22012-02-21 21:23:202436 DCHECK(job->is_queued());
2437 ++it;
[email protected]0f292de02012-02-01 22:28:202438 }
[email protected]ef4c40c2010-09-01 14:42:032439 }
[email protected]b3601bc22012-02-21 21:23:202440
[email protected]daae1322013-09-05 18:26:502441 // Pause the dispatcher so it won't start any new dispatcher jobs while
2442 // aborting the old ones. This is needed so that it won't start the second
2443 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2444 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002445 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2446 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502447 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122448
[email protected]57a48d32012-03-03 00:04:552449 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072450 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552451
[email protected]16ee26d2012-03-08 03:34:352452 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212453 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552454 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112455 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202456 }
[email protected]daae1322013-09-05 18:26:502457
2458 if (self)
[email protected]106ccd2c2014-06-17 09:21:002459 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502460}
2461
2462void HostResolverImpl::AbortDnsTasks() {
2463 // Pause the dispatcher so it won't start any new dispatcher jobs while
2464 // aborting the old ones. This is needed so that it won't start the second
2465 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002466 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2467 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502468 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2469
avi9e72eb482016-12-09 21:10:542470 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502471 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002472 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032473}
2474
[email protected]78eac2a2012-03-14 19:09:272475void HostResolverImpl::TryServingAllJobsFromHosts() {
2476 if (!HaveDnsConfig())
2477 return;
2478
2479 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2480 // http://crbug.com/117655
2481
2482 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072483 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272484
avi9e72eb482016-12-09 21:10:542485 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2486 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272487 ++it;
2488 // This could remove |job| from |jobs_|, but iterator will remain valid.
2489 job->ServeFromHosts();
2490 }
2491}
2492
[email protected]be1a48b2011-01-20 00:12:132493void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372494 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182495 // Abandon all ProbeJobs.
2496 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172497 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102498 cache_->OnNetworkChange();
[email protected]7c466e92013-07-20 01:44:482499#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232500 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132501#endif
2502 AbortAllInProgressJobs();
2503 // |this| may be deleted inside AbortAllInProgressJobs().
2504}
2505
ttuttlecf1158bf2016-03-18 16:37:442506void HostResolverImpl::OnConnectionTypeChanged(
2507 NetworkChangeNotifier::ConnectionType type) {
2508 proc_params_.unresponsive_delay =
2509 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2510 "DnsUnresponsiveDelayMsByConnectionType",
2511 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2512 type);
2513}
2514
pauljensen101ed372015-04-17 00:11:422515void HostResolverImpl::OnInitialDNSConfigRead() {
2516 UpdateDNSConfig(false);
2517}
2518
[email protected]bb0e34542012-08-31 19:52:402519void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422520 UpdateDNSConfig(true);
2521}
2522
2523void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402524 DnsConfig dns_config;
2525 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592526
[email protected]b4481b222012-03-16 17:13:112527 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002528 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2529 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112530 }
2531
[email protected]01b3b9d2012-08-13 16:18:142532 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192533 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522534 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2535 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272536
[email protected]a8883e452012-11-17 05:58:062537 num_dns_failures_ = 0;
2538
[email protected]01b3b9d2012-08-13 16:18:142539 // We want a new DnsSession in place, before we Abort running Jobs, so that
2540 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022541 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192542 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422543 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022544 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422545 // If we just switched DnsClients, restart jobs using new resolver.
2546 // TODO(pauljensen): Is this necessary?
2547 config_changed = true;
2548 }
[email protected]f0f602bd2012-11-15 18:01:022549 }
[email protected]01b3b9d2012-08-13 16:18:142550
pauljensen101ed372015-04-17 00:11:422551 if (config_changed) {
2552 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232553 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422554 // as NSCD's cache should be dropped automatically by the OS when
2555 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172556 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232557 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142558
pauljensen101ed372015-04-17 00:11:422559 // Life check to bail once |this| is deleted.
2560 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022561
pauljensen101ed372015-04-17 00:11:422562 // Existing jobs will have been sent to the original server so they need to
2563 // be aborted.
2564 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142565
pauljensen101ed372015-04-17 00:11:422566 // |this| may be deleted inside AbortAllInProgressJobs().
2567 if (self.get())
2568 TryServingAllJobsFromHosts();
2569 }
[email protected]78eac2a2012-03-14 19:09:272570}
2571
2572bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252573 // Use DnsClient only if it's fully configured and there is no override by
2574 // ScopedDefaultHostResolverProc.
2575 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2576 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042577 return dns_client_ && dns_client_->GetConfig() &&
2578 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202579}
2580
[email protected]1ffdda82012-12-12 23:04:222581void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022582 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222583 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022584 num_dns_failures_ = 0;
2585 return;
2586 }
2587 ++num_dns_failures_;
2588 if (num_dns_failures_ < kMaximumDnsFailures)
2589 return;
[email protected]daae1322013-09-05 18:26:502590
2591 // Disable DnsClient until the next DNS change. Must be done before aborting
2592 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022593 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502594
2595 // Switch jobs with active DnsTasks over to using ProcTasks.
2596 AbortDnsTasks();
2597
[email protected]f0f602bd2012-11-15 18:01:022598 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
davidbenad6fc442015-05-18 20:59:132599 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2600 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022601}
2602
danakj22f90e72016-04-16 01:55:402603void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502604 // DnsClient and config must be updated before aborting DnsTasks, since doing
2605 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482606 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502607 if (dns_client_ && !dns_client_->GetConfig() &&
2608 num_dns_failures_ < kMaximumDnsFailures) {
2609 DnsConfig dns_config;
2610 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2611 dns_client_->SetConfig(dns_config);
2612 num_dns_failures_ = 0;
2613 if (dns_client_->GetConfig())
2614 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062615 }
[email protected]daae1322013-09-05 18:26:502616
2617 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062618}
2619
juliatuttled7fa5852016-07-29 13:16:572620void HostResolverImpl::InitializePersistence(
2621 const PersistCallback& persist_callback,
2622 std::unique_ptr<const base::Value> old_data) {
2623 DCHECK(!persist_initialized_);
2624 persist_callback_ = persist_callback;
2625 persist_initialized_ = true;
2626 if (old_data)
2627 ApplyPersistentData(std::move(old_data));
2628}
2629
juliatuttle7e8bf1c2016-08-02 19:09:092630void HostResolverImpl::ApplyPersistentData(
2631 std::unique_ptr<const base::Value> data) {}
2632
2633std::unique_ptr<const base::Value> HostResolverImpl::GetPersistentData() {
2634 return std::unique_ptr<const base::Value>();
2635}
2636
juliatuttled7fa5852016-07-29 13:16:572637void HostResolverImpl::SchedulePersist() {
2638 if (!persist_initialized_ || persist_timer_.IsRunning())
2639 return;
2640 persist_timer_.Start(
2641 FROM_HERE, base::TimeDelta::FromSeconds(kPersistDelaySec),
2642 base::Bind(&HostResolverImpl::DoPersist, weak_ptr_factory_.GetWeakPtr()));
2643}
2644
2645void HostResolverImpl::DoPersist() {
2646 DCHECK(persist_initialized_);
2647 persist_callback_.Run(GetPersistentData());
2648}
2649
maksim.sisov31452af2016-07-27 06:38:102650HostResolverImpl::RequestImpl::~RequestImpl() {
2651 if (job_)
2652 job_->CancelRequest(this);
2653}
2654
2655void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2656 RequestPriority priority) {
2657 job_->ChangeRequestPriority(this, priority);
2658}
2659
[email protected]b59ff372009-07-15 22:04:322660} // namespace net