blob: adadb247a568847973742785a7a0aec1013550fd [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"
mmenke91c17162016-06-02 16:03:2334#include "base/debug/leak_annotations.h"
[email protected]58580352010-10-26 04:07:5035#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4636#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2337#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4538#include "base/metrics/field_trial.h"
davidbenad6fc442015-05-18 20:59:1339#include "base/metrics/histogram_macros.h"
40#include "base/metrics/sparse_histogram.h"
eromane1867242015-04-23 23:07:4441#include "base/profiler/scoped_tracker.h"
anujk.sharma7c907f02015-05-29 02:55:4442#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4843#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0544#include "base/strings/utf_string_conversions.h"
gabf767595f2016-05-11 18:50:3545#include "base/threading/thread_task_runner_handle.h"
[email protected]ac9ba8fe2010-12-30 18:08:3646#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3147#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5648#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4649#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2050#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3251#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5152#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5153#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4854#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1555#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4856#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1857#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4658#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2759#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2060#include "net/dns/dns_config_service.h"
61#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3562#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2063#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2064#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0365#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5366#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0767#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1968#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0069#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1970#include "net/log/net_log_parameters_callback.h"
71#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0072#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1973#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5174#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2675#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1476#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3277
78#if defined(OS_WIN)
79#include "net/base/winsock_init.h"
80#endif
81
tfarinada9e1362017-03-14 16:49:0682#if defined(OS_ANDROID)
83#include "net/android/network_library.h"
84#endif
85
[email protected]b59ff372009-07-15 22:04:3286namespace net {
87
[email protected]e95d3aca2010-01-11 22:47:4388namespace {
89
ttuttlecf1158bf2016-03-18 16:37:4490// Default delay between calls to the system resolver for the same hostname.
91// (Can be overridden by field trial.)
92const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
93
[email protected]6e78dfb2011-07-28 21:34:4794// Limit the size of hostnames that will be resolved to combat issues in
95// some platform's resolvers.
96const size_t kMaxHostLength = 4096;
97
[email protected]a2730882012-01-21 00:56:2798// Default TTL for successful resolutions with ProcTask.
99const unsigned kCacheEntryTTLSeconds = 60;
100
[email protected]b3601bc22012-02-21 21:23:20101// Default TTL for unsuccessful resolutions with ProcTask.
102const unsigned kNegativeCacheEntryTTLSeconds = 0;
103
[email protected]895123222012-10-25 15:21:17104// Minimum TTL for successful resolutions with DnsTask.
105const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
106
sergeyub8cdc212015-05-14 18:50:37107// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
108// cached.
109const int kIPv6ProbePeriodMs = 1000;
110
111// Google DNS address used for IPv6 probes.
112const uint8_t kIPv6ProbeAddress[] =
113 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
114 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
115
[email protected]24f4bab2010-10-15 01:27:11116// We use a separate histogram name for each platform to facilitate the
117// display of error codes by their symbolic name (since each platform has
118// different mappings).
119const char kOSErrorsForGetAddrinfoHistogramName[] =
120#if defined(OS_WIN)
121 "Net.OSErrorsForGetAddrinfo_Win";
122#elif defined(OS_MACOSX)
123 "Net.OSErrorsForGetAddrinfo_Mac";
124#elif defined(OS_LINUX)
125 "Net.OSErrorsForGetAddrinfo_Linux";
126#else
127 "Net.OSErrorsForGetAddrinfo";
128#endif
129
[email protected]c89b2442011-05-26 14:28:27130// Gets a list of the likely error codes that getaddrinfo() can return
131// (non-exhaustive). These are the error codes that we will track via
132// a histogram.
133std::vector<int> GetAllGetAddrinfoOSErrors() {
134 int os_errors[] = {
135#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51136#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37137#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45138 // EAI_ADDRFAMILY has been declared obsolete in Android's and
139 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27140 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37141#endif
[email protected]c48aef92011-11-22 23:41:45142 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51143 EAI_NODATA,
144#endif
[email protected]c89b2442011-05-26 14:28:27145 EAI_AGAIN,
146 EAI_BADFLAGS,
147 EAI_FAIL,
148 EAI_FAMILY,
149 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27150 EAI_NONAME,
151 EAI_SERVICE,
152 EAI_SOCKTYPE,
153 EAI_SYSTEM,
154#elif defined(OS_WIN)
155 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
156 WSA_NOT_ENOUGH_MEMORY,
157 WSAEAFNOSUPPORT,
158 WSAEINVAL,
159 WSAESOCKTNOSUPPORT,
160 WSAHOST_NOT_FOUND,
161 WSANO_DATA,
162 WSANO_RECOVERY,
163 WSANOTINITIALISED,
164 WSATRY_AGAIN,
165 WSATYPE_NOT_FOUND,
166 // The following are not in doc, but might be to appearing in results :-(.
167 WSA_INVALID_HANDLE,
168#endif
169 };
170
171 // Ensure all errors are positive, as histogram only tracks positive values.
172 for (size_t i = 0; i < arraysize(os_errors); ++i) {
173 os_errors[i] = std::abs(os_errors[i]);
174 }
175
176 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
177 arraysize(os_errors));
178}
179
[email protected]1def74c2012-03-22 20:07:00180enum DnsResolveStatus {
181 RESOLVE_STATUS_DNS_SUCCESS = 0,
182 RESOLVE_STATUS_PROC_SUCCESS,
183 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33184 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00185 RESOLVE_STATUS_MAX
186};
187
eroman91dd3602015-03-26 03:46:33188// ICANN uses this localhost address to indicate a name collision.
189//
190// The policy in Chromium is to fail host resolving if it resolves to
191// this special address.
192//
193// Not however that IP literals are exempt from this policy, so it is still
194// possible to navigate to http://127.0.53.53/ directly.
195//
196// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51197const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33198
eroman1efc237c2016-12-14 00:00:45199bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
200 for (const auto& endpoint : addr_list) {
201 const IPAddress& addr = endpoint.address();
202 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
203 return true;
204 }
205 }
206 return false;
207}
208
[email protected]1def74c2012-03-22 20:07:00209void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
210 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
211 result,
212 RESOLVE_STATUS_MAX);
213}
214
[email protected]1d932852012-06-19 19:40:33215bool ResemblesNetBIOSName(const std::string& hostname) {
216 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
217}
218
219// True if |hostname| ends with either ".local" or ".local.".
220bool ResemblesMulticastDNSName(const std::string& hostname) {
221 DCHECK(!hostname.empty());
222 const char kSuffix[] = ".local.";
223 const size_t kSuffixLen = sizeof(kSuffix) - 1;
224 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36225 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33226 return hostname.size() > kSuffixLen &&
227 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
228 }
229 return hostname.size() > kSuffixLenTrimmed &&
230 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
231 kSuffix, kSuffixLenTrimmed);
232}
233
[email protected]34e61362013-07-24 20:41:56234// Attempts to connect a UDP socket to |dest|:53.
tfarina428341112016-09-22 13:38:20235bool IsGloballyReachable(const IPAddress& dest,
236 const NetLogWithSource& net_log) {
eroman0eb394e2015-04-30 23:25:46237 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
238 tracked_objects::ScopedTracker tracking_profile_1(
eroman2734a9d2015-05-05 19:24:38239 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
eroman0eb394e2015-04-30 23:25:46240
danakj22f90e72016-04-16 01:55:40241 std::unique_ptr<DatagramClientSocket> socket(
[email protected]9db6f702013-04-10 18:10:51242 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
danakj22f90e72016-04-16 01:55:40243 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
[email protected]2b74a2f2013-07-23 19:37:38244 net_log.source()));
[email protected]34e61362013-07-24 20:41:56245 int rv = socket->Connect(IPEndPoint(dest, 53));
[email protected]e9051722013-04-12 21:58:18246 if (rv != OK)
247 return false;
248 IPEndPoint endpoint;
249 rv = socket->GetLocalAddress(&endpoint);
250 if (rv != OK)
251 return false;
[email protected]1c7cf3f82014-08-07 21:33:48252 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
martijna23c8962016-03-04 18:18:51253 const IPAddress& address = endpoint.address();
254
255 bool is_link_local =
256 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
[email protected]e9051722013-04-12 21:58:18257 if (is_link_local)
258 return false;
martijna23c8962016-03-04 18:18:51259
Avi Drissman13fc8932015-12-20 04:40:46260 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
martijna23c8962016-03-04 18:18:51261 if (IPAddressStartsWith(address, kTeredoPrefix))
[email protected]e9051722013-04-12 21:58:18262 return false;
martijna23c8962016-03-04 18:18:51263
[email protected]e9051722013-04-12 21:58:18264 return true;
[email protected]9db6f702013-04-10 18:10:51265}
266
[email protected]51b9a6b2012-06-25 21:50:29267// Provide a common macro to simplify code and readability. We must use a
268// macro as the underlying HISTOGRAM macro creates static variables.
269#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
270 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
271
272// A macro to simplify code and readability.
273#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
274 do { \
275 switch (priority) { \
276 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
277 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
278 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
279 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
280 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
mmenke2f23b70292016-10-26 23:26:42281 case THROTTLED: DNS_HISTOGRAM(basename "_THROTTLED", time); break; \
[email protected]51b9a6b2012-06-25 21:50:29282 } \
283 DNS_HISTOGRAM(basename, time); \
284 } while (0)
285
286// Record time from Request creation until a valid DNS response.
287void RecordTotalTime(bool had_dns_config,
288 bool speculative,
289 base::TimeDelta duration) {
290 if (had_dns_config) {
291 if (speculative) {
292 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
293 } else {
294 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
295 }
296 } else {
297 if (speculative) {
298 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
299 } else {
300 DNS_HISTOGRAM("DNS.TotalTime", duration);
301 }
302 }
303}
304
[email protected]1339a2a22012-10-17 08:39:43305void RecordTTL(base::TimeDelta ttl) {
306 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
307 base::TimeDelta::FromSeconds(1),
308 base::TimeDelta::FromDays(1), 100);
309}
310
[email protected]16c2bd72013-06-28 01:19:22311bool ConfigureAsyncDnsNoFallbackFieldTrial() {
312 const bool kDefault = false;
313
314 // Configure the AsyncDns field trial as follows:
315 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
316 // groups AsyncDnsA and AsyncDnsB: return false,
317 // groups SystemDnsA and SystemDnsB: return false,
318 // otherwise (trial absent): return default.
319 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29320 if (!group_name.empty()) {
321 return base::StartsWith(group_name, "AsyncDnsNoFallback",
322 base::CompareCase::INSENSITIVE_ASCII);
323 }
[email protected]16c2bd72013-06-28 01:19:22324 return kDefault;
325}
326
[email protected]d7b9a2b2012-05-31 22:31:19327//-----------------------------------------------------------------------------
328
Avi Drissman13fc8932015-12-20 04:40:46329AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17330 if (list.empty() || list.front().port() == port)
331 return list;
332 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56333}
334
[email protected]ec666ab22013-04-17 20:05:59335// Returns true if |addresses| contains only IPv4 loopback addresses.
336bool IsAllIPv4Loopback(const AddressList& addresses) {
337 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51338 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59339 switch (addresses[i].GetFamily()) {
340 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51341 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59342 return false;
343 break;
344 case ADDRESS_FAMILY_IPV6:
345 return false;
346 default:
347 NOTREACHED();
348 return false;
349 }
350 }
351 return true;
352}
353
tfarinada9e1362017-03-14 16:49:06354// Returns true if it can determine that only loopback addresses are configured.
355// i.e. if only 127.0.0.1 and ::1 are routable.
356// Also returns false if it cannot determine this.
357bool HaveOnlyLoopbackAddresses() {
358#if defined(OS_ANDROID)
359 return android::HaveOnlyLoopbackAddresses();
360#elif defined(OS_NACL)
361 NOTIMPLEMENTED();
362 return false;
363#elif defined(OS_POSIX)
364 struct ifaddrs* interface_addr = NULL;
365 int rv = getifaddrs(&interface_addr);
366 if (rv != 0) {
367 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
368 return false;
369 }
370
371 bool result = true;
372 for (struct ifaddrs* interface = interface_addr;
373 interface != NULL;
374 interface = interface->ifa_next) {
375 if (!(IFF_UP & interface->ifa_flags))
376 continue;
377 if (IFF_LOOPBACK & interface->ifa_flags)
378 continue;
379 const struct sockaddr* addr = interface->ifa_addr;
380 if (!addr)
381 continue;
382 if (addr->sa_family == AF_INET6) {
383 // Safe cast since this is AF_INET6.
384 const struct sockaddr_in6* addr_in6 =
385 reinterpret_cast<const struct sockaddr_in6*>(addr);
386 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
387 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
388 continue;
389 }
390 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
391 continue;
392
393 result = false;
394 break;
395 }
396 freeifaddrs(interface_addr);
397 return result;
398#elif defined(OS_WIN)
399 // TODO(wtc): implement with the GetAdaptersAddresses function.
400 NOTIMPLEMENTED();
401 return false;
402#else
403 NOTIMPLEMENTED();
404 return false;
405#endif // defined(various platforms)
406}
407
[email protected]cd565142012-06-12 16:21:45408// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40409std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46410 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17411 int net_error,
412 int os_error,
413 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40414 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45415 if (attempt_number)
416 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46417
[email protected]cd565142012-06-12 16:21:45418 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16419
[email protected]cd565142012-06-12 16:21:45420 if (os_error) {
421 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46422#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45423 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46424#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45425 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04426 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08427 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
428 0, // Use the internal message table.
429 os_error,
430 0, // Use default language.
431 (LPWSTR)&error_string,
432 0, // Buffer size.
433 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01434 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45435 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46436#endif
[email protected]21526002010-05-16 19:42:46437 }
438
dchengc7eeda422015-12-26 03:56:48439 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45440}
[email protected]a9813302012-04-28 09:29:28441
[email protected]cd565142012-06-12 16:21:45442// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40443std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11444 int net_error,
445 int dns_error,
446 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40447 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45448 dict->SetInteger("net_error", net_error);
449 if (dns_error)
450 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48451 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36452}
[email protected]ee094b82010-08-24 15:55:51453
[email protected]cd565142012-06-12 16:21:45454// Creates NetLog parameters containing the information in a RequestInfo object,
mikecironef22f9812016-10-04 03:40:19455// along with the associated NetLogSource.
danakj22f90e72016-04-16 01:55:40456std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11457 const HostResolver::RequestInfo* info,
458 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40459 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20460
[email protected]cd565142012-06-12 16:21:45461 dict->SetString("host", info->host_port_pair().ToString());
462 dict->SetInteger("address_family",
463 static_cast<int>(info->address_family()));
464 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
465 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48466 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45467}
[email protected]b3601bc22012-02-21 21:23:20468
[email protected]cd565142012-06-12 16:21:45469// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40470std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19471 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11472 const std::string* host,
473 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40474 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11475 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45476 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48477 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45478}
[email protected]a9813302012-04-28 09:29:28479
[email protected]cd565142012-06-12 16:21:45480// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40481std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19482 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11483 RequestPriority priority,
484 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40485 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11486 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56487 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48488 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45489}
[email protected]b3601bc22012-02-21 21:23:20490
[email protected]cd565142012-06-12 16:21:45491// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40492std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11493 const DnsConfig* config,
494 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08495 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45496}
[email protected]b4481b222012-03-16 17:13:11497
danakj22f90e72016-04-16 01:55:40498std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11499 bool ipv6_available,
500 bool cached,
501 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40502 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37503 dict->SetBoolean("ipv6_available", ipv6_available);
504 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48505 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37506}
507
[email protected]0f292de02012-02-01 22:28:20508// The logging routines are defined here because some requests are resolved
509// without a Request object.
510
511// Logs when a request has just been started.
tfarina428341112016-09-22 13:38:20512void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20513 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00514 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
515 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20516}
517
518// Logs when a request has just completed (before its callback is run).
tfarina428341112016-09-22 13:38:20519void LogFinishRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20520 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20521 int net_error) {
xunjieli26f90452014-11-10 16:23:02522 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00523 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20524}
525
526// Logs when a request has been cancelled.
tfarina428341112016-09-22 13:38:20527void LogCancelRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20528 const HostResolverImpl::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00529 source_net_log.AddEvent(NetLogEventType::CANCELLED);
530 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20531}
532
[email protected]b59ff372009-07-15 22:04:32533//-----------------------------------------------------------------------------
534
[email protected]0f292de02012-02-01 22:28:20535// Keeps track of the highest priority.
536class PriorityTracker {
537 public:
[email protected]8c98d002012-07-18 19:02:27538 explicit PriorityTracker(RequestPriority initial_priority)
539 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20540 memset(counts_, 0, sizeof(counts_));
541 }
542
543 RequestPriority highest_priority() const {
544 return highest_priority_;
545 }
546
547 size_t total_count() const {
548 return total_count_;
549 }
550
551 void Add(RequestPriority req_priority) {
552 ++total_count_;
553 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05554 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20555 highest_priority_ = req_priority;
556 }
557
558 void Remove(RequestPriority req_priority) {
559 DCHECK_GT(total_count_, 0u);
560 DCHECK_GT(counts_[req_priority], 0u);
561 --total_count_;
562 --counts_[req_priority];
563 size_t i;
thestiga74ad2b2016-07-11 20:52:36564 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
565 }
[email protected]0f292de02012-02-01 22:28:20566 highest_priority_ = static_cast<RequestPriority>(i);
567
[email protected]31ae7ab2012-04-24 21:09:05568 // In absence of requests, default to MINIMUM_PRIORITY.
569 if (total_count_ == 0)
570 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20571 }
572
573 private:
574 RequestPriority highest_priority_;
575 size_t total_count_;
576 size_t counts_[NUM_PRIORITIES];
577};
578
juliatuttle9fb7aeb2016-06-06 20:16:33579void MakeNotStale(HostCache::EntryStaleness* stale_info) {
580 if (!stale_info)
581 return;
582 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
583 stale_info->network_changes = 0;
584 stale_info->stale_hits = 0;
585}
586
juliatuttled7fa5852016-07-29 13:16:57587// Persist data every five minutes (potentially, cache and learned RTT).
588const int64_t kPersistDelaySec = 300;
589
[email protected]c54a8912012-10-22 22:09:43590} // namespace
[email protected]0f292de02012-02-01 22:28:20591
592//-----------------------------------------------------------------------------
593
tfarina9ed7f8c52016-02-19 17:50:18594bool ResolveLocalHostname(base::StringPiece host,
595 uint16_t port,
596 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18597 address_list->clear();
598
599 bool is_local6;
600 if (!IsLocalHostname(host, &is_local6))
601 return false;
602
martijna23c8962016-03-04 18:18:51603 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18604 if (!is_local6) {
martijna23c8962016-03-04 18:18:51605 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18606 }
607
608 return true;
609}
610
[email protected]daae1322013-09-05 18:26:50611const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
612
[email protected]0f292de02012-02-01 22:28:20613// Holds the data for a request that could not be completed synchronously.
614// It is owned by a Job. Canceled Requests are only marked as canceled rather
615// than removed from the Job's |requests_| list.
maksim.sisov31452af2016-07-27 06:38:10616class HostResolverImpl::RequestImpl : public HostResolver::Request {
[email protected]b59ff372009-07-15 22:04:32617 public:
tfarina428341112016-09-22 13:38:20618 RequestImpl(const NetLogWithSource& source_net_log,
maksim.sisov31452af2016-07-27 06:38:10619 const RequestInfo& info,
620 RequestPriority priority,
621 const CompletionCallback& callback,
622 AddressList* addresses,
623 Job* job)
[email protected]ee094b82010-08-24 15:55:51624 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09625 info_(info),
[email protected]5109c1952013-08-20 18:44:10626 priority_(priority),
maksim.sisov31452af2016-07-27 06:38:10627 job_(job),
[email protected]54e13772009-08-14 03:01:09628 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29629 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10630 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32631
maksim.sisov31452af2016-07-27 06:38:10632 ~RequestImpl() override;
633
634 void ChangeRequestPriority(RequestPriority priority) override;
635
636 void OnJobCancelled(Job* job) {
637 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04638 job_ = nullptr;
639 addresses_ = nullptr;
[email protected]aa22b242011-11-16 18:58:29640 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32641 }
642
[email protected]0f292de02012-02-01 22:28:20643 // Prepare final AddressList and call completion callback.
maksim.sisov31452af2016-07-27 06:38:10644 void OnJobCompleted(Job* job, int error, const AddressList& addr_list) {
645 DCHECK_EQ(job_, job);
[email protected]895123222012-10-25 15:21:17646 if (error == OK)
647 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
maksim.sisov31452af2016-07-27 06:38:10648 job_ = nullptr;
649 addresses_ = nullptr;
650 base::ResetAndReturn(&callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32651 }
652
[email protected]b59ff372009-07-15 22:04:32653 Job* job() const {
654 return job_;
655 }
656
[email protected]0f292de02012-02-01 22:28:20657 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20658 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51659
[email protected]b59ff372009-07-15 22:04:32660 const RequestInfo& info() const {
661 return info_;
662 }
663
[email protected]5109c1952013-08-20 18:44:10664 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31665 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10666
667 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29668
[email protected]b59ff372009-07-15 22:04:32669 private:
tfarina428341112016-09-22 13:38:20670 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09671
[email protected]b59ff372009-07-15 22:04:32672 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10673 const RequestInfo info_;
674
juliatuttlec53b19a72016-05-05 13:51:31675 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32676
[email protected]0f292de02012-02-01 22:28:20677 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32678 Job* job_;
679
680 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29681 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32682
683 // The address list to save result into.
684 AddressList* addresses_;
685
[email protected]51b9a6b2012-06-25 21:50:29686 const base::TimeTicks request_time_;
687
maksim.sisov31452af2016-07-27 06:38:10688 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32689};
690
[email protected]1e9bbd22010-10-15 16:42:45691//------------------------------------------------------------------------------
692
mmenke91c17162016-06-02 16:03:23693// Calls HostResolverProc using a worker task runner. Performs retries if
694// necessary.
[email protected]0f292de02012-02-01 22:28:20695//
696// Whenever we try to resolve the host, we post a delayed task to check if host
697// resolution (OnLookupComplete) is completed or not. If the original attempt
698// hasn't completed, then we start another attempt for host resolution. We take
699// the results from the first attempt that finishes and ignore the results from
700// all other attempts.
701//
702// TODO(szym): Move to separate source file for testing and mocking.
703//
704class HostResolverImpl::ProcTask
705 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32706 public:
[email protected]b3601bc22012-02-21 21:23:20707 typedef base::Callback<void(int net_error,
708 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32709
[email protected]0f292de02012-02-01 22:28:20710 ProcTask(const Key& key,
711 const ProcTaskParams& params,
712 const Callback& callback,
mmenke91c17162016-06-02 16:03:23713 scoped_refptr<base::TaskRunner> worker_task_runner,
tfarina428341112016-09-22 13:38:20714 const NetLogWithSource& job_net_log)
[email protected]0f292de02012-02-01 22:28:20715 : key_(key),
716 params_(params),
717 callback_(callback),
mmenke91c17162016-06-02 16:03:23718 worker_task_runner_(std::move(worker_task_runner)),
719 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
[email protected]0f292de02012-02-01 22:28:20720 attempt_number_(0),
721 completed_attempt_number_(0),
722 completed_attempt_error_(ERR_UNEXPECTED),
723 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20724 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50725 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20726 params_.resolver_proc = HostResolverProc::GetDefault();
727 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50728 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06729 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32730 }
731
[email protected]b59ff372009-07-15 22:04:32732 void Start() {
mmenke91c17162016-06-02 16:03:23733 DCHECK(network_task_runner_->BelongsToCurrentThread());
mikecirone8b85c432016-09-08 19:11:00734 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54735 StartLookupAttempt();
736 }
[email protected]252b699b2010-02-05 21:38:06737
[email protected]0f292de02012-02-01 22:28:20738 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23739 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20740 // attempts complete will the final reference to this ProcTask be released.
741 void Cancel() {
mmenke91c17162016-06-02 16:03:23742 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20743
[email protected]0adcb2b2012-08-15 21:30:46744 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20745 return;
746
[email protected]0f292de02012-02-01 22:28:20747 callback_.Reset();
mikecirone8b85c432016-09-08 19:11:00748 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20749 }
750
751 void set_had_non_speculative_request() {
mmenke91c17162016-06-02 16:03:23752 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20753 had_non_speculative_request_ = true;
754 }
755
756 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23757 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20758 return callback_.is_null();
759 }
760
761 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23762 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20763 return completed_attempt_number_ > 0;
764 }
765
766 private:
[email protected]a9813302012-04-28 09:29:28767 friend class base::RefCountedThreadSafe<ProcTask>;
768 ~ProcTask() {}
769
[email protected]189163e2011-05-11 01:48:54770 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23771 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54772 base::TimeTicks start_time = base::TimeTicks::Now();
773 ++attempt_number_;
774 // Dispatch the lookup attempt to a worker thread.
mmenke91c17162016-06-02 16:03:23775 if (!worker_task_runner_->PostTask(
776 FROM_HERE, base::Bind(&ProcTask::DoLookup, this, start_time,
777 attempt_number_))) {
[email protected]b59ff372009-07-15 22:04:32778 NOTREACHED();
779
mmenke91c17162016-06-02 16:03:23780 // Since this method may have been called from Resolve(), can't just call
781 // OnLookupComplete(). Instead, must wait until Resolve() has returned
782 // (IO_PENDING).
783 network_task_runner_->PostTask(
784 FROM_HERE,
785 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
786 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54787 return;
[email protected]b59ff372009-07-15 22:04:32788 }
[email protected]13024882011-05-18 23:19:16789
mikecirone8b85c432016-09-08 19:11:00790 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28791 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16792
mmenke91c17162016-06-02 16:03:23793 // If the results aren't received within a given time, RetryIfNotComplete
794 // will start a new attempt if none of the outstanding attempts have
795 // completed yet.
[email protected]0f292de02012-02-01 22:28:20796 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23797 network_task_runner_->PostDelayedTask(
798 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42799 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58800 }
[email protected]b59ff372009-07-15 22:04:32801 }
802
mmenke91c17162016-06-02 16:03:23803 // WARNING: In production, this code runs on a worker pool. The shutdown code
804 // cannot wait for it to finish, so this code must be very careful about using
805 // other objects (like MessageLoops, Singletons, etc). During shutdown these
806 // objects may no longer exist. Multiple DoLookups() could be running in
807 // parallel, so any state inside of |this| must not mutate .
[email protected]189163e2011-05-11 01:48:54808 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46809 const uint32_t attempt_number) {
[email protected]189163e2011-05-11 01:48:54810 AddressList results;
811 int os_error = 0;
mmenke91c17162016-06-02 16:03:23812 // Running on a worker task runner.
[email protected]0f292de02012-02-01 22:28:20813 int error = params_.resolver_proc->Resolve(key_.hostname,
814 key_.address_family,
815 key_.host_resolver_flags,
816 &results,
817 &os_error);
[email protected]b59ff372009-07-15 22:04:32818
mmenke91c17162016-06-02 16:03:23819 network_task_runner_->PostTask(
820 FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
821 start_time, attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54822 }
823
mmenke91c17162016-06-02 16:03:23824 // Makes next attempt if DoLookup() has not finished.
[email protected]0f292de02012-02-01 22:28:20825 void RetryIfNotComplete() {
mmenke91c17162016-06-02 16:03:23826 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54827
[email protected]0f292de02012-02-01 22:28:20828 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54829 return;
830
[email protected]0f292de02012-02-01 22:28:20831 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54832 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32833 }
834
anujk.sharma7c907f02015-05-29 02:55:44835 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54836 void OnLookupComplete(const AddressList& results,
837 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46838 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54839 int error,
840 const int os_error) {
xunjieli0b7f5b62016-12-06 20:43:48841 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
mmenke91c17162016-06-02 16:03:23842 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23843 // If results are empty, we should return an error.
844 bool empty_list_on_ok = (error == OK && results.empty());
845 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
846 if (empty_list_on_ok)
847 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54848
849 bool was_retry_attempt = attempt_number > 1;
850
[email protected]2d3b7762010-10-09 00:35:47851 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20852 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23853 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54854 if (error != OK && NetworkChangeNotifier::IsOffline())
855 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47856
[email protected]b3601bc22012-02-21 21:23:20857 // If this is the first attempt that is finishing later, then record data
858 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54859 if (!was_retry_attempt)
860 RecordPerformanceHistograms(start_time, error, os_error);
861
862 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35863
[email protected]0f292de02012-02-01 22:28:20864 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32865 return;
866
mikecironef22f9812016-10-04 03:40:19867 NetLogParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20868 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45869 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
870 attempt_number,
871 error,
872 os_error);
[email protected]0f292de02012-02-01 22:28:20873 } else {
tfarina5e24b242015-10-27 13:11:28874 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20875 }
mikecirone8b85c432016-09-08 19:11:00876 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
[email protected]cd565142012-06-12 16:21:45877 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20878
879 if (was_completed())
880 return;
881
882 // Copy the results from the first worker thread that resolves the host.
883 results_ = results;
884 completed_attempt_number_ = attempt_number;
885 completed_attempt_error_ = error;
886
[email protected]e87b8b512011-06-14 22:12:52887 if (was_retry_attempt) {
888 // If retry attempt finishes before 1st attempt, then get stats on how
889 // much time is saved by having spawned an extra attempt.
890 retry_attempt_finished_time_ = base::TimeTicks::Now();
891 }
892
[email protected]189163e2011-05-11 01:48:54893 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45894 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
895 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51896 } else {
[email protected]cd565142012-06-12 16:21:45897 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51898 }
mikecirone8b85c432016-09-08 19:11:00899 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45900 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51901
[email protected]b3601bc22012-02-21 21:23:20902 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32903 }
904
[email protected]189163e2011-05-11 01:48:54905 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
906 const int error,
907 const int os_error) const {
mmenke91c17162016-06-02 16:03:23908 DCHECK(network_task_runner_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35909 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45910 RESOLVE_SUCCESS,
911 RESOLVE_FAIL,
912 RESOLVE_SPECULATIVE_SUCCESS,
913 RESOLVE_SPECULATIVE_FAIL,
914 RESOLVE_MAX, // Bounding value.
915 };
916 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
917
[email protected]189163e2011-05-11 01:48:54918 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
919 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45920 if (had_non_speculative_request_) {
921 category = RESOLVE_SUCCESS;
922 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
923 } else {
924 category = RESOLVE_SPECULATIVE_SUCCESS;
925 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
926 }
[email protected]7e96d792011-06-10 17:08:23927
[email protected]78eac2a2012-03-14 19:09:27928 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23929 // if IPv4 or IPv4/6 lookups are faster or slower.
thestiga74ad2b2016-07-11 20:52:36930 switch (key_.address_family) {
[email protected]7e96d792011-06-10 17:08:23931 case ADDRESS_FAMILY_IPV4:
932 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
933 break;
934 case ADDRESS_FAMILY_IPV6:
935 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
936 break;
937 case ADDRESS_FAMILY_UNSPECIFIED:
938 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
939 break;
940 }
[email protected]1e9bbd22010-10-15 16:42:45941 } else {
942 if (had_non_speculative_request_) {
943 category = RESOLVE_FAIL;
944 DNS_HISTOGRAM("DNS.ResolveFail", duration);
945 } else {
946 category = RESOLVE_SPECULATIVE_FAIL;
947 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
948 }
[email protected]78eac2a2012-03-14 19:09:27949 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23950 // if IPv4 or IPv4/6 lookups are faster or slower.
thestiga74ad2b2016-07-11 20:52:36951 switch (key_.address_family) {
[email protected]7e96d792011-06-10 17:08:23952 case ADDRESS_FAMILY_IPV4:
953 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
954 break;
955 case ADDRESS_FAMILY_IPV6:
956 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
957 break;
958 case ADDRESS_FAMILY_UNSPECIFIED:
959 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
960 break;
961 }
[email protected]c833e322010-10-16 23:51:36962 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54963 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45964 GetAllGetAddrinfoOSErrors());
965 }
[email protected]051b6ab2010-10-18 16:50:46966 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45967
968 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45969 }
970
[email protected]189163e2011-05-11 01:48:54971 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46972 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54973 const int error,
974 const int os_error) const {
mmenke91c17162016-06-02 16:03:23975 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54976 bool first_attempt_to_complete =
977 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52978 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45979
[email protected]189163e2011-05-11 01:48:54980 if (first_attempt_to_complete) {
981 // If this was first attempt to complete, then record the resolution
982 // status of the attempt.
983 if (completed_attempt_error_ == OK) {
984 UMA_HISTOGRAM_ENUMERATION(
985 "DNS.AttemptFirstSuccess", attempt_number, 100);
986 } else {
987 UMA_HISTOGRAM_ENUMERATION(
988 "DNS.AttemptFirstFailure", attempt_number, 100);
989 }
990 }
991
992 if (error == OK)
993 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
994 else
995 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
996
[email protected]e87b8b512011-06-14 22:12:52997 // If first attempt didn't finish before retry attempt, then calculate stats
998 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20999 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:521000 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
1001 base::TimeTicks::Now() - retry_attempt_finished_time_);
1002 }
1003
[email protected]0f292de02012-02-01 22:28:201004 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:541005 // Count those attempts which completed after the job was already canceled
1006 // OR after the job was already completed by an earlier attempt (so in
1007 // effect).
1008 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
1009
[email protected]0f292de02012-02-01 22:28:201010 // Record if job is canceled.
1011 if (was_canceled())
[email protected]189163e2011-05-11 01:48:541012 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
1013 }
1014
1015 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
1016 if (error == OK)
1017 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
1018 else
1019 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
1020 }
[email protected]1e9bbd22010-10-15 16:42:451021
anujk.sharma7c907f02015-05-29 02:55:441022 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:571023 Key key_;
[email protected]b59ff372009-07-15 22:04:321024
[email protected]0f292de02012-02-01 22:28:201025 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:321026 // This may not be the current resolver procedure by the time we call
1027 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
1028 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:201029 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:321030
[email protected]0f292de02012-02-01 22:28:201031 // The listener to the results of this ProcTask.
1032 Callback callback_;
1033
mmenke91c17162016-06-02 16:03:231034 // Task runner for the call to the HostResolverProc.
1035 scoped_refptr<base::TaskRunner> worker_task_runner_;
1036
1037 // Used to post events onto the network thread.
1038 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
[email protected]189163e2011-05-11 01:48:541039
1040 // Keeps track of the number of attempts we have made so far to resolve the
1041 // host. Whenever we start an attempt to resolve the host, we increase this
1042 // number.
Avi Drissman13fc8932015-12-20 04:40:461043 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:541044
1045 // The index of the attempt which finished first (or 0 if the job is still in
1046 // progress).
Avi Drissman13fc8932015-12-20 04:40:461047 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:541048
1049 // The result (a net error code) from the first attempt to complete.
1050 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:061051
[email protected]e87b8b512011-06-14 22:12:521052 // The time when retry attempt was finished.
1053 base::TimeTicks retry_attempt_finished_time_;
1054
[email protected]252b699b2010-02-05 21:38:061055 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:201056 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:061057 // This boolean is used for histogramming the duration of jobs used to
1058 // service non-speculative requests.
1059 bool had_non_speculative_request_;
1060
[email protected]b59ff372009-07-15 22:04:321061 AddressList results_;
1062
tfarina428341112016-09-22 13:38:201063 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:511064
[email protected]0f292de02012-02-01 22:28:201065 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:321066};
1067
1068//-----------------------------------------------------------------------------
1069
mmenke91c17162016-06-02 16:03:231070// Wraps a call to HaveOnlyLoopbackAddresses to be executed on a
1071// |worker_task_runner|, as it takes 40-100ms and should not block
1072// initialization.
[email protected]12faa4c2012-11-06 04:44:181073class HostResolverImpl::LoopbackProbeJob {
1074 public:
mmenke91c17162016-06-02 16:03:231075 LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver,
1076 base::TaskRunner* worker_task_runner)
1077 : resolver_(resolver), result_(false) {
[email protected]11fbca0b2013-06-02 23:37:211078 DCHECK(resolver.get());
mmenke91c17162016-06-02 16:03:231079
1080 // |worker_task_runner| may posts tasks to the WorkerPool, so need this to
1081 // avoid reporting worker pool leaks in tests. The WorkerPool doesn't have a
1082 // flushing API, so can't do anything about them, other than using another
1083 // task runner.
1084 // http://crbug.com/248513
1085 ANNOTATE_SCOPED_MEMORY_LEAK;
1086
1087 worker_task_runner->PostTaskAndReply(
[email protected]12faa4c2012-11-06 04:44:181088 FROM_HERE,
1089 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
mmenke91c17162016-06-02 16:03:231090 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)));
[email protected]12faa4c2012-11-06 04:44:181091 }
1092
1093 virtual ~LoopbackProbeJob() {}
1094
1095 private:
1096 // Runs on worker thread.
1097 void DoProbe() {
1098 result_ = HaveOnlyLoopbackAddresses();
1099 }
1100
1101 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:211102 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:181103 return;
1104 resolver_->SetHaveOnlyLoopbackAddresses(result_);
1105 }
1106
anujk.sharma7c907f02015-05-29 02:55:441107 // Used/set only on task runner thread.
[email protected]12faa4c2012-11-06 04:44:181108 base::WeakPtr<HostResolverImpl> resolver_;
1109
1110 bool result_;
1111
1112 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
1113};
1114
[email protected]0f8f1b432010-03-16 19:06:031115//-----------------------------------------------------------------------------
1116
[email protected]b3601bc22012-02-21 21:23:201117// Resolves the hostname using DnsTransaction.
1118// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461119class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201120 public:
[email protected]daae1322013-09-05 18:26:501121 class Delegate {
1122 public:
1123 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1124 int net_error,
1125 const AddressList& addr_list,
1126 base::TimeDelta ttl) = 0;
1127
1128 // Called when the first of two jobs succeeds. If the first completed
1129 // transaction fails, this is not called. Also not called when the DnsTask
1130 // only needs to run one transaction.
1131 virtual void OnFirstDnsTransactionComplete() = 0;
1132
1133 protected:
1134 Delegate() {}
1135 virtual ~Delegate() {}
1136 };
[email protected]b3601bc22012-02-21 21:23:201137
[email protected]0adcb2b2012-08-15 21:30:461138 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201139 const Key& key,
[email protected]daae1322013-09-05 18:26:501140 Delegate* delegate,
tfarina428341112016-09-22 13:38:201141 const NetLogWithSource& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461142 : client_(client),
[email protected]daae1322013-09-05 18:26:501143 key_(key),
1144 delegate_(delegate),
1145 net_log_(job_net_log),
1146 num_completed_transactions_(0),
1147 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461148 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501149 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501150 }
1151
[email protected]daae1322013-09-05 18:26:501152 bool needs_two_transactions() const {
1153 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1154 }
1155
1156 bool needs_another_transaction() const {
1157 return needs_two_transactions() && !transaction_aaaa_;
1158 }
1159
1160 void StartFirstTransaction() {
1161 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001162 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501163 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1164 StartAAAA();
1165 } else {
1166 StartA();
1167 }
1168 }
1169
1170 void StartSecondTransaction() {
1171 DCHECK(needs_two_transactions());
1172 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121173 }
1174
1175 private:
[email protected]daae1322013-09-05 18:26:501176 void StartA() {
1177 DCHECK(!transaction_a_);
1178 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1179 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1180 transaction_a_->Start();
1181 }
1182
1183 void StartAAAA() {
1184 DCHECK(!transaction_aaaa_);
1185 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1186 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1187 transaction_aaaa_->Start();
1188 }
1189
danakj22f90e72016-04-16 01:55:401190 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501191 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1192 return client_->GetTransactionFactory()->CreateTransaction(
1193 key_.hostname,
1194 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1195 dns_protocol::kTypeA,
1196 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1197 base::TimeTicks::Now()),
1198 net_log_);
1199 }
1200
1201 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001202 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201203 int net_error,
1204 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471205 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511206 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461207 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511208 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461209 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1210 return;
[email protected]6c411902012-08-14 22:36:361211 }
[email protected]0adcb2b2012-08-15 21:30:461212
[email protected]02cd6982013-01-10 20:12:511213 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1214 switch (transaction->GetType()) {
1215 case dns_protocol::kTypeA:
1216 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1217 break;
1218 case dns_protocol::kTypeAAAA:
1219 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1220 break;
1221 }
[email protected]daae1322013-09-05 18:26:501222
[email protected]0adcb2b2012-08-15 21:30:461223 AddressList addr_list;
1224 base::TimeDelta ttl;
1225 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1226 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1227 result,
1228 DnsResponse::DNS_PARSE_RESULT_MAX);
1229 if (result != DnsResponse::DNS_PARSE_OK) {
1230 // Fail even if the other query succeeds.
1231 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1232 return;
1233 }
1234
[email protected]daae1322013-09-05 18:26:501235 ++num_completed_transactions_;
1236 if (num_completed_transactions_ == 1) {
1237 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461238 } else {
[email protected]daae1322013-09-05 18:26:501239 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461240 }
1241
[email protected]daae1322013-09-05 18:26:501242 if (transaction->GetType() == dns_protocol::kTypeA) {
1243 DCHECK_EQ(transaction_a_.get(), transaction);
1244 // Place IPv4 addresses after IPv6.
1245 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1246 } else {
1247 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1248 // Place IPv6 addresses before IPv4.
1249 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1250 }
1251
1252 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1253 // No need to repeat the suffix search.
1254 key_.hostname = transaction->GetHostname();
1255 delegate_->OnFirstDnsTransactionComplete();
1256 return;
1257 }
1258
1259 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121260 // TODO(szym): Don't fallback to ProcTask in this case.
1261 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461262 return;
1263 }
1264
[email protected]daae1322013-09-05 18:26:501265 // If there are multiple addresses, and at least one is IPv6, need to sort
1266 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1267 // sufficient to just check the family of the first address.
1268 if (addr_list_.size() > 1 &&
1269 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1270 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461271 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501272 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071273 base::Bind(&DnsTask::OnSortComplete,
1274 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501275 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461276 } else {
[email protected]daae1322013-09-05 18:26:501277 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461278 }
1279 }
1280
1281 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461282 bool success,
1283 const AddressList& addr_list) {
1284 if (!success) {
1285 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1286 base::TimeTicks::Now() - start_time);
1287 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1288 return;
1289 }
1290
1291 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1292 base::TimeTicks::Now() - start_time);
1293
1294 // AddressSorter prunes unusable destinations.
1295 if (addr_list.empty()) {
1296 LOG(WARNING) << "Address list empty after RFC3484 sort";
1297 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1298 return;
1299 }
1300
[email protected]daae1322013-09-05 18:26:501301 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461302 }
1303
1304 void OnFailure(int net_error, DnsResponse::Result result) {
1305 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451306 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001307 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451308 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501309 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1310 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201311 }
1312
[email protected]daae1322013-09-05 18:26:501313 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001314 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461315 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501316 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461317 }
1318
1319 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501320 Key key_;
1321
[email protected]b3601bc22012-02-21 21:23:201322 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501323 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201324 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201325
danakj22f90e72016-04-16 01:55:401326 std::unique_ptr<DnsTransaction> transaction_a_;
1327 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461328
[email protected]daae1322013-09-05 18:26:501329 unsigned num_completed_transactions_;
1330
1331 // These are updated as each transaction completes.
1332 base::TimeDelta ttl_;
1333 // IPv6 addresses must appear first in the list.
1334 AddressList addr_list_;
1335
1336 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461337
1338 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201339};
1340
1341//-----------------------------------------------------------------------------
1342
[email protected]0f292de02012-02-01 22:28:201343// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501344class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1345 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391346 public:
[email protected]0f292de02012-02-01 22:28:201347 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351348 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181349 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201350 const Key& key,
[email protected]8c98d002012-07-18 19:02:271351 RequestPriority priority,
mmenke91c17162016-06-02 16:03:231352 scoped_refptr<base::TaskRunner> worker_task_runner,
tfarina428341112016-09-22 13:38:201353 const NetLogWithSource& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181354 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201355 key_(key),
[email protected]8c98d002012-07-18 19:02:271356 priority_tracker_(priority),
mmenke91c17162016-06-02 16:03:231357 worker_task_runner_(std::move(worker_task_runner)),
[email protected]0f292de02012-02-01 22:28:201358 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291359 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501360 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331361 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291362 creation_time_(base::TimeTicks::Now()),
1363 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201364 net_log_(
1365 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001366 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1367 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201368
mikecirone8b85c432016-09-08 19:11:001369 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1370 base::Bind(&NetLogJobCreationCallback,
1371 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391372 }
1373
dchengb03027d2014-10-21 12:00:201374 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201375 if (is_running()) {
1376 // |resolver_| was destroyed with this Job still in flight.
1377 // Clean-up, record in the log, but don't run any callbacks.
1378 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201379 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041380 proc_task_ = nullptr;
[email protected]0f292de02012-02-01 22:28:201381 }
[email protected]16ee26d2012-03-08 03:34:351382 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501383 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001384 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201385 ERR_ABORTED);
1386 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551387 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351388 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001389 net_log_.AddEvent(NetLogEventType::CANCELLED);
1390 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391391 }
[email protected]b3601bc22012-02-21 21:23:201392 // else CompleteRequests logged EndEvent.
maksim.sisov31452af2016-07-27 06:38:101393 if (!requests_.empty()) {
1394 // Log any remaining Requests as cancelled.
1395 for (RequestImpl* req : requests_) {
1396 DCHECK_EQ(this, req->job());
maksim.sisov31452af2016-07-27 06:38:101397 LogCancelRequest(req->source_net_log(), req->info());
maksim.sisov320d5962016-08-15 18:02:511398 req->OnJobCancelled(this);
maksim.sisov31452af2016-07-27 06:38:101399 }
1400 requests_.clear();
[email protected]b3601bc22012-02-21 21:23:201401 }
[email protected]68ad3ee2010-01-30 03:45:391402 }
1403
[email protected]daae1322013-09-05 18:26:501404 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1405 // of the queue.
1406 void Schedule(bool at_head) {
1407 DCHECK(!is_queued());
1408 PrioritizedDispatcher::Handle handle;
1409 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001410 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501411 } else {
[email protected]106ccd2c2014-06-17 09:21:001412 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501413 }
1414 // The dispatcher could have started |this| in the above call to Add, which
1415 // could have called Schedule again. In that case |handle| will be null,
1416 // but |handle_| may have been set by the other nested call to Schedule.
1417 if (!handle.is_null()) {
1418 DCHECK(handle_.is_null());
1419 handle_ = handle;
1420 }
[email protected]16ee26d2012-03-08 03:34:351421 }
1422
maksim.sisov31452af2016-07-27 06:38:101423 void AddRequest(RequestImpl* request) {
1424 DCHECK_EQ(key_.hostname, request->info().hostname());
[email protected]0f292de02012-02-01 22:28:201425
maksim.sisov31452af2016-07-27 06:38:101426 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201427
maksim.sisov31452af2016-07-27 06:38:101428 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001429 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451430 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201431
1432 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001433 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101434 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451435 priority()));
[email protected]0f292de02012-02-01 22:28:201436
1437 // TODO(szym): Check if this is still needed.
maksim.sisov31452af2016-07-27 06:38:101438 if (!request->info().is_speculative()) {
[email protected]0f292de02012-02-01 22:28:201439 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501440 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201441 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391442 }
[email protected]b3601bc22012-02-21 21:23:201443
maksim.sisov31452af2016-07-27 06:38:101444 requests_.push_back(request);
[email protected]b3601bc22012-02-21 21:23:201445
[email protected]51b9a6b2012-06-25 21:50:291446 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391447 }
1448
maksim.sisov31452af2016-07-27 06:38:101449 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
juliatuttlec53b19a72016-05-05 13:51:311450 DCHECK_EQ(key_.hostname, req->info().hostname());
juliatuttlec53b19a72016-05-05 13:51:311451
1452 priority_tracker_.Remove(req->priority());
1453 req->set_priority(priority);
1454 priority_tracker_.Add(req->priority());
1455 UpdatePriority();
1456 }
1457
maksim.sisov31452af2016-07-27 06:38:101458 // Detach cancelled request. If it was the last active Request, also finishes
1459 // this Job.
1460 void CancelRequest(RequestImpl* request) {
1461 DCHECK_EQ(key_.hostname, request->info().hostname());
1462 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351463
maksim.sisov31452af2016-07-27 06:38:101464 LogCancelRequest(request->source_net_log(), request->info());
[email protected]16ee26d2012-03-08 03:34:351465
maksim.sisov31452af2016-07-27 06:38:101466 priority_tracker_.Remove(request->priority());
1467 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001468 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101469 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1470 priority()));
[email protected]b3601bc22012-02-21 21:23:201471
[email protected]16ee26d2012-03-08 03:34:351472 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291473 UpdatePriority();
maksim.sisov31452af2016-07-27 06:38:101474 RemoveRequest(request);
[email protected]16ee26d2012-03-08 03:34:351475 } else {
1476 // If we were called from a Request's callback within CompleteRequests,
1477 // that Request could not have been cancelled, so num_active_requests()
1478 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431479 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201480 }
[email protected]68ad3ee2010-01-30 03:45:391481 }
1482
maksim.sisov31452af2016-07-27 06:38:101483 void RemoveRequest(RequestImpl* request) {
1484 auto it = std::find(requests_.begin(), requests_.end(), request);
1485 DCHECK(it != requests_.end());
1486 requests_.erase(it);
1487 }
1488
[email protected]7af985a2012-12-14 22:40:421489 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1490 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111491 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201492 void Abort() {
[email protected]0f292de02012-02-01 22:28:201493 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421494 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201495 }
1496
[email protected]f0f602bd2012-11-15 18:01:021497 // If DnsTask present, abort it and fall back to ProcTask.
1498 void AbortDnsTask() {
1499 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501500 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021501 dns_task_error_ = OK;
1502 StartProcTask();
1503 }
1504 }
1505
[email protected]16ee26d2012-03-08 03:34:351506 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1507 // Completes all requests and destroys the job.
1508 void OnEvicted() {
1509 DCHECK(!is_running());
1510 DCHECK(is_queued());
1511 handle_.Reset();
1512
mikecirone8b85c432016-09-08 19:11:001513 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351514
1515 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431516 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351517 }
1518
[email protected]78eac2a2012-03-14 19:09:271519 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1520 // this Job was destroyed.
1521 bool ServeFromHosts() {
1522 DCHECK_GT(num_active_requests(), 0u);
1523 AddressList addr_list;
1524 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031525 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271526 &addr_list)) {
1527 // This will destroy the Job.
eroman0cd87b62016-12-14 19:13:451528 CompleteRequests(MakeCacheEntry(OK, addr_list), base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271529 return true;
1530 }
1531 return false;
1532 }
1533
tanay.c6ddd5f6f2015-08-25 06:34:571534 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111535
1536 bool is_queued() const {
1537 return !handle_.is_null();
1538 }
1539
1540 bool is_running() const {
1541 return is_dns_running() || is_proc_running();
1542 }
1543
[email protected]16ee26d2012-03-08 03:34:351544 private:
[email protected]daae1322013-09-05 18:26:501545 void KillDnsTask() {
1546 if (dns_task_) {
1547 ReduceToOneJobSlot();
1548 dns_task_.reset();
1549 }
1550 }
1551
1552 // Reduce the number of job slots occupied and queued in the dispatcher
1553 // to one. If the second Job slot is queued in the dispatcher, cancels the
1554 // queued job. Otherwise, the second Job has been started by the
1555 // PrioritizedDispatcher, so signals it is complete.
1556 void ReduceToOneJobSlot() {
1557 DCHECK_GE(num_occupied_job_slots_, 1u);
1558 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001559 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501560 handle_.Reset();
1561 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001562 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501563 --num_occupied_job_slots_;
1564 }
1565 DCHECK_EQ(1u, num_occupied_job_slots_);
1566 }
1567
eroman0cd87b62016-12-14 19:13:451568 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1569 // HostCache::Entry(). The address list is omited from the cache entry
1570 // for errors.
1571 HostCache::Entry MakeCacheEntry(int net_error,
1572 const AddressList& addr_list) const {
1573 return HostCache::Entry(
1574 net_error,
1575 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList());
1576 }
1577
1578 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1579 const AddressList& addr_list,
1580 base::TimeDelta ttl) const {
1581 return HostCache::Entry(
1582 net_error,
1583 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1584 ttl);
1585 }
1586
juliatuttlec53b19a72016-05-05 13:51:311587 AddressList MakeAddressListForRequest(const AddressList& list) const {
1588 if (requests_.empty())
1589 return list;
1590 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1591 }
1592
[email protected]51b9a6b2012-06-25 21:50:291593 void UpdatePriority() {
1594 if (is_queued()) {
1595 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1596 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001597 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291598 }
1599 }
1600
[email protected]16ee26d2012-03-08 03:34:351601 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201602 void Start() override {
[email protected]daae1322013-09-05 18:26:501603 DCHECK_LE(num_occupied_job_slots_, 1u);
1604
[email protected]70c04ab2013-08-22 16:05:121605 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501606 ++num_occupied_job_slots_;
1607
1608 if (num_occupied_job_slots_ == 2) {
1609 StartSecondDnsTransaction();
1610 return;
1611 }
1612
1613 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201614
mikecirone8b85c432016-09-08 19:11:001615 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201616
[email protected]51b9a6b2012-06-25 21:50:291617 had_dns_config_ = resolver_->HaveDnsConfig();
1618
1619 base::TimeTicks now = base::TimeTicks::Now();
1620 base::TimeDelta queue_time = now - creation_time_;
1621 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1622
1623 if (had_dns_config_) {
1624 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1625 queue_time);
1626 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1627 queue_time_after_change);
1628 } else {
1629 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1630 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1631 queue_time_after_change);
1632 }
1633
[email protected]443714fad2013-09-19 04:52:011634 bool system_only =
1635 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1636
[email protected]1d932852012-06-19 19:40:331637 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011638 if (!system_only && had_dns_config_ &&
1639 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201640 StartDnsTask();
1641 } else {
1642 StartProcTask();
1643 }
1644 }
1645
[email protected]b3601bc22012-02-21 21:23:201646 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1647 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1648 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1649 // tighter limits.
1650 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351651 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231652 proc_task_ =
1653 new ProcTask(key_, resolver_->proc_params_,
1654 base::Bind(&Job::OnProcTaskComplete,
1655 base::Unretained(this), base::TimeTicks::Now()),
1656 worker_task_runner_, net_log_);
[email protected]0f292de02012-02-01 22:28:201657
1658 if (had_non_speculative_request_)
1659 proc_task_->set_had_non_speculative_request();
1660 // Start() could be called from within Resolve(), hence it must NOT directly
1661 // call OnProcTaskComplete, for example, on synchronous failure.
1662 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391663 }
1664
[email protected]0f292de02012-02-01 22:28:201665 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371666 void OnProcTaskComplete(base::TimeTicks start_time,
1667 int net_error,
1668 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201669 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391670
[email protected]62e86ba2013-01-29 18:59:161671 if (!resolver_->resolved_known_ipv6_hostname_ &&
1672 net_error == OK &&
1673 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1674 if (key_.hostname == "www.google.com") {
1675 resolver_->resolved_known_ipv6_hostname_ = true;
1676 bool got_ipv6_address = false;
1677 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021678 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161679 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021680 break;
1681 }
[email protected]62e86ba2013-01-29 18:59:161682 }
1683 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1684 }
1685 }
1686
[email protected]1d932852012-06-19 19:40:331687 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371688 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001689 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371690 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331691 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1692 ResemblesNetBIOSName(key_.hostname)) {
1693 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1694 } else {
1695 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1696 }
davidbenad6fc442015-05-18 20:59:131697 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1698 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221699 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001700 } else {
[email protected]e3bd4822012-10-23 18:01:371701 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001702 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1703 }
1704 }
1705
eroman1efc237c2016-12-14 00:00:451706 if (ContainsIcannNameCollisionIp(addr_list))
1707 net_error = ERR_ICANN_NAME_COLLISION;
1708
[email protected]1339a2a22012-10-17 08:39:431709 base::TimeDelta ttl =
1710 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201711 if (net_error == OK)
1712 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391713
[email protected]895123222012-10-25 15:21:171714 // Don't store the |ttl| in cache since it's not obtained from the server.
eroman0cd87b62016-12-14 19:13:451715 CompleteRequests(MakeCacheEntry(net_error, addr_list), ttl);
[email protected]b3601bc22012-02-21 21:23:201716 }
1717
1718 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271719 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501720 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1721 net_log_));
[email protected]b3601bc22012-02-21 21:23:201722
[email protected]daae1322013-09-05 18:26:501723 dns_task_->StartFirstTransaction();
1724 // Schedule a second transaction, if needed.
1725 if (dns_task_->needs_two_transactions())
1726 Schedule(true);
1727 }
1728
1729 void StartSecondDnsTransaction() {
1730 DCHECK(dns_task_->needs_two_transactions());
1731 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221732 }
1733
1734 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1735 // deleted before this callback. In this case dns_task is deleted as well,
1736 // so we use it as indicator whether Job is still valid.
1737 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1738 base::TimeDelta duration,
1739 int net_error) {
1740 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1741
wezb9820d42016-06-22 23:41:041742 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221743 return;
1744
1745 dns_task_error_ = net_error;
1746
1747 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1748 // http://crbug.com/117655
1749
1750 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1751 // ProcTask in that case is a waste of time.
1752 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501753 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221754 StartProcTask();
1755 } else {
1756 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1757 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201758 }
1759 }
1760
[email protected]daae1322013-09-05 18:26:501761
1762 // HostResolverImpl::DnsTask::Delegate implementation:
1763
dchengb03027d2014-10-21 12:00:201764 void OnDnsTaskComplete(base::TimeTicks start_time,
1765 int net_error,
1766 const AddressList& addr_list,
1767 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201768 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201769
[email protected]e3bd4822012-10-23 18:01:371770 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201771 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221772 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201773 return;
1774 }
[email protected]e3bd4822012-10-23 18:01:371775 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511776 // Log DNS lookups based on |address_family|.
thestiga74ad2b2016-07-11 20:52:361777 switch (key_.address_family) {
[email protected]02cd6982013-01-10 20:12:511778 case ADDRESS_FAMILY_IPV4:
1779 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1780 break;
1781 case ADDRESS_FAMILY_IPV6:
1782 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1783 break;
1784 case ADDRESS_FAMILY_UNSPECIFIED:
1785 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1786 break;
1787 }
[email protected]b3601bc22012-02-21 21:23:201788
[email protected]1def74c2012-03-22 20:07:001789 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431790 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461791
[email protected]1ffdda82012-12-12 23:04:221792 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021793
[email protected]895123222012-10-25 15:21:171794 base::TimeDelta bounded_ttl =
1795 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1796
eroman0cd87b62016-12-14 19:13:451797 if (ContainsIcannNameCollisionIp(addr_list)) {
1798 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1799 } else {
1800 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list, ttl),
1801 bounded_ttl);
1802 }
[email protected]b3601bc22012-02-21 21:23:201803 }
1804
dchengb03027d2014-10-21 12:00:201805 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501806 DCHECK(dns_task_->needs_two_transactions());
1807 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1808 // No longer need to occupy two dispatcher slots.
1809 ReduceToOneJobSlot();
1810
1811 // We already have a job slot at the dispatcher, so if the second
1812 // transaction hasn't started, reuse it now instead of waiting in the queue
1813 // for the second slot.
1814 if (dns_task_->needs_another_transaction())
1815 dns_task_->StartSecondTransaction();
1816 }
1817
[email protected]16ee26d2012-03-08 03:34:351818 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171819 void CompleteRequests(const HostCache::Entry& entry,
1820 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211821 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201822
[email protected]16ee26d2012-03-08 03:34:351823 // This job must be removed from resolver's |jobs_| now to make room for a
1824 // new job with the same key in case one of the OnComplete callbacks decides
1825 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1826 // is done.
danakj22f90e72016-04-16 01:55:401827 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351828
1829 resolver_->RemoveJob(this);
1830
[email protected]16ee26d2012-03-08 03:34:351831 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351832 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501833 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351834 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041835 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351836 }
[email protected]daae1322013-09-05 18:26:501837 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351838
1839 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001840 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351841 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001842 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351843 handle_.Reset();
1844 }
1845
1846 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001847 net_log_.AddEvent(NetLogEventType::CANCELLED);
1848 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351849 OK);
1850 return;
1851 }
[email protected]b3601bc22012-02-21 21:23:201852
mikecirone8b85c432016-09-08 19:11:001853 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221854 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391855
juliatuttled7fa5852016-07-29 13:16:571856 resolver_->SchedulePersist();
1857
[email protected]78eac2a2012-03-14 19:09:271858 DCHECK(!requests_.empty());
1859
eroman1efc237c2016-12-14 00:00:451860 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191861 // Record this histogram here, when we know the system has a valid DNS
1862 // configuration.
[email protected]539df6c2012-06-19 21:21:291863 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1864 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191865 }
[email protected]16ee26d2012-03-08 03:34:351866
juliatuttle317860e2016-05-12 14:47:221867 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1868 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
juliatuttle7e8bf1c2016-08-02 19:09:091869 if (did_complete) {
[email protected]1339a2a22012-10-17 08:39:431870 resolver_->CacheResult(key_, entry, ttl);
juliatuttle7e8bf1c2016-08-02 19:09:091871 // Erase any previous cache hit callbacks, since a new DNS request went
1872 // out since they were set.
1873 resolver_->cache_hit_callbacks_.erase(key_);
1874 }
[email protected]16ee26d2012-03-08 03:34:351875
maksim.sisov31452af2016-07-27 06:38:101876 // Complete all of the requests that were attached to the job and
1877 // detach them.
1878 while (!requests_.empty()) {
1879 RequestImpl* req = requests_.front();
1880 requests_.pop_front();
[email protected]0f292de02012-02-01 22:28:201881 DCHECK_EQ(this, req->job());
1882 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221883 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291884 if (did_complete) {
juliatuttle7e8bf1c2016-08-02 19:09:091885 resolver_->MaybeAddCacheHitCallback(key_, req->info());
[email protected]51b9a6b2012-06-25 21:50:291886 // Record effective total time from creation to completion.
1887 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1888 base::TimeTicks::Now() - req->request_time());
1889 }
maksim.sisov31452af2016-07-27 06:38:101890 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201891
1892 // Check if the resolver was destroyed as a result of running the
1893 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211894 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201895 return;
1896 }
1897 }
1898
[email protected]1339a2a22012-10-17 08:39:431899 // Convenience wrapper for CompleteRequests in case of failure.
1900 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171901 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1902 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431903 }
1904
[email protected]b4481b222012-03-16 17:13:111905 RequestPriority priority() const {
1906 return priority_tracker_.highest_priority();
1907 }
1908
1909 // Number of non-canceled requests in |requests_|.
1910 size_t num_active_requests() const {
1911 return priority_tracker_.total_count();
1912 }
1913
wezb9820d42016-06-22 23:41:041914 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111915
wezb9820d42016-06-22 23:41:041916 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111917
[email protected]0f292de02012-02-01 22:28:201918 base::WeakPtr<HostResolverImpl> resolver_;
1919
1920 Key key_;
1921
1922 // Tracks the highest priority across |requests_|.
1923 PriorityTracker priority_tracker_;
1924
mmenke91c17162016-06-02 16:03:231925 // Task runner where the HostResolverProc is invoked.
1926 scoped_refptr<base::TaskRunner> worker_task_runner_;
1927
[email protected]0f292de02012-02-01 22:28:201928 bool had_non_speculative_request_;
1929
[email protected]51b9a6b2012-06-25 21:50:291930 // Distinguishes measurements taken while DnsClient was fully configured.
1931 bool had_dns_config_;
1932
[email protected]daae1322013-09-05 18:26:501933 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1934 unsigned num_occupied_job_slots_;
1935
[email protected]1d932852012-06-19 19:40:331936 // Result of DnsTask.
1937 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001938
[email protected]51b9a6b2012-06-25 21:50:291939 const base::TimeTicks creation_time_;
1940 base::TimeTicks priority_change_time_;
1941
tfarina428341112016-09-22 13:38:201942 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201943
[email protected]b3601bc22012-02-21 21:23:201944 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201945 scoped_refptr<ProcTask> proc_task_;
1946
[email protected]b3601bc22012-02-21 21:23:201947 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401948 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201949
[email protected]0f292de02012-02-01 22:28:201950 // All Requests waiting for the result of this Job. Some can be canceled.
maksim.sisov31452af2016-07-27 06:38:101951 std::deque<RequestImpl*> requests_;
[email protected]0f292de02012-02-01 22:28:201952
[email protected]16ee26d2012-03-08 03:34:351953 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201954 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391955};
1956
1957//-----------------------------------------------------------------------------
1958
[email protected]0f292de02012-02-01 22:28:201959HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431960 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201961 size_t max_retry_attempts)
1962 : resolver_proc(resolver_proc),
1963 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441964 unresponsive_delay(
1965 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201966 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001967 // Maximum of 4 retry attempts for host resolution.
1968 static const size_t kDefaultMaxRetryAttempts = 4u;
1969 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1970 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201971}
1972
vmpstracd23b72016-02-26 21:08:551973HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1974 default;
1975
[email protected]0f292de02012-02-01 22:28:201976HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1977
[email protected]106ccd2c2014-06-17 09:21:001978HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231979 : HostResolverImpl(
1980 options,
1981 net_log,
1982 base::WorkerPool::GetTaskRunner(true /* task_is_slow */)) {}
[email protected]b59ff372009-07-15 22:04:321983
1984HostResolverImpl::~HostResolverImpl() {
[email protected]daae1322013-09-05 18:26:501985 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001986 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541987 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501988 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541989 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431990
[email protected]232a5812011-03-04 22:42:081991 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441992 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401993 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321994}
1995
[email protected]0f292de02012-02-01 22:28:201996void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001997 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201998 DCHECK_GT(value, 0u);
1999 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:132000}
2001
[email protected]684970b2009-08-14 04:54:462002int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:102003 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:322004 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:292005 const CompletionCallback& callback,
maksim.sisov31452af2016-07-27 06:38:102006 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:202007 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:402008 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:142009 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:292010 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:102011 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:142012
[email protected]e806cd72013-05-17 02:08:432013 // Check that the caller supplied a valid hostname to resolve.
mmenked6e9161aff2016-09-09 21:55:442014 if (!IsValidDNSDomain(info.hostname()))
[email protected]e806cd72013-05-17 02:08:432015 return ERR_NAME_NOT_RESOLVED;
2016
xunjieli26f90452014-11-10 16:23:022017 LogStartRequest(source_net_log, info);
[email protected]b59ff372009-07-15 22:04:322018
martijna23c8962016-03-04 18:18:512019 IPAddress ip_address;
2020 IPAddress* ip_address_ptr = nullptr;
2021 if (ip_address.AssignFromIPLiteral(info.hostname()))
2022 ip_address_ptr = &ip_address;
pauljensen19eb73422015-04-15 23:20:062023
[email protected]123ab1e32009-10-21 19:12:572024 // Build a key that identifies the request in the cache and in the
2025 // outstanding jobs map.
martijna23c8962016-03-04 18:18:512026 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
[email protected]123ab1e32009-10-21 19:12:572027
juliatuttle9fb7aeb2016-06-06 20:16:332028 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, false, nullptr,
2029 source_net_log);
[email protected]95a214c2011-08-04 21:50:402030 if (rv != ERR_DNS_CACHE_MISS) {
juliatuttle7e8bf1c2016-08-02 19:09:092031 MaybeAddCacheHitCallback(key, info);
xunjieli26f90452014-11-10 16:23:022032 LogFinishRequest(source_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:292033 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:402034 return rv;
[email protected]38368712011-03-02 08:09:402035 }
2036
[email protected]0f292de02012-02-01 22:28:202037 // Next we need to attach our request to a "job". This job is responsible for
2038 // calling "getaddrinfo(hostname)" on a worker thread.
2039
avi9e72eb482016-12-09 21:10:542040 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:202041 Job* job;
2042 if (jobit == jobs_.end()) {
mmenke91c17162016-06-02 16:03:232043 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
2044 worker_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:502045 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:202046
2047 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:002048 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
2049 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:202050 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:352051 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:202052 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:202053 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:022054 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:202055 return rv;
2056 }
[email protected]0f292de02012-02-01 22:28:202057 }
avi9e72eb482016-12-09 21:10:542058 jobs_[key] = base::WrapUnique(job);
[email protected]0f292de02012-02-01 22:28:202059 } else {
avi9e72eb482016-12-09 21:10:542060 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:202061 }
2062
2063 // Can't complete synchronously. Create and attach request.
avi9e72eb482016-12-09 21:10:542064 auto req = base::MakeUnique<RequestImpl>(source_net_log, info, priority,
2065 callback, addresses, job);
maksim.sisov31452af2016-07-27 06:38:102066 job->AddRequest(req.get());
2067 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:322068
[email protected]0f292de02012-02-01 22:28:202069 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:322070 return ERR_IO_PENDING;
2071}
2072
mmenke91c17162016-06-02 16:03:232073HostResolverImpl::HostResolverImpl(
2074 const Options& options,
2075 NetLog* net_log,
2076 scoped_refptr<base::TaskRunner> worker_task_runner)
2077 : max_queued_jobs_(0),
2078 proc_params_(NULL, options.max_retry_attempts),
2079 net_log_(net_log),
2080 received_dns_config_(false),
2081 num_dns_failures_(0),
mgersh3eba057d2017-02-28 18:50:562082 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
mmenke91c17162016-06-02 16:03:232083 use_local_ipv6_(false),
2084 last_ipv6_probe_result_(true),
2085 resolved_known_ipv6_hostname_(false),
2086 additional_resolver_flags_(0),
2087 fallback_to_proctask_(true),
2088 worker_task_runner_(std::move(worker_task_runner)),
juliatuttled7fa5852016-07-29 13:16:572089 persist_initialized_(false),
mmenke91c17162016-06-02 16:03:232090 weak_ptr_factory_(this),
2091 probe_weak_ptr_factory_(this) {
2092 if (options.enable_caching)
2093 cache_ = HostCache::CreateDefaultCache();
2094
2095 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2096 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2097 max_queued_jobs_ = job_limits.total_jobs * 100u;
2098
2099 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2100
2101#if defined(OS_WIN)
2102 EnsureWinsockInit();
2103#endif
2104#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2105 RunLoopbackProbeJob();
2106#endif
2107 NetworkChangeNotifier::AddIPAddressObserver(this);
2108 NetworkChangeNotifier::AddConnectionTypeObserver(this);
2109 NetworkChangeNotifier::AddDNSObserver(this);
2110#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
2111 !defined(OS_ANDROID)
2112 EnsureDnsReloaderInit();
2113#endif
2114
2115 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
2116
2117 {
2118 DnsConfig dns_config;
2119 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2120 received_dns_config_ = dns_config.IsValid();
2121 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2122 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2123 }
2124
2125 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2126}
2127
2128void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2129 if (result) {
2130 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2131 } else {
2132 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2133 }
2134}
2135
[email protected]287d7c22011-11-15 17:34:252136int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:402137 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512138 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402139 AddressList* addresses,
juliatuttle9fb7aeb2016-06-06 20:16:332140 bool allow_stale,
2141 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202142 const NetLogWithSource& source_net_log) {
juliatuttle9fb7aeb2016-06-06 20:16:332143 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402144 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2145 // On Windows it gives the default interface's address, whereas on Linux it
2146 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332147 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2148 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402149 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332150 }
[email protected]95a214c2011-08-04 21:50:402151
2152 int net_error = ERR_UNEXPECTED;
juliatuttle9fb7aeb2016-06-06 20:16:332153 if (ResolveAsIP(key, info, ip_address, &net_error, addresses)) {
2154 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402155 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332156 }
2157 if (ServeFromCache(key, info, &net_error, addresses, allow_stale,
2158 stale_info)) {
mgersh33d23c02017-03-29 20:24:252159 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2160 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332161 // |ServeFromCache()| will set |*stale_info| as needed.
juliatuttle7e8bf1c2016-08-02 19:09:092162 RunCacheHitCallbacks(key, info);
[email protected]78eac2a2012-03-14 19:09:272163 return net_error;
2164 }
2165 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2166 // http://crbug.com/117655
2167 if (ServeFromHosts(key, info, addresses)) {
mgersh33d23c02017-03-29 20:24:252168 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2169 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332170 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272171 return OK;
2172 }
estarkd1bc206e2015-06-20 00:44:392173
juliatuttle9fb7aeb2016-06-06 20:16:332174 if (ServeLocalhost(key, info, addresses)) {
2175 MakeNotStale(stale_info);
estarkd1bc206e2015-06-20 00:44:392176 return OK;
juliatuttle9fb7aeb2016-06-06 20:16:332177 }
estarkd1bc206e2015-06-20 00:44:392178
[email protected]78eac2a2012-03-14 19:09:272179 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402180}
2181
2182int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2183 AddressList* addresses,
tfarina428341112016-09-22 13:38:202184 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:402185 DCHECK(CalledOnValidThread());
2186 DCHECK(addresses);
2187
[email protected]95a214c2011-08-04 21:50:402188 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022189 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402190
martijna23c8962016-03-04 18:18:512191 IPAddress ip_address;
2192 IPAddress* ip_address_ptr = nullptr;
2193 if (ip_address.AssignFromIPLiteral(info.hostname()))
2194 ip_address_ptr = &ip_address;
[email protected]95a214c2011-08-04 21:50:402195
martijna23c8962016-03-04 18:18:512196 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
pauljensen19eb73422015-04-15 23:20:062197
juliatuttle9fb7aeb2016-06-06 20:16:332198 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, false, nullptr,
2199 source_net_log);
xunjieli26f90452014-11-10 16:23:022200 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402201 return rv;
2202}
2203
[email protected]a8883e452012-11-17 05:58:062204void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2205 DCHECK(CalledOnValidThread());
2206#if defined(ENABLE_BUILT_IN_DNS)
2207 if (enabled && !dns_client_) {
2208 SetDnsClient(DnsClient::CreateClient(net_log_));
2209 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402210 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062211 }
2212#endif
2213}
2214
[email protected]489d1a82011-10-12 03:09:112215HostCache* HostResolverImpl::GetHostCache() {
2216 return cache_.get();
2217}
[email protected]95a214c2011-08-04 21:50:402218
danakj22f90e72016-04-16 01:55:402219std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242220 // Check if async DNS is disabled.
2221 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082222 return nullptr;
[email protected]17e92032012-03-29 00:56:242223
2224 // Check if async DNS is enabled, but we currently have no configuration
2225 // for it.
2226 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042227 if (!dns_config)
ricea2deef682016-09-09 08:04:072228 return base::MakeUnique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242229
2230 return dns_config->ToValue();
2231}
2232
juliatuttle9fb7aeb2016-06-06 20:16:332233int HostResolverImpl::ResolveStaleFromCache(
2234 const RequestInfo& info,
2235 AddressList* addresses,
2236 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202237 const NetLogWithSource& source_net_log) {
juliatuttle9fb7aeb2016-06-06 20:16:332238 DCHECK(CalledOnValidThread());
2239 DCHECK(addresses);
2240 DCHECK(stale_info);
2241
2242 // Update the net log and notify registered observers.
2243 LogStartRequest(source_net_log, info);
2244
2245 IPAddress ip_address;
2246 IPAddress* ip_address_ptr = nullptr;
2247 if (ip_address.AssignFromIPLiteral(info.hostname()))
2248 ip_address_ptr = &ip_address;
2249
2250 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2251
2252 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, true, stale_info,
2253 source_net_log);
2254 LogFinishRequest(source_net_log, info, rv);
2255 return rv;
2256}
2257
mgersh3eba057d2017-02-28 18:50:562258void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
2259 DCHECK(CalledOnValidThread());
2260 default_address_family_ = address_family;
2261}
2262
2263AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
2264 return default_address_family_;
2265}
2266
[email protected]95a214c2011-08-04 21:50:402267bool HostResolverImpl::ResolveAsIP(const Key& key,
2268 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512269 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402270 int* net_error,
2271 AddressList* addresses) {
2272 DCHECK(addresses);
2273 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512274 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402275 return false;
2276
[email protected]95a214c2011-08-04 21:50:402277 *net_error = OK;
martijna23c8962016-03-04 18:18:512278 AddressFamily family = GetAddressFamily(*ip_address);
mgersh3eba057d2017-02-28 18:50:562279 if (family == ADDRESS_FAMILY_IPV6 &&
2280 default_address_family_ == ADDRESS_FAMILY_IPV4) {
2281 // Don't return IPv6 addresses if default address family is set to IPv4.
2282 *net_error = ERR_NAME_NOT_RESOLVED;
2283 }
cbentzel1906f872015-06-05 16:25:252284 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2285 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482286 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402287 *net_error = ERR_NAME_NOT_RESOLVED;
2288 } else {
martijna23c8962016-03-04 18:18:512289 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562290 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2291 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402292 }
2293 return true;
2294}
2295
2296bool HostResolverImpl::ServeFromCache(const Key& key,
2297 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402298 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332299 AddressList* addresses,
2300 bool allow_stale,
2301 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402302 DCHECK(addresses);
2303 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332304 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402305 if (!info.allow_cached_response() || !cache_.get())
2306 return false;
2307
juliatuttle9fb7aeb2016-06-06 20:16:332308 const HostCache::Entry* cache_entry;
2309 if (allow_stale)
2310 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2311 else
2312 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402313 if (!cache_entry)
2314 return false;
2315
juliatuttle317860e2016-05-12 14:47:222316 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562317 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432318 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222319 RecordTTL(cache_entry->ttl());
2320 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562321 }
[email protected]95a214c2011-08-04 21:50:402322 return true;
2323}
2324
[email protected]78eac2a2012-03-14 19:09:272325bool HostResolverImpl::ServeFromHosts(const Key& key,
2326 const RequestInfo& info,
2327 AddressList* addresses) {
2328 DCHECK(addresses);
2329 if (!HaveDnsConfig())
2330 return false;
[email protected]05a79d42013-03-28 07:30:092331 addresses->clear();
2332
[email protected]cb507622012-03-23 16:17:062333 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222334 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062335
[email protected]05a79d42013-03-28 07:30:092336 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2337
[email protected]78eac2a2012-03-14 19:09:272338 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2339 // (glibc and c-ares) return the first matching line. We have more
2340 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092341 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2342 // necessary.
2343 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2344 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2345 DnsHosts::const_iterator it = hosts.find(
2346 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2347 if (it != hosts.end())
2348 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272349 }
2350
[email protected]05a79d42013-03-28 07:30:092351 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2352 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2353 DnsHosts::const_iterator it = hosts.find(
2354 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2355 if (it != hosts.end())
2356 addresses->push_back(IPEndPoint(it->second, info.port()));
2357 }
2358
[email protected]ec666ab22013-04-17 20:05:592359 // If got only loopback addresses and the family was restricted, resolve
2360 // again, without restrictions. See SystemHostResolverCall for rationale.
2361 if ((key.host_resolver_flags &
2362 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2363 IsAllIPv4Loopback(*addresses)) {
2364 Key new_key(key);
2365 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2366 new_key.host_resolver_flags &=
2367 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2368 return ServeFromHosts(new_key, info, addresses);
2369 }
[email protected]05a79d42013-03-28 07:30:092370 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272371}
2372
estarkd1bc206e2015-06-20 00:44:392373bool HostResolverImpl::ServeLocalhost(const Key& key,
2374 const RequestInfo& info,
2375 AddressList* addresses) {
2376 AddressList resolved_addresses;
2377 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2378 return false;
2379
2380 addresses->clear();
2381
2382 for (const auto& address : resolved_addresses) {
2383 // Include the address if:
2384 // - caller didn't specify an address family, or
2385 // - caller specifically asked for the address family of this address, or
2386 // - this is an IPv6 address and caller specifically asked for IPv4 due
2387 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2388 // rationale).
2389 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2390 key.address_family == address.GetFamily() ||
2391 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2392 key.address_family == ADDRESS_FAMILY_IPV4 &&
2393 (key.host_resolver_flags &
2394 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2395 addresses->push_back(address);
2396 }
2397 }
2398
2399 return true;
2400}
2401
[email protected]16ee26d2012-03-08 03:34:352402void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432403 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352404 base::TimeDelta ttl) {
2405 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432406 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032407}
2408
[email protected]0f292de02012-02-01 22:28:202409void HostResolverImpl::RemoveJob(Job* job) {
2410 DCHECK(job);
avi9e72eb482016-12-09 21:10:542411 auto it = jobs_.find(job->key());
2412 if (it != jobs_.end() && it->second.get() == job) {
2413 it->second.release();
[email protected]16ee26d2012-03-08 03:34:352414 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542415 }
[email protected]b59ff372009-07-15 22:04:322416}
2417
[email protected]137af622010-02-05 02:14:352418HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062419 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512420 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202421 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272422 HostResolverFlags effective_flags =
2423 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352424 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512425
mgersh3eba057d2017-02-28 18:50:562426 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED)
2427 effective_address_family = default_address_family_;
2428
2429 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2430 // When resolving IPv4 literals, there's no need to probe for IPv6.
2431 // When resolving IPv6 literals, there's no benefit to artificially
2432 // limiting our resolution based on a probe. Prior logic ensures
2433 // that this query is UNSPECIFIED (see effective_address_family
2434 // check above) so the code requesting the resolution should be amenable
2435 // to receiving a IPv6 resolution.
2436 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2437 effective_address_family = ADDRESS_FAMILY_IPV4;
2438 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512439 }
2440
estarkd1bc206e2015-06-20 00:44:392441 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352442}
2443
tfarina428341112016-09-22 13:38:202444bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
eroman1a17ef32016-12-14 01:06:092445 // Cache the result for kIPv6ProbePeriodMs (measured from after
2446 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372447 bool cached = true;
eroman1a17ef32016-12-14 01:06:092448 if ((base::TimeTicks::Now() - last_ipv6_probe_time_).InMilliseconds() >
2449 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512450 last_ipv6_probe_result_ =
2451 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
eroman1a17ef32016-12-14 01:06:092452 last_ipv6_probe_time_ = base::TimeTicks::Now();
sergeyub8cdc212015-05-14 18:50:372453 cached = false;
2454 }
mikecirone8b85c432016-09-08 19:11:002455 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372456 base::Bind(&NetLogIPv6AvailableCallback,
2457 last_ipv6_probe_result_, cached));
2458 return last_ipv6_probe_result_;
2459}
2460
mmenke91c17162016-06-02 16:03:232461void HostResolverImpl::RunLoopbackProbeJob() {
2462 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr(),
2463 worker_task_runner_.get());
2464}
2465
[email protected]35ddc282010-09-21 23:42:062466void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202467 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2468 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402469 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542470 for (auto it = jobs_.begin(); it != jobs_.end();) {
2471 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202472 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542473 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202474 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202475 } else {
[email protected]b3601bc22012-02-21 21:23:202476 DCHECK(job->is_queued());
2477 ++it;
[email protected]0f292de02012-02-01 22:28:202478 }
[email protected]ef4c40c2010-09-01 14:42:032479 }
[email protected]b3601bc22012-02-21 21:23:202480
[email protected]daae1322013-09-05 18:26:502481 // Pause the dispatcher so it won't start any new dispatcher jobs while
2482 // aborting the old ones. This is needed so that it won't start the second
2483 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2484 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002485 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2486 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502487 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122488
[email protected]57a48d32012-03-03 00:04:552489 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072490 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552491
[email protected]16ee26d2012-03-08 03:34:352492 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212493 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552494 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112495 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202496 }
[email protected]daae1322013-09-05 18:26:502497
2498 if (self)
[email protected]106ccd2c2014-06-17 09:21:002499 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502500}
2501
2502void HostResolverImpl::AbortDnsTasks() {
2503 // Pause the dispatcher so it won't start any new dispatcher jobs while
2504 // aborting the old ones. This is needed so that it won't start the second
2505 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002506 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2507 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502508 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2509
avi9e72eb482016-12-09 21:10:542510 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502511 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002512 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032513}
2514
[email protected]78eac2a2012-03-14 19:09:272515void HostResolverImpl::TryServingAllJobsFromHosts() {
2516 if (!HaveDnsConfig())
2517 return;
2518
2519 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2520 // http://crbug.com/117655
2521
2522 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072523 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272524
avi9e72eb482016-12-09 21:10:542525 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2526 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272527 ++it;
2528 // This could remove |job| from |jobs_|, but iterator will remain valid.
2529 job->ServeFromHosts();
2530 }
2531}
2532
[email protected]be1a48b2011-01-20 00:12:132533void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162534 resolved_known_ipv6_hostname_ = false;
sergeyub8cdc212015-05-14 18:50:372535 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182536 // Abandon all ProbeJobs.
2537 probe_weak_ptr_factory_.InvalidateWeakPtrs();
juliatuttle7e8bf1c2016-08-02 19:09:092538 if (cache_.get()) {
mgersh5bb3b9d2017-02-13 21:27:102539 cache_->OnNetworkChange();
juliatuttle7e8bf1c2016-08-02 19:09:092540 cache_hit_callbacks_.clear();
2541 }
[email protected]7c466e92013-07-20 01:44:482542#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232543 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132544#endif
2545 AbortAllInProgressJobs();
2546 // |this| may be deleted inside AbortAllInProgressJobs().
2547}
2548
ttuttlecf1158bf2016-03-18 16:37:442549void HostResolverImpl::OnConnectionTypeChanged(
2550 NetworkChangeNotifier::ConnectionType type) {
2551 proc_params_.unresponsive_delay =
2552 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2553 "DnsUnresponsiveDelayMsByConnectionType",
2554 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2555 type);
2556}
2557
pauljensen101ed372015-04-17 00:11:422558void HostResolverImpl::OnInitialDNSConfigRead() {
2559 UpdateDNSConfig(false);
2560}
2561
[email protected]bb0e34542012-08-31 19:52:402562void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422563 UpdateDNSConfig(true);
2564}
2565
2566void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402567 DnsConfig dns_config;
2568 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592569
[email protected]b4481b222012-03-16 17:13:112570 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002571 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2572 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112573 }
2574
[email protected]01b3b9d2012-08-13 16:18:142575 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192576 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522577 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2578 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272579
[email protected]a8883e452012-11-17 05:58:062580 num_dns_failures_ = 0;
2581
[email protected]01b3b9d2012-08-13 16:18:142582 // We want a new DnsSession in place, before we Abort running Jobs, so that
2583 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022584 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192585 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422586 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022587 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422588 // If we just switched DnsClients, restart jobs using new resolver.
2589 // TODO(pauljensen): Is this necessary?
2590 config_changed = true;
2591 }
[email protected]f0f602bd2012-11-15 18:01:022592 }
[email protected]01b3b9d2012-08-13 16:18:142593
pauljensen101ed372015-04-17 00:11:422594 if (config_changed) {
2595 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232596 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422597 // as NSCD's cache should be dropped automatically by the OS when
2598 // resolv.conf changes so we don't need to do anything to clear that cache.
juliatuttle7e8bf1c2016-08-02 19:09:092599 if (cache_.get()) {
mgersh92b1af12017-03-29 15:49:232600 cache_->OnNetworkChange();
juliatuttle7e8bf1c2016-08-02 19:09:092601 cache_hit_callbacks_.clear();
2602 }
[email protected]01b3b9d2012-08-13 16:18:142603
pauljensen101ed372015-04-17 00:11:422604 // Life check to bail once |this| is deleted.
2605 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022606
pauljensen101ed372015-04-17 00:11:422607 // Existing jobs will have been sent to the original server so they need to
2608 // be aborted.
2609 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142610
pauljensen101ed372015-04-17 00:11:422611 // |this| may be deleted inside AbortAllInProgressJobs().
2612 if (self.get())
2613 TryServingAllJobsFromHosts();
2614 }
[email protected]78eac2a2012-03-14 19:09:272615}
2616
2617bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252618 // Use DnsClient only if it's fully configured and there is no override by
2619 // ScopedDefaultHostResolverProc.
2620 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2621 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042622 return dns_client_ && dns_client_->GetConfig() &&
2623 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202624}
2625
[email protected]1ffdda82012-12-12 23:04:222626void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022627 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222628 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022629 num_dns_failures_ = 0;
2630 return;
2631 }
2632 ++num_dns_failures_;
2633 if (num_dns_failures_ < kMaximumDnsFailures)
2634 return;
[email protected]daae1322013-09-05 18:26:502635
2636 // Disable DnsClient until the next DNS change. Must be done before aborting
2637 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022638 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502639
2640 // Switch jobs with active DnsTasks over to using ProcTasks.
2641 AbortDnsTasks();
2642
[email protected]f0f602bd2012-11-15 18:01:022643 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
davidbenad6fc442015-05-18 20:59:132644 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2645 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022646}
2647
juliatuttle7e8bf1c2016-08-02 19:09:092648void HostResolverImpl::OnCacheEntryEvicted(const HostCache::Key& key,
2649 const HostCache::Entry& entry) {
2650 cache_hit_callbacks_.erase(key);
2651}
2652
2653void HostResolverImpl::MaybeAddCacheHitCallback(const HostCache::Key& key,
2654 const RequestInfo& info) {
2655 const RequestInfo::CacheHitCallback& callback = info.cache_hit_callback();
2656 if (callback.is_null())
2657 return;
2658 cache_hit_callbacks_[key].push_back(callback);
2659}
2660
2661void HostResolverImpl::RunCacheHitCallbacks(const HostCache::Key& key,
2662 const RequestInfo& info) {
2663 auto it = cache_hit_callbacks_.find(key);
2664 if (it == cache_hit_callbacks_.end())
2665 return;
2666 for (auto& callback : it->second)
2667 callback.Run(info);
2668}
2669
danakj22f90e72016-04-16 01:55:402670void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502671 // DnsClient and config must be updated before aborting DnsTasks, since doing
2672 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482673 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502674 if (dns_client_ && !dns_client_->GetConfig() &&
2675 num_dns_failures_ < kMaximumDnsFailures) {
2676 DnsConfig dns_config;
2677 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2678 dns_client_->SetConfig(dns_config);
2679 num_dns_failures_ = 0;
2680 if (dns_client_->GetConfig())
2681 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062682 }
[email protected]daae1322013-09-05 18:26:502683
2684 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062685}
2686
juliatuttled7fa5852016-07-29 13:16:572687void HostResolverImpl::InitializePersistence(
2688 const PersistCallback& persist_callback,
2689 std::unique_ptr<const base::Value> old_data) {
2690 DCHECK(!persist_initialized_);
2691 persist_callback_ = persist_callback;
2692 persist_initialized_ = true;
2693 if (old_data)
2694 ApplyPersistentData(std::move(old_data));
2695}
2696
juliatuttle7e8bf1c2016-08-02 19:09:092697void HostResolverImpl::ApplyPersistentData(
2698 std::unique_ptr<const base::Value> data) {}
2699
2700std::unique_ptr<const base::Value> HostResolverImpl::GetPersistentData() {
2701 return std::unique_ptr<const base::Value>();
2702}
2703
juliatuttled7fa5852016-07-29 13:16:572704void HostResolverImpl::SchedulePersist() {
2705 if (!persist_initialized_ || persist_timer_.IsRunning())
2706 return;
2707 persist_timer_.Start(
2708 FROM_HERE, base::TimeDelta::FromSeconds(kPersistDelaySec),
2709 base::Bind(&HostResolverImpl::DoPersist, weak_ptr_factory_.GetWeakPtr()));
2710}
2711
2712void HostResolverImpl::DoPersist() {
2713 DCHECK(persist_initialized_);
2714 persist_callback_.Run(GetPersistentData());
2715}
2716
maksim.sisov31452af2016-07-27 06:38:102717HostResolverImpl::RequestImpl::~RequestImpl() {
2718 if (job_)
2719 job_->CancelRequest(this);
2720}
2721
2722void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2723 RequestPriority priority) {
2724 job_->ChangeRequestPriority(this, priority);
2725}
2726
[email protected]b59ff372009-07-15 22:04:322727} // namespace net