blob: 2fdb3dbc3801e6e7a4f022273317698261b81a78 [file] [log] [blame]
[email protected]a2730882012-01-21 00:56:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]b59ff372009-07-15 22:04:322// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f2cb3cf2013-03-21 01:40:535#include "net/dns/host_resolver_impl.h"
[email protected]b59ff372009-07-15 22:04:326
[email protected]21526002010-05-16 19:42:467#if defined(OS_WIN)
8#include <Winsock2.h>
9#elif defined(OS_POSIX)
10#include <netdb.h>
11#endif
12
tfarinada9e1362017-03-14 16:49:0613#if defined(OS_POSIX)
14#include <netinet/in.h>
15#if !defined(OS_NACL)
16#include <net/if.h>
17#if !defined(OS_ANDROID)
18#include <ifaddrs.h>
19#endif // !defined(OS_ANDROID)
20#endif // !defined(OS_NACL)
21#endif // defined(OS_POSIX)
22
[email protected]68ad3ee2010-01-30 03:45:3923#include <cmath>
thestiga74ad2b2016-07-11 20:52:3624#include <memory>
[email protected]0f292de02012-02-01 22:28:2025#include <utility>
[email protected]21526002010-05-16 19:42:4626#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3927
[email protected]33152acc2011-10-20 23:37:1228#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2929#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2030#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1031#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3232#include "base/compiler_specific.h"
Brett Wilsonc6a0c822017-09-12 00:04:2933#include "base/containers/circular_deque.h"
[email protected]58580352010-10-26 04:07:5034#include "base/debug/debugger.h"
[email protected]58580352010-10-26 04:07:5035#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4636#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2337#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4538#include "base/metrics/field_trial.h"
davidbenad6fc442015-05-18 20:59:1339#include "base/metrics/histogram_macros.h"
40#include "base/metrics/sparse_histogram.h"
anujk.sharma7c907f02015-05-29 02:55:4441#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4842#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0543#include "base/strings/utf_string_conversions.h"
Francois Doraya2d01ba2017-09-25 19:17:4044#include "base/task_scheduler/post_task.h"
45#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3546#include "base/threading/thread_task_runner_handle.h"
[email protected]66e96c42013-06-28 15:20:3147#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5648#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4649#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2050#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3251#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5152#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5153#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4854#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1555#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4856#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1857#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4658#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2759#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2060#include "net/dns/dns_config_service.h"
61#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3562#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2063#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2064#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0365#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5366#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0767#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1968#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0069#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1970#include "net/log/net_log_parameters_callback.h"
71#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0072#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1973#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5174#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2675#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1476#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3277
78#if defined(OS_WIN)
79#include "net/base/winsock_init.h"
80#endif
81
tfarinada9e1362017-03-14 16:49:0682#if defined(OS_ANDROID)
83#include "net/android/network_library.h"
84#endif
85
[email protected]b59ff372009-07-15 22:04:3286namespace net {
87
[email protected]e95d3aca2010-01-11 22:47:4388namespace {
89
ttuttlecf1158bf2016-03-18 16:37:4490// Default delay between calls to the system resolver for the same hostname.
91// (Can be overridden by field trial.)
92const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
93
[email protected]6e78dfb2011-07-28 21:34:4794// Limit the size of hostnames that will be resolved to combat issues in
95// some platform's resolvers.
96const size_t kMaxHostLength = 4096;
97
[email protected]a2730882012-01-21 00:56:2798// Default TTL for successful resolutions with ProcTask.
99const unsigned kCacheEntryTTLSeconds = 60;
100
[email protected]b3601bc22012-02-21 21:23:20101// Default TTL for unsuccessful resolutions with ProcTask.
102const unsigned kNegativeCacheEntryTTLSeconds = 0;
103
[email protected]895123222012-10-25 15:21:17104// Minimum TTL for successful resolutions with DnsTask.
105const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
106
sergeyub8cdc212015-05-14 18:50:37107// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
108// cached.
109const int kIPv6ProbePeriodMs = 1000;
110
111// Google DNS address used for IPv6 probes.
112const uint8_t kIPv6ProbeAddress[] =
113 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
114 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
115
[email protected]24f4bab2010-10-15 01:27:11116// We use a separate histogram name for each platform to facilitate the
117// display of error codes by their symbolic name (since each platform has
118// different mappings).
119const char kOSErrorsForGetAddrinfoHistogramName[] =
120#if defined(OS_WIN)
121 "Net.OSErrorsForGetAddrinfo_Win";
122#elif defined(OS_MACOSX)
123 "Net.OSErrorsForGetAddrinfo_Mac";
124#elif defined(OS_LINUX)
125 "Net.OSErrorsForGetAddrinfo_Linux";
126#else
127 "Net.OSErrorsForGetAddrinfo";
128#endif
129
[email protected]c89b2442011-05-26 14:28:27130// Gets a list of the likely error codes that getaddrinfo() can return
131// (non-exhaustive). These are the error codes that we will track via
132// a histogram.
133std::vector<int> GetAllGetAddrinfoOSErrors() {
134 int os_errors[] = {
135#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51136#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37137#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45138 // EAI_ADDRFAMILY has been declared obsolete in Android's and
139 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27140 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37141#endif
[email protected]c48aef92011-11-22 23:41:45142 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51143 EAI_NODATA,
144#endif
[email protected]c89b2442011-05-26 14:28:27145 EAI_AGAIN,
146 EAI_BADFLAGS,
147 EAI_FAIL,
148 EAI_FAMILY,
149 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27150 EAI_NONAME,
151 EAI_SERVICE,
152 EAI_SOCKTYPE,
153 EAI_SYSTEM,
154#elif defined(OS_WIN)
155 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
156 WSA_NOT_ENOUGH_MEMORY,
157 WSAEAFNOSUPPORT,
158 WSAEINVAL,
159 WSAESOCKTNOSUPPORT,
160 WSAHOST_NOT_FOUND,
161 WSANO_DATA,
162 WSANO_RECOVERY,
163 WSANOTINITIALISED,
164 WSATRY_AGAIN,
165 WSATYPE_NOT_FOUND,
166 // The following are not in doc, but might be to appearing in results :-(.
167 WSA_INVALID_HANDLE,
168#endif
169 };
170
171 // Ensure all errors are positive, as histogram only tracks positive values.
172 for (size_t i = 0; i < arraysize(os_errors); ++i) {
173 os_errors[i] = std::abs(os_errors[i]);
174 }
175
176 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
177 arraysize(os_errors));
178}
179
[email protected]1def74c2012-03-22 20:07:00180enum DnsResolveStatus {
181 RESOLVE_STATUS_DNS_SUCCESS = 0,
182 RESOLVE_STATUS_PROC_SUCCESS,
183 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33184 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00185 RESOLVE_STATUS_MAX
186};
187
eroman91dd3602015-03-26 03:46:33188// ICANN uses this localhost address to indicate a name collision.
189//
190// The policy in Chromium is to fail host resolving if it resolves to
191// this special address.
192//
193// Not however that IP literals are exempt from this policy, so it is still
194// possible to navigate to http://127.0.53.53/ directly.
195//
196// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51197const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33198
eroman1efc237c2016-12-14 00:00:45199bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
200 for (const auto& endpoint : addr_list) {
201 const IPAddress& addr = endpoint.address();
202 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
203 return true;
204 }
205 }
206 return false;
207}
208
[email protected]1def74c2012-03-22 20:07:00209void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
210 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
211 result,
212 RESOLVE_STATUS_MAX);
213}
214
[email protected]1d932852012-06-19 19:40:33215bool ResemblesNetBIOSName(const std::string& hostname) {
216 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
217}
218
219// True if |hostname| ends with either ".local" or ".local.".
220bool ResemblesMulticastDNSName(const std::string& hostname) {
221 DCHECK(!hostname.empty());
222 const char kSuffix[] = ".local.";
223 const size_t kSuffixLen = sizeof(kSuffix) - 1;
224 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36225 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33226 return hostname.size() > kSuffixLen &&
227 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
228 }
229 return hostname.size() > kSuffixLenTrimmed &&
230 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
231 kSuffix, kSuffixLenTrimmed);
232}
233
[email protected]51b9a6b2012-06-25 21:50:29234// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21235#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
236 do { \
237 switch (priority) { \
238 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28239 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21240 break; \
241 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28242 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21243 break; \
244 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28245 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21246 break; \
247 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28248 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21249 break; \
250 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28251 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21252 break; \
253 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28254 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21255 break; \
256 } \
257 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29258 } while (0)
259
260// Record time from Request creation until a valid DNS response.
Miriam Gershenson90d05e02017-09-28 19:29:28261void RecordTotalTime(bool speculative,
262 bool from_cache,
[email protected]51b9a6b2012-06-25 21:50:29263 base::TimeDelta duration) {
Miriam Gershenson90d05e02017-09-28 19:29:28264 if (speculative) {
265 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime.Speculative", duration);
[email protected]51b9a6b2012-06-25 21:50:29266 } else {
Miriam Gershenson90d05e02017-09-28 19:29:28267 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
268 }
269
270 if (!from_cache) {
[email protected]51b9a6b2012-06-25 21:50:29271 if (speculative) {
Miriam Gershenson90d05e02017-09-28 19:29:28272 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached.Speculative",
273 duration);
[email protected]51b9a6b2012-06-25 21:50:29274 } else {
Miriam Gershenson90d05e02017-09-28 19:29:28275 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
[email protected]51b9a6b2012-06-25 21:50:29276 }
277 }
278}
279
[email protected]1339a2a22012-10-17 08:39:43280void RecordTTL(base::TimeDelta ttl) {
281 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
282 base::TimeDelta::FromSeconds(1),
283 base::TimeDelta::FromDays(1), 100);
284}
285
[email protected]16c2bd72013-06-28 01:19:22286bool ConfigureAsyncDnsNoFallbackFieldTrial() {
287 const bool kDefault = false;
288
289 // Configure the AsyncDns field trial as follows:
290 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
291 // groups AsyncDnsA and AsyncDnsB: return false,
292 // groups SystemDnsA and SystemDnsB: return false,
293 // otherwise (trial absent): return default.
294 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29295 if (!group_name.empty()) {
296 return base::StartsWith(group_name, "AsyncDnsNoFallback",
297 base::CompareCase::INSENSITIVE_ASCII);
298 }
[email protected]16c2bd72013-06-28 01:19:22299 return kDefault;
300}
301
[email protected]d7b9a2b2012-05-31 22:31:19302//-----------------------------------------------------------------------------
303
Avi Drissman13fc8932015-12-20 04:40:46304AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17305 if (list.empty() || list.front().port() == port)
306 return list;
307 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56308}
309
[email protected]ec666ab22013-04-17 20:05:59310// Returns true if |addresses| contains only IPv4 loopback addresses.
311bool IsAllIPv4Loopback(const AddressList& addresses) {
312 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51313 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59314 switch (addresses[i].GetFamily()) {
315 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51316 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59317 return false;
318 break;
319 case ADDRESS_FAMILY_IPV6:
320 return false;
321 default:
322 NOTREACHED();
323 return false;
324 }
325 }
326 return true;
327}
328
tfarinada9e1362017-03-14 16:49:06329// Returns true if it can determine that only loopback addresses are configured.
330// i.e. if only 127.0.0.1 and ::1 are routable.
331// Also returns false if it cannot determine this.
332bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40333 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
tfarinada9e1362017-03-14 16:49:06334#if defined(OS_ANDROID)
335 return android::HaveOnlyLoopbackAddresses();
336#elif defined(OS_NACL)
337 NOTIMPLEMENTED();
338 return false;
339#elif defined(OS_POSIX)
340 struct ifaddrs* interface_addr = NULL;
341 int rv = getifaddrs(&interface_addr);
342 if (rv != 0) {
343 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
344 return false;
345 }
346
347 bool result = true;
348 for (struct ifaddrs* interface = interface_addr;
349 interface != NULL;
350 interface = interface->ifa_next) {
351 if (!(IFF_UP & interface->ifa_flags))
352 continue;
353 if (IFF_LOOPBACK & interface->ifa_flags)
354 continue;
355 const struct sockaddr* addr = interface->ifa_addr;
356 if (!addr)
357 continue;
358 if (addr->sa_family == AF_INET6) {
359 // Safe cast since this is AF_INET6.
360 const struct sockaddr_in6* addr_in6 =
361 reinterpret_cast<const struct sockaddr_in6*>(addr);
362 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
363 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
364 continue;
365 }
366 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
367 continue;
368
369 result = false;
370 break;
371 }
372 freeifaddrs(interface_addr);
373 return result;
374#elif defined(OS_WIN)
375 // TODO(wtc): implement with the GetAdaptersAddresses function.
376 NOTIMPLEMENTED();
377 return false;
378#else
379 NOTIMPLEMENTED();
380 return false;
381#endif // defined(various platforms)
382}
383
[email protected]cd565142012-06-12 16:21:45384// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40385std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46386 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17387 int net_error,
388 int os_error,
389 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40390 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45391 if (attempt_number)
392 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46393
[email protected]cd565142012-06-12 16:21:45394 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16395
[email protected]cd565142012-06-12 16:21:45396 if (os_error) {
397 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46398#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45399 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46400#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45401 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04402 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08403 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
404 0, // Use the internal message table.
405 os_error,
406 0, // Use default language.
407 (LPWSTR)&error_string,
408 0, // Buffer size.
409 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01410 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45411 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46412#endif
[email protected]21526002010-05-16 19:42:46413 }
414
dchengc7eeda422015-12-26 03:56:48415 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45416}
[email protected]a9813302012-04-28 09:29:28417
[email protected]cd565142012-06-12 16:21:45418// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40419std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11420 int net_error,
421 int dns_error,
422 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40423 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45424 dict->SetInteger("net_error", net_error);
425 if (dns_error)
426 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48427 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36428}
[email protected]ee094b82010-08-24 15:55:51429
[email protected]cd565142012-06-12 16:21:45430// Creates NetLog parameters containing the information in a RequestInfo object,
mikecironef22f9812016-10-04 03:40:19431// along with the associated NetLogSource.
danakj22f90e72016-04-16 01:55:40432std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11433 const HostResolver::RequestInfo* info,
434 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40435 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20436
[email protected]cd565142012-06-12 16:21:45437 dict->SetString("host", info->host_port_pair().ToString());
438 dict->SetInteger("address_family",
439 static_cast<int>(info->address_family()));
440 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
441 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48442 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45443}
[email protected]b3601bc22012-02-21 21:23:20444
[email protected]cd565142012-06-12 16:21:45445// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40446std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19447 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11448 const std::string* host,
449 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40450 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11451 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45452 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48453 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45454}
[email protected]a9813302012-04-28 09:29:28455
[email protected]cd565142012-06-12 16:21:45456// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40457std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19458 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11459 RequestPriority priority,
460 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40461 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11462 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56463 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48464 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45465}
[email protected]b3601bc22012-02-21 21:23:20466
[email protected]cd565142012-06-12 16:21:45467// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40468std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11469 const DnsConfig* config,
470 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08471 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45472}
[email protected]b4481b222012-03-16 17:13:11473
danakj22f90e72016-04-16 01:55:40474std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11475 bool ipv6_available,
476 bool cached,
477 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40478 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37479 dict->SetBoolean("ipv6_available", ipv6_available);
480 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48481 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37482}
483
[email protected]0f292de02012-02-01 22:28:20484// The logging routines are defined here because some requests are resolved
485// without a Request object.
486
487// Logs when a request has just been started.
tfarina428341112016-09-22 13:38:20488void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20489 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00490 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
491 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20492}
493
494// Logs when a request has just completed (before its callback is run).
tfarina428341112016-09-22 13:38:20495void LogFinishRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20496 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20497 int net_error) {
xunjieli26f90452014-11-10 16:23:02498 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00499 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20500}
501
502// Logs when a request has been cancelled.
tfarina428341112016-09-22 13:38:20503void LogCancelRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20504 const HostResolverImpl::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00505 source_net_log.AddEvent(NetLogEventType::CANCELLED);
506 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20507}
508
[email protected]b59ff372009-07-15 22:04:32509//-----------------------------------------------------------------------------
510
[email protected]0f292de02012-02-01 22:28:20511// Keeps track of the highest priority.
512class PriorityTracker {
513 public:
[email protected]8c98d002012-07-18 19:02:27514 explicit PriorityTracker(RequestPriority initial_priority)
515 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20516 memset(counts_, 0, sizeof(counts_));
517 }
518
519 RequestPriority highest_priority() const {
520 return highest_priority_;
521 }
522
523 size_t total_count() const {
524 return total_count_;
525 }
526
527 void Add(RequestPriority req_priority) {
528 ++total_count_;
529 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05530 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20531 highest_priority_ = req_priority;
532 }
533
534 void Remove(RequestPriority req_priority) {
535 DCHECK_GT(total_count_, 0u);
536 DCHECK_GT(counts_[req_priority], 0u);
537 --total_count_;
538 --counts_[req_priority];
539 size_t i;
thestiga74ad2b2016-07-11 20:52:36540 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
541 }
[email protected]0f292de02012-02-01 22:28:20542 highest_priority_ = static_cast<RequestPriority>(i);
543
[email protected]31ae7ab2012-04-24 21:09:05544 // In absence of requests, default to MINIMUM_PRIORITY.
545 if (total_count_ == 0)
546 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20547 }
548
549 private:
550 RequestPriority highest_priority_;
551 size_t total_count_;
552 size_t counts_[NUM_PRIORITIES];
553};
554
juliatuttle9fb7aeb2016-06-06 20:16:33555void MakeNotStale(HostCache::EntryStaleness* stale_info) {
556 if (!stale_info)
557 return;
558 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
559 stale_info->network_changes = 0;
560 stale_info->stale_hits = 0;
561}
562
juliatuttled7fa5852016-07-29 13:16:57563// Persist data every five minutes (potentially, cache and learned RTT).
564const int64_t kPersistDelaySec = 300;
565
[email protected]c54a8912012-10-22 22:09:43566} // namespace
[email protected]0f292de02012-02-01 22:28:20567
568//-----------------------------------------------------------------------------
569
tfarina9ed7f8c52016-02-19 17:50:18570bool ResolveLocalHostname(base::StringPiece host,
571 uint16_t port,
572 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18573 address_list->clear();
574
575 bool is_local6;
576 if (!IsLocalHostname(host, &is_local6))
577 return false;
578
martijna23c8962016-03-04 18:18:51579 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18580 if (!is_local6) {
martijna23c8962016-03-04 18:18:51581 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18582 }
583
584 return true;
585}
586
[email protected]daae1322013-09-05 18:26:50587const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
588
[email protected]0f292de02012-02-01 22:28:20589// Holds the data for a request that could not be completed synchronously.
590// It is owned by a Job. Canceled Requests are only marked as canceled rather
591// than removed from the Job's |requests_| list.
maksim.sisov31452af2016-07-27 06:38:10592class HostResolverImpl::RequestImpl : public HostResolver::Request {
[email protected]b59ff372009-07-15 22:04:32593 public:
tfarina428341112016-09-22 13:38:20594 RequestImpl(const NetLogWithSource& source_net_log,
maksim.sisov31452af2016-07-27 06:38:10595 const RequestInfo& info,
596 RequestPriority priority,
597 const CompletionCallback& callback,
598 AddressList* addresses,
599 Job* job)
[email protected]ee094b82010-08-24 15:55:51600 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09601 info_(info),
[email protected]5109c1952013-08-20 18:44:10602 priority_(priority),
maksim.sisov31452af2016-07-27 06:38:10603 job_(job),
[email protected]54e13772009-08-14 03:01:09604 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29605 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10606 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32607
maksim.sisov31452af2016-07-27 06:38:10608 ~RequestImpl() override;
609
610 void ChangeRequestPriority(RequestPriority priority) override;
611
612 void OnJobCancelled(Job* job) {
613 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04614 job_ = nullptr;
615 addresses_ = nullptr;
[email protected]aa22b242011-11-16 18:58:29616 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32617 }
618
[email protected]0f292de02012-02-01 22:28:20619 // Prepare final AddressList and call completion callback.
maksim.sisov31452af2016-07-27 06:38:10620 void OnJobCompleted(Job* job, int error, const AddressList& addr_list) {
621 DCHECK_EQ(job_, job);
[email protected]895123222012-10-25 15:21:17622 if (error == OK)
623 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
maksim.sisov31452af2016-07-27 06:38:10624 job_ = nullptr;
625 addresses_ = nullptr;
626 base::ResetAndReturn(&callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32627 }
628
[email protected]b59ff372009-07-15 22:04:32629 Job* job() const {
630 return job_;
631 }
632
[email protected]0f292de02012-02-01 22:28:20633 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20634 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51635
[email protected]b59ff372009-07-15 22:04:32636 const RequestInfo& info() const {
637 return info_;
638 }
639
[email protected]5109c1952013-08-20 18:44:10640 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31641 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10642
643 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29644
[email protected]b59ff372009-07-15 22:04:32645 private:
tfarina428341112016-09-22 13:38:20646 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09647
[email protected]b59ff372009-07-15 22:04:32648 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10649 const RequestInfo info_;
650
juliatuttlec53b19a72016-05-05 13:51:31651 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32652
[email protected]0f292de02012-02-01 22:28:20653 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32654 Job* job_;
655
656 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29657 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32658
659 // The address list to save result into.
660 AddressList* addresses_;
661
[email protected]51b9a6b2012-06-25 21:50:29662 const base::TimeTicks request_time_;
663
maksim.sisov31452af2016-07-27 06:38:10664 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32665};
666
[email protected]1e9bbd22010-10-15 16:42:45667//------------------------------------------------------------------------------
668
Francois Doraya2d01ba2017-09-25 19:17:40669// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20670//
671// Whenever we try to resolve the host, we post a delayed task to check if host
672// resolution (OnLookupComplete) is completed or not. If the original attempt
673// hasn't completed, then we start another attempt for host resolution. We take
674// the results from the first attempt that finishes and ignore the results from
675// all other attempts.
676//
677// TODO(szym): Move to separate source file for testing and mocking.
678//
679class HostResolverImpl::ProcTask
680 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32681 public:
[email protected]b3601bc22012-02-21 21:23:20682 typedef base::Callback<void(int net_error,
683 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32684
[email protected]0f292de02012-02-01 22:28:20685 ProcTask(const Key& key,
686 const ProcTaskParams& params,
687 const Callback& callback,
tfarina428341112016-09-22 13:38:20688 const NetLogWithSource& job_net_log)
[email protected]0f292de02012-02-01 22:28:20689 : key_(key),
690 params_(params),
691 callback_(callback),
mmenke91c17162016-06-02 16:03:23692 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
[email protected]0f292de02012-02-01 22:28:20693 attempt_number_(0),
694 completed_attempt_number_(0),
695 completed_attempt_error_(ERR_UNEXPECTED),
[email protected]b3601bc22012-02-21 21:23:20696 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50697 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20698 params_.resolver_proc = HostResolverProc::GetDefault();
699 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50700 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06701 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32702 }
703
[email protected]b59ff372009-07-15 22:04:32704 void Start() {
mmenke91c17162016-06-02 16:03:23705 DCHECK(network_task_runner_->BelongsToCurrentThread());
mikecirone8b85c432016-09-08 19:11:00706 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54707 StartLookupAttempt();
708 }
[email protected]252b699b2010-02-05 21:38:06709
[email protected]0f292de02012-02-01 22:28:20710 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23711 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20712 // attempts complete will the final reference to this ProcTask be released.
713 void Cancel() {
mmenke91c17162016-06-02 16:03:23714 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20715
[email protected]0adcb2b2012-08-15 21:30:46716 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20717 return;
718
[email protected]0f292de02012-02-01 22:28:20719 callback_.Reset();
mikecirone8b85c432016-09-08 19:11:00720 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20721 }
722
[email protected]0f292de02012-02-01 22:28:20723 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23724 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20725 return callback_.is_null();
726 }
727
728 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23729 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20730 return completed_attempt_number_ > 0;
731 }
732
733 private:
[email protected]a9813302012-04-28 09:29:28734 friend class base::RefCountedThreadSafe<ProcTask>;
735 ~ProcTask() {}
736
[email protected]189163e2011-05-11 01:48:54737 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23738 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54739 base::TimeTicks start_time = base::TimeTicks::Now();
740 ++attempt_number_;
741 // Dispatch the lookup attempt to a worker thread.
Francois Doraya2d01ba2017-09-25 19:17:40742 base::PostTaskWithTraits(
743 FROM_HERE,
744 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
745 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_));
[email protected]13024882011-05-18 23:19:16746
mikecirone8b85c432016-09-08 19:11:00747 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28748 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16749
mmenke91c17162016-06-02 16:03:23750 // If the results aren't received within a given time, RetryIfNotComplete
751 // will start a new attempt if none of the outstanding attempts have
752 // completed yet.
[email protected]0f292de02012-02-01 22:28:20753 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23754 network_task_runner_->PostDelayedTask(
755 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42756 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58757 }
[email protected]b59ff372009-07-15 22:04:32758 }
759
Francois Doraya2d01ba2017-09-25 19:17:40760 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
761 // shutdown code cannot wait for it to finish, so this code must be very
762 // careful about using other objects (like MessageLoops, Singletons, etc).
763 // During shutdown these objects may no longer exist. Multiple DoLookups()
764 // could be running in parallel, so any state inside of |this| must not
765 // mutate.
[email protected]189163e2011-05-11 01:48:54766 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46767 const uint32_t attempt_number) {
Miriam Gershenson1ac86662017-10-09 20:50:57768 TRACE_HEAP_PROFILER_API_SCOPED_TASK_EXECUTION scoped_heap_context(
769 "net/dns/proctask");
[email protected]189163e2011-05-11 01:48:54770 AddressList results;
771 int os_error = 0;
[email protected]0f292de02012-02-01 22:28:20772 int error = params_.resolver_proc->Resolve(key_.hostname,
773 key_.address_family,
774 key_.host_resolver_flags,
775 &results,
776 &os_error);
[email protected]b59ff372009-07-15 22:04:32777
mmenke91c17162016-06-02 16:03:23778 network_task_runner_->PostTask(
779 FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
780 start_time, attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54781 }
782
mmenke91c17162016-06-02 16:03:23783 // Makes next attempt if DoLookup() has not finished.
[email protected]0f292de02012-02-01 22:28:20784 void RetryIfNotComplete() {
mmenke91c17162016-06-02 16:03:23785 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54786
[email protected]0f292de02012-02-01 22:28:20787 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54788 return;
789
[email protected]0f292de02012-02-01 22:28:20790 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54791 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32792 }
793
anujk.sharma7c907f02015-05-29 02:55:44794 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54795 void OnLookupComplete(const AddressList& results,
796 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46797 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54798 int error,
799 const int os_error) {
xunjieli0b7f5b62016-12-06 20:43:48800 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
mmenke91c17162016-06-02 16:03:23801 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23802 // If results are empty, we should return an error.
803 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23804 if (empty_list_on_ok)
805 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54806
807 bool was_retry_attempt = attempt_number > 1;
808
[email protected]2d3b7762010-10-09 00:35:47809 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20810 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23811 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54812 if (error != OK && NetworkChangeNotifier::IsOffline())
813 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47814
[email protected]189163e2011-05-11 01:48:54815 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35816
[email protected]0f292de02012-02-01 22:28:20817 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32818 return;
819
mikecironef22f9812016-10-04 03:40:19820 NetLogParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20821 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45822 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
823 attempt_number,
824 error,
825 os_error);
[email protected]0f292de02012-02-01 22:28:20826 } else {
tfarina5e24b242015-10-27 13:11:28827 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20828 }
mikecirone8b85c432016-09-08 19:11:00829 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
[email protected]cd565142012-06-12 16:21:45830 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20831
832 if (was_completed())
833 return;
834
Miriam Gershenson61604662017-09-28 23:51:11835 RecordTaskHistograms(start_time, error, os_error);
836
[email protected]0f292de02012-02-01 22:28:20837 // Copy the results from the first worker thread that resolves the host.
838 results_ = results;
839 completed_attempt_number_ = attempt_number;
840 completed_attempt_error_ = error;
841
[email protected]e87b8b512011-06-14 22:12:52842 if (was_retry_attempt) {
843 // If retry attempt finishes before 1st attempt, then get stats on how
844 // much time is saved by having spawned an extra attempt.
845 retry_attempt_finished_time_ = base::TimeTicks::Now();
846 }
847
[email protected]189163e2011-05-11 01:48:54848 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45849 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
850 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51851 } else {
[email protected]cd565142012-06-12 16:21:45852 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51853 }
mikecirone8b85c432016-09-08 19:11:00854 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45855 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51856
[email protected]b3601bc22012-02-21 21:23:20857 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32858 }
859
Miriam Gershenson61604662017-09-28 23:51:11860 void RecordTaskHistograms(const base::TimeTicks& start_time,
861 const int error,
862 const int os_error) const {
mmenke91c17162016-06-02 16:03:23863 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54864 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
Miriam Gershenson61604662017-09-28 23:51:11865 if (error == OK)
866 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.SuccessTime", duration);
867 else
868 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.FailureTime", duration);
[email protected]7e96d792011-06-10 17:08:23869
Miriam Gershenson61604662017-09-28 23:51:11870 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
871 std::abs(os_error),
872 GetAllGetAddrinfoOSErrors());
[email protected]1e9bbd22010-10-15 16:42:45873 }
874
[email protected]189163e2011-05-11 01:48:54875 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46876 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54877 const int error,
878 const int os_error) const {
mmenke91c17162016-06-02 16:03:23879 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54880 bool first_attempt_to_complete =
881 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52882 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45883
[email protected]189163e2011-05-11 01:48:54884 if (first_attempt_to_complete) {
885 // If this was first attempt to complete, then record the resolution
886 // status of the attempt.
887 if (completed_attempt_error_ == OK) {
888 UMA_HISTOGRAM_ENUMERATION(
889 "DNS.AttemptFirstSuccess", attempt_number, 100);
890 } else {
891 UMA_HISTOGRAM_ENUMERATION(
892 "DNS.AttemptFirstFailure", attempt_number, 100);
893 }
894 }
895
896 if (error == OK)
897 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
898 else
899 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
900
[email protected]e87b8b512011-06-14 22:12:52901 // If first attempt didn't finish before retry attempt, then calculate stats
902 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20903 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21904 UMA_HISTOGRAM_LONG_TIMES_100(
905 "DNS.AttemptTimeSavedByRetry",
906 base::TimeTicks::Now() - retry_attempt_finished_time_);
[email protected]e87b8b512011-06-14 22:12:52907 }
908
[email protected]0f292de02012-02-01 22:28:20909 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54910 // Count those attempts which completed after the job was already canceled
911 // OR after the job was already completed by an earlier attempt (so in
912 // effect).
913 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
914
[email protected]0f292de02012-02-01 22:28:20915 // Record if job is canceled.
916 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54917 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
918 }
919
920 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
921 if (error == OK)
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21922 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptSuccessDuration", duration);
[email protected]189163e2011-05-11 01:48:54923 else
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21924 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptFailDuration", duration);
[email protected]189163e2011-05-11 01:48:54925 }
[email protected]1e9bbd22010-10-15 16:42:45926
anujk.sharma7c907f02015-05-29 02:55:44927 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57928 Key key_;
[email protected]b59ff372009-07-15 22:04:32929
[email protected]0f292de02012-02-01 22:28:20930 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32931 // This may not be the current resolver procedure by the time we call
932 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
933 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20934 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32935
[email protected]0f292de02012-02-01 22:28:20936 // The listener to the results of this ProcTask.
937 Callback callback_;
938
mmenke91c17162016-06-02 16:03:23939 // Used to post events onto the network thread.
940 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
[email protected]189163e2011-05-11 01:48:54941
942 // Keeps track of the number of attempts we have made so far to resolve the
943 // host. Whenever we start an attempt to resolve the host, we increase this
944 // number.
Avi Drissman13fc8932015-12-20 04:40:46945 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54946
947 // The index of the attempt which finished first (or 0 if the job is still in
948 // progress).
Avi Drissman13fc8932015-12-20 04:40:46949 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:54950
951 // The result (a net error code) from the first attempt to complete.
952 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06953
[email protected]e87b8b512011-06-14 22:12:52954 // The time when retry attempt was finished.
955 base::TimeTicks retry_attempt_finished_time_;
956
[email protected]b59ff372009-07-15 22:04:32957 AddressList results_;
958
tfarina428341112016-09-22 13:38:20959 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51960
[email protected]0f292de02012-02-01 22:28:20961 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32962};
963
964//-----------------------------------------------------------------------------
965
[email protected]b3601bc22012-02-21 21:23:20966// Resolves the hostname using DnsTransaction.
967// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46968class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20969 public:
[email protected]daae1322013-09-05 18:26:50970 class Delegate {
971 public:
972 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
973 int net_error,
974 const AddressList& addr_list,
975 base::TimeDelta ttl) = 0;
976
977 // Called when the first of two jobs succeeds. If the first completed
978 // transaction fails, this is not called. Also not called when the DnsTask
979 // only needs to run one transaction.
980 virtual void OnFirstDnsTransactionComplete() = 0;
981
982 protected:
983 Delegate() {}
984 virtual ~Delegate() {}
985 };
[email protected]b3601bc22012-02-21 21:23:20986
[email protected]0adcb2b2012-08-15 21:30:46987 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:20988 const Key& key,
[email protected]daae1322013-09-05 18:26:50989 Delegate* delegate,
tfarina428341112016-09-22 13:38:20990 const NetLogWithSource& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:46991 : client_(client),
[email protected]daae1322013-09-05 18:26:50992 key_(key),
993 delegate_(delegate),
994 net_log_(job_net_log),
995 num_completed_transactions_(0),
996 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:46997 DCHECK(client);
[email protected]daae1322013-09-05 18:26:50998 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:50999 }
1000
[email protected]daae1322013-09-05 18:26:501001 bool needs_two_transactions() const {
1002 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1003 }
1004
1005 bool needs_another_transaction() const {
1006 return needs_two_transactions() && !transaction_aaaa_;
1007 }
1008
1009 void StartFirstTransaction() {
1010 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001011 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501012 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1013 StartAAAA();
1014 } else {
1015 StartA();
1016 }
1017 }
1018
1019 void StartSecondTransaction() {
1020 DCHECK(needs_two_transactions());
1021 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121022 }
1023
1024 private:
[email protected]daae1322013-09-05 18:26:501025 void StartA() {
1026 DCHECK(!transaction_a_);
1027 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1028 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1029 transaction_a_->Start();
1030 }
1031
1032 void StartAAAA() {
1033 DCHECK(!transaction_aaaa_);
1034 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1035 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1036 transaction_aaaa_->Start();
1037 }
1038
danakj22f90e72016-04-16 01:55:401039 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501040 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1041 return client_->GetTransactionFactory()->CreateTransaction(
1042 key_.hostname,
1043 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1044 dns_protocol::kTypeA,
1045 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1046 base::TimeTicks::Now()),
1047 net_log_);
1048 }
1049
1050 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001051 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201052 int net_error,
1053 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471054 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511055 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461056 if (net_error != OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211057 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461058 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1059 return;
[email protected]6c411902012-08-14 22:36:361060 }
[email protected]0adcb2b2012-08-15 21:30:461061
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211062 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511063 switch (transaction->GetType()) {
1064 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211065 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511066 break;
1067 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211068 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1069 duration);
[email protected]02cd6982013-01-10 20:12:511070 break;
1071 }
[email protected]daae1322013-09-05 18:26:501072
[email protected]0adcb2b2012-08-15 21:30:461073 AddressList addr_list;
1074 base::TimeDelta ttl;
1075 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1076 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1077 result,
1078 DnsResponse::DNS_PARSE_RESULT_MAX);
1079 if (result != DnsResponse::DNS_PARSE_OK) {
1080 // Fail even if the other query succeeds.
1081 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1082 return;
1083 }
1084
[email protected]daae1322013-09-05 18:26:501085 ++num_completed_transactions_;
1086 if (num_completed_transactions_ == 1) {
1087 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461088 } else {
[email protected]daae1322013-09-05 18:26:501089 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461090 }
1091
[email protected]daae1322013-09-05 18:26:501092 if (transaction->GetType() == dns_protocol::kTypeA) {
1093 DCHECK_EQ(transaction_a_.get(), transaction);
1094 // Place IPv4 addresses after IPv6.
1095 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1096 } else {
1097 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1098 // Place IPv6 addresses before IPv4.
1099 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1100 }
1101
1102 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1103 // No need to repeat the suffix search.
1104 key_.hostname = transaction->GetHostname();
1105 delegate_->OnFirstDnsTransactionComplete();
1106 return;
1107 }
1108
1109 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121110 // TODO(szym): Don't fallback to ProcTask in this case.
1111 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461112 return;
1113 }
1114
[email protected]daae1322013-09-05 18:26:501115 // If there are multiple addresses, and at least one is IPv6, need to sort
1116 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1117 // sufficient to just check the family of the first address.
1118 if (addr_list_.size() > 1 &&
1119 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1120 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461121 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501122 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071123 base::Bind(&DnsTask::OnSortComplete,
1124 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501125 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461126 } else {
[email protected]daae1322013-09-05 18:26:501127 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461128 }
1129 }
1130
1131 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461132 bool success,
1133 const AddressList& addr_list) {
1134 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211135 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
1136 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461137 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1138 return;
1139 }
1140
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211141 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
1142 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461143
1144 // AddressSorter prunes unusable destinations.
1145 if (addr_list.empty()) {
1146 LOG(WARNING) << "Address list empty after RFC3484 sort";
1147 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1148 return;
1149 }
1150
[email protected]daae1322013-09-05 18:26:501151 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461152 }
1153
1154 void OnFailure(int net_error, DnsResponse::Result result) {
1155 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451156 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001157 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451158 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501159 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1160 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201161 }
1162
[email protected]daae1322013-09-05 18:26:501163 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001164 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461165 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501166 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461167 }
1168
1169 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501170 Key key_;
1171
[email protected]b3601bc22012-02-21 21:23:201172 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501173 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201174 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201175
danakj22f90e72016-04-16 01:55:401176 std::unique_ptr<DnsTransaction> transaction_a_;
1177 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461178
[email protected]daae1322013-09-05 18:26:501179 unsigned num_completed_transactions_;
1180
1181 // These are updated as each transaction completes.
1182 base::TimeDelta ttl_;
1183 // IPv6 addresses must appear first in the list.
1184 AddressList addr_list_;
1185
1186 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461187
1188 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201189};
1190
1191//-----------------------------------------------------------------------------
1192
[email protected]0f292de02012-02-01 22:28:201193// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501194class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1195 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391196 public:
[email protected]0f292de02012-02-01 22:28:201197 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351198 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181199 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201200 const Key& key,
[email protected]8c98d002012-07-18 19:02:271201 RequestPriority priority,
tfarina428341112016-09-22 13:38:201202 const NetLogWithSource& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181203 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201204 key_(key),
[email protected]8c98d002012-07-18 19:02:271205 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201206 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291207 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501208 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331209 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291210 creation_time_(base::TimeTicks::Now()),
1211 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201212 net_log_(
1213 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001214 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1215 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201216
mikecirone8b85c432016-09-08 19:11:001217 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1218 base::Bind(&NetLogJobCreationCallback,
1219 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391220 }
1221
dchengb03027d2014-10-21 12:00:201222 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201223 if (is_running()) {
1224 // |resolver_| was destroyed with this Job still in flight.
1225 // Clean-up, record in the log, but don't run any callbacks.
1226 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201227 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041228 proc_task_ = nullptr;
[email protected]0f292de02012-02-01 22:28:201229 }
[email protected]16ee26d2012-03-08 03:34:351230 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501231 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001232 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201233 ERR_ABORTED);
1234 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551235 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351236 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001237 net_log_.AddEvent(NetLogEventType::CANCELLED);
1238 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391239 }
[email protected]b3601bc22012-02-21 21:23:201240 // else CompleteRequests logged EndEvent.
maksim.sisov31452af2016-07-27 06:38:101241 if (!requests_.empty()) {
1242 // Log any remaining Requests as cancelled.
1243 for (RequestImpl* req : requests_) {
1244 DCHECK_EQ(this, req->job());
maksim.sisov31452af2016-07-27 06:38:101245 LogCancelRequest(req->source_net_log(), req->info());
maksim.sisov320d5962016-08-15 18:02:511246 req->OnJobCancelled(this);
maksim.sisov31452af2016-07-27 06:38:101247 }
1248 requests_.clear();
[email protected]b3601bc22012-02-21 21:23:201249 }
[email protected]68ad3ee2010-01-30 03:45:391250 }
1251
[email protected]daae1322013-09-05 18:26:501252 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1253 // of the queue.
1254 void Schedule(bool at_head) {
1255 DCHECK(!is_queued());
1256 PrioritizedDispatcher::Handle handle;
1257 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001258 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501259 } else {
[email protected]106ccd2c2014-06-17 09:21:001260 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501261 }
1262 // The dispatcher could have started |this| in the above call to Add, which
1263 // could have called Schedule again. In that case |handle| will be null,
1264 // but |handle_| may have been set by the other nested call to Schedule.
1265 if (!handle.is_null()) {
1266 DCHECK(handle_.is_null());
1267 handle_ = handle;
1268 }
[email protected]16ee26d2012-03-08 03:34:351269 }
1270
maksim.sisov31452af2016-07-27 06:38:101271 void AddRequest(RequestImpl* request) {
1272 DCHECK_EQ(key_.hostname, request->info().hostname());
[email protected]0f292de02012-02-01 22:28:201273
maksim.sisov31452af2016-07-27 06:38:101274 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201275
maksim.sisov31452af2016-07-27 06:38:101276 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001277 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451278 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201279
1280 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001281 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101282 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451283 priority()));
[email protected]0f292de02012-02-01 22:28:201284
Miriam Gershenson61604662017-09-28 23:51:111285 if (!request->info().is_speculative())
[email protected]0f292de02012-02-01 22:28:201286 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201287
maksim.sisov31452af2016-07-27 06:38:101288 requests_.push_back(request);
[email protected]b3601bc22012-02-21 21:23:201289
[email protected]51b9a6b2012-06-25 21:50:291290 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391291 }
1292
maksim.sisov31452af2016-07-27 06:38:101293 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
juliatuttlec53b19a72016-05-05 13:51:311294 DCHECK_EQ(key_.hostname, req->info().hostname());
juliatuttlec53b19a72016-05-05 13:51:311295
1296 priority_tracker_.Remove(req->priority());
1297 req->set_priority(priority);
1298 priority_tracker_.Add(req->priority());
1299 UpdatePriority();
1300 }
1301
maksim.sisov31452af2016-07-27 06:38:101302 // Detach cancelled request. If it was the last active Request, also finishes
1303 // this Job.
1304 void CancelRequest(RequestImpl* request) {
1305 DCHECK_EQ(key_.hostname, request->info().hostname());
1306 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351307
maksim.sisov31452af2016-07-27 06:38:101308 LogCancelRequest(request->source_net_log(), request->info());
[email protected]16ee26d2012-03-08 03:34:351309
maksim.sisov31452af2016-07-27 06:38:101310 priority_tracker_.Remove(request->priority());
1311 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001312 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101313 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1314 priority()));
[email protected]b3601bc22012-02-21 21:23:201315
[email protected]16ee26d2012-03-08 03:34:351316 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291317 UpdatePriority();
maksim.sisov31452af2016-07-27 06:38:101318 RemoveRequest(request);
[email protected]16ee26d2012-03-08 03:34:351319 } else {
1320 // If we were called from a Request's callback within CompleteRequests,
1321 // that Request could not have been cancelled, so num_active_requests()
1322 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431323 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201324 }
[email protected]68ad3ee2010-01-30 03:45:391325 }
1326
maksim.sisov31452af2016-07-27 06:38:101327 void RemoveRequest(RequestImpl* request) {
1328 auto it = std::find(requests_.begin(), requests_.end(), request);
1329 DCHECK(it != requests_.end());
1330 requests_.erase(it);
1331 }
1332
[email protected]7af985a2012-12-14 22:40:421333 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1334 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111335 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201336 void Abort() {
[email protected]0f292de02012-02-01 22:28:201337 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421338 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201339 }
1340
[email protected]f0f602bd2012-11-15 18:01:021341 // If DnsTask present, abort it and fall back to ProcTask.
1342 void AbortDnsTask() {
1343 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501344 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021345 dns_task_error_ = OK;
1346 StartProcTask();
1347 }
1348 }
1349
[email protected]16ee26d2012-03-08 03:34:351350 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1351 // Completes all requests and destroys the job.
1352 void OnEvicted() {
1353 DCHECK(!is_running());
1354 DCHECK(is_queued());
1355 handle_.Reset();
1356
mikecirone8b85c432016-09-08 19:11:001357 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351358
1359 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431360 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351361 }
1362
[email protected]78eac2a2012-03-14 19:09:271363 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1364 // this Job was destroyed.
1365 bool ServeFromHosts() {
1366 DCHECK_GT(num_active_requests(), 0u);
1367 AddressList addr_list;
1368 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031369 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271370 &addr_list)) {
1371 // This will destroy the Job.
eroman0cd87b62016-12-14 19:13:451372 CompleteRequests(MakeCacheEntry(OK, addr_list), base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271373 return true;
1374 }
1375 return false;
1376 }
1377
tanay.c6ddd5f6f2015-08-25 06:34:571378 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111379
1380 bool is_queued() const {
1381 return !handle_.is_null();
1382 }
1383
1384 bool is_running() const {
1385 return is_dns_running() || is_proc_running();
1386 }
1387
[email protected]16ee26d2012-03-08 03:34:351388 private:
[email protected]daae1322013-09-05 18:26:501389 void KillDnsTask() {
1390 if (dns_task_) {
1391 ReduceToOneJobSlot();
1392 dns_task_.reset();
1393 }
1394 }
1395
1396 // Reduce the number of job slots occupied and queued in the dispatcher
1397 // to one. If the second Job slot is queued in the dispatcher, cancels the
1398 // queued job. Otherwise, the second Job has been started by the
1399 // PrioritizedDispatcher, so signals it is complete.
1400 void ReduceToOneJobSlot() {
1401 DCHECK_GE(num_occupied_job_slots_, 1u);
1402 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001403 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501404 handle_.Reset();
1405 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001406 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501407 --num_occupied_job_slots_;
1408 }
1409 DCHECK_EQ(1u, num_occupied_job_slots_);
1410 }
1411
eroman0cd87b62016-12-14 19:13:451412 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1413 // HostCache::Entry(). The address list is omited from the cache entry
1414 // for errors.
1415 HostCache::Entry MakeCacheEntry(int net_error,
1416 const AddressList& addr_list) const {
1417 return HostCache::Entry(
1418 net_error,
1419 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList());
1420 }
1421
1422 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1423 const AddressList& addr_list,
1424 base::TimeDelta ttl) const {
1425 return HostCache::Entry(
1426 net_error,
1427 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1428 ttl);
1429 }
1430
juliatuttlec53b19a72016-05-05 13:51:311431 AddressList MakeAddressListForRequest(const AddressList& list) const {
1432 if (requests_.empty())
1433 return list;
1434 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1435 }
1436
[email protected]51b9a6b2012-06-25 21:50:291437 void UpdatePriority() {
1438 if (is_queued()) {
1439 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1440 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001441 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291442 }
1443 }
1444
[email protected]16ee26d2012-03-08 03:34:351445 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201446 void Start() override {
[email protected]daae1322013-09-05 18:26:501447 DCHECK_LE(num_occupied_job_slots_, 1u);
1448
[email protected]70c04ab2013-08-22 16:05:121449 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501450 ++num_occupied_job_slots_;
1451
1452 if (num_occupied_job_slots_ == 2) {
1453 StartSecondDnsTransaction();
1454 return;
1455 }
1456
1457 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201458
mikecirone8b85c432016-09-08 19:11:001459 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201460
[email protected]51b9a6b2012-06-25 21:50:291461 had_dns_config_ = resolver_->HaveDnsConfig();
1462
Miriam Gershenson61604662017-09-28 23:51:111463 start_time_ = base::TimeTicks::Now();
1464 base::TimeDelta queue_time = start_time_ - creation_time_;
1465 base::TimeDelta queue_time_after_change =
1466 start_time_ - priority_change_time_;
[email protected]51b9a6b2012-06-25 21:50:291467
Miriam Gershenson90d05e02017-09-28 19:29:281468 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTime", priority(), queue_time);
1469 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTimeAfterChange", priority(),
1470 queue_time_after_change);
[email protected]51b9a6b2012-06-25 21:50:291471
[email protected]443714fad2013-09-19 04:52:011472 bool system_only =
1473 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1474
[email protected]1d932852012-06-19 19:40:331475 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011476 if (!system_only && had_dns_config_ &&
1477 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201478 StartDnsTask();
1479 } else {
1480 StartProcTask();
1481 }
1482 }
1483
[email protected]b3601bc22012-02-21 21:23:201484 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401485 // the limits on |dispatcher_|. But in order to keep the number of
1486 // TaskScheduler threads low, we will need to use an "inner"
1487 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201488 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351489 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231490 proc_task_ =
1491 new ProcTask(key_, resolver_->proc_params_,
1492 base::Bind(&Job::OnProcTaskComplete,
1493 base::Unretained(this), base::TimeTicks::Now()),
Francois Doraya2d01ba2017-09-25 19:17:401494 net_log_);
[email protected]0f292de02012-02-01 22:28:201495
[email protected]0f292de02012-02-01 22:28:201496 // Start() could be called from within Resolve(), hence it must NOT directly
1497 // call OnProcTaskComplete, for example, on synchronous failure.
1498 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391499 }
1500
[email protected]0f292de02012-02-01 22:28:201501 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371502 void OnProcTaskComplete(base::TimeTicks start_time,
1503 int net_error,
1504 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201505 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391506
[email protected]1d932852012-06-19 19:40:331507 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371508 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001509 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211510 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331511 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1512 ResemblesNetBIOSName(key_.hostname)) {
1513 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1514 } else {
1515 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1516 }
Miriam Gershenson61604662017-09-28 23:51:111517 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.DNS.DnsTask.Errors",
davidbenad6fc442015-05-18 20:59:131518 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221519 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001520 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211521 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001522 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1523 }
1524 }
1525
eroman1efc237c2016-12-14 00:00:451526 if (ContainsIcannNameCollisionIp(addr_list))
1527 net_error = ERR_ICANN_NAME_COLLISION;
1528
[email protected]1339a2a22012-10-17 08:39:431529 base::TimeDelta ttl =
1530 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201531 if (net_error == OK)
1532 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391533
[email protected]895123222012-10-25 15:21:171534 // Don't store the |ttl| in cache since it's not obtained from the server.
eroman0cd87b62016-12-14 19:13:451535 CompleteRequests(MakeCacheEntry(net_error, addr_list), ttl);
[email protected]b3601bc22012-02-21 21:23:201536 }
1537
1538 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271539 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501540 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1541 net_log_));
[email protected]b3601bc22012-02-21 21:23:201542
[email protected]daae1322013-09-05 18:26:501543 dns_task_->StartFirstTransaction();
1544 // Schedule a second transaction, if needed.
1545 if (dns_task_->needs_two_transactions())
1546 Schedule(true);
1547 }
1548
1549 void StartSecondDnsTransaction() {
1550 DCHECK(dns_task_->needs_two_transactions());
1551 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221552 }
1553
1554 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1555 // deleted before this callback. In this case dns_task is deleted as well,
1556 // so we use it as indicator whether Job is still valid.
1557 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1558 base::TimeDelta duration,
1559 int net_error) {
Miriam Gershenson61604662017-09-28 23:51:111560 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221561
wezb9820d42016-06-22 23:41:041562 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221563 return;
1564
1565 dns_task_error_ = net_error;
1566
1567 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1568 // http://crbug.com/117655
1569
1570 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1571 // ProcTask in that case is a waste of time.
1572 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501573 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221574 StartProcTask();
1575 } else {
1576 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1577 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201578 }
1579 }
1580
[email protected]daae1322013-09-05 18:26:501581
1582 // HostResolverImpl::DnsTask::Delegate implementation:
1583
dchengb03027d2014-10-21 12:00:201584 void OnDnsTaskComplete(base::TimeTicks start_time,
1585 int net_error,
1586 const AddressList& addr_list,
1587 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201588 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201589
[email protected]e3bd4822012-10-23 18:01:371590 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201591 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221592 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201593 return;
1594 }
Miriam Gershenson61604662017-09-28 23:51:111595
1596 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201597
[email protected]1def74c2012-03-22 20:07:001598 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431599 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461600
[email protected]1ffdda82012-12-12 23:04:221601 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021602
[email protected]895123222012-10-25 15:21:171603 base::TimeDelta bounded_ttl =
1604 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1605
eroman0cd87b62016-12-14 19:13:451606 if (ContainsIcannNameCollisionIp(addr_list)) {
1607 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1608 } else {
1609 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list, ttl),
1610 bounded_ttl);
1611 }
[email protected]b3601bc22012-02-21 21:23:201612 }
1613
dchengb03027d2014-10-21 12:00:201614 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501615 DCHECK(dns_task_->needs_two_transactions());
1616 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1617 // No longer need to occupy two dispatcher slots.
1618 ReduceToOneJobSlot();
1619
1620 // We already have a job slot at the dispatcher, so if the second
1621 // transaction hasn't started, reuse it now instead of waiting in the queue
1622 // for the second slot.
1623 if (dns_task_->needs_another_transaction())
1624 dns_task_->StartSecondTransaction();
1625 }
1626
Miriam Gershenson61604662017-09-28 23:51:111627 void RecordJobHistograms(int error) {
1628 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
1629 RESOLVE_SUCCESS,
1630 RESOLVE_FAIL,
1631 RESOLVE_SPECULATIVE_SUCCESS,
1632 RESOLVE_SPECULATIVE_FAIL,
1633 RESOLVE_MAX, // Bounding value.
1634 };
1635 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1636
1637 base::TimeDelta duration = base::TimeTicks::Now() - start_time_;
1638 if (error == OK) {
1639 if (had_non_speculative_request_) {
1640 category = RESOLVE_SUCCESS;
1641 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
1642 switch (key_.address_family) {
1643 case ADDRESS_FAMILY_IPV4:
1644 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1645 duration);
1646 break;
1647 case ADDRESS_FAMILY_IPV6:
1648 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1649 duration);
1650 break;
1651 case ADDRESS_FAMILY_UNSPECIFIED:
1652 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1653 duration);
1654 break;
1655 }
1656 } else {
1657 category = RESOLVE_SPECULATIVE_SUCCESS;
1658 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.Speculative",
1659 duration);
1660 }
1661 } else {
1662 if (had_non_speculative_request_) {
1663 category = RESOLVE_FAIL;
1664 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
1665 switch (key_.address_family) {
1666 case ADDRESS_FAMILY_IPV4:
1667 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1668 duration);
1669 break;
1670 case ADDRESS_FAMILY_IPV6:
1671 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1672 duration);
1673 break;
1674 case ADDRESS_FAMILY_UNSPECIFIED:
1675 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1676 duration);
1677 break;
1678 }
1679 } else {
1680 category = RESOLVE_SPECULATIVE_FAIL;
1681 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.Speculative",
1682 duration);
1683 }
1684 }
1685 DCHECK_LT(static_cast<int>(category),
1686 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1687 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
1688 }
1689
[email protected]16ee26d2012-03-08 03:34:351690 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171691 void CompleteRequests(const HostCache::Entry& entry,
1692 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211693 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201694
[email protected]16ee26d2012-03-08 03:34:351695 // This job must be removed from resolver's |jobs_| now to make room for a
1696 // new job with the same key in case one of the OnComplete callbacks decides
1697 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1698 // is done.
danakj22f90e72016-04-16 01:55:401699 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351700
1701 resolver_->RemoveJob(this);
1702
[email protected]16ee26d2012-03-08 03:34:351703 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351704 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501705 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351706 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041707 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351708 }
[email protected]daae1322013-09-05 18:26:501709 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351710
1711 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001712 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351713 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001714 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351715 handle_.Reset();
1716 }
1717
1718 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001719 net_log_.AddEvent(NetLogEventType::CANCELLED);
1720 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351721 OK);
1722 return;
1723 }
[email protected]b3601bc22012-02-21 21:23:201724
mikecirone8b85c432016-09-08 19:11:001725 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221726 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391727
juliatuttled7fa5852016-07-29 13:16:571728 resolver_->SchedulePersist();
1729
[email protected]78eac2a2012-03-14 19:09:271730 DCHECK(!requests_.empty());
1731
eroman1efc237c2016-12-14 00:00:451732 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191733 // Record this histogram here, when we know the system has a valid DNS
1734 // configuration.
[email protected]539df6c2012-06-19 21:21:291735 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1736 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191737 }
[email protected]16ee26d2012-03-08 03:34:351738
juliatuttle317860e2016-05-12 14:47:221739 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1740 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Miriam Gershenson61604662017-09-28 23:51:111741 if (did_complete) {
[email protected]1339a2a22012-10-17 08:39:431742 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershenson61604662017-09-28 23:51:111743 RecordJobHistograms(entry.error());
1744 }
[email protected]16ee26d2012-03-08 03:34:351745
maksim.sisov31452af2016-07-27 06:38:101746 // Complete all of the requests that were attached to the job and
1747 // detach them.
1748 while (!requests_.empty()) {
1749 RequestImpl* req = requests_.front();
1750 requests_.pop_front();
[email protected]0f292de02012-02-01 22:28:201751 DCHECK_EQ(this, req->job());
1752 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221753 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291754 if (did_complete) {
[email protected]51b9a6b2012-06-25 21:50:291755 // Record effective total time from creation to completion.
Miriam Gershenson90d05e02017-09-28 19:29:281756 RecordTotalTime(req->info().is_speculative(), false,
[email protected]51b9a6b2012-06-25 21:50:291757 base::TimeTicks::Now() - req->request_time());
1758 }
maksim.sisov31452af2016-07-27 06:38:101759 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201760
1761 // Check if the resolver was destroyed as a result of running the
1762 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211763 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201764 return;
1765 }
1766 }
1767
[email protected]1339a2a22012-10-17 08:39:431768 // Convenience wrapper for CompleteRequests in case of failure.
1769 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171770 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1771 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431772 }
1773
[email protected]b4481b222012-03-16 17:13:111774 RequestPriority priority() const {
1775 return priority_tracker_.highest_priority();
1776 }
1777
1778 // Number of non-canceled requests in |requests_|.
1779 size_t num_active_requests() const {
1780 return priority_tracker_.total_count();
1781 }
1782
wezb9820d42016-06-22 23:41:041783 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111784
wezb9820d42016-06-22 23:41:041785 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111786
[email protected]0f292de02012-02-01 22:28:201787 base::WeakPtr<HostResolverImpl> resolver_;
1788
1789 Key key_;
1790
1791 // Tracks the highest priority across |requests_|.
1792 PriorityTracker priority_tracker_;
1793
[email protected]0f292de02012-02-01 22:28:201794 bool had_non_speculative_request_;
1795
[email protected]51b9a6b2012-06-25 21:50:291796 // Distinguishes measurements taken while DnsClient was fully configured.
1797 bool had_dns_config_;
1798
[email protected]daae1322013-09-05 18:26:501799 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1800 unsigned num_occupied_job_slots_;
1801
[email protected]1d932852012-06-19 19:40:331802 // Result of DnsTask.
1803 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001804
[email protected]51b9a6b2012-06-25 21:50:291805 const base::TimeTicks creation_time_;
1806 base::TimeTicks priority_change_time_;
Miriam Gershenson61604662017-09-28 23:51:111807 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:291808
tfarina428341112016-09-22 13:38:201809 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201810
[email protected]b3601bc22012-02-21 21:23:201811 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201812 scoped_refptr<ProcTask> proc_task_;
1813
[email protected]b3601bc22012-02-21 21:23:201814 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401815 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201816
[email protected]0f292de02012-02-01 22:28:201817 // All Requests waiting for the result of this Job. Some can be canceled.
Brett Wilsonc6a0c822017-09-12 00:04:291818 base::circular_deque<RequestImpl*> requests_;
[email protected]0f292de02012-02-01 22:28:201819
[email protected]16ee26d2012-03-08 03:34:351820 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201821 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391822};
1823
1824//-----------------------------------------------------------------------------
1825
[email protected]0f292de02012-02-01 22:28:201826HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431827 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201828 size_t max_retry_attempts)
1829 : resolver_proc(resolver_proc),
1830 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441831 unresponsive_delay(
1832 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201833 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001834 // Maximum of 4 retry attempts for host resolution.
1835 static const size_t kDefaultMaxRetryAttempts = 4u;
1836 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1837 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201838}
1839
vmpstracd23b72016-02-26 21:08:551840HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1841 default;
1842
[email protected]0f292de02012-02-01 22:28:201843HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1844
[email protected]b59ff372009-07-15 22:04:321845HostResolverImpl::~HostResolverImpl() {
gab47aa7da2017-06-02 16:09:431846 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]daae1322013-09-05 18:26:501847 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001848 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541849 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501850 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541851 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431852
[email protected]232a5812011-03-04 22:42:081853 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441854 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401855 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321856}
1857
[email protected]0f292de02012-02-01 22:28:201858void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001859 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201860 DCHECK_GT(value, 0u);
1861 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131862}
1863
[email protected]684970b2009-08-14 04:54:461864int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101865 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321866 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291867 const CompletionCallback& callback,
maksim.sisov31452af2016-07-27 06:38:101868 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:201869 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401870 DCHECK(addresses);
gab47aa7da2017-06-02 16:09:431871 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]aa22b242011-11-16 18:58:291872 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:101873 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:141874
Chris Palmer9cbf4212017-07-19 01:54:551875 LogStartRequest(source_net_log, info);
pauljensen19eb73422015-04-15 23:20:061876
Matt Menke23b4bbf82017-07-20 19:11:291877 Key key;
1878 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:401879 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021880 LogFinishRequest(source_net_log, info, rv);
Miriam Gershenson90d05e02017-09-28 19:29:281881 RecordTotalTime(info.is_speculative(), true, base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401882 return rv;
[email protected]38368712011-03-02 08:09:401883 }
1884
[email protected]0f292de02012-02-01 22:28:201885 // Next we need to attach our request to a "job". This job is responsible for
1886 // calling "getaddrinfo(hostname)" on a worker thread.
1887
avi9e72eb482016-12-09 21:10:541888 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:201889 Job* job;
1890 if (jobit == jobs_.end()) {
Francois Doraya2d01ba2017-09-25 19:17:401891 job =
1892 new Job(weak_ptr_factory_.GetWeakPtr(), key, priority, source_net_log);
[email protected]daae1322013-09-05 18:26:501893 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201894
1895 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001896 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1897 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201898 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351899 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201900 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201901 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021902 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201903 return rv;
1904 }
[email protected]0f292de02012-02-01 22:28:201905 }
avi9e72eb482016-12-09 21:10:541906 jobs_[key] = base::WrapUnique(job);
[email protected]0f292de02012-02-01 22:28:201907 } else {
avi9e72eb482016-12-09 21:10:541908 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:201909 }
1910
1911 // Can't complete synchronously. Create and attach request.
Jeremy Roman0579ed62017-08-29 15:56:191912 auto req = std::make_unique<RequestImpl>(source_net_log, info, priority,
avi9e72eb482016-12-09 21:10:541913 callback, addresses, job);
maksim.sisov31452af2016-07-27 06:38:101914 job->AddRequest(req.get());
1915 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:321916
[email protected]0f292de02012-02-01 22:28:201917 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321918 return ERR_IO_PENDING;
1919}
1920
Francois Doraya2d01ba2017-09-25 19:17:401921HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231922 : max_queued_jobs_(0),
1923 proc_params_(NULL, options.max_retry_attempts),
1924 net_log_(net_log),
1925 received_dns_config_(false),
1926 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:031927 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:231928 use_local_ipv6_(false),
1929 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:231930 additional_resolver_flags_(0),
1931 fallback_to_proctask_(true),
juliatuttled7fa5852016-07-29 13:16:571932 persist_initialized_(false),
mmenke91c17162016-06-02 16:03:231933 weak_ptr_factory_(this),
1934 probe_weak_ptr_factory_(this) {
1935 if (options.enable_caching)
1936 cache_ = HostCache::CreateDefaultCache();
1937
1938 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1939 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1940 max_queued_jobs_ = job_limits.total_jobs * 100u;
1941
1942 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
1943
1944#if defined(OS_WIN)
1945 EnsureWinsockInit();
1946#endif
1947#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
1948 RunLoopbackProbeJob();
1949#endif
1950 NetworkChangeNotifier::AddIPAddressObserver(this);
1951 NetworkChangeNotifier::AddConnectionTypeObserver(this);
1952 NetworkChangeNotifier::AddDNSObserver(this);
1953#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Sergey Ulanov49085572017-07-10 23:25:461954 !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:231955 EnsureDnsReloaderInit();
1956#endif
1957
1958 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
1959
1960 {
1961 DnsConfig dns_config;
1962 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1963 received_dns_config_ = dns_config.IsValid();
1964 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1965 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
1966 }
1967
1968 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
1969}
1970
1971void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
1972 if (result) {
1973 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
1974 } else {
1975 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
1976 }
1977}
1978
Matt Menke23b4bbf82017-07-20 19:11:291979int HostResolverImpl::ResolveHelper(const RequestInfo& info,
juliatuttle9fb7aeb2016-06-06 20:16:331980 bool allow_stale,
1981 HostCache::EntryStaleness* stale_info,
Matt Menke23b4bbf82017-07-20 19:11:291982 const NetLogWithSource& source_net_log,
1983 AddressList* addresses,
1984 Key* key) {
1985 IPAddress ip_address;
1986 IPAddress* ip_address_ptr = nullptr;
1987 if (ip_address.AssignFromIPLiteral(info.hostname())) {
1988 ip_address_ptr = &ip_address;
1989 } else {
1990 // Check that the caller supplied a valid hostname to resolve.
1991 if (!IsValidDNSDomain(info.hostname()))
1992 return ERR_NAME_NOT_RESOLVED;
1993 }
1994
1995 // Build a key that identifies the request in the cache and in the
1996 // outstanding jobs map.
1997 *key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
1998
juliatuttle9fb7aeb2016-06-06 20:16:331999 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402000 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2001 // On Windows it gives the default interface's address, whereas on Linux it
2002 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332003 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2004 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402005 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332006 }
[email protected]95a214c2011-08-04 21:50:402007
2008 int net_error = ERR_UNEXPECTED;
Matt Menke23b4bbf82017-07-20 19:11:292009 if (ResolveAsIP(*key, info, ip_address_ptr, &net_error, addresses)) {
juliatuttle9fb7aeb2016-06-06 20:16:332010 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402011 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332012 }
Mike Westda1c690e2017-08-12 05:57:162013
2014 // Special-case localhost names, as per the recommendations in
2015 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2016 if (ServeLocalhost(*key, info, addresses)) {
2017 MakeNotStale(stale_info);
2018 return OK;
2019 }
2020
Matt Menke23b4bbf82017-07-20 19:11:292021 if (ServeFromCache(*key, info, &net_error, addresses, allow_stale,
juliatuttle9fb7aeb2016-06-06 20:16:332022 stale_info)) {
mgersh33d23c02017-03-29 20:24:252023 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2024 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332025 // |ServeFromCache()| will set |*stale_info| as needed.
[email protected]78eac2a2012-03-14 19:09:272026 return net_error;
2027 }
Mike Westda1c690e2017-08-12 05:57:162028
[email protected]78eac2a2012-03-14 19:09:272029 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2030 // http://crbug.com/117655
Matt Menke23b4bbf82017-07-20 19:11:292031 if (ServeFromHosts(*key, info, addresses)) {
mgersh33d23c02017-03-29 20:24:252032 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2033 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332034 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272035 return OK;
2036 }
estarkd1bc206e2015-06-20 00:44:392037
[email protected]78eac2a2012-03-14 19:09:272038 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402039}
2040
2041int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2042 AddressList* addresses,
tfarina428341112016-09-22 13:38:202043 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432044 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402045 DCHECK(addresses);
2046
[email protected]95a214c2011-08-04 21:50:402047 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022048 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402049
Matt Menke23b4bbf82017-07-20 19:11:292050 Key key;
2051 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402052
xunjieli26f90452014-11-10 16:23:022053 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402054 return rv;
2055}
2056
[email protected]a8883e452012-11-17 05:58:062057void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432058 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062059#if defined(ENABLE_BUILT_IN_DNS)
2060 if (enabled && !dns_client_) {
2061 SetDnsClient(DnsClient::CreateClient(net_log_));
2062 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402063 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062064 }
2065#endif
2066}
2067
[email protected]489d1a82011-10-12 03:09:112068HostCache* HostResolverImpl::GetHostCache() {
2069 return cache_.get();
2070}
[email protected]95a214c2011-08-04 21:50:402071
danakj22f90e72016-04-16 01:55:402072std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242073 // Check if async DNS is disabled.
2074 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082075 return nullptr;
[email protected]17e92032012-03-29 00:56:242076
2077 // Check if async DNS is enabled, but we currently have no configuration
2078 // for it.
2079 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042080 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192081 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242082
2083 return dns_config->ToValue();
2084}
2085
juliatuttle9fb7aeb2016-06-06 20:16:332086int HostResolverImpl::ResolveStaleFromCache(
2087 const RequestInfo& info,
2088 AddressList* addresses,
2089 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202090 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432091 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
juliatuttle9fb7aeb2016-06-06 20:16:332092 DCHECK(addresses);
2093 DCHECK(stale_info);
2094
2095 // Update the net log and notify registered observers.
2096 LogStartRequest(source_net_log, info);
2097
Matt Menke23b4bbf82017-07-20 19:11:292098 Key key;
2099 int rv =
2100 ResolveHelper(info, true, stale_info, source_net_log, addresses, &key);
juliatuttle9fb7aeb2016-06-06 20:16:332101 LogFinishRequest(source_net_log, info, rv);
2102 return rv;
2103}
2104
Miriam Gershenson2839ef112017-08-30 03:25:372105size_t HostResolverImpl::LastRestoredCacheSize() const {
2106 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2107
2108 return cache_ ? cache_->last_restore_size() : 0;
2109}
2110
2111size_t HostResolverImpl::CacheSize() const {
2112 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2113
2114 return cache_ ? cache_->size() : 0;
2115}
2116
mgershaf9a9232017-04-13 20:19:032117void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432118 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032119 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2120}
2121
2122bool HostResolverImpl::GetNoIPv6OnWifi() {
2123 return assume_ipv6_failure_on_wifi_;
2124}
2125
[email protected]95a214c2011-08-04 21:50:402126bool HostResolverImpl::ResolveAsIP(const Key& key,
2127 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512128 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402129 int* net_error,
2130 AddressList* addresses) {
2131 DCHECK(addresses);
2132 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512133 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402134 return false;
2135
[email protected]95a214c2011-08-04 21:50:402136 *net_error = OK;
martijna23c8962016-03-04 18:18:512137 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252138 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2139 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482140 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402141 *net_error = ERR_NAME_NOT_RESOLVED;
2142 } else {
martijna23c8962016-03-04 18:18:512143 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562144 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2145 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402146 }
2147 return true;
2148}
2149
2150bool HostResolverImpl::ServeFromCache(const Key& key,
2151 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402152 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332153 AddressList* addresses,
2154 bool allow_stale,
2155 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402156 DCHECK(addresses);
2157 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332158 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402159 if (!info.allow_cached_response() || !cache_.get())
2160 return false;
2161
juliatuttle9fb7aeb2016-06-06 20:16:332162 const HostCache::Entry* cache_entry;
2163 if (allow_stale)
2164 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2165 else
2166 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402167 if (!cache_entry)
2168 return false;
2169
juliatuttle317860e2016-05-12 14:47:222170 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562171 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432172 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222173 RecordTTL(cache_entry->ttl());
2174 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562175 }
[email protected]95a214c2011-08-04 21:50:402176 return true;
2177}
2178
[email protected]78eac2a2012-03-14 19:09:272179bool HostResolverImpl::ServeFromHosts(const Key& key,
2180 const RequestInfo& info,
2181 AddressList* addresses) {
2182 DCHECK(addresses);
2183 if (!HaveDnsConfig())
2184 return false;
[email protected]05a79d42013-03-28 07:30:092185 addresses->clear();
2186
[email protected]cb507622012-03-23 16:17:062187 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222188 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062189
[email protected]05a79d42013-03-28 07:30:092190 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2191
[email protected]78eac2a2012-03-14 19:09:272192 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2193 // (glibc and c-ares) return the first matching line. We have more
2194 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092195 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2196 // necessary.
2197 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2198 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2199 DnsHosts::const_iterator it = hosts.find(
2200 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2201 if (it != hosts.end())
2202 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272203 }
2204
[email protected]05a79d42013-03-28 07:30:092205 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2206 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2207 DnsHosts::const_iterator it = hosts.find(
2208 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2209 if (it != hosts.end())
2210 addresses->push_back(IPEndPoint(it->second, info.port()));
2211 }
2212
[email protected]ec666ab22013-04-17 20:05:592213 // If got only loopback addresses and the family was restricted, resolve
2214 // again, without restrictions. See SystemHostResolverCall for rationale.
2215 if ((key.host_resolver_flags &
2216 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2217 IsAllIPv4Loopback(*addresses)) {
2218 Key new_key(key);
2219 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2220 new_key.host_resolver_flags &=
2221 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2222 return ServeFromHosts(new_key, info, addresses);
2223 }
[email protected]05a79d42013-03-28 07:30:092224 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272225}
2226
estarkd1bc206e2015-06-20 00:44:392227bool HostResolverImpl::ServeLocalhost(const Key& key,
2228 const RequestInfo& info,
2229 AddressList* addresses) {
2230 AddressList resolved_addresses;
2231 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2232 return false;
2233
2234 addresses->clear();
2235
2236 for (const auto& address : resolved_addresses) {
2237 // Include the address if:
2238 // - caller didn't specify an address family, or
2239 // - caller specifically asked for the address family of this address, or
2240 // - this is an IPv6 address and caller specifically asked for IPv4 due
2241 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2242 // rationale).
2243 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2244 key.address_family == address.GetFamily() ||
2245 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2246 key.address_family == ADDRESS_FAMILY_IPV4 &&
2247 (key.host_resolver_flags &
2248 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2249 addresses->push_back(address);
2250 }
2251 }
2252
2253 return true;
2254}
2255
[email protected]16ee26d2012-03-08 03:34:352256void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432257 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352258 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052259 // Don't cache an error unless it has a positive TTL.
2260 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
[email protected]1339a2a22012-10-17 08:39:432261 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032262}
2263
[email protected]0f292de02012-02-01 22:28:202264void HostResolverImpl::RemoveJob(Job* job) {
2265 DCHECK(job);
avi9e72eb482016-12-09 21:10:542266 auto it = jobs_.find(job->key());
2267 if (it != jobs_.end() && it->second.get() == job) {
2268 it->second.release();
[email protected]16ee26d2012-03-08 03:34:352269 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542270 }
[email protected]b59ff372009-07-15 22:04:322271}
2272
[email protected]137af622010-02-05 02:14:352273HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062274 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512275 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202276 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272277 HostResolverFlags effective_flags =
2278 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352279 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512280
mgersh3eba057d2017-02-28 18:50:562281 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2282 // When resolving IPv4 literals, there's no need to probe for IPv6.
2283 // When resolving IPv6 literals, there's no benefit to artificially
2284 // limiting our resolution based on a probe. Prior logic ensures
2285 // that this query is UNSPECIFIED (see effective_address_family
2286 // check above) so the code requesting the resolution should be amenable
2287 // to receiving a IPv6 resolution.
2288 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2289 effective_address_family = ADDRESS_FAMILY_IPV4;
2290 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512291 }
2292
estarkd1bc206e2015-06-20 00:44:392293 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352294}
2295
tfarina428341112016-09-22 13:38:202296bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032297 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2298 // work on WiFi.
2299 if (assume_ipv6_failure_on_wifi_ &&
2300 NetworkChangeNotifier::GetConnectionType() ==
2301 NetworkChangeNotifier::CONNECTION_WIFI) {
2302 return false;
2303 }
2304
eroman1a17ef32016-12-14 01:06:092305 // Cache the result for kIPv6ProbePeriodMs (measured from after
2306 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372307 bool cached = true;
eroman1a17ef32016-12-14 01:06:092308 if ((base::TimeTicks::Now() - last_ipv6_probe_time_).InMilliseconds() >
2309 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512310 last_ipv6_probe_result_ =
2311 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
eroman1a17ef32016-12-14 01:06:092312 last_ipv6_probe_time_ = base::TimeTicks::Now();
sergeyub8cdc212015-05-14 18:50:372313 cached = false;
2314 }
mikecirone8b85c432016-09-08 19:11:002315 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372316 base::Bind(&NetLogIPv6AvailableCallback,
2317 last_ipv6_probe_result_, cached));
2318 return last_ipv6_probe_result_;
2319}
2320
mgershaf9a9232017-04-13 20:19:032321bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2322 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032323 std::unique_ptr<DatagramClientSocket> socket(
2324 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
2325 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
2326 net_log.source()));
2327 int rv = socket->Connect(IPEndPoint(dest, 53));
2328 if (rv != OK)
2329 return false;
2330 IPEndPoint endpoint;
2331 rv = socket->GetLocalAddress(&endpoint);
2332 if (rv != OK)
2333 return false;
2334 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2335 const IPAddress& address = endpoint.address();
2336
2337 bool is_link_local =
2338 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2339 if (is_link_local)
2340 return false;
2341
2342 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2343 if (IPAddressStartsWith(address, kTeredoPrefix))
2344 return false;
2345
2346 return true;
2347}
2348
mmenke91c17162016-06-02 16:03:232349void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402350 // Run this asynchronously as it can take 40-100ms and should not block
2351 // initialization.
2352 base::PostTaskWithTraitsAndReplyWithResult(
2353 FROM_HERE,
2354 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2355 base::BindOnce(&HaveOnlyLoopbackAddresses),
2356 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2357 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232358}
2359
[email protected]35ddc282010-09-21 23:42:062360void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202361 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2362 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402363 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542364 for (auto it = jobs_.begin(); it != jobs_.end();) {
2365 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202366 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542367 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202368 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202369 } else {
[email protected]b3601bc22012-02-21 21:23:202370 DCHECK(job->is_queued());
2371 ++it;
[email protected]0f292de02012-02-01 22:28:202372 }
[email protected]ef4c40c2010-09-01 14:42:032373 }
[email protected]b3601bc22012-02-21 21:23:202374
[email protected]daae1322013-09-05 18:26:502375 // Pause the dispatcher so it won't start any new dispatcher jobs while
2376 // aborting the old ones. This is needed so that it won't start the second
2377 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2378 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002379 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2380 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502381 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122382
[email protected]57a48d32012-03-03 00:04:552383 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072384 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552385
[email protected]16ee26d2012-03-08 03:34:352386 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212387 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552388 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112389 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202390 }
[email protected]daae1322013-09-05 18:26:502391
2392 if (self)
[email protected]106ccd2c2014-06-17 09:21:002393 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502394}
2395
2396void HostResolverImpl::AbortDnsTasks() {
2397 // Pause the dispatcher so it won't start any new dispatcher jobs while
2398 // aborting the old ones. This is needed so that it won't start the second
2399 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002400 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2401 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502402 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2403
avi9e72eb482016-12-09 21:10:542404 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502405 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002406 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032407}
2408
[email protected]78eac2a2012-03-14 19:09:272409void HostResolverImpl::TryServingAllJobsFromHosts() {
2410 if (!HaveDnsConfig())
2411 return;
2412
2413 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2414 // http://crbug.com/117655
2415
2416 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072417 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272418
avi9e72eb482016-12-09 21:10:542419 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2420 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272421 ++it;
2422 // This could remove |job| from |jobs_|, but iterator will remain valid.
2423 job->ServeFromHosts();
2424 }
2425}
2426
[email protected]be1a48b2011-01-20 00:12:132427void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372428 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182429 // Abandon all ProbeJobs.
2430 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172431 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102432 cache_->OnNetworkChange();
[email protected]7c466e92013-07-20 01:44:482433#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232434 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132435#endif
2436 AbortAllInProgressJobs();
2437 // |this| may be deleted inside AbortAllInProgressJobs().
2438}
2439
ttuttlecf1158bf2016-03-18 16:37:442440void HostResolverImpl::OnConnectionTypeChanged(
2441 NetworkChangeNotifier::ConnectionType type) {
2442 proc_params_.unresponsive_delay =
2443 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2444 "DnsUnresponsiveDelayMsByConnectionType",
2445 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2446 type);
2447}
2448
pauljensen101ed372015-04-17 00:11:422449void HostResolverImpl::OnInitialDNSConfigRead() {
2450 UpdateDNSConfig(false);
2451}
2452
[email protected]bb0e34542012-08-31 19:52:402453void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422454 UpdateDNSConfig(true);
2455}
2456
2457void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402458 DnsConfig dns_config;
2459 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592460
[email protected]b4481b222012-03-16 17:13:112461 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002462 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2463 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112464 }
2465
[email protected]01b3b9d2012-08-13 16:18:142466 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192467 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522468 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2469 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272470
[email protected]a8883e452012-11-17 05:58:062471 num_dns_failures_ = 0;
2472
[email protected]01b3b9d2012-08-13 16:18:142473 // We want a new DnsSession in place, before we Abort running Jobs, so that
2474 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022475 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192476 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422477 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022478 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422479 // If we just switched DnsClients, restart jobs using new resolver.
2480 // TODO(pauljensen): Is this necessary?
2481 config_changed = true;
2482 }
[email protected]f0f602bd2012-11-15 18:01:022483 }
[email protected]01b3b9d2012-08-13 16:18:142484
pauljensen101ed372015-04-17 00:11:422485 if (config_changed) {
2486 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232487 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422488 // as NSCD's cache should be dropped automatically by the OS when
2489 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172490 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232491 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142492
pauljensen101ed372015-04-17 00:11:422493 // Life check to bail once |this| is deleted.
2494 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022495
pauljensen101ed372015-04-17 00:11:422496 // Existing jobs will have been sent to the original server so they need to
2497 // be aborted.
2498 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142499
pauljensen101ed372015-04-17 00:11:422500 // |this| may be deleted inside AbortAllInProgressJobs().
2501 if (self.get())
2502 TryServingAllJobsFromHosts();
2503 }
[email protected]78eac2a2012-03-14 19:09:272504}
2505
2506bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252507 // Use DnsClient only if it's fully configured and there is no override by
2508 // ScopedDefaultHostResolverProc.
2509 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2510 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042511 return dns_client_ && dns_client_->GetConfig() &&
2512 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202513}
2514
[email protected]1ffdda82012-12-12 23:04:222515void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022516 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222517 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022518 num_dns_failures_ = 0;
2519 return;
2520 }
2521 ++num_dns_failures_;
2522 if (num_dns_failures_ < kMaximumDnsFailures)
2523 return;
[email protected]daae1322013-09-05 18:26:502524
2525 // Disable DnsClient until the next DNS change. Must be done before aborting
2526 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022527 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502528
2529 // Switch jobs with active DnsTasks over to using ProcTasks.
2530 AbortDnsTasks();
2531
[email protected]f0f602bd2012-11-15 18:01:022532 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
davidbenad6fc442015-05-18 20:59:132533 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2534 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022535}
2536
danakj22f90e72016-04-16 01:55:402537void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502538 // DnsClient and config must be updated before aborting DnsTasks, since doing
2539 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482540 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502541 if (dns_client_ && !dns_client_->GetConfig() &&
2542 num_dns_failures_ < kMaximumDnsFailures) {
2543 DnsConfig dns_config;
2544 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2545 dns_client_->SetConfig(dns_config);
2546 num_dns_failures_ = 0;
2547 if (dns_client_->GetConfig())
2548 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062549 }
[email protected]daae1322013-09-05 18:26:502550
2551 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062552}
2553
juliatuttled7fa5852016-07-29 13:16:572554void HostResolverImpl::InitializePersistence(
2555 const PersistCallback& persist_callback,
2556 std::unique_ptr<const base::Value> old_data) {
2557 DCHECK(!persist_initialized_);
2558 persist_callback_ = persist_callback;
2559 persist_initialized_ = true;
2560 if (old_data)
2561 ApplyPersistentData(std::move(old_data));
2562}
2563
juliatuttle7e8bf1c2016-08-02 19:09:092564void HostResolverImpl::ApplyPersistentData(
2565 std::unique_ptr<const base::Value> data) {}
2566
2567std::unique_ptr<const base::Value> HostResolverImpl::GetPersistentData() {
2568 return std::unique_ptr<const base::Value>();
2569}
2570
juliatuttled7fa5852016-07-29 13:16:572571void HostResolverImpl::SchedulePersist() {
2572 if (!persist_initialized_ || persist_timer_.IsRunning())
2573 return;
2574 persist_timer_.Start(
2575 FROM_HERE, base::TimeDelta::FromSeconds(kPersistDelaySec),
2576 base::Bind(&HostResolverImpl::DoPersist, weak_ptr_factory_.GetWeakPtr()));
2577}
2578
2579void HostResolverImpl::DoPersist() {
2580 DCHECK(persist_initialized_);
2581 persist_callback_.Run(GetPersistentData());
2582}
2583
maksim.sisov31452af2016-07-27 06:38:102584HostResolverImpl::RequestImpl::~RequestImpl() {
2585 if (job_)
2586 job_->CancelRequest(this);
2587}
2588
2589void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2590 RequestPriority priority) {
2591 job_->ChangeRequestPriority(this, priority);
2592}
2593
[email protected]b59ff372009-07-15 22:04:322594} // namespace net