blob: 818c55fa1d8031822860ae443ccf9c8e9f169d71 [file] [log] [blame]
[email protected]a2730882012-01-21 00:56:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]b59ff372009-07-15 22:04:322// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f2cb3cf2013-03-21 01:40:535#include "net/dns/host_resolver_impl.h"
[email protected]b59ff372009-07-15 22:04:326
[email protected]21526002010-05-16 19:42:467#if defined(OS_WIN)
8#include <Winsock2.h>
Fabrice de Gans-Riberi7de47372018-05-08 20:23:479#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]21526002010-05-16 19:42:4610#include <netdb.h>
tfarinada9e1362017-03-14 16:49:0611#include <netinet/in.h>
12#if !defined(OS_NACL)
13#include <net/if.h>
14#if !defined(OS_ANDROID)
15#include <ifaddrs.h>
16#endif // !defined(OS_ANDROID)
17#endif // !defined(OS_NACL)
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4718#endif // defined(OS_WIN)
tfarinada9e1362017-03-14 16:49:0619
Eric Orth70992982018-07-24 00:25:0020#include <algorithm>
[email protected]68ad3ee2010-01-30 03:45:3921#include <cmath>
Eric Orth70992982018-07-24 00:25:0022#include <limits>
thestiga74ad2b2016-07-11 20:52:3623#include <memory>
[email protected]0f292de02012-02-01 22:28:2024#include <utility>
[email protected]21526002010-05-16 19:42:4625#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3926
[email protected]33152acc2011-10-20 23:37:1227#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2928#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2029#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1030#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3231#include "base/compiler_specific.h"
David Benjamina5677192018-04-23 23:25:4232#include "base/containers/linked_list.h"
[email protected]58580352010-10-26 04:07:5033#include "base/debug/debugger.h"
34#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4635#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2336#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4537#include "base/metrics/field_trial.h"
Maks Orlovich5393c8682018-02-26 16:17:5038#include "base/metrics/field_trial_params.h"
Ilya Sherman0eb39802017-12-08 20:58:1839#include "base/metrics/histogram_functions.h"
davidbenad6fc442015-05-18 20:59:1340#include "base/metrics/histogram_macros.h"
Paul Jensen41dc3e9f2018-11-06 22:10:1041#include "base/no_destructor.h"
anujk.sharma7c907f02015-05-29 02:55:4442#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4843#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0544#include "base/strings/utf_string_conversions.h"
Gabriel Charette44db1422018-08-06 11:19:3345#include "base/task/post_task.h"
Francois Doraya2d01ba2017-09-25 19:17:4046#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3547#include "base/threading/thread_task_runner_handle.h"
Misha Efimovb99e7da2018-05-30 16:59:0248#include "base/time/default_tick_clock.h"
[email protected]66e96c42013-06-28 15:20:3149#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5650#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4651#include "base/values.h"
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4752#include "build/build_config.h"
[email protected]b3601bc22012-02-21 21:23:2053#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3254#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5155#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5156#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4857#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1558#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4859#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1860#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4661#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2762#include "net/dns/dns_client.h"
tfarina47598f042015-10-07 23:08:3563#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2064#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2065#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0366#include "net/dns/dns_util.h"
Eric Orth9871aafa2018-10-02 19:59:1867#include "net/dns/host_resolver_mdns_task.h"
[email protected]f2cb3cf2013-03-21 01:40:5368#include "net/dns/host_resolver_proc.h"
Eric Orth9871aafa2018-10-02 19:59:1869#include "net/dns/mdns_client.h"
Eric Orth8afaf152018-11-07 21:01:2670#include "net/dns/public/dns_protocol.h"
eroman87c53d62015-04-02 06:51:0771#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1972#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0073#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1974#include "net/log/net_log_parameters_callback.h"
75#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0076#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1977#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5178#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2679#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1480#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3281
Eric Orth9871aafa2018-10-02 19:59:1882#if BUILDFLAG(ENABLE_MDNS)
83#include "net/dns/mdns_client_impl.h"
84#endif
85
[email protected]b59ff372009-07-15 22:04:3286#if defined(OS_WIN)
87#include "net/base/winsock_init.h"
88#endif
89
tfarinada9e1362017-03-14 16:49:0690#if defined(OS_ANDROID)
Paul Jensen41dc3e9f2018-11-06 22:10:1091#include "base/android/build_info.h"
tfarinada9e1362017-03-14 16:49:0692#include "net/android/network_library.h"
93#endif
94
[email protected]b59ff372009-07-15 22:04:3295namespace net {
96
[email protected]e95d3aca2010-01-11 22:47:4397namespace {
98
ttuttlecf1158bf2016-03-18 16:37:4499// Default delay between calls to the system resolver for the same hostname.
100// (Can be overridden by field trial.)
101const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
102
[email protected]6e78dfb2011-07-28 21:34:47103// Limit the size of hostnames that will be resolved to combat issues in
104// some platform's resolvers.
105const size_t kMaxHostLength = 4096;
106
[email protected]a2730882012-01-21 00:56:27107// Default TTL for successful resolutions with ProcTask.
108const unsigned kCacheEntryTTLSeconds = 60;
109
[email protected]b3601bc22012-02-21 21:23:20110// Default TTL for unsuccessful resolutions with ProcTask.
111const unsigned kNegativeCacheEntryTTLSeconds = 0;
112
[email protected]895123222012-10-25 15:21:17113// Minimum TTL for successful resolutions with DnsTask.
114const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
115
sergeyub8cdc212015-05-14 18:50:37116// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
117// cached.
118const int kIPv6ProbePeriodMs = 1000;
119
120// Google DNS address used for IPv6 probes.
121const uint8_t kIPv6ProbeAddress[] =
122 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
123 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
124
[email protected]1def74c2012-03-22 20:07:00125enum DnsResolveStatus {
126 RESOLVE_STATUS_DNS_SUCCESS = 0,
127 RESOLVE_STATUS_PROC_SUCCESS,
128 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33129 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00130 RESOLVE_STATUS_MAX
131};
132
eroman91dd3602015-03-26 03:46:33133// ICANN uses this localhost address to indicate a name collision.
134//
135// The policy in Chromium is to fail host resolving if it resolves to
136// this special address.
137//
138// Not however that IP literals are exempt from this policy, so it is still
139// possible to navigate to http://127.0.53.53/ directly.
140//
141// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51142const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33143
eroman1efc237c2016-12-14 00:00:45144bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
145 for (const auto& endpoint : addr_list) {
146 const IPAddress& addr = endpoint.address();
147 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
148 return true;
149 }
150 }
151 return false;
152}
153
[email protected]1def74c2012-03-22 20:07:00154void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
155 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
156 result,
157 RESOLVE_STATUS_MAX);
158}
159
[email protected]1d932852012-06-19 19:40:33160bool ResemblesNetBIOSName(const std::string& hostname) {
161 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
162}
163
164// True if |hostname| ends with either ".local" or ".local.".
165bool ResemblesMulticastDNSName(const std::string& hostname) {
166 DCHECK(!hostname.empty());
167 const char kSuffix[] = ".local.";
168 const size_t kSuffixLen = sizeof(kSuffix) - 1;
169 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36170 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33171 return hostname.size() > kSuffixLen &&
172 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
173 }
174 return hostname.size() > kSuffixLenTrimmed &&
175 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
176 kSuffix, kSuffixLenTrimmed);
177}
178
[email protected]51b9a6b2012-06-25 21:50:29179// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21180#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
181 do { \
182 switch (priority) { \
183 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28184 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21185 break; \
186 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28187 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21188 break; \
189 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28190 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21191 break; \
192 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28193 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21194 break; \
195 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28196 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21197 break; \
198 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28199 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21200 break; \
201 } \
202 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29203 } while (0)
204
[email protected]1339a2a22012-10-17 08:39:43205void RecordTTL(base::TimeDelta ttl) {
206 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
207 base::TimeDelta::FromSeconds(1),
208 base::TimeDelta::FromDays(1), 100);
209}
210
[email protected]16c2bd72013-06-28 01:19:22211bool ConfigureAsyncDnsNoFallbackFieldTrial() {
212 const bool kDefault = false;
213
214 // Configure the AsyncDns field trial as follows:
215 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
216 // groups AsyncDnsA and AsyncDnsB: return false,
217 // groups SystemDnsA and SystemDnsB: return false,
218 // otherwise (trial absent): return default.
219 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29220 if (!group_name.empty()) {
221 return base::StartsWith(group_name, "AsyncDnsNoFallback",
222 base::CompareCase::INSENSITIVE_ASCII);
223 }
[email protected]16c2bd72013-06-28 01:19:22224 return kDefault;
225}
226
Maks Orlovich5393c8682018-02-26 16:17:50227const base::FeatureParam<base::TaskPriority>::Option prio_modes[] = {
228 {base::TaskPriority::USER_VISIBLE, "default"},
229 {base::TaskPriority::USER_BLOCKING, "user_blocking"}};
230const base::Feature kSystemResolverPriorityExperiment = {
231 "SystemResolverPriorityExperiment", base::FEATURE_DISABLED_BY_DEFAULT};
232const base::FeatureParam<base::TaskPriority> priority_mode{
233 &kSystemResolverPriorityExperiment, "mode",
234 base::TaskPriority::USER_VISIBLE, &prio_modes};
235
[email protected]d7b9a2b2012-05-31 22:31:19236//-----------------------------------------------------------------------------
237
Avi Drissman13fc8932015-12-20 04:40:46238AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17239 if (list.empty() || list.front().port() == port)
240 return list;
241 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56242}
243
[email protected]ec666ab22013-04-17 20:05:59244// Returns true if |addresses| contains only IPv4 loopback addresses.
245bool IsAllIPv4Loopback(const AddressList& addresses) {
246 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51247 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59248 switch (addresses[i].GetFamily()) {
249 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51250 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59251 return false;
252 break;
253 case ADDRESS_FAMILY_IPV6:
254 return false;
255 default:
256 NOTREACHED();
257 return false;
258 }
259 }
260 return true;
261}
262
tfarinada9e1362017-03-14 16:49:06263// Returns true if it can determine that only loopback addresses are configured.
264// i.e. if only 127.0.0.1 and ::1 are routable.
265// Also returns false if it cannot determine this.
266bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40267 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47268#if defined(OS_WIN)
269 // TODO(wtc): implement with the GetAdaptersAddresses function.
270 NOTIMPLEMENTED();
271 return false;
272#elif defined(OS_ANDROID)
tfarinada9e1362017-03-14 16:49:06273 return android::HaveOnlyLoopbackAddresses();
274#elif defined(OS_NACL)
275 NOTIMPLEMENTED();
276 return false;
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47277#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tfarinada9e1362017-03-14 16:49:06278 struct ifaddrs* interface_addr = NULL;
279 int rv = getifaddrs(&interface_addr);
280 if (rv != 0) {
281 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
282 return false;
283 }
284
285 bool result = true;
286 for (struct ifaddrs* interface = interface_addr;
287 interface != NULL;
288 interface = interface->ifa_next) {
289 if (!(IFF_UP & interface->ifa_flags))
290 continue;
291 if (IFF_LOOPBACK & interface->ifa_flags)
292 continue;
293 const struct sockaddr* addr = interface->ifa_addr;
294 if (!addr)
295 continue;
296 if (addr->sa_family == AF_INET6) {
297 // Safe cast since this is AF_INET6.
298 const struct sockaddr_in6* addr_in6 =
299 reinterpret_cast<const struct sockaddr_in6*>(addr);
300 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
301 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
302 continue;
303 }
304 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
305 continue;
306
307 result = false;
308 break;
309 }
310 freeifaddrs(interface_addr);
311 return result;
tfarinada9e1362017-03-14 16:49:06312#endif // defined(various platforms)
313}
314
[email protected]cd565142012-06-12 16:21:45315// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40316std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46317 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17318 int net_error,
319 int os_error,
320 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40321 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45322 if (attempt_number)
323 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46324
[email protected]cd565142012-06-12 16:21:45325 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16326
[email protected]cd565142012-06-12 16:21:45327 if (os_error) {
328 dict->SetInteger("os_error", os_error);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47329#if defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45330 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04331 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08332 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
333 0, // Use the internal message table.
334 os_error,
335 0, // Use default language.
336 (LPWSTR)&error_string,
337 0, // Buffer size.
338 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01339 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45340 LocalFree(error_string);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47341#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
342 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46343#endif
[email protected]21526002010-05-16 19:42:46344 }
345
dchengc7eeda422015-12-26 03:56:48346 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45347}
[email protected]a9813302012-04-28 09:29:28348
[email protected]cd565142012-06-12 16:21:45349// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40350std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11351 int net_error,
352 int dns_error,
353 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40354 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45355 dict->SetInteger("net_error", net_error);
356 if (dns_error)
357 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48358 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36359}
[email protected]ee094b82010-08-24 15:55:51360
[email protected]cd565142012-06-12 16:21:45361// Creates NetLog parameters containing the information in a RequestInfo object,
Eric Orth70992982018-07-24 00:25:00362// along with the associated NetLogSource. Use NetLogRequestCallback() if the
363// request information is not specified via RequestInfo.
danakj22f90e72016-04-16 01:55:40364std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11365 const HostResolver::RequestInfo* info,
366 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40367 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20368
[email protected]cd565142012-06-12 16:21:45369 dict->SetString("host", info->host_port_pair().ToString());
370 dict->SetInteger("address_family",
371 static_cast<int>(info->address_family()));
372 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
373 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48374 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45375}
[email protected]b3601bc22012-02-21 21:23:20376
Eric Orth70992982018-07-24 00:25:00377// Creates NetLog parameters containing the information of the request. Use
378// NetLogRequestInfoCallback if the request is specified via RequestInfo.
379std::unique_ptr<base::Value> NetLogRequestCallback(
380 const HostPortPair& host,
381 NetLogCaptureMode /* capture_mode */) {
382 auto dict = std::make_unique<base::DictionaryValue>();
383
384 dict->SetString("host", host.ToString());
385 dict->SetInteger("address_family",
386 static_cast<int>(ADDRESS_FAMILY_UNSPECIFIED));
387 dict->SetBoolean("allow_cached_response", true);
388 dict->SetBoolean("is_speculative", false);
389 return std::move(dict);
390}
391
[email protected]cd565142012-06-12 16:21:45392// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40393std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19394 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11395 const std::string* host,
396 NetLogCaptureMode /* capture_mode */) {
Eric Orth70992982018-07-24 00:25:00397 auto dict = std::make_unique<base::DictionaryValue>();
estade5e5529d2015-05-21 20:59:11398 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45399 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48400 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45401}
[email protected]a9813302012-04-28 09:29:28402
[email protected]cd565142012-06-12 16:21:45403// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40404std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19405 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11406 RequestPriority priority,
407 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40408 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11409 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56410 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48411 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45412}
[email protected]b3601bc22012-02-21 21:23:20413
[email protected]cd565142012-06-12 16:21:45414// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40415std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11416 const DnsConfig* config,
417 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08418 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45419}
[email protected]b4481b222012-03-16 17:13:11420
danakj22f90e72016-04-16 01:55:40421std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11422 bool ipv6_available,
423 bool cached,
424 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40425 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37426 dict->SetBoolean("ipv6_available", ipv6_available);
427 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48428 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37429}
430
[email protected]0f292de02012-02-01 22:28:20431// The logging routines are defined here because some requests are resolved
432// without a Request object.
433
Eric Orth70992982018-07-24 00:25:00434// Logs when a request has just been started. Overloads for whether or not the
435// request information is specified via a RequestInfo object.
tfarina428341112016-09-22 13:38:20436void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20437 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00438 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
439 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20440}
Eric Orth70992982018-07-24 00:25:00441void LogStartRequest(const NetLogWithSource& source_net_log,
442 const HostPortPair& host) {
443 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
444 base::BindRepeating(&NetLogRequestCallback, host));
445}
[email protected]0f292de02012-02-01 22:28:20446
447// Logs when a request has just completed (before its callback is run).
Eric Orth70992982018-07-24 00:25:00448void LogFinishRequest(const NetLogWithSource& source_net_log, int net_error) {
xunjieli26f90452014-11-10 16:23:02449 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00450 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20451}
452
453// Logs when a request has been cancelled.
Eric Orth70992982018-07-24 00:25:00454void LogCancelRequest(const NetLogWithSource& source_net_log) {
mikecirone8b85c432016-09-08 19:11:00455 source_net_log.AddEvent(NetLogEventType::CANCELLED);
456 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20457}
458
[email protected]b59ff372009-07-15 22:04:32459//-----------------------------------------------------------------------------
460
[email protected]0f292de02012-02-01 22:28:20461// Keeps track of the highest priority.
462class PriorityTracker {
463 public:
[email protected]8c98d002012-07-18 19:02:27464 explicit PriorityTracker(RequestPriority initial_priority)
465 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20466 memset(counts_, 0, sizeof(counts_));
467 }
468
469 RequestPriority highest_priority() const {
470 return highest_priority_;
471 }
472
473 size_t total_count() const {
474 return total_count_;
475 }
476
477 void Add(RequestPriority req_priority) {
478 ++total_count_;
479 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05480 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20481 highest_priority_ = req_priority;
482 }
483
484 void Remove(RequestPriority req_priority) {
485 DCHECK_GT(total_count_, 0u);
486 DCHECK_GT(counts_[req_priority], 0u);
487 --total_count_;
488 --counts_[req_priority];
489 size_t i;
thestiga74ad2b2016-07-11 20:52:36490 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
491 }
[email protected]0f292de02012-02-01 22:28:20492 highest_priority_ = static_cast<RequestPriority>(i);
493
[email protected]31ae7ab2012-04-24 21:09:05494 // In absence of requests, default to MINIMUM_PRIORITY.
495 if (total_count_ == 0)
496 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20497 }
498
499 private:
500 RequestPriority highest_priority_;
501 size_t total_count_;
502 size_t counts_[NUM_PRIORITIES];
503};
504
juliatuttle9fb7aeb2016-06-06 20:16:33505void MakeNotStale(HostCache::EntryStaleness* stale_info) {
506 if (!stale_info)
507 return;
508 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
509 stale_info->network_changes = 0;
510 stale_info->stale_hits = 0;
511}
512
Paul Jensen41dc3e9f2018-11-06 22:10:10513// Is |dns_server| within the list of known DNS servers that also support
514// DNS-over-HTTPS?
515bool DnsServerSupportsDoh(const IPAddress& dns_server) {
516 const static base::NoDestructor<std::unordered_set<std::string>>
517 upgradable_servers({
518 // Google Public DNS
519 "8.8.8.8", "8.8.4.4", "2001:4860:4860::8888", "2001:4860:4860::8844",
520 // Cloudflare DNS
521 "1.1.1.1", "1.0.0.1", "2606:4700:4700::1111", "2606:4700:4700::1001",
522 // Quad9 DNS
523 "9.9.9.9", "149.112.112.112", "2620:fe::fe", "2620:fe::9",
524 });
525 return upgradable_servers->find(dns_server.ToString()) !=
526 upgradable_servers->end();
527}
528
[email protected]c54a8912012-10-22 22:09:43529} // namespace
[email protected]0f292de02012-02-01 22:28:20530
531//-----------------------------------------------------------------------------
532
tfarina9ed7f8c52016-02-19 17:50:18533bool ResolveLocalHostname(base::StringPiece host,
534 uint16_t port,
535 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18536 address_list->clear();
537
538 bool is_local6;
539 if (!IsLocalHostname(host, &is_local6))
540 return false;
541
martijna23c8962016-03-04 18:18:51542 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18543 if (!is_local6) {
martijna23c8962016-03-04 18:18:51544 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18545 }
546
547 return true;
548}
549
[email protected]daae1322013-09-05 18:26:50550const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
551
Eric Roman91aab1e62018-04-24 20:31:32552// Holds the callback and request parameters for an outstanding request.
553//
554// The RequestImpl is owned by the end user of host resolution. Deletion prior
555// to the request having completed means the request was cancelled by the
556// caller.
557//
558// Both the RequestImpl and its associated Job hold non-owning pointers to each
559// other. Care must be taken to clear the corresponding pointer when
560// cancellation is initiated by the Job (OnJobCancelled) vs by the end user
561// (~RequestImpl).
David Benjamina5677192018-04-23 23:25:42562class HostResolverImpl::RequestImpl
Eric Orth70992982018-07-24 00:25:00563 : public HostResolver::ResolveHostRequest,
David Benjamina5677192018-04-23 23:25:42564 public base::LinkNode<HostResolverImpl::RequestImpl> {
[email protected]b59ff372009-07-15 22:04:32565 public:
tfarina428341112016-09-22 13:38:20566 RequestImpl(const NetLogWithSource& source_net_log,
Eric Orth70992982018-07-24 00:25:00567 const HostPortPair& request_host,
Eric Orth00fe5a62018-08-15 22:20:00568 const base::Optional<ResolveHostParameters>& optional_parameters,
Eric Orth70992982018-07-24 00:25:00569 base::WeakPtr<HostResolverImpl> resolver)
[email protected]ee094b82010-08-24 15:55:51570 : source_net_log_(source_net_log),
Eric Orth70992982018-07-24 00:25:00571 request_host_(request_host),
Eric Orth00fe5a62018-08-15 22:20:00572 parameters_(optional_parameters ? optional_parameters.value()
573 : ResolveHostParameters()),
Eric Orthdc35748e2018-08-23 22:41:48574 host_resolver_flags_(ParametersToHostResolverFlags(parameters_)),
Eric Orth00fe5a62018-08-15 22:20:00575 priority_(parameters_.initial_priority),
Eric Orth70992982018-07-24 00:25:00576 job_(nullptr),
577 resolver_(resolver),
578 complete_(false) {}
[email protected]b59ff372009-07-15 22:04:32579
maksim.sisov31452af2016-07-27 06:38:10580 ~RequestImpl() override;
581
Eric Orth70992982018-07-24 00:25:00582 int Start(CompletionOnceCallback callback) override {
583 DCHECK(callback);
584 // Start() may only be called once per request.
585 DCHECK(!job_);
586 DCHECK(!complete_);
587 DCHECK(!callback_);
588 // Parent HostResolver must still be alive to call Start().
589 DCHECK(resolver_);
maksim.sisov31452af2016-07-27 06:38:10590
Eric Orth70992982018-07-24 00:25:00591 int rv = resolver_->Resolve(this);
592 DCHECK(!complete_);
593 if (rv == ERR_IO_PENDING) {
594 DCHECK(job_);
595 callback_ = std::move(callback);
596 } else {
597 DCHECK(!job_);
598 complete_ = true;
599 }
600 resolver_ = nullptr;
601
602 return rv;
603 }
604
605 const base::Optional<AddressList>& GetAddressResults() const override {
606 DCHECK(complete_);
607 return address_results_;
608 }
609
610 void set_address_results(const AddressList& address_results) {
611 // Should only be called at most once and before request is marked
612 // completed.
613 DCHECK(!complete_);
614 DCHECK(!address_results_);
Eric Orthb30bc172018-08-17 21:09:57615 DCHECK(!parameters_.is_speculative);
Eric Orth70992982018-07-24 00:25:00616
617 address_results_ = address_results;
618 }
619
620 void ChangeRequestPriority(RequestPriority priority);
621
622 void AssignJob(Job* job) {
623 DCHECK(job);
624 DCHECK(!job_);
625
626 job_ = job;
627 }
628
629 // Unassigns the Job without calling completion callback.
maksim.sisov31452af2016-07-27 06:38:10630 void OnJobCancelled(Job* job) {
631 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04632 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00633 DCHECK(!complete_);
634 DCHECK(callback_);
[email protected]aa22b242011-11-16 18:58:29635 callback_.Reset();
Eric Orth70992982018-07-24 00:25:00636
637 // No results should be set.
638 DCHECK(!address_results_);
[email protected]b59ff372009-07-15 22:04:32639 }
640
Eric Orth70992982018-07-24 00:25:00641 // Cleans up Job assignment, marks request completed, and calls the completion
642 // callback.
643 void OnJobCompleted(Job* job, int error) {
maksim.sisov31452af2016-07-27 06:38:10644 DCHECK_EQ(job_, job);
maksim.sisov31452af2016-07-27 06:38:10645 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00646
647 DCHECK(!complete_);
648 complete_ = true;
649
650 DCHECK(callback_);
Bence Béky0f26a5812018-06-13 03:18:40651 std::move(callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32652 }
653
Eric Orth70992982018-07-24 00:25:00654 Job* job() const { return job_; }
[email protected]b59ff372009-07-15 22:04:32655
[email protected]0f292de02012-02-01 22:28:20656 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20657 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51658
Eric Orth70992982018-07-24 00:25:00659 const HostPortPair& request_host() const { return request_host_; }
660
Eric Orth00fe5a62018-08-15 22:20:00661 const ResolveHostParameters& parameters() const { return parameters_; }
662
Eric Orth322af3e42018-08-20 18:12:59663 HostResolverFlags host_resolver_flags() const { return host_resolver_flags_; }
664
[email protected]5109c1952013-08-20 18:44:10665 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31666 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10667
Eric Orth70992982018-07-24 00:25:00668 bool complete() const { return complete_; }
669
670 base::TimeTicks request_time() const {
671 DCHECK(!request_time_.is_null());
672 return request_time_;
673 }
674 void set_request_time(base::TimeTicks request_time) {
675 DCHECK(request_time_.is_null());
676 DCHECK(!request_time.is_null());
677 request_time_ = request_time;
678 }
[email protected]51b9a6b2012-06-25 21:50:29679
[email protected]b59ff372009-07-15 22:04:32680 private:
tfarina428341112016-09-22 13:38:20681 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09682
Eric Orth70992982018-07-24 00:25:00683 const HostPortPair request_host_;
Eric Orth00fe5a62018-08-15 22:20:00684 const ResolveHostParameters parameters_;
Eric Orth322af3e42018-08-20 18:12:59685 const HostResolverFlags host_resolver_flags_;
[email protected]5109c1952013-08-20 18:44:10686
juliatuttlec53b19a72016-05-05 13:51:31687 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32688
[email protected]0f292de02012-02-01 22:28:20689 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32690 Job* job_;
Eric Orth70992982018-07-24 00:25:00691 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]b59ff372009-07-15 22:04:32692
693 // The user's callback to invoke when the request completes.
Bence Béky0f26a5812018-06-13 03:18:40694 CompletionOnceCallback callback_;
[email protected]b59ff372009-07-15 22:04:32695
Eric Orth70992982018-07-24 00:25:00696 bool complete_;
697 base::Optional<AddressList> address_results_;
[email protected]b59ff372009-07-15 22:04:32698
Eric Orth70992982018-07-24 00:25:00699 base::TimeTicks request_time_;
[email protected]51b9a6b2012-06-25 21:50:29700
maksim.sisov31452af2016-07-27 06:38:10701 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32702};
703
Eric Orth70992982018-07-24 00:25:00704// Wraps a RequestImpl to implement Request objects from the legacy Resolve()
705// API. The wrapped request must not yet have been started.
706//
707// TODO(crbug.com/821021): Delete this class once all usage has been
708// converted to the new CreateRequest() API.
709class HostResolverImpl::LegacyRequestImpl : public HostResolver::Request {
710 public:
711 explicit LegacyRequestImpl(std::unique_ptr<RequestImpl> inner_request)
712 : inner_request_(std::move(inner_request)) {
713 DCHECK(!inner_request_->job());
714 DCHECK(!inner_request_->complete());
715 }
716
717 ~LegacyRequestImpl() override {}
718
719 void ChangeRequestPriority(RequestPriority priority) override {
720 inner_request_->ChangeRequestPriority(priority);
721 }
722
723 int Start() {
724 return inner_request_->Start(base::BindOnce(
725 &LegacyRequestImpl::LegacyApiCallback, base::Unretained(this)));
726 }
727
728 // Do not call to assign the callback until we are running an async job (after
729 // Start() returns ERR_IO_PENDING) and before completion. Until then, the
730 // legacy HostResolverImpl::Resolve() needs to hang onto |callback| to ensure
731 // it stays alive for the duration of the method call, as some callers may be
732 // binding objects, eg the AddressList, with the callback.
733 void AssignCallback(CompletionOnceCallback callback,
734 AddressList* addresses_result_ptr) {
735 DCHECK(callback);
736 DCHECK(addresses_result_ptr);
737 DCHECK(inner_request_->job());
738 DCHECK(!inner_request_->complete());
739
740 callback_ = std::move(callback);
741 addresses_result_ptr_ = addresses_result_ptr;
742 }
743
744 const RequestImpl& inner_request() const { return *inner_request_; }
745
746 private:
747 // Result callback to bridge results handled entirely via ResolveHostRequest
748 // to legacy API styles where AddressList was a separate method out parameter.
749 void LegacyApiCallback(int error) {
750 // Must call AssignCallback() before async results.
751 DCHECK(callback_);
752
Eric Orthb30bc172018-08-17 21:09:57753 if (error == OK && !inner_request_->parameters().is_speculative) {
Eric Orth70992982018-07-24 00:25:00754 // Legacy API does not allow non-address results (eg TXT), so AddressList
755 // is always expected to be present on OK.
756 DCHECK(inner_request_->GetAddressResults());
757 *addresses_result_ptr_ = inner_request_->GetAddressResults().value();
758 }
759 addresses_result_ptr_ = nullptr;
760 std::move(callback_).Run(error);
761 }
762
763 const std::unique_ptr<RequestImpl> inner_request_;
764
765 CompletionOnceCallback callback_;
766 // This is a caller-provided pointer and should not be used once |callback_|
767 // is invoked.
768 AddressList* addresses_result_ptr_;
769
770 DISALLOW_COPY_AND_ASSIGN(LegacyRequestImpl);
771};
772
[email protected]1e9bbd22010-10-15 16:42:45773//------------------------------------------------------------------------------
774
Francois Doraya2d01ba2017-09-25 19:17:40775// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20776//
Miriam Gershenson02592182018-03-22 17:42:37777// In non-test code, the HostResolverProc is always SystemHostResolverProc,
778// which calls a platform API that implements host resolution.
779//
[email protected]0f292de02012-02-01 22:28:20780// Whenever we try to resolve the host, we post a delayed task to check if host
781// resolution (OnLookupComplete) is completed or not. If the original attempt
782// hasn't completed, then we start another attempt for host resolution. We take
783// the results from the first attempt that finishes and ignore the results from
784// all other attempts.
785//
786// TODO(szym): Move to separate source file for testing and mocking.
787//
Eric Orth9a037562018-07-03 21:24:38788class HostResolverImpl::ProcTask {
[email protected]b59ff372009-07-15 22:04:32789 public:
Eric Orth9a037562018-07-03 21:24:38790 typedef base::OnceCallback<void(int net_error, const AddressList& addr_list)>
791 Callback;
[email protected]b59ff372009-07-15 22:04:32792
[email protected]0f292de02012-02-01 22:28:20793 ProcTask(const Key& key,
794 const ProcTaskParams& params,
Eric Orth9a037562018-07-03 21:24:38795 Callback callback,
Miriam Gershensone42adb22017-10-16 16:19:38796 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:02797 const NetLogWithSource& job_net_log,
798 const base::TickClock* tick_clock)
[email protected]0f292de02012-02-01 22:28:20799 : key_(key),
800 params_(params),
Eric Orth9a037562018-07-03 21:24:38801 callback_(std::move(callback)),
mmenke91c17162016-06-02 16:03:23802 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38803 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20804 attempt_number_(0),
Misha Efimovb99e7da2018-05-30 16:59:02805 net_log_(job_net_log),
Eric Orth9a037562018-07-03 21:24:38806 tick_clock_(tick_clock),
807 weak_ptr_factory_(this) {
808 DCHECK(callback_);
[email protected]90499482013-06-01 00:39:50809 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20810 params_.resolver_proc = HostResolverProc::GetDefault();
811 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50812 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06813 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32814 }
815
Eric Orth9a037562018-07-03 21:24:38816 // Cancels this ProcTask. Any outstanding resolve attempts running on worker
817 // thread will continue running, but they will post back to the network thread
818 // before checking their WeakPtrs to find that this task is cancelled.
819 ~ProcTask() {
820 DCHECK(network_task_runner_->BelongsToCurrentThread());
821
822 // If this is cancellation, log the EndEvent (otherwise this was logged in
823 // OnLookupComplete()).
824 if (!was_completed())
825 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
826 }
827
[email protected]b59ff372009-07-15 22:04:32828 void Start() {
mmenke91c17162016-06-02 16:03:23829 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38830 DCHECK(!was_completed());
mikecirone8b85c432016-09-08 19:11:00831 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54832 StartLookupAttempt();
833 }
[email protected]252b699b2010-02-05 21:38:06834
Eric Orth9a037562018-07-03 21:24:38835 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23836 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20837 return callback_.is_null();
838 }
839
[email protected]0f292de02012-02-01 22:28:20840 private:
Eric Orth9a037562018-07-03 21:24:38841 using AttemptCompletionCallback = base::OnceCallback<
842 void(const AddressList& results, int error, const int os_error)>;
[email protected]a9813302012-04-28 09:29:28843
[email protected]189163e2011-05-11 01:48:54844 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23845 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38846 DCHECK(!was_completed());
Misha Efimovb99e7da2018-05-30 16:59:02847 base::TimeTicks start_time = tick_clock_->NowTicks();
[email protected]189163e2011-05-11 01:48:54848 ++attempt_number_;
849 // Dispatch the lookup attempt to a worker thread.
Eric Orth9a037562018-07-03 21:24:38850 AttemptCompletionCallback completion_callback = base::BindOnce(
851 &ProcTask::OnLookupAttemptComplete, weak_ptr_factory_.GetWeakPtr(),
852 start_time, attempt_number_, tick_clock_);
Miriam Gershensone42adb22017-10-16 16:19:38853 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40854 FROM_HERE,
Eric Orth9a037562018-07-03 21:24:38855 base::BindOnce(&ProcTask::DoLookup, key_, params_.resolver_proc,
856 network_task_runner_, std::move(completion_callback)));
[email protected]13024882011-05-18 23:19:16857
mikecirone8b85c432016-09-08 19:11:00858 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28859 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16860
mmenke91c17162016-06-02 16:03:23861 // If the results aren't received within a given time, RetryIfNotComplete
862 // will start a new attempt if none of the outstanding attempts have
863 // completed yet.
Eric Orth9a037562018-07-03 21:24:38864 // Use a WeakPtr to avoid keeping the ProcTask alive after completion or
865 // cancellation.
[email protected]0f292de02012-02-01 22:28:20866 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23867 network_task_runner_->PostDelayedTask(
Eric Orth9a037562018-07-03 21:24:38868 FROM_HERE,
869 base::BindOnce(&ProcTask::StartLookupAttempt,
870 weak_ptr_factory_.GetWeakPtr()),
871 params_.unresponsive_delay *
872 std::pow(params_.retry_factor, attempt_number_ - 1));
[email protected]06ef6d92011-05-19 04:24:58873 }
[email protected]b59ff372009-07-15 22:04:32874 }
875
Francois Doraya2d01ba2017-09-25 19:17:40876 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
877 // shutdown code cannot wait for it to finish, so this code must be very
878 // careful about using other objects (like MessageLoops, Singletons, etc).
Eric Orth9a037562018-07-03 21:24:38879 // During shutdown these objects may no longer exist.
880 static void DoLookup(
881 Key key,
882 scoped_refptr<HostResolverProc> resolver_proc,
883 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
884 AttemptCompletionCallback completion_callback) {
[email protected]189163e2011-05-11 01:48:54885 AddressList results;
886 int os_error = 0;
Eric Orth9a037562018-07-03 21:24:38887 int error =
888 resolver_proc->Resolve(key.hostname, key.address_family,
889 key.host_resolver_flags, &results, &os_error);
[email protected]b59ff372009-07-15 22:04:32890
Eric Orth9a037562018-07-03 21:24:38891 network_task_runner->PostTask(
892 FROM_HERE, base::BindOnce(std::move(completion_callback), results,
893 error, os_error));
[email protected]189163e2011-05-11 01:48:54894 }
895
Eric Orth9a037562018-07-03 21:24:38896 // Callback for when DoLookup() completes (runs on task runner thread). Now
897 // that we're back in the network thread, checks that |proc_task| is still
898 // valid, and if so, passes back to the object.
899 static void OnLookupAttemptComplete(base::WeakPtr<ProcTask> proc_task,
900 const base::TimeTicks& start_time,
901 const uint32_t attempt_number,
902 const base::TickClock* tick_clock,
903 const AddressList& results,
904 int error,
905 const int os_error) {
Alexandr Ilin33126632018-11-14 14:48:17906 TRACE_EVENT0(NetTracingCategory(), "ProcTask::OnLookupComplete");
Eric Orth9a037562018-07-03 21:24:38907
[email protected]49b70b222013-05-07 21:24:23908 // If results are empty, we should return an error.
909 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23910 if (empty_list_on_ok)
911 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54912
[email protected]2d3b7762010-10-09 00:35:47913 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20914 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23915 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54916 if (error != OK && NetworkChangeNotifier::IsOffline())
917 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47918
Paul Jensenb7352f92018-11-08 00:02:49919 if (!proc_task)
Luciano Pachecob4426082018-07-02 08:04:18920 return;
Eric Orth9a037562018-07-03 21:24:38921
922 proc_task->OnLookupComplete(results, start_time, attempt_number, error,
923 os_error);
924 }
925
926 void OnLookupComplete(const AddressList& results,
927 const base::TimeTicks& start_time,
928 const uint32_t attempt_number,
929 int error,
930 const int os_error) {
931 DCHECK(network_task_runner_->BelongsToCurrentThread());
932 DCHECK(!was_completed());
933
934 // Invalidate WeakPtrs to cancel handling of all outstanding lookup attempts
935 // and retries.
936 weak_ptr_factory_.InvalidateWeakPtrs();
937
Eric Orthcb8862f2018-06-27 18:08:35938 NetLogParametersCallback net_log_callback;
Eric Orth9a037562018-07-03 21:24:38939 NetLogParametersCallback attempt_net_log_callback;
[email protected]0f292de02012-02-01 22:28:20940 if (error != OK) {
Eric Orth70992982018-07-24 00:25:00941 net_log_callback = base::BindRepeating(&NetLogProcTaskFailedCallback, 0,
942 error, os_error);
943 attempt_net_log_callback = base::BindRepeating(
944 &NetLogProcTaskFailedCallback, attempt_number, error, os_error);
[email protected]ee094b82010-08-24 15:55:51945 } else {
Eric Orth9a037562018-07-03 21:24:38946 net_log_callback = results.CreateNetLogCallback();
947 attempt_net_log_callback =
948 NetLog::IntCallback("attempt_number", attempt_number);
[email protected]ee094b82010-08-24 15:55:51949 }
mikecirone8b85c432016-09-08 19:11:00950 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45951 net_log_callback);
Eric Orth9a037562018-07-03 21:24:38952 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
953 attempt_net_log_callback);
[email protected]ee094b82010-08-24 15:55:51954
Eric Orth9a037562018-07-03 21:24:38955 std::move(callback_).Run(error, results);
[email protected]b59ff372009-07-15 22:04:32956 }
957
[email protected]123ab1e32009-10-21 19:12:57958 Key key_;
[email protected]b59ff372009-07-15 22:04:32959
[email protected]0f292de02012-02-01 22:28:20960 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32961 // This may not be the current resolver procedure by the time we call
962 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
963 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20964 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32965
[email protected]0f292de02012-02-01 22:28:20966 // The listener to the results of this ProcTask.
967 Callback callback_;
968
mmenke91c17162016-06-02 16:03:23969 // Used to post events onto the network thread.
970 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:38971 // Used to post blocking HostResolverProc tasks.
972 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:54973
974 // Keeps track of the number of attempts we have made so far to resolve the
975 // host. Whenever we start an attempt to resolve the host, we increase this
976 // number.
Avi Drissman13fc8932015-12-20 04:40:46977 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54978
tfarina428341112016-09-22 13:38:20979 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51980
Misha Efimovb99e7da2018-05-30 16:59:02981 const base::TickClock* tick_clock_;
982
Eric Orth9a037562018-07-03 21:24:38983 // Used to loop back from the blocking lookup attempt tasks as well as from
984 // delayed retry tasks. Invalidate WeakPtrs on completion and cancellation to
985 // cancel handling of such posted tasks.
986 base::WeakPtrFactory<ProcTask> weak_ptr_factory_;
987
[email protected]0f292de02012-02-01 22:28:20988 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32989};
990
991//-----------------------------------------------------------------------------
992
Miriam Gershenson02592182018-03-22 17:42:37993// Resolves the hostname using DnsTransaction, which is a full implementation of
994// a DNS stub resolver. One DnsTransaction is created for each resolution
995// needed, which for AF_UNSPEC resolutions includes both A and AAAA. The
996// transactions are scheduled separately and started separately.
997//
[email protected]b3601bc22012-02-21 21:23:20998// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46999class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201000 public:
[email protected]daae1322013-09-05 18:26:501001 class Delegate {
1002 public:
1003 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1004 int net_error,
1005 const AddressList& addr_list,
1006 base::TimeDelta ttl) = 0;
1007
1008 // Called when the first of two jobs succeeds. If the first completed
1009 // transaction fails, this is not called. Also not called when the DnsTask
1010 // only needs to run one transaction.
1011 virtual void OnFirstDnsTransactionComplete() = 0;
1012
Brad Lassey786929ad2018-02-21 20:54:271013 virtual URLRequestContext* url_request_context() = 0;
1014 virtual RequestPriority priority() const = 0;
1015
[email protected]daae1322013-09-05 18:26:501016 protected:
Chris Watkins68b15032017-12-01 03:07:131017 Delegate() = default;
1018 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:501019 };
[email protected]b3601bc22012-02-21 21:23:201020
[email protected]0adcb2b2012-08-15 21:30:461021 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201022 const Key& key,
Eric Orth60931742018-11-05 23:40:571023 bool allow_fallback_resolution,
[email protected]daae1322013-09-05 18:26:501024 Delegate* delegate,
Misha Efimovb99e7da2018-05-30 16:59:021025 const NetLogWithSource& job_net_log,
1026 const base::TickClock* tick_clock)
[email protected]0adcb2b2012-08-15 21:30:461027 : client_(client),
[email protected]daae1322013-09-05 18:26:501028 key_(key),
Eric Orth60931742018-11-05 23:40:571029 allow_fallback_resolution_(allow_fallback_resolution),
[email protected]daae1322013-09-05 18:26:501030 delegate_(delegate),
1031 net_log_(job_net_log),
1032 num_completed_transactions_(0),
Misha Efimovb99e7da2018-05-30 16:59:021033 tick_clock_(tick_clock),
1034 task_start_time_(tick_clock_->NowTicks()) {
[email protected]0adcb2b2012-08-15 21:30:461035 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501036 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501037 }
1038
Eric Orth60931742018-11-05 23:40:571039 bool allow_fallback_resolution() const { return allow_fallback_resolution_; }
1040
[email protected]daae1322013-09-05 18:26:501041 bool needs_two_transactions() const {
1042 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1043 }
1044
1045 bool needs_another_transaction() const {
1046 return needs_two_transactions() && !transaction_aaaa_;
1047 }
1048
1049 void StartFirstTransaction() {
1050 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001051 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501052 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1053 StartAAAA();
1054 } else {
1055 StartA();
1056 }
1057 }
1058
1059 void StartSecondTransaction() {
1060 DCHECK(needs_two_transactions());
1061 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121062 }
1063
Brad Lassey2e8f185d2018-05-21 22:25:211064 base::TimeDelta ttl() { return ttl_; }
1065
[email protected]70c04ab2013-08-22 16:05:121066 private:
[email protected]daae1322013-09-05 18:26:501067 void StartA() {
1068 DCHECK(!transaction_a_);
1069 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1070 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1071 transaction_a_->Start();
1072 }
1073
1074 void StartAAAA() {
1075 DCHECK(!transaction_aaaa_);
1076 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1077 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1078 transaction_aaaa_->Start();
1079 }
1080
danakj22f90e72016-04-16 01:55:401081 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501082 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
Brad Lassey786929ad2018-02-21 20:54:271083 std::unique_ptr<DnsTransaction> trans =
1084 client_->GetTransactionFactory()->CreateTransaction(
1085 key_.hostname,
1086 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA
1087 : dns_protocol::kTypeA,
Brad Lasseydba0a84b2018-02-23 22:18:531088 base::BindOnce(&DnsTask::OnTransactionComplete,
Misha Efimovb99e7da2018-05-30 16:59:021089 base::Unretained(this), tick_clock_->NowTicks()),
Brad Lassey786929ad2018-02-21 20:54:271090 net_log_);
1091 trans->SetRequestContext(delegate_->url_request_context());
1092 trans->SetRequestPriority(delegate_->priority());
1093 return trans;
[email protected]daae1322013-09-05 18:26:501094 }
1095
1096 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001097 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201098 int net_error,
1099 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471100 DCHECK(transaction);
Misha Efimovb99e7da2018-05-30 16:59:021101 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Brad Lassey2e8f185d2018-05-21 22:25:211102 if (net_error != OK && !(net_error == ERR_NAME_NOT_RESOLVED && response &&
1103 response->IsValid())) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211104 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461105 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1106 return;
[email protected]6c411902012-08-14 22:36:361107 }
[email protected]0adcb2b2012-08-15 21:30:461108
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211109 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511110 switch (transaction->GetType()) {
1111 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211112 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511113 break;
1114 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211115 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1116 duration);
[email protected]02cd6982013-01-10 20:12:511117 break;
1118 }
[email protected]daae1322013-09-05 18:26:501119
[email protected]0adcb2b2012-08-15 21:30:461120 AddressList addr_list;
1121 base::TimeDelta ttl;
1122 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1123 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1124 result,
1125 DnsResponse::DNS_PARSE_RESULT_MAX);
1126 if (result != DnsResponse::DNS_PARSE_OK) {
1127 // Fail even if the other query succeeds.
1128 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1129 return;
1130 }
1131
[email protected]daae1322013-09-05 18:26:501132 ++num_completed_transactions_;
1133 if (num_completed_transactions_ == 1) {
1134 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461135 } else {
[email protected]daae1322013-09-05 18:26:501136 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461137 }
1138
[email protected]daae1322013-09-05 18:26:501139 if (transaction->GetType() == dns_protocol::kTypeA) {
1140 DCHECK_EQ(transaction_a_.get(), transaction);
1141 // Place IPv4 addresses after IPv6.
1142 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1143 } else {
1144 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1145 // Place IPv6 addresses before IPv4.
1146 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1147 }
1148
Asanka Herath2d0226c2018-10-24 14:35:551149 // If requested via HOST_RESOLVER_CANONNAME, store the canonical name from
1150 // the response. Prefer the name from the AAAA response. Only look at name
1151 // if there is at least one address record.
1152 if ((key_.host_resolver_flags & HOST_RESOLVER_CANONNAME) != 0 &&
1153 !addr_list.empty() &&
1154 (transaction->GetType() == dns_protocol::kTypeAAAA ||
1155 addr_list_.canonical_name().empty())) {
1156 addr_list_.set_canonical_name(addr_list.canonical_name());
1157 }
1158
[email protected]daae1322013-09-05 18:26:501159 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1160 // No need to repeat the suffix search.
1161 key_.hostname = transaction->GetHostname();
1162 delegate_->OnFirstDnsTransactionComplete();
1163 return;
1164 }
1165
1166 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121167 // TODO(szym): Don't fallback to ProcTask in this case.
1168 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461169 return;
1170 }
1171
[email protected]daae1322013-09-05 18:26:501172 // If there are multiple addresses, and at least one is IPv6, need to sort
1173 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1174 // sufficient to just check the family of the first address.
1175 if (addr_list_.size() > 1 &&
1176 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1177 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461178 client_->GetAddressSorter()->Sort(
Bence Békyd5e474c2018-08-02 18:45:081179 addr_list_, base::BindOnce(&DnsTask::OnSortComplete, AsWeakPtr(),
1180 tick_clock_->NowTicks()));
[email protected]0adcb2b2012-08-15 21:30:461181 } else {
[email protected]daae1322013-09-05 18:26:501182 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461183 }
1184 }
1185
1186 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461187 bool success,
1188 const AddressList& addr_list) {
1189 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211190 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
Misha Efimovb99e7da2018-05-30 16:59:021191 tick_clock_->NowTicks() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461192 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1193 return;
1194 }
1195
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211196 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
Misha Efimovb99e7da2018-05-30 16:59:021197 tick_clock_->NowTicks() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461198
1199 // AddressSorter prunes unusable destinations.
1200 if (addr_list.empty()) {
1201 LOG(WARNING) << "Address list empty after RFC3484 sort";
1202 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1203 return;
1204 }
1205
[email protected]daae1322013-09-05 18:26:501206 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461207 }
1208
1209 void OnFailure(int net_error, DnsResponse::Result result) {
1210 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451211 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001212 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451213 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
Brad Lassey2e8f185d2018-05-21 22:25:211214 base::TimeDelta ttl = ttl_ < base::TimeDelta::FromSeconds(
1215 std::numeric_limits<uint32_t>::max()) &&
1216 num_completed_transactions_ > 0
1217 ? ttl_
1218 : base::TimeDelta::FromSeconds(0);
Miriam Gershenson66024d72017-12-05 04:30:321219 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
Brad Lassey2e8f185d2018-05-21 22:25:211220 ttl);
[email protected]b3601bc22012-02-21 21:23:201221 }
1222
[email protected]daae1322013-09-05 18:26:501223 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001224 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461225 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501226 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461227 }
1228
1229 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501230 Key key_;
1231
Eric Orth60931742018-11-05 23:40:571232 // Whether resolution may fallback to other task types (e.g. ProcTask) on
1233 // failure of this task.
1234 bool allow_fallback_resolution_;
1235
[email protected]b3601bc22012-02-21 21:23:201236 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501237 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201238 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201239
danakj22f90e72016-04-16 01:55:401240 std::unique_ptr<DnsTransaction> transaction_a_;
1241 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461242
[email protected]daae1322013-09-05 18:26:501243 unsigned num_completed_transactions_;
1244
1245 // These are updated as each transaction completes.
1246 base::TimeDelta ttl_;
1247 // IPv6 addresses must appear first in the list.
1248 AddressList addr_list_;
1249
Misha Efimovb99e7da2018-05-30 16:59:021250 const base::TickClock* tick_clock_;
[email protected]daae1322013-09-05 18:26:501251 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461252
1253 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201254};
1255
1256//-----------------------------------------------------------------------------
1257
[email protected]0f292de02012-02-01 22:28:201258// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501259class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1260 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391261 public:
[email protected]0f292de02012-02-01 22:28:201262 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351263 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181264 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201265 const Key& key,
[email protected]8c98d002012-07-18 19:02:271266 RequestPriority priority,
Miriam Gershensone42adb22017-10-16 16:19:381267 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:021268 const NetLogWithSource& source_net_log,
1269 const base::TickClock* tick_clock)
[email protected]12faa4c2012-11-06 04:44:181270 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201271 key_(key),
[email protected]8c98d002012-07-18 19:02:271272 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381273 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201274 had_non_speculative_request_(false),
[email protected]daae1322013-09-05 18:26:501275 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331276 dns_task_error_(OK),
Misha Efimovb99e7da2018-05-30 16:59:021277 tick_clock_(tick_clock),
tfarina428341112016-09-22 13:38:201278 net_log_(
1279 NetLogWithSource::Make(source_net_log.net_log(),
Eric Orth60931742018-11-05 23:40:571280 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)),
1281 weak_ptr_factory_(this) {
mikecirone8b85c432016-09-08 19:11:001282 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201283
mikecirone8b85c432016-09-08 19:11:001284 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1285 base::Bind(&NetLogJobCreationCallback,
1286 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391287 }
1288
dchengb03027d2014-10-21 12:00:201289 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201290 if (is_running()) {
1291 // |resolver_| was destroyed with this Job still in flight.
1292 // Clean-up, record in the log, but don't run any callbacks.
Eric Orth9a037562018-07-03 21:24:381293 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351294 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501295 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001296 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201297 ERR_ABORTED);
1298 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551299 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351300 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001301 net_log_.AddEvent(NetLogEventType::CANCELLED);
1302 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391303 }
[email protected]b3601bc22012-02-21 21:23:201304 // else CompleteRequests logged EndEvent.
David Benjamina5677192018-04-23 23:25:421305 while (!requests_.empty()) {
maksim.sisov31452af2016-07-27 06:38:101306 // Log any remaining Requests as cancelled.
David Benjamina5677192018-04-23 23:25:421307 RequestImpl* req = requests_.head()->value();
1308 req->RemoveFromList();
1309 DCHECK_EQ(this, req->job());
Eric Orth70992982018-07-24 00:25:001310 LogCancelRequest(req->source_net_log());
David Benjamina5677192018-04-23 23:25:421311 req->OnJobCancelled(this);
[email protected]b3601bc22012-02-21 21:23:201312 }
[email protected]68ad3ee2010-01-30 03:45:391313 }
1314
[email protected]daae1322013-09-05 18:26:501315 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1316 // of the queue.
1317 void Schedule(bool at_head) {
1318 DCHECK(!is_queued());
1319 PrioritizedDispatcher::Handle handle;
1320 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001321 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501322 } else {
[email protected]106ccd2c2014-06-17 09:21:001323 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501324 }
1325 // The dispatcher could have started |this| in the above call to Add, which
1326 // could have called Schedule again. In that case |handle| will be null,
1327 // but |handle_| may have been set by the other nested call to Schedule.
1328 if (!handle.is_null()) {
1329 DCHECK(handle_.is_null());
1330 handle_ = handle;
1331 }
[email protected]16ee26d2012-03-08 03:34:351332 }
1333
maksim.sisov31452af2016-07-27 06:38:101334 void AddRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001335 DCHECK_EQ(key_.hostname, request->request_host().host());
1336
1337 request->AssignJob(this);
[email protected]0f292de02012-02-01 22:28:201338
maksim.sisov31452af2016-07-27 06:38:101339 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201340
maksim.sisov31452af2016-07-27 06:38:101341 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001342 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451343 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201344
1345 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001346 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101347 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451348 priority()));
[email protected]0f292de02012-02-01 22:28:201349
Eric Orthb30bc172018-08-17 21:09:571350 if (!request->parameters().is_speculative)
[email protected]0f292de02012-02-01 22:28:201351 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201352
David Benjamina5677192018-04-23 23:25:421353 requests_.Append(request);
[email protected]b3601bc22012-02-21 21:23:201354
[email protected]51b9a6b2012-06-25 21:50:291355 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391356 }
1357
maksim.sisov31452af2016-07-27 06:38:101358 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
Eric Orth70992982018-07-24 00:25:001359 DCHECK_EQ(key_.hostname, req->request_host().host());
juliatuttlec53b19a72016-05-05 13:51:311360
1361 priority_tracker_.Remove(req->priority());
1362 req->set_priority(priority);
1363 priority_tracker_.Add(req->priority());
1364 UpdatePriority();
1365 }
1366
maksim.sisov31452af2016-07-27 06:38:101367 // Detach cancelled request. If it was the last active Request, also finishes
1368 // this Job.
1369 void CancelRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001370 DCHECK_EQ(key_.hostname, request->request_host().host());
maksim.sisov31452af2016-07-27 06:38:101371 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351372
Eric Orth70992982018-07-24 00:25:001373 LogCancelRequest(request->source_net_log());
[email protected]16ee26d2012-03-08 03:34:351374
maksim.sisov31452af2016-07-27 06:38:101375 priority_tracker_.Remove(request->priority());
1376 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001377 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101378 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1379 priority()));
[email protected]b3601bc22012-02-21 21:23:201380
[email protected]16ee26d2012-03-08 03:34:351381 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291382 UpdatePriority();
David Benjamina5677192018-04-23 23:25:421383 request->RemoveFromList();
[email protected]16ee26d2012-03-08 03:34:351384 } else {
1385 // If we were called from a Request's callback within CompleteRequests,
1386 // that Request could not have been cancelled, so num_active_requests()
1387 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431388 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201389 }
[email protected]68ad3ee2010-01-30 03:45:391390 }
1391
[email protected]7af985a2012-12-14 22:40:421392 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1393 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111394 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201395 void Abort() {
[email protected]0f292de02012-02-01 22:28:201396 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421397 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201398 }
1399
Eric Orth60931742018-11-05 23:40:571400 // Gets a closure that will abort a DnsTask (see AbortDnsTask()) iff |this| is
1401 // still valid. Useful if aborting a list of Jobs as some may be cancelled
1402 // while aborting others.
1403 base::OnceClosure GetAbortDnsTaskClosure(int error, bool fallback_only) {
1404 return base::BindOnce(&Job::AbortDnsTask, weak_ptr_factory_.GetWeakPtr(),
1405 error, fallback_only);
1406 }
1407
1408 // If DnsTask present, abort it. Depending on task settings, either fall back
1409 // to ProcTask or abort the job entirely. Warning, aborting a job may cause
1410 // other jobs to be aborted, thus |jobs_| may be unpredictably changed by
1411 // calling this method.
1412 //
1413 // |error| is the net error that will be returned to requests if this method
1414 // results in completely aborting the job.
1415 void AbortDnsTask(int error, bool fallback_only) {
[email protected]f0f602bd2012-11-15 18:01:021416 if (dns_task_) {
Eric Orth60931742018-11-05 23:40:571417 if (dns_task_->allow_fallback_resolution()) {
1418 KillDnsTask();
1419 dns_task_error_ = OK;
1420 StartProcTask();
1421 } else if (!fallback_only) {
1422 CompleteRequestsWithError(error);
1423 }
[email protected]f0f602bd2012-11-15 18:01:021424 }
1425 }
1426
[email protected]16ee26d2012-03-08 03:34:351427 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1428 // Completes all requests and destroys the job.
1429 void OnEvicted() {
1430 DCHECK(!is_running());
1431 DCHECK(is_queued());
1432 handle_.Reset();
1433
mikecirone8b85c432016-09-08 19:11:001434 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351435
1436 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431437 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351438 }
1439
[email protected]78eac2a2012-03-14 19:09:271440 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1441 // this Job was destroyed.
1442 bool ServeFromHosts() {
1443 DCHECK_GT(num_active_requests(), 0u);
1444 AddressList addr_list;
Eric Orth70992982018-07-24 00:25:001445 if (resolver_->ServeFromHosts(
1446 key(), requests_.head()->value()->request_host().port(),
1447 &addr_list)) {
[email protected]78eac2a2012-03-14 19:09:271448 // This will destroy the Job.
Rob Percival94f21ad2017-11-14 10:20:241449 CompleteRequests(
1450 MakeCacheEntry(OK, addr_list, HostCache::Entry::SOURCE_HOSTS),
Eric Orth9871aafa2018-10-02 19:59:181451 base::TimeDelta(), true /* allow_cache */);
[email protected]78eac2a2012-03-14 19:09:271452 return true;
1453 }
1454 return false;
1455 }
1456
tanay.c6ddd5f6f2015-08-25 06:34:571457 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111458
1459 bool is_queued() const {
1460 return !handle_.is_null();
1461 }
1462
1463 bool is_running() const {
Eric Orth9871aafa2018-10-02 19:59:181464 return is_dns_running() || is_mdns_running() || is_proc_running();
[email protected]b4481b222012-03-16 17:13:111465 }
1466
[email protected]16ee26d2012-03-08 03:34:351467 private:
[email protected]daae1322013-09-05 18:26:501468 void KillDnsTask() {
1469 if (dns_task_) {
1470 ReduceToOneJobSlot();
1471 dns_task_.reset();
1472 }
1473 }
1474
1475 // Reduce the number of job slots occupied and queued in the dispatcher
1476 // to one. If the second Job slot is queued in the dispatcher, cancels the
1477 // queued job. Otherwise, the second Job has been started by the
1478 // PrioritizedDispatcher, so signals it is complete.
1479 void ReduceToOneJobSlot() {
1480 DCHECK_GE(num_occupied_job_slots_, 1u);
1481 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001482 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501483 handle_.Reset();
1484 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001485 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501486 --num_occupied_job_slots_;
1487 }
1488 DCHECK_EQ(1u, num_occupied_job_slots_);
1489 }
1490
eroman0cd87b62016-12-14 19:13:451491 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1492 // HostCache::Entry(). The address list is omited from the cache entry
1493 // for errors.
1494 HostCache::Entry MakeCacheEntry(int net_error,
Rob Percival94f21ad2017-11-14 10:20:241495 const AddressList& addr_list,
1496 HostCache::Entry::Source source) const {
eroman0cd87b62016-12-14 19:13:451497 return HostCache::Entry(
1498 net_error,
Rob Percival94f21ad2017-11-14 10:20:241499 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1500 source);
eroman0cd87b62016-12-14 19:13:451501 }
1502
1503 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1504 const AddressList& addr_list,
Rob Percival94f21ad2017-11-14 10:20:241505 HostCache::Entry::Source source,
eroman0cd87b62016-12-14 19:13:451506 base::TimeDelta ttl) const {
1507 return HostCache::Entry(
1508 net_error,
1509 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
Rob Percival94f21ad2017-11-14 10:20:241510 source, ttl);
eroman0cd87b62016-12-14 19:13:451511 }
1512
juliatuttlec53b19a72016-05-05 13:51:311513 AddressList MakeAddressListForRequest(const AddressList& list) const {
1514 if (requests_.empty())
1515 return list;
Eric Orth70992982018-07-24 00:25:001516 return AddressList::CopyWithPort(
1517 list, requests_.head()->value()->request_host().port());
juliatuttlec53b19a72016-05-05 13:51:311518 }
1519
[email protected]51b9a6b2012-06-25 21:50:291520 void UpdatePriority() {
Paul Jensenb7352f92018-11-08 00:02:491521 if (is_queued())
[email protected]106ccd2c2014-06-17 09:21:001522 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291523 }
1524
[email protected]16ee26d2012-03-08 03:34:351525 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201526 void Start() override {
[email protected]daae1322013-09-05 18:26:501527 DCHECK_LE(num_occupied_job_slots_, 1u);
1528
[email protected]70c04ab2013-08-22 16:05:121529 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501530 ++num_occupied_job_slots_;
1531
1532 if (num_occupied_job_slots_ == 2) {
1533 StartSecondDnsTransaction();
1534 return;
1535 }
1536
1537 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201538
mikecirone8b85c432016-09-08 19:11:001539 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201540
Misha Efimovb99e7da2018-05-30 16:59:021541 start_time_ = tick_clock_->NowTicks();
[email protected]51b9a6b2012-06-25 21:50:291542
Eric Orthdc35748e2018-08-23 22:41:481543 switch (key_.host_resolver_source) {
1544 case HostResolverSource::ANY:
Eric Orth60931742018-11-05 23:40:571545 if (!ResemblesMulticastDNSName(key_.hostname)) {
1546 StartDnsTask(true /* allow_fallback_resolution */);
Eric Orthdc35748e2018-08-23 22:41:481547 } else {
1548 StartProcTask();
1549 }
1550 break;
1551 case HostResolverSource::SYSTEM:
1552 StartProcTask();
1553 break;
1554 case HostResolverSource::DNS:
Eric Orth60931742018-11-05 23:40:571555 StartDnsTask(false /* allow_fallback_resolution */);
Eric Orthdc35748e2018-08-23 22:41:481556 break;
Eric Orth9871aafa2018-10-02 19:59:181557 case HostResolverSource::MULTICAST_DNS:
1558 StartMdnsTask();
1559 break;
Eric Orthdc35748e2018-08-23 22:41:481560 }
[email protected]443714fad2013-09-19 04:52:011561
[email protected]1d932852012-06-19 19:40:331562 // Caution: Job::Start must not complete synchronously.
[email protected]b3601bc22012-02-21 21:23:201563 }
1564
[email protected]b3601bc22012-02-21 21:23:201565 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401566 // the limits on |dispatcher_|. But in order to keep the number of
1567 // TaskScheduler threads low, we will need to use an "inner"
1568 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201569 void StartProcTask() {
Eric Orth9871aafa2018-10-02 19:59:181570 DCHECK(!is_running());
Eric Orth9a037562018-07-03 21:24:381571 proc_task_ = std::make_unique<ProcTask>(
Misha Efimovb99e7da2018-05-30 16:59:021572 key_, resolver_->proc_params_,
Eric Orth70992982018-07-24 00:25:001573 base::BindOnce(&Job::OnProcTaskComplete, base::Unretained(this),
1574 tick_clock_->NowTicks()),
Misha Efimovb99e7da2018-05-30 16:59:021575 proc_task_runner_, net_log_, tick_clock_);
[email protected]0f292de02012-02-01 22:28:201576
[email protected]0f292de02012-02-01 22:28:201577 // Start() could be called from within Resolve(), hence it must NOT directly
1578 // call OnProcTaskComplete, for example, on synchronous failure.
1579 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391580 }
1581
[email protected]0f292de02012-02-01 22:28:201582 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371583 void OnProcTaskComplete(base::TimeTicks start_time,
1584 int net_error,
1585 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201586 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391587
[email protected]1d932852012-06-19 19:40:331588 if (dns_task_error_ != OK) {
Eric Orth60931742018-11-05 23:40:571589 // This ProcTask was a fallback resolution after a failed DnsTask.
Misha Efimovb99e7da2018-05-30 16:59:021590 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]1def74c2012-03-22 20:07:001591 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211592 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331593 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1594 ResemblesNetBIOSName(key_.hostname)) {
1595 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1596 } else {
1597 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1598 }
Ilya Sherman0eb39802017-12-08 20:58:181599 base::UmaHistogramSparse("Net.DNS.DnsTask.Errors",
1600 std::abs(dns_task_error_));
Eric Orth60931742018-11-05 23:40:571601 resolver_->OnFallbackResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001602 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211603 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001604 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1605 }
1606 }
1607
eroman1efc237c2016-12-14 00:00:451608 if (ContainsIcannNameCollisionIp(addr_list))
1609 net_error = ERR_ICANN_NAME_COLLISION;
1610
[email protected]1339a2a22012-10-17 08:39:431611 base::TimeDelta ttl =
1612 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201613 if (net_error == OK)
1614 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391615
Rob Percival94f21ad2017-11-14 10:20:241616 // Source unknown because the system resolver could have gotten it from a
1617 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171618 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241619 CompleteRequests(
1620 MakeCacheEntry(net_error, addr_list, HostCache::Entry::SOURCE_UNKNOWN),
Eric Orth9871aafa2018-10-02 19:59:181621 ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201622 }
1623
Eric Orth60931742018-11-05 23:40:571624 void StartDnsTask(bool allow_fallback_resolution) {
1625 if ((!resolver_->HaveDnsConfig() || resolver_->use_proctask_by_default_) &&
1626 allow_fallback_resolution) {
1627 // DnsClient or config is not available, but we're allowed to switch to
1628 // ProcTask instead.
1629 StartProcTask();
1630 return;
1631 }
[email protected]b3601bc22012-02-21 21:23:201632
Eric Orth60931742018-11-05 23:40:571633 // Need to create the task even if we're going to post a failure instead of
1634 // running it, as a "started" job needs a task to be properly cleaned up.
1635 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_,
1636 allow_fallback_resolution, this, net_log_,
1637 tick_clock_));
1638
1639 if (resolver_->HaveDnsConfig()) {
1640 dns_task_->StartFirstTransaction();
1641 // Schedule a second transaction, if needed.
1642 if (dns_task_->needs_two_transactions())
1643 Schedule(true);
1644 } else {
1645 // Cannot start a DNS task when DnsClient or config is not available.
1646 // Since we cannot complete synchronously from here, post a failure.
1647 base::SequencedTaskRunnerHandle::Get()->PostTask(
1648 FROM_HERE,
1649 base::BindOnce(&Job::OnDnsTaskFailure, weak_ptr_factory_.GetWeakPtr(),
1650 dns_task_->AsWeakPtr(), base::TimeDelta(),
1651 ERR_FAILED));
1652 }
[email protected]daae1322013-09-05 18:26:501653 }
1654
1655 void StartSecondDnsTransaction() {
1656 DCHECK(dns_task_->needs_two_transactions());
1657 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221658 }
1659
1660 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1661 // deleted before this callback. In this case dns_task is deleted as well,
1662 // so we use it as indicator whether Job is still valid.
1663 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1664 base::TimeDelta duration,
1665 int net_error) {
Miriam Gershenson61604662017-09-28 23:51:111666 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221667
wezb9820d42016-06-22 23:41:041668 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221669 return;
1670
Miriam Gershenson19faef812018-02-07 23:56:441671 if (duration < base::TimeDelta::FromMilliseconds(10)) {
1672 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Fast",
1673 std::abs(net_error));
1674 } else {
1675 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Slow",
1676 std::abs(net_error));
1677 }
[email protected]16c2bd72013-06-28 01:19:221678 dns_task_error_ = net_error;
1679
1680 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1681 // http://crbug.com/117655
1682
1683 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1684 // ProcTask in that case is a waste of time.
Eric Orth60931742018-11-05 23:40:571685 if (resolver_->allow_fallback_to_proctask_ &&
1686 dns_task->allow_fallback_resolution()) {
[email protected]daae1322013-09-05 18:26:501687 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221688 StartProcTask();
1689 } else {
1690 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Brad Lassey2e8f185d2018-05-21 22:25:211691 // If the ttl is max, we didn't get one from the record, so set it to 0
1692 base::TimeDelta ttl =
1693 dns_task->ttl() < base::TimeDelta::FromSeconds(
1694 std::numeric_limits<uint32_t>::max())
1695 ? dns_task->ttl()
1696 : base::TimeDelta::FromSeconds(0);
1697 CompleteRequests(
1698 HostCache::Entry(net_error, AddressList(),
1699 HostCache::Entry::Source::SOURCE_UNKNOWN, ttl),
Eric Orth9871aafa2018-10-02 19:59:181700 ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201701 }
1702 }
1703
[email protected]daae1322013-09-05 18:26:501704 // HostResolverImpl::DnsTask::Delegate implementation:
1705
dchengb03027d2014-10-21 12:00:201706 void OnDnsTaskComplete(base::TimeTicks start_time,
1707 int net_error,
1708 const AddressList& addr_list,
1709 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201710 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201711
Misha Efimovb99e7da2018-05-30 16:59:021712 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]b3601bc22012-02-21 21:23:201713 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221714 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201715 return;
1716 }
Miriam Gershenson61604662017-09-28 23:51:111717
1718 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201719
[email protected]1def74c2012-03-22 20:07:001720 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431721 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461722
Eric Orth60931742018-11-05 23:40:571723 resolver_->OnDnsTaskResolve();
[email protected]f0f602bd2012-11-15 18:01:021724
[email protected]895123222012-10-25 15:21:171725 base::TimeDelta bounded_ttl =
1726 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1727
eroman0cd87b62016-12-14 19:13:451728 if (ContainsIcannNameCollisionIp(addr_list)) {
1729 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1730 } else {
Rob Percival94f21ad2017-11-14 10:20:241731 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list,
1732 HostCache::Entry::SOURCE_DNS, ttl),
Eric Orth9871aafa2018-10-02 19:59:181733 bounded_ttl, true /* allow_cache */);
eroman0cd87b62016-12-14 19:13:451734 }
[email protected]b3601bc22012-02-21 21:23:201735 }
1736
dchengb03027d2014-10-21 12:00:201737 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501738 DCHECK(dns_task_->needs_two_transactions());
1739 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1740 // No longer need to occupy two dispatcher slots.
1741 ReduceToOneJobSlot();
1742
1743 // We already have a job slot at the dispatcher, so if the second
1744 // transaction hasn't started, reuse it now instead of waiting in the queue
1745 // for the second slot.
1746 if (dns_task_->needs_another_transaction())
1747 dns_task_->StartSecondTransaction();
1748 }
1749
Eric Orth9871aafa2018-10-02 19:59:181750 void StartMdnsTask() {
1751 DCHECK(!is_running());
1752
1753 // No flags are supported for MDNS except
1754 // HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6 (which is not actually an
1755 // input flag).
1756 DCHECK_EQ(0, key_.host_resolver_flags &
1757 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
1758
1759 std::vector<HostResolver::DnsQueryType> query_types;
1760 switch (key_.address_family) {
1761 case ADDRESS_FAMILY_UNSPECIFIED:
1762 query_types.push_back(HostResolver::DnsQueryType::A);
1763 query_types.push_back(HostResolver::DnsQueryType::AAAA);
1764 break;
1765 case ADDRESS_FAMILY_IPV4:
1766 query_types.push_back(HostResolver::DnsQueryType::A);
1767 break;
1768 case ADDRESS_FAMILY_IPV6:
1769 query_types.push_back(HostResolver::DnsQueryType::AAAA);
1770 break;
1771 }
1772
1773 mdns_task_ = std::make_unique<HostResolverMdnsTask>(
1774 resolver_->GetOrCreateMdnsClient(), key_.hostname, query_types);
1775 mdns_task_->Start(
1776 base::BindOnce(&Job::OnMdnsTaskComplete, base::Unretained(this)));
1777 }
1778
1779 void OnMdnsTaskComplete(int error) {
1780 DCHECK(is_mdns_running());
1781 // TODO(crbug.com/846423): Consider adding MDNS-specific logging.
1782
1783 if (error != OK) {
1784 CompleteRequestsWithError(error);
1785 } else if (ContainsIcannNameCollisionIp(mdns_task_->result_addresses())) {
1786 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1787 } else {
1788 // MDNS uses a separate cache, so skip saving result to cache.
1789 // TODO(crbug.com/846423): Consider merging caches.
1790 CompleteRequestsWithoutCache(error, mdns_task_->result_addresses());
1791 }
1792 }
1793
Brad Lassey786929ad2018-02-21 20:54:271794 URLRequestContext* url_request_context() override {
1795 return resolver_->url_request_context_;
1796 }
1797
Miriam Gershenson61604662017-09-28 23:51:111798 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581799 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1800 // deprecated values.
1801 enum Category {
1802 RESOLVE_SUCCESS = 0,
1803 RESOLVE_FAIL = 1,
1804 RESOLVE_SPECULATIVE_SUCCESS = 2,
1805 RESOLVE_SPECULATIVE_FAIL = 3,
1806 RESOLVE_ABORT = 4,
1807 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111808 RESOLVE_MAX, // Bounding value.
1809 };
1810 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1811
Misha Efimovb99e7da2018-05-30 16:59:021812 base::TimeDelta duration = tick_clock_->NowTicks() - start_time_;
Miriam Gershenson61604662017-09-28 23:51:111813 if (error == OK) {
1814 if (had_non_speculative_request_) {
1815 category = RESOLVE_SUCCESS;
1816 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
1817 switch (key_.address_family) {
1818 case ADDRESS_FAMILY_IPV4:
1819 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1820 duration);
1821 break;
1822 case ADDRESS_FAMILY_IPV6:
1823 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1824 duration);
1825 break;
1826 case ADDRESS_FAMILY_UNSPECIFIED:
1827 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1828 duration);
1829 break;
1830 }
1831 } else {
1832 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111833 }
Miriam Gershensonc282ab42017-11-20 23:19:581834 } else if (error == ERR_NETWORK_CHANGED ||
1835 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1836 category = had_non_speculative_request_ ? RESOLVE_ABORT
1837 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111838 } else {
1839 if (had_non_speculative_request_) {
1840 category = RESOLVE_FAIL;
1841 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
1842 switch (key_.address_family) {
1843 case ADDRESS_FAMILY_IPV4:
Miriam Gershensonc282ab42017-11-20 23:19:581844 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111845 duration);
1846 break;
1847 case ADDRESS_FAMILY_IPV6:
Miriam Gershensonc282ab42017-11-20 23:19:581848 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111849 duration);
1850 break;
1851 case ADDRESS_FAMILY_UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581852 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111853 duration);
1854 break;
1855 }
1856 } else {
1857 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111858 }
1859 }
1860 DCHECK_LT(static_cast<int>(category),
1861 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1862 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061863
1864 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1865 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181866 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061867 else
Ilya Sherman0eb39802017-12-08 20:58:181868 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061869 }
Miriam Gershenson61604662017-09-28 23:51:111870 }
1871
[email protected]16ee26d2012-03-08 03:34:351872 // Performs Job's last rites. Completes all Requests. Deletes this.
Eric Orth9871aafa2018-10-02 19:59:181873 //
1874 // If not |allow_cache|, result will not be stored in the host cache, even if
1875 // result would otherwise allow doing so.
[email protected]895123222012-10-25 15:21:171876 void CompleteRequests(const HostCache::Entry& entry,
Eric Orth9871aafa2018-10-02 19:59:181877 base::TimeDelta ttl,
1878 bool allow_cache) {
[email protected]11fbca0b2013-06-02 23:37:211879 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201880
[email protected]16ee26d2012-03-08 03:34:351881 // This job must be removed from resolver's |jobs_| now to make room for a
1882 // new job with the same key in case one of the OnComplete callbacks decides
Eric Orth18544ae2018-06-11 22:57:161883 // to spawn one. Consequently, if the job was owned by |jobs_|, the job
1884 // deletes itself when CompleteRequests is done.
1885 std::unique_ptr<Job> self_deleter = resolver_->RemoveJob(this);
[email protected]16ee26d2012-03-08 03:34:351886
[email protected]16ee26d2012-03-08 03:34:351887 if (is_running()) {
Eric Orth9a037562018-07-03 21:24:381888 proc_task_ = nullptr;
[email protected]daae1322013-09-05 18:26:501889 KillDnsTask();
Eric Orth9871aafa2018-10-02 19:59:181890 mdns_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351891
1892 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001893 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351894 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001895 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351896 handle_.Reset();
1897 }
1898
1899 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001900 net_log_.AddEvent(NetLogEventType::CANCELLED);
1901 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351902 OK);
1903 return;
1904 }
[email protected]b3601bc22012-02-21 21:23:201905
mikecirone8b85c432016-09-08 19:11:001906 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221907 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391908
[email protected]78eac2a2012-03-14 19:09:271909 DCHECK(!requests_.empty());
1910
eroman1efc237c2016-12-14 00:00:451911 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191912 // Record this histogram here, when we know the system has a valid DNS
1913 // configuration.
[email protected]539df6c2012-06-19 21:21:291914 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1915 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191916 }
[email protected]16ee26d2012-03-08 03:34:351917
juliatuttle317860e2016-05-12 14:47:221918 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1919 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Eric Orth9871aafa2018-10-02 19:59:181920 if (did_complete && allow_cache)
[email protected]1339a2a22012-10-17 08:39:431921 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581922
1923 RecordJobHistograms(entry.error());
[email protected]16ee26d2012-03-08 03:34:351924
maksim.sisov31452af2016-07-27 06:38:101925 // Complete all of the requests that were attached to the job and
1926 // detach them.
1927 while (!requests_.empty()) {
David Benjamina5677192018-04-23 23:25:421928 RequestImpl* req = requests_.head()->value();
1929 req->RemoveFromList();
[email protected]0f292de02012-02-01 22:28:201930 DCHECK_EQ(this, req->job());
1931 // Update the net log and notify registered observers.
Eric Orth70992982018-07-24 00:25:001932 LogFinishRequest(req->source_net_log(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291933 if (did_complete) {
1934 // Record effective total time from creation to completion.
Paul Jensen41dc3e9f2018-11-06 22:10:101935 resolver_->RecordTotalTime(
1936 req->parameters().is_speculative, false /* from_cache */,
1937 tick_clock_->NowTicks() - req->request_time());
[email protected]51b9a6b2012-06-25 21:50:291938 }
Eric Orthb30bc172018-08-17 21:09:571939 if (entry.error() == OK && !req->parameters().is_speculative) {
Eric Orth70992982018-07-24 00:25:001940 req->set_address_results(EnsurePortOnAddressList(
1941 entry.addresses(), req->request_host().port()));
1942 }
1943 req->OnJobCompleted(this, entry.error());
[email protected]0f292de02012-02-01 22:28:201944
1945 // Check if the resolver was destroyed as a result of running the
1946 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211947 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201948 return;
1949 }
1950 }
1951
Eric Orth9871aafa2018-10-02 19:59:181952 void CompleteRequestsWithoutCache(int error, const AddressList& addresses) {
1953 CompleteRequests(
1954 MakeCacheEntry(error, addresses, HostCache::Entry::SOURCE_UNKNOWN),
1955 base::TimeDelta(), false /* allow_cache */);
1956 }
1957
[email protected]1339a2a22012-10-17 08:39:431958 // Convenience wrapper for CompleteRequests in case of failure.
1959 void CompleteRequestsWithError(int net_error) {
Rob Percival94f21ad2017-11-14 10:20:241960 CompleteRequests(HostCache::Entry(net_error, AddressList(),
1961 HostCache::Entry::SOURCE_UNKNOWN),
Eric Orth9871aafa2018-10-02 19:59:181962 base::TimeDelta(), true /* allow_cache */);
[email protected]1339a2a22012-10-17 08:39:431963 }
1964
Brad Lassey786929ad2018-02-21 20:54:271965 RequestPriority priority() const override {
[email protected]b4481b222012-03-16 17:13:111966 return priority_tracker_.highest_priority();
1967 }
1968
1969 // Number of non-canceled requests in |requests_|.
1970 size_t num_active_requests() const {
1971 return priority_tracker_.total_count();
1972 }
1973
wezb9820d42016-06-22 23:41:041974 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111975
Eric Orth9871aafa2018-10-02 19:59:181976 bool is_mdns_running() const { return !!mdns_task_; }
1977
wezb9820d42016-06-22 23:41:041978 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111979
[email protected]0f292de02012-02-01 22:28:201980 base::WeakPtr<HostResolverImpl> resolver_;
1981
1982 Key key_;
1983
1984 // Tracks the highest priority across |requests_|.
1985 PriorityTracker priority_tracker_;
1986
Miriam Gershensone42adb22017-10-16 16:19:381987 // Task runner used for HostResolverProc.
1988 scoped_refptr<base::TaskRunner> proc_task_runner_;
1989
[email protected]0f292de02012-02-01 22:28:201990 bool had_non_speculative_request_;
1991
[email protected]daae1322013-09-05 18:26:501992 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1993 unsigned num_occupied_job_slots_;
1994
[email protected]1d932852012-06-19 19:40:331995 // Result of DnsTask.
1996 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001997
Misha Efimovb99e7da2018-05-30 16:59:021998 const base::TickClock* tick_clock_;
Miriam Gershenson61604662017-09-28 23:51:111999 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:292000
tfarina428341112016-09-22 13:38:202001 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:202002
[email protected]b3601bc22012-02-21 21:23:202003 // Resolves the host using a HostResolverProc.
Eric Orth9a037562018-07-03 21:24:382004 std::unique_ptr<ProcTask> proc_task_;
[email protected]0f292de02012-02-01 22:28:202005
[email protected]b3601bc22012-02-21 21:23:202006 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:402007 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:202008
Eric Orth9871aafa2018-10-02 19:59:182009 // Resolves the host using MDnsClient.
2010 std::unique_ptr<HostResolverMdnsTask> mdns_task_;
2011
[email protected]0f292de02012-02-01 22:28:202012 // All Requests waiting for the result of this Job. Some can be canceled.
David Benjamina5677192018-04-23 23:25:422013 base::LinkedList<RequestImpl> requests_;
[email protected]0f292de02012-02-01 22:28:202014
[email protected]16ee26d2012-03-08 03:34:352015 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:202016 PrioritizedDispatcher::Handle handle_;
Eric Orth60931742018-11-05 23:40:572017
2018 base::WeakPtrFactory<Job> weak_ptr_factory_;
[email protected]68ad3ee2010-01-30 03:45:392019};
2020
2021//-----------------------------------------------------------------------------
2022
[email protected]0f292de02012-02-01 22:28:202023HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:432024 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:202025 size_t max_retry_attempts)
2026 : resolver_proc(resolver_proc),
2027 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:442028 unresponsive_delay(
2029 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:202030 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:002031 // Maximum of 4 retry attempts for host resolution.
2032 static const size_t kDefaultMaxRetryAttempts = 4u;
2033 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
2034 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:202035}
2036
vmpstracd23b72016-02-26 21:08:552037HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
2038 default;
2039
Chris Watkins68b15032017-12-01 03:07:132040HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:202041
Francois Doraya2d01ba2017-09-25 19:17:402042HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:232043 : max_queued_jobs_(0),
2044 proc_params_(NULL, options.max_retry_attempts),
2045 net_log_(net_log),
2046 received_dns_config_(false),
2047 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:032048 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:232049 use_local_ipv6_(false),
2050 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:232051 additional_resolver_flags_(0),
Eric Orth60931742018-11-05 23:40:572052 use_proctask_by_default_(false),
2053 allow_fallback_to_proctask_(true),
Brad Lassey73e67ee2018-05-31 00:11:592054 url_request_context_(nullptr),
Misha Efimovb99e7da2018-05-30 16:59:022055 tick_clock_(base::DefaultTickClock::GetInstance()),
mmenke91c17162016-06-02 16:03:232056 weak_ptr_factory_(this),
2057 probe_weak_ptr_factory_(this) {
2058 if (options.enable_caching)
2059 cache_ = HostCache::CreateDefaultCache();
2060
2061 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2062 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2063 max_queued_jobs_ = job_limits.total_jobs * 100u;
2064
2065 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2066
Miriam Gershensone42adb22017-10-16 16:19:382067 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
Maks Orlovich5393c8682018-02-26 16:17:502068 {base::MayBlock(), priority_mode.Get(),
2069 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
Miriam Gershensone42adb22017-10-16 16:19:382070
mmenke91c17162016-06-02 16:03:232071#if defined(OS_WIN)
2072 EnsureWinsockInit();
2073#endif
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472074#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2075 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232076 RunLoopbackProbeJob();
2077#endif
Paul Jensenf47bbab2018-09-14 16:34:042078 NetworkChangeNotifier::AddIPAddressObserver(this);
2079 NetworkChangeNotifier::AddConnectionTypeObserver(this);
mmenke91c17162016-06-02 16:03:232080 NetworkChangeNotifier::AddDNSObserver(this);
2081#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Fabrice de Gans-Riberi65421f62018-05-22 23:16:182082 !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232083 EnsureDnsReloaderInit();
2084#endif
2085
Paul Jensenf47bbab2018-09-14 16:34:042086 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
mmenke91c17162016-06-02 16:03:232087
2088 {
Eric Orthe366fe62018-10-24 16:38:312089 DnsConfig dns_config = GetBaseDnsConfig();
mmenke91c17162016-06-02 16:03:232090 received_dns_config_ = dns_config.IsValid();
2091 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2092 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
Paul Jensen41dc3e9f2018-11-06 22:10:102093 UpdateModeForHistogram(dns_config);
mmenke91c17162016-06-02 16:03:232094 }
2095
Eric Orth60931742018-11-05 23:40:572096 allow_fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
mmenke91c17162016-06-02 16:03:232097}
2098
Eric Orth70992982018-07-24 00:25:002099HostResolverImpl::~HostResolverImpl() {
2100 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2101 // Prevent the dispatcher from starting new jobs.
2102 dispatcher_->SetLimitsToZero();
2103 // It's now safe for Jobs to call KillDnsTask on destruction, because
2104 // OnJobComplete will not start any new jobs.
2105 jobs_.clear();
2106
Paul Jensenf47bbab2018-09-14 16:34:042107 NetworkChangeNotifier::RemoveIPAddressObserver(this);
2108 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
Eric Orth70992982018-07-24 00:25:002109 NetworkChangeNotifier::RemoveDNSObserver(this);
mmenke91c17162016-06-02 16:03:232110}
2111
Eric Orth70992982018-07-24 00:25:002112void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
2113 // DnsClient and config must be updated before aborting DnsTasks, since doing
2114 // so may start new jobs.
2115 dns_client_ = std::move(dns_client);
2116 if (dns_client_ && !dns_client_->GetConfig() &&
2117 num_dns_failures_ < kMaximumDnsFailures) {
Eric Orthc823a23d2018-10-30 22:12:482118 DnsConfig dns_config;
2119 // Skip retrieving the base config if all values will be overridden.
2120 if (!dns_config_overrides_.OverridesEverything())
2121 dns_config = GetBaseDnsConfig();
Eric Orthc1eb1292018-10-09 22:07:072122 DnsConfig overridden_config =
2123 dns_config_overrides_.ApplyOverrides(dns_config);
2124 dns_client_->SetConfig(overridden_config);
Eric Orth70992982018-07-24 00:25:002125 num_dns_failures_ = 0;
2126 if (dns_client_->GetConfig())
2127 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2128 }
2129
Eric Orth60931742018-11-05 23:40:572130 AbortDnsTasks(ERR_NETWORK_CHANGED, false /* fallback_only */);
Findite5a94e02018-07-13 21:56:212131}
2132
Eric Orth70992982018-07-24 00:25:002133std::unique_ptr<HostResolver::ResolveHostRequest>
Eric Orth00fe5a62018-08-15 22:20:002134HostResolverImpl::CreateRequest(
2135 const HostPortPair& host,
2136 const NetLogWithSource& net_log,
2137 const base::Optional<ResolveHostParameters>& optional_parameters) {
2138 return std::make_unique<RequestImpl>(net_log, host, optional_parameters,
Eric Orth00fe5a62018-08-15 22:20:002139 weak_ptr_factory_.GetWeakPtr());
Eric Orth70992982018-07-24 00:25:002140}
2141
2142int HostResolverImpl::Resolve(const RequestInfo& info,
2143 RequestPriority priority,
2144 AddressList* addresses,
2145 CompletionOnceCallback callback,
2146 std::unique_ptr<Request>* out_req,
2147 const NetLogWithSource& source_net_log) {
2148 DCHECK(addresses);
2149 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2150 DCHECK(callback);
2151 DCHECK(out_req);
2152
2153 auto request = std::make_unique<RequestImpl>(
Eric Orth00fe5a62018-08-15 22:20:002154 source_net_log, info.host_port_pair(),
2155 RequestInfoToResolveHostParameters(info, priority),
Eric Orthb30bc172018-08-17 21:09:572156 weak_ptr_factory_.GetWeakPtr());
Eric Orth70992982018-07-24 00:25:002157 auto wrapped_request =
2158 std::make_unique<LegacyRequestImpl>(std::move(request));
2159
2160 int rv = wrapped_request->Start();
2161
Eric Orthb30bc172018-08-17 21:09:572162 if (rv == OK && !info.is_speculative()) {
Eric Orth70992982018-07-24 00:25:002163 DCHECK(wrapped_request->inner_request().GetAddressResults());
2164 *addresses = wrapped_request->inner_request().GetAddressResults().value();
2165 } else if (rv == ERR_IO_PENDING) {
2166 wrapped_request->AssignCallback(std::move(callback), addresses);
2167 *out_req = std::move(wrapped_request);
Eric Orthfac527992018-07-13 21:11:162168 }
2169
Eric Orth70992982018-07-24 00:25:002170 return rv;
[email protected]95a214c2011-08-04 21:50:402171}
2172
2173int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2174 AddressList* addresses,
tfarina428341112016-09-22 13:38:202175 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432176 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402177 DCHECK(addresses);
2178
[email protected]95a214c2011-08-04 21:50:402179 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022180 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402181
Matt Menke23b4bbf82017-07-20 19:11:292182 Key key;
Eric Orth70992982018-07-24 00:25:002183 int rv = ResolveLocally(
Eric Orth00fe5a62018-08-15 22:20:002184 info.host_port_pair(), AddressFamilyToDnsQueryType(info.address_family()),
Eric Orthdc35748e2018-08-23 22:41:482185 FlagsToSource(info.host_resolver_flags()), info.host_resolver_flags(),
2186 info.allow_cached_response(), false /* allow_stale */,
2187 nullptr /* stale_info */, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402188
Eric Orth70992982018-07-24 00:25:002189 LogFinishRequest(source_net_log, rv);
2190 return rv;
2191}
2192
2193int HostResolverImpl::ResolveStaleFromCache(
2194 const RequestInfo& info,
2195 AddressList* addresses,
2196 HostCache::EntryStaleness* stale_info,
2197 const NetLogWithSource& source_net_log) {
2198 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2199 DCHECK(addresses);
2200 DCHECK(stale_info);
2201
2202 // Update the net log and notify registered observers.
2203 LogStartRequest(source_net_log, info);
2204
2205 Key key;
Eric Orth00fe5a62018-08-15 22:20:002206 int rv = ResolveLocally(
2207 info.host_port_pair(), AddressFamilyToDnsQueryType(info.address_family()),
Eric Orthdc35748e2018-08-23 22:41:482208 FlagsToSource(info.host_resolver_flags()), info.host_resolver_flags(),
2209 info.allow_cached_response(), true /* allow_stale */, stale_info,
2210 source_net_log, addresses, &key);
Eric Orth70992982018-07-24 00:25:002211 LogFinishRequest(source_net_log, rv);
[email protected]95a214c2011-08-04 21:50:402212 return rv;
2213}
2214
[email protected]a8883e452012-11-17 05:58:062215void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432216 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062217#if defined(ENABLE_BUILT_IN_DNS)
2218 if (enabled && !dns_client_) {
2219 SetDnsClient(DnsClient::CreateClient(net_log_));
2220 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402221 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062222 }
2223#endif
2224}
2225
[email protected]489d1a82011-10-12 03:09:112226HostCache* HostResolverImpl::GetHostCache() {
2227 return cache_.get();
2228}
[email protected]95a214c2011-08-04 21:50:402229
Rob Percivalbc658a22017-12-13 08:24:422230bool HostResolverImpl::HasCached(base::StringPiece hostname,
2231 HostCache::Entry::Source* source_out,
2232 HostCache::EntryStaleness* stale_out) const {
2233 if (!cache_)
2234 return false;
2235
2236 return cache_->HasEntry(hostname, source_out, stale_out);
2237}
2238
danakj22f90e72016-04-16 01:55:402239std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242240 // Check if async DNS is disabled.
2241 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082242 return nullptr;
[email protected]17e92032012-03-29 00:56:242243
2244 // Check if async DNS is enabled, but we currently have no configuration
2245 // for it.
2246 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042247 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192248 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242249
2250 return dns_config->ToValue();
2251}
2252
Miriam Gershenson2839ef112017-08-30 03:25:372253size_t HostResolverImpl::LastRestoredCacheSize() const {
2254 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2255
2256 return cache_ ? cache_->last_restore_size() : 0;
2257}
2258
2259size_t HostResolverImpl::CacheSize() const {
2260 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2261
2262 return cache_ ? cache_->size() : 0;
2263}
2264
mgershaf9a9232017-04-13 20:19:032265void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432266 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032267 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2268}
2269
2270bool HostResolverImpl::GetNoIPv6OnWifi() {
2271 return assume_ipv6_failure_on_wifi_;
2272}
2273
Eric Orthc1eb1292018-10-09 22:07:072274void HostResolverImpl::SetDnsConfigOverrides(
2275 const DnsConfigOverrides& overrides) {
2276 if (dns_config_overrides_ == overrides)
2277 return;
2278
2279 dns_config_overrides_ = overrides;
Eric Orthc823a23d2018-10-30 22:12:482280 if (dns_client_.get())
Eric Orthc1eb1292018-10-09 22:07:072281 UpdateDNSConfig(true);
2282}
2283
Brad Lassey786929ad2018-02-21 20:54:272284void HostResolverImpl::SetRequestContext(URLRequestContext* context) {
2285 if (context != url_request_context_) {
2286 url_request_context_ = context;
2287 }
2288}
2289
Matt Menkeb67c0a8e2018-06-14 22:41:042290const std::vector<DnsConfig::DnsOverHttpsServerConfig>*
2291HostResolverImpl::GetDnsOverHttpsServersForTesting() const {
Eric Orthc1eb1292018-10-09 22:07:072292 if (!dns_config_overrides_.dns_over_https_servers ||
2293 dns_config_overrides_.dns_over_https_servers.value().empty()) {
Matt Menkeb67c0a8e2018-06-14 22:41:042294 return nullptr;
Eric Orthc1eb1292018-10-09 22:07:072295 }
2296 return &dns_config_overrides_.dns_over_https_servers.value();
Matt Menkeb67c0a8e2018-06-14 22:41:042297}
2298
Eric Orth70992982018-07-24 00:25:002299void HostResolverImpl::SetTickClockForTesting(
2300 const base::TickClock* tick_clock) {
2301 tick_clock_ = tick_clock;
2302 cache_->set_tick_clock_for_testing(tick_clock);
2303}
2304
2305void HostResolverImpl::SetMaxQueuedJobsForTesting(size_t value) {
2306 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
2307 DCHECK_GE(value, 0u);
2308 max_queued_jobs_ = value;
2309}
2310
2311void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2312 if (result) {
2313 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2314 } else {
2315 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2316 }
2317}
2318
Eric Orth9871aafa2018-10-02 19:59:182319void HostResolverImpl::SetMdnsSocketFactoryForTesting(
2320 std::unique_ptr<MDnsSocketFactory> socket_factory) {
2321 DCHECK(!mdns_client_);
2322 mdns_socket_factory_ = std::move(socket_factory);
2323}
2324
2325void HostResolverImpl::SetMdnsClientForTesting(
2326 std::unique_ptr<MDnsClient> client) {
2327 mdns_client_ = std::move(client);
2328}
2329
Eric Orthe366fe62018-10-24 16:38:312330void HostResolverImpl::SetBaseDnsConfigForTesting(
2331 const DnsConfig& base_config) {
2332 test_base_config_ = base_config;
2333 UpdateDNSConfig(true);
2334}
2335
Eric Orth70992982018-07-24 00:25:002336void HostResolverImpl::SetTaskRunnerForTesting(
2337 scoped_refptr<base::TaskRunner> task_runner) {
2338 proc_task_runner_ = std::move(task_runner);
2339}
2340
2341int HostResolverImpl::Resolve(RequestImpl* request) {
2342 // Request should not yet have a scheduled Job.
2343 DCHECK(!request->job());
2344 // Request may only be resolved once.
2345 DCHECK(!request->complete());
Eric Orth9871aafa2018-10-02 19:59:182346 // MDNS requests do not support skipping cache.
2347 // TODO(crbug.com/846423): Either add support for skipping the MDNS cache, or
2348 // merge to use the normal host cache for MDNS requests.
2349 DCHECK(request->parameters().source != HostResolverSource::MULTICAST_DNS ||
2350 request->parameters().allow_cached_response);
Eric Orth70992982018-07-24 00:25:002351
2352 request->set_request_time(tick_clock_->NowTicks());
2353
2354 LogStartRequest(request->source_net_log(), request->request_host());
2355
2356 AddressList addresses;
2357 Key key;
Eric Orth00fe5a62018-08-15 22:20:002358 int rv = ResolveLocally(
2359 request->request_host(), request->parameters().dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482360 request->parameters().source, request->host_resolver_flags(),
2361 request->parameters().allow_cached_response, false /* allow_stale */,
2362 nullptr /* stale_info */, request->source_net_log(), &addresses, &key);
Eric Orthb30bc172018-08-17 21:09:572363 if (rv == OK && !request->parameters().is_speculative) {
Eric Orth70992982018-07-24 00:25:002364 request->set_address_results(
2365 EnsurePortOnAddressList(addresses, request->request_host().port()));
2366 }
2367 if (rv != ERR_DNS_CACHE_MISS) {
2368 LogFinishRequest(request->source_net_log(), rv);
Eric Orthb30bc172018-08-17 21:09:572369 RecordTotalTime(request->parameters().is_speculative, true /* from_cache */,
Eric Orth70992982018-07-24 00:25:002370 base::TimeDelta());
2371 return rv;
2372 }
2373
2374 rv = CreateAndStartJob(key, request);
2375 // At this point, expect only async or errors.
2376 DCHECK_NE(OK, rv);
2377
2378 return rv;
2379}
2380
2381int HostResolverImpl::ResolveLocally(const HostPortPair& host,
Eric Orth00fe5a62018-08-15 22:20:002382 DnsQueryType dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482383 HostResolverSource source,
Eric Orth70992982018-07-24 00:25:002384 HostResolverFlags flags,
2385 bool allow_cache,
2386 bool allow_stale,
2387 HostCache::EntryStaleness* stale_info,
2388 const NetLogWithSource& source_net_log,
2389 AddressList* addresses,
2390 Key* key) {
2391 IPAddress ip_address;
2392 IPAddress* ip_address_ptr = nullptr;
2393 if (ip_address.AssignFromIPLiteral(host.host())) {
2394 ip_address_ptr = &ip_address;
2395 } else {
2396 // Check that the caller supplied a valid hostname to resolve.
2397 if (!IsValidDNSDomain(host.host()))
2398 return ERR_NAME_NOT_RESOLVED;
2399 }
2400
2401 // Build a key that identifies the request in the cache and in the
2402 // outstanding jobs map.
Eric Orthdc35748e2018-08-23 22:41:482403 *key = GetEffectiveKeyForRequest(host.host(), dns_query_type, source, flags,
Eric Orth70992982018-07-24 00:25:002404 ip_address_ptr, source_net_log);
2405
2406 DCHECK(allow_stale == !!stale_info);
2407 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2408 // On Windows it gives the default interface's address, whereas on Linux it
2409 // gives an error. We will make it fail on all platforms for consistency.
2410 if (host.host().empty() || host.host().size() > kMaxHostLength) {
2411 MakeNotStale(stale_info);
2412 return ERR_NAME_NOT_RESOLVED;
2413 }
2414
2415 int net_error = ERR_UNEXPECTED;
2416 if (ResolveAsIP(*key, host.port(), ip_address_ptr, &net_error, addresses)) {
2417 MakeNotStale(stale_info);
2418 return net_error;
2419 }
2420
2421 // Special-case localhost names, as per the recommendations in
2422 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2423 if (ServeLocalhost(*key, host.port(), addresses)) {
2424 MakeNotStale(stale_info);
2425 return OK;
2426 }
2427
2428 if (allow_cache && ServeFromCache(*key, host.port(), &net_error, addresses,
2429 allow_stale, stale_info)) {
2430 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2431 addresses->CreateNetLogCallback());
2432 // |ServeFromCache()| will set |*stale_info| as needed.
2433 return net_error;
2434 }
2435
2436 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2437 // http://crbug.com/117655
2438 if (ServeFromHosts(*key, host.port(), addresses)) {
2439 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2440 addresses->CreateNetLogCallback());
2441 MakeNotStale(stale_info);
2442 return OK;
2443 }
2444
2445 return ERR_DNS_CACHE_MISS;
2446}
2447
2448int HostResolverImpl::CreateAndStartJob(const Key& key, RequestImpl* request) {
2449 auto jobit = jobs_.find(key);
2450 Job* job;
2451 if (jobit == jobs_.end()) {
2452 auto new_job = std::make_unique<Job>(
2453 weak_ptr_factory_.GetWeakPtr(), key, request->priority(),
2454 proc_task_runner_, request->source_net_log(), tick_clock_);
2455 job = new_job.get();
2456 new_job->Schedule(false);
2457
2458 // Check for queue overflow.
2459 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
2460 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
2461 DCHECK(evicted);
2462 evicted->OnEvicted();
2463 if (evicted == new_job.get()) {
2464 LogFinishRequest(request->source_net_log(),
2465 ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
2466 return ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
2467 }
2468 }
2469 jobs_[key] = std::move(new_job);
2470 } else {
2471 job = jobit->second.get();
2472 }
2473
2474 // Can't complete synchronously. Attach request and job to each other.
2475 job->AddRequest(request);
2476 return ERR_IO_PENDING;
2477}
2478
[email protected]95a214c2011-08-04 21:50:402479bool HostResolverImpl::ResolveAsIP(const Key& key,
Eric Orth70992982018-07-24 00:25:002480 uint16_t host_port,
martijna23c8962016-03-04 18:18:512481 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402482 int* net_error,
2483 AddressList* addresses) {
2484 DCHECK(addresses);
2485 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512486 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402487 return false;
2488
[email protected]95a214c2011-08-04 21:50:402489 *net_error = OK;
martijna23c8962016-03-04 18:18:512490 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252491 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2492 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482493 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402494 *net_error = ERR_NAME_NOT_RESOLVED;
2495 } else {
Eric Orth70992982018-07-24 00:25:002496 *addresses = AddressList::CreateFromIPAddress(*ip_address, host_port);
[email protected]7054e78f2012-05-07 21:44:562497 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2498 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402499 }
2500 return true;
2501}
2502
2503bool HostResolverImpl::ServeFromCache(const Key& key,
Eric Orth70992982018-07-24 00:25:002504 uint16_t host_port,
[email protected]95a214c2011-08-04 21:50:402505 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332506 AddressList* addresses,
2507 bool allow_stale,
2508 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402509 DCHECK(addresses);
2510 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332511 DCHECK(allow_stale == !!stale_info);
Eric Orth70992982018-07-24 00:25:002512 if (!cache_.get())
[email protected]95a214c2011-08-04 21:50:402513 return false;
2514
juliatuttle9fb7aeb2016-06-06 20:16:332515 const HostCache::Entry* cache_entry;
2516 if (allow_stale)
Misha Efimovb99e7da2018-05-30 16:59:022517 cache_entry = cache_->LookupStale(key, tick_clock_->NowTicks(), stale_info);
juliatuttle9fb7aeb2016-06-06 20:16:332518 else
Misha Efimovb99e7da2018-05-30 16:59:022519 cache_entry = cache_->Lookup(key, tick_clock_->NowTicks());
[email protected]95a214c2011-08-04 21:50:402520 if (!cache_entry)
2521 return false;
2522
juliatuttle317860e2016-05-12 14:47:222523 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562524 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432525 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222526 RecordTTL(cache_entry->ttl());
Eric Orth70992982018-07-24 00:25:002527 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), host_port);
[email protected]7054e78f2012-05-07 21:44:562528 }
[email protected]95a214c2011-08-04 21:50:402529 return true;
2530}
2531
[email protected]78eac2a2012-03-14 19:09:272532bool HostResolverImpl::ServeFromHosts(const Key& key,
Eric Orth70992982018-07-24 00:25:002533 uint16_t host_port,
[email protected]78eac2a2012-03-14 19:09:272534 AddressList* addresses) {
2535 DCHECK(addresses);
2536 if (!HaveDnsConfig())
2537 return false;
[email protected]05a79d42013-03-28 07:30:092538 addresses->clear();
2539
[email protected]cb507622012-03-23 16:17:062540 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222541 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062542
[email protected]05a79d42013-03-28 07:30:092543 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2544
[email protected]78eac2a2012-03-14 19:09:272545 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2546 // (glibc and c-ares) return the first matching line. We have more
2547 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092548 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2549 // necessary.
2550 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2551 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
jdoerrie22a91d8b92018-10-05 08:43:262552 auto it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
[email protected]05a79d42013-03-28 07:30:092553 if (it != hosts.end())
Eric Orth70992982018-07-24 00:25:002554 addresses->push_back(IPEndPoint(it->second, host_port));
[email protected]78eac2a2012-03-14 19:09:272555 }
2556
[email protected]05a79d42013-03-28 07:30:092557 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2558 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
jdoerrie22a91d8b92018-10-05 08:43:262559 auto it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
[email protected]05a79d42013-03-28 07:30:092560 if (it != hosts.end())
Eric Orth70992982018-07-24 00:25:002561 addresses->push_back(IPEndPoint(it->second, host_port));
[email protected]05a79d42013-03-28 07:30:092562 }
2563
[email protected]ec666ab22013-04-17 20:05:592564 // If got only loopback addresses and the family was restricted, resolve
2565 // again, without restrictions. See SystemHostResolverCall for rationale.
2566 if ((key.host_resolver_flags &
2567 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2568 IsAllIPv4Loopback(*addresses)) {
2569 Key new_key(key);
2570 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2571 new_key.host_resolver_flags &=
2572 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Eric Orth70992982018-07-24 00:25:002573 return ServeFromHosts(new_key, host_port, addresses);
[email protected]ec666ab22013-04-17 20:05:592574 }
[email protected]05a79d42013-03-28 07:30:092575 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272576}
2577
estarkd1bc206e2015-06-20 00:44:392578bool HostResolverImpl::ServeLocalhost(const Key& key,
Eric Orth70992982018-07-24 00:25:002579 uint16_t host_port,
estarkd1bc206e2015-06-20 00:44:392580 AddressList* addresses) {
2581 AddressList resolved_addresses;
Eric Orth70992982018-07-24 00:25:002582 if (!ResolveLocalHostname(key.hostname, host_port, &resolved_addresses))
estarkd1bc206e2015-06-20 00:44:392583 return false;
2584
2585 addresses->clear();
2586
2587 for (const auto& address : resolved_addresses) {
2588 // Include the address if:
2589 // - caller didn't specify an address family, or
2590 // - caller specifically asked for the address family of this address, or
2591 // - this is an IPv6 address and caller specifically asked for IPv4 due
2592 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2593 // rationale).
2594 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2595 key.address_family == address.GetFamily() ||
2596 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2597 key.address_family == ADDRESS_FAMILY_IPV4 &&
2598 (key.host_resolver_flags &
2599 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2600 addresses->push_back(address);
2601 }
2602 }
2603
2604 return true;
2605}
2606
[email protected]16ee26d2012-03-08 03:34:352607void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432608 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352609 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052610 // Don't cache an error unless it has a positive TTL.
2611 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
Misha Efimovb99e7da2018-05-30 16:59:022612 cache_->Set(key, entry, tick_clock_->NowTicks(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032613}
2614
Paul Jensen41dc3e9f2018-11-06 22:10:102615// Record time from Request creation until a valid DNS response.
2616void HostResolverImpl::RecordTotalTime(bool speculative,
2617 bool from_cache,
2618 base::TimeDelta duration) const {
2619 if (!speculative) {
2620 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
2621
2622 switch (mode_for_histogram_) {
2623 case MODE_FOR_HISTOGRAM_SYSTEM:
2624 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.System", duration);
2625 break;
2626 case MODE_FOR_HISTOGRAM_SYSTEM_SUPPORTS_DOH:
2627 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.SystemSupportsDoh",
2628 duration);
2629 break;
2630 case MODE_FOR_HISTOGRAM_SYSTEM_PRIVATE_DNS:
2631 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.SystemPrivate",
2632 duration);
2633 break;
2634 case MODE_FOR_HISTOGRAM_ASYNC_DNS:
2635 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.Async", duration);
2636 break;
2637 case MODE_FOR_HISTOGRAM_ASYNC_DNS_PRIVATE_SUPPORTS_DOH:
2638 UMA_HISTOGRAM_MEDIUM_TIMES(
2639 "Net.DNS.TotalTimeTyped.AsyncPrivateSupportsDoh", duration);
2640 break;
2641 }
2642
2643 if (!from_cache)
2644 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
2645 }
2646}
2647
Eric Orth18544ae2018-06-11 22:57:162648std::unique_ptr<HostResolverImpl::Job> HostResolverImpl::RemoveJob(Job* job) {
[email protected]0f292de02012-02-01 22:28:202649 DCHECK(job);
Eric Orth18544ae2018-06-11 22:57:162650 std::unique_ptr<Job> retval;
avi9e72eb482016-12-09 21:10:542651 auto it = jobs_.find(job->key());
2652 if (it != jobs_.end() && it->second.get() == job) {
Eric Orth18544ae2018-06-11 22:57:162653 it->second.swap(retval);
[email protected]16ee26d2012-03-08 03:34:352654 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542655 }
Eric Orth18544ae2018-06-11 22:57:162656 return retval;
[email protected]b59ff372009-07-15 22:04:322657}
2658
[email protected]137af622010-02-05 02:14:352659HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
Eric Orth70992982018-07-24 00:25:002660 const std::string& hostname,
Eric Orth00fe5a62018-08-15 22:20:002661 DnsQueryType dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482662 HostResolverSource source,
Eric Orth70992982018-07-24 00:25:002663 HostResolverFlags flags,
martijna23c8962016-03-04 18:18:512664 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202665 const NetLogWithSource& net_log) {
Eric Orth70992982018-07-24 00:25:002666 HostResolverFlags effective_flags = flags | additional_resolver_flags_;
Eric Orth00fe5a62018-08-15 22:20:002667
2668 AddressFamily effective_address_family =
2669 DnsQueryTypeToAddressFamily(dns_query_type);
[email protected]9db6f702013-04-10 18:10:512670
mgersh3eba057d2017-02-28 18:50:562671 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2672 // When resolving IPv4 literals, there's no need to probe for IPv6.
2673 // When resolving IPv6 literals, there's no benefit to artificially
2674 // limiting our resolution based on a probe. Prior logic ensures
2675 // that this query is UNSPECIFIED (see effective_address_family
2676 // check above) so the code requesting the resolution should be amenable
2677 // to receiving a IPv6 resolution.
2678 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2679 effective_address_family = ADDRESS_FAMILY_IPV4;
2680 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512681 }
2682
Eric Orthdc35748e2018-08-23 22:41:482683 return Key(hostname, effective_address_family, effective_flags, source);
[email protected]137af622010-02-05 02:14:352684}
2685
tfarina428341112016-09-22 13:38:202686bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032687 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2688 // work on WiFi.
2689 if (assume_ipv6_failure_on_wifi_ &&
2690 NetworkChangeNotifier::GetConnectionType() ==
2691 NetworkChangeNotifier::CONNECTION_WIFI) {
2692 return false;
2693 }
2694
eroman1a17ef32016-12-14 01:06:092695 // Cache the result for kIPv6ProbePeriodMs (measured from after
2696 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372697 bool cached = true;
Misha Efimovb99e7da2018-05-30 16:59:022698 if ((tick_clock_->NowTicks() - last_ipv6_probe_time_).InMilliseconds() >
eroman1a17ef32016-12-14 01:06:092699 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512700 last_ipv6_probe_result_ =
2701 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
Misha Efimovb99e7da2018-05-30 16:59:022702 last_ipv6_probe_time_ = tick_clock_->NowTicks();
sergeyub8cdc212015-05-14 18:50:372703 cached = false;
2704 }
mikecirone8b85c432016-09-08 19:11:002705 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372706 base::Bind(&NetLogIPv6AvailableCallback,
2707 last_ipv6_probe_result_, cached));
2708 return last_ipv6_probe_result_;
2709}
2710
mgershaf9a9232017-04-13 20:19:032711bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2712 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032713 std::unique_ptr<DatagramClientSocket> socket(
2714 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
Sergey Ulanovcbdfc8852018-03-16 20:13:282715 DatagramSocket::DEFAULT_BIND, net_log.net_log(), net_log.source()));
mgershaf9a9232017-04-13 20:19:032716 int rv = socket->Connect(IPEndPoint(dest, 53));
2717 if (rv != OK)
2718 return false;
2719 IPEndPoint endpoint;
2720 rv = socket->GetLocalAddress(&endpoint);
2721 if (rv != OK)
2722 return false;
2723 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2724 const IPAddress& address = endpoint.address();
2725
2726 bool is_link_local =
2727 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2728 if (is_link_local)
2729 return false;
2730
2731 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2732 if (IPAddressStartsWith(address, kTeredoPrefix))
2733 return false;
2734
2735 return true;
2736}
2737
mmenke91c17162016-06-02 16:03:232738void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402739 // Run this asynchronously as it can take 40-100ms and should not block
2740 // initialization.
2741 base::PostTaskWithTraitsAndReplyWithResult(
2742 FROM_HERE,
2743 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2744 base::BindOnce(&HaveOnlyLoopbackAddresses),
2745 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2746 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232747}
2748
[email protected]35ddc282010-09-21 23:42:062749void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202750 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2751 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402752 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542753 for (auto it = jobs_.begin(); it != jobs_.end();) {
2754 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202755 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542756 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202757 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202758 } else {
[email protected]b3601bc22012-02-21 21:23:202759 DCHECK(job->is_queued());
2760 ++it;
[email protected]0f292de02012-02-01 22:28:202761 }
[email protected]ef4c40c2010-09-01 14:42:032762 }
[email protected]b3601bc22012-02-21 21:23:202763
[email protected]daae1322013-09-05 18:26:502764 // Pause the dispatcher so it won't start any new dispatcher jobs while
2765 // aborting the old ones. This is needed so that it won't start the second
2766 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2767 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002768 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2769 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502770 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122771
[email protected]57a48d32012-03-03 00:04:552772 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072773 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552774
[email protected]16ee26d2012-03-08 03:34:352775 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212776 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552777 jobs_to_abort[i]->Abort();
[email protected]b3601bc22012-02-21 21:23:202778 }
[email protected]daae1322013-09-05 18:26:502779
2780 if (self)
[email protected]106ccd2c2014-06-17 09:21:002781 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502782}
2783
Eric Orth60931742018-11-05 23:40:572784void HostResolverImpl::AbortDnsTasks(int error, bool fallback_only) {
2785 // Aborting jobs potentially modifies |jobs_| and may even delete some jobs.
2786 // Create safe closures of all current jobs.
2787 std::vector<base::OnceClosure> job_abort_closures;
2788 for (auto& job : jobs_) {
2789 job_abort_closures.push_back(
2790 job.second->GetAbortDnsTaskClosure(error, fallback_only));
2791 }
2792
[email protected]daae1322013-09-05 18:26:502793 // Pause the dispatcher so it won't start any new dispatcher jobs while
2794 // aborting the old ones. This is needed so that it won't start the second
2795 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002796 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2797 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502798 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2799
Eric Orth60931742018-11-05 23:40:572800 for (base::OnceClosure& closure : job_abort_closures)
2801 std::move(closure).Run();
2802
[email protected]106ccd2c2014-06-17 09:21:002803 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032804}
2805
[email protected]78eac2a2012-03-14 19:09:272806void HostResolverImpl::TryServingAllJobsFromHosts() {
2807 if (!HaveDnsConfig())
2808 return;
2809
2810 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2811 // http://crbug.com/117655
2812
2813 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072814 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272815
avi9e72eb482016-12-09 21:10:542816 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2817 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272818 ++it;
2819 // This could remove |job| from |jobs_|, but iterator will remain valid.
2820 job->ServeFromHosts();
2821 }
2822}
2823
Paul Jensenf47bbab2018-09-14 16:34:042824void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372825 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182826 // Abandon all ProbeJobs.
2827 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172828 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102829 cache_->OnNetworkChange();
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472830#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2831 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232832 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132833#endif
2834 AbortAllInProgressJobs();
2835 // |this| may be deleted inside AbortAllInProgressJobs().
2836}
2837
Paul Jensenf47bbab2018-09-14 16:34:042838void HostResolverImpl::OnConnectionTypeChanged(
ttuttlecf1158bf2016-03-18 16:37:442839 NetworkChangeNotifier::ConnectionType type) {
2840 proc_params_.unresponsive_delay =
2841 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2842 "DnsUnresponsiveDelayMsByConnectionType",
2843 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2844 type);
2845}
2846
pauljensen101ed372015-04-17 00:11:422847void HostResolverImpl::OnInitialDNSConfigRead() {
2848 UpdateDNSConfig(false);
2849}
2850
[email protected]bb0e34542012-08-31 19:52:402851void HostResolverImpl::OnDNSChanged() {
Eric Orthc823a23d2018-10-30 22:12:482852 // Ignore changes if we're using a test config or if we have overriding
2853 // configuration that overrides everything from the base config.
2854 if (test_base_config_ || dns_config_overrides_.OverridesEverything())
Eric Orthe366fe62018-10-24 16:38:312855 return;
2856
pauljensen101ed372015-04-17 00:11:422857 UpdateDNSConfig(true);
2858}
2859
Eric Orthe366fe62018-10-24 16:38:312860DnsConfig HostResolverImpl::GetBaseDnsConfig() const {
[email protected]bb0e34542012-08-31 19:52:402861 DnsConfig dns_config;
Eric Orthe366fe62018-10-24 16:38:312862 if (test_base_config_)
2863 dns_config = test_base_config_.value();
2864 else
2865 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2866 return dns_config;
2867}
2868
2869void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
Eric Orthc823a23d2018-10-30 22:12:482870 DnsConfig dns_config;
[email protected]ec666ab22013-04-17 20:05:592871
Eric Orthc823a23d2018-10-30 22:12:482872 // Skip retrieving the base config if all values will be overridden.
2873 if (!dns_config_overrides_.OverridesEverything()) {
2874 dns_config = GetBaseDnsConfig();
2875
2876 if (net_log_) {
2877 net_log_->AddGlobalEntry(
2878 NetLogEventType::DNS_CONFIG_CHANGED,
2879 base::BindRepeating(&NetLogDnsConfigCallback, &dns_config));
2880 }
2881
2882 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
2883 received_dns_config_ = dns_config.IsValid();
[email protected]b4481b222012-03-16 17:13:112884 }
2885
Eric Orthc1eb1292018-10-09 22:07:072886 dns_config = dns_config_overrides_.ApplyOverrides(dns_config);
2887
[email protected]c9fa8f312013-09-17 12:24:522888 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2889 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272890
[email protected]a8883e452012-11-17 05:58:062891 num_dns_failures_ = 0;
2892
[email protected]01b3b9d2012-08-13 16:18:142893 // We want a new DnsSession in place, before we Abort running Jobs, so that
2894 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022895 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252896 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532897 // wasn't already a DnsConfig or it's the same one.
2898 DCHECK(config_changed || !dns_client_->GetConfig() ||
2899 dns_client_->GetConfig()->Equals(dns_config));
[email protected]d7b9a2b2012-05-31 22:31:192900 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252901 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022902 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022903 }
Eric Orth60931742018-11-05 23:40:572904 use_proctask_by_default_ = false;
[email protected]01b3b9d2012-08-13 16:18:142905
pauljensen101ed372015-04-17 00:11:422906 if (config_changed) {
2907 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232908 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422909 // as NSCD's cache should be dropped automatically by the OS when
2910 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172911 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232912 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142913
pauljensen101ed372015-04-17 00:11:422914 // Life check to bail once |this| is deleted.
2915 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022916
pauljensen101ed372015-04-17 00:11:422917 // Existing jobs will have been sent to the original server so they need to
2918 // be aborted.
2919 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142920
pauljensen101ed372015-04-17 00:11:422921 // |this| may be deleted inside AbortAllInProgressJobs().
2922 if (self.get())
2923 TryServingAllJobsFromHosts();
2924 }
Paul Jensen41dc3e9f2018-11-06 22:10:102925
2926 UpdateModeForHistogram(dns_config);
[email protected]78eac2a2012-03-14 19:09:272927}
2928
2929bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252930 // Use DnsClient only if it's fully configured and there is no override by
2931 // ScopedDefaultHostResolverProc.
2932 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2933 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042934 return dns_client_ && dns_client_->GetConfig() &&
2935 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202936}
2937
Eric Orth60931742018-11-05 23:40:572938void HostResolverImpl::OnDnsTaskResolve() {
[email protected]f0f602bd2012-11-15 18:01:022939 DCHECK(dns_client_);
Eric Orth60931742018-11-05 23:40:572940 num_dns_failures_ = 0;
2941}
2942
2943void HostResolverImpl::OnFallbackResolve(int dns_task_error) {
2944 DCHECK(dns_client_);
2945 DCHECK_NE(OK, dns_task_error);
2946
[email protected]f0f602bd2012-11-15 18:01:022947 ++num_dns_failures_;
2948 if (num_dns_failures_ < kMaximumDnsFailures)
2949 return;
[email protected]daae1322013-09-05 18:26:502950
Eric Orth60931742018-11-05 23:40:572951 // Force fallback until the next DNS change. Must be done before aborting
2952 // DnsTasks, since doing so may start new jobs. Do not fully clear out or
2953 // disable the DnsClient as some requests (e.g. those specifying DNS source)
2954 // are not allowed to fallback and will continue using DnsTask.
2955 use_proctask_by_default_ = true;
[email protected]daae1322013-09-05 18:26:502956
Eric Orth60931742018-11-05 23:40:572957 // Fallback all fallback-allowed DnsTasks to ProcTasks.
2958 AbortDnsTasks(ERR_FAILED, true /* fallback_only */);
[email protected]daae1322013-09-05 18:26:502959
[email protected]f0f602bd2012-11-15 18:01:022960 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:182961 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
Eric Orth60931742018-11-05 23:40:572962 std::abs(dns_task_error));
[email protected]f0f602bd2012-11-15 18:01:022963}
2964
Eric Orth9871aafa2018-10-02 19:59:182965MDnsClient* HostResolverImpl::GetOrCreateMdnsClient() {
2966#if BUILDFLAG(ENABLE_MDNS)
2967 if (!mdns_client_) {
2968 if (!mdns_socket_factory_)
2969 mdns_socket_factory_ = std::make_unique<MDnsSocketFactoryImpl>(net_log_);
2970
2971 mdns_client_ = MDnsClient::CreateDefault();
2972 mdns_client_->StartListening(mdns_socket_factory_.get());
2973 }
2974
2975 DCHECK(mdns_client_->IsListening());
2976 return mdns_client_.get();
2977#else
2978 // Should not request MDNS resoltuion unless MDNS is enabled.
2979 NOTREACHED();
2980 return nullptr;
2981#endif
2982}
2983
Paul Jensen41dc3e9f2018-11-06 22:10:102984void HostResolverImpl::UpdateModeForHistogram(const DnsConfig& dns_config) {
2985 // Resolving with Async DNS resolver?
2986 if (HaveDnsConfig()) {
2987 mode_for_histogram_ = MODE_FOR_HISTOGRAM_ASYNC_DNS;
2988 for (const auto& dns_server : dns_client_->GetConfig()->nameservers) {
2989 if (DnsServerSupportsDoh(dns_server.address())) {
2990 mode_for_histogram_ = MODE_FOR_HISTOGRAM_ASYNC_DNS_PRIVATE_SUPPORTS_DOH;
2991 break;
2992 }
2993 }
2994 } else {
2995 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM;
2996 for (const auto& dns_server : dns_config.nameservers) {
2997 if (DnsServerSupportsDoh(dns_server.address())) {
2998 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM_SUPPORTS_DOH;
2999 break;
3000 }
3001 }
3002#if defined(OS_ANDROID)
3003 if (base::android::BuildInfo::GetInstance()->sdk_int() >=
3004 base::android::SDK_VERSION_P) {
3005 std::vector<IPEndPoint> dns_servers;
3006 if (net::android::GetDnsServers(&dns_servers) ==
3007 internal::CONFIG_PARSE_POSIX_PRIVATE_DNS_ACTIVE) {
3008 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM_PRIVATE_DNS;
3009 }
3010 }
3011#endif // defined(OS_ANDROID)
3012 }
3013}
3014
maksim.sisov31452af2016-07-27 06:38:103015HostResolverImpl::RequestImpl::~RequestImpl() {
3016 if (job_)
3017 job_->CancelRequest(this);
3018}
3019
3020void HostResolverImpl::RequestImpl::ChangeRequestPriority(
3021 RequestPriority priority) {
3022 job_->ChangeRequestPriority(this, priority);
3023}
3024
[email protected]b59ff372009-07-15 22:04:323025} // namespace net