blob: 47cf9efd286e724ea7ace4f409c021d57a45d050 [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>
Eric Orth192e3bb2018-11-14 19:30:3224#include <unordered_set>
[email protected]0f292de02012-02-01 22:28:2025#include <utility>
[email protected]21526002010-05-16 19:42:4626#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3927
[email protected]33152acc2011-10-20 23:37:1228#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2929#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2030#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1031#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3232#include "base/compiler_specific.h"
David Benjamina5677192018-04-23 23:25:4233#include "base/containers/linked_list.h"
[email protected]58580352010-10-26 04:07:5034#include "base/debug/debugger.h"
35#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4636#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2337#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4538#include "base/metrics/field_trial.h"
Maks Orlovich5393c8682018-02-26 16:17:5039#include "base/metrics/field_trial_params.h"
Ilya Sherman0eb39802017-12-08 20:58:1840#include "base/metrics/histogram_functions.h"
davidbenad6fc442015-05-18 20:59:1341#include "base/metrics/histogram_macros.h"
Paul Jensen41dc3e9f2018-11-06 22:10:1042#include "base/no_destructor.h"
anujk.sharma7c907f02015-05-29 02:55:4443#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4844#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0545#include "base/strings/utf_string_conversions.h"
Gabriel Charette44db1422018-08-06 11:19:3346#include "base/task/post_task.h"
Francois Doraya2d01ba2017-09-25 19:17:4047#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3548#include "base/threading/thread_task_runner_handle.h"
Misha Efimovb99e7da2018-05-30 16:59:0249#include "base/time/default_tick_clock.h"
[email protected]66e96c42013-06-28 15:20:3150#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5651#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4652#include "base/values.h"
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4753#include "build/build_config.h"
[email protected]b3601bc22012-02-21 21:23:2054#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3255#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5156#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5157#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4858#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1559#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4860#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1861#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4662#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2763#include "net/dns/dns_client.h"
tfarina47598f042015-10-07 23:08:3564#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2065#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2066#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0367#include "net/dns/dns_util.h"
Eric Orth9871aafa2018-10-02 19:59:1868#include "net/dns/host_resolver_mdns_task.h"
[email protected]f2cb3cf2013-03-21 01:40:5369#include "net/dns/host_resolver_proc.h"
Eric Orth9871aafa2018-10-02 19:59:1870#include "net/dns/mdns_client.h"
Eric Orth8afaf152018-11-07 21:01:2671#include "net/dns/public/dns_protocol.h"
eroman87c53d62015-04-02 06:51:0772#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1973#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0074#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1975#include "net/log/net_log_parameters_callback.h"
76#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0077#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1978#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5179#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2680#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1481#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3282
Eric Orth9871aafa2018-10-02 19:59:1883#if BUILDFLAG(ENABLE_MDNS)
84#include "net/dns/mdns_client_impl.h"
85#endif
86
[email protected]b59ff372009-07-15 22:04:3287#if defined(OS_WIN)
88#include "net/base/winsock_init.h"
89#endif
90
tfarinada9e1362017-03-14 16:49:0691#if defined(OS_ANDROID)
Paul Jensen41dc3e9f2018-11-06 22:10:1092#include "base/android/build_info.h"
tfarinada9e1362017-03-14 16:49:0693#include "net/android/network_library.h"
94#endif
95
[email protected]b59ff372009-07-15 22:04:3296namespace net {
97
[email protected]e95d3aca2010-01-11 22:47:4398namespace {
99
ttuttlecf1158bf2016-03-18 16:37:44100// Default delay between calls to the system resolver for the same hostname.
101// (Can be overridden by field trial.)
102const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
103
[email protected]6e78dfb2011-07-28 21:34:47104// Limit the size of hostnames that will be resolved to combat issues in
105// some platform's resolvers.
106const size_t kMaxHostLength = 4096;
107
[email protected]a2730882012-01-21 00:56:27108// Default TTL for successful resolutions with ProcTask.
109const unsigned kCacheEntryTTLSeconds = 60;
110
[email protected]b3601bc22012-02-21 21:23:20111// Default TTL for unsuccessful resolutions with ProcTask.
112const unsigned kNegativeCacheEntryTTLSeconds = 0;
113
[email protected]895123222012-10-25 15:21:17114// Minimum TTL for successful resolutions with DnsTask.
115const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
116
sergeyub8cdc212015-05-14 18:50:37117// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
118// cached.
119const int kIPv6ProbePeriodMs = 1000;
120
121// Google DNS address used for IPv6 probes.
122const uint8_t kIPv6ProbeAddress[] =
123 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
124 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
125
[email protected]1def74c2012-03-22 20:07:00126enum DnsResolveStatus {
127 RESOLVE_STATUS_DNS_SUCCESS = 0,
128 RESOLVE_STATUS_PROC_SUCCESS,
129 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33130 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00131 RESOLVE_STATUS_MAX
132};
133
eroman91dd3602015-03-26 03:46:33134// ICANN uses this localhost address to indicate a name collision.
135//
136// The policy in Chromium is to fail host resolving if it resolves to
137// this special address.
138//
139// Not however that IP literals are exempt from this policy, so it is still
140// possible to navigate to http://127.0.53.53/ directly.
141//
142// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51143const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33144
eroman1efc237c2016-12-14 00:00:45145bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
146 for (const auto& endpoint : addr_list) {
147 const IPAddress& addr = endpoint.address();
148 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
149 return true;
150 }
151 }
152 return false;
153}
154
[email protected]1def74c2012-03-22 20:07:00155void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
156 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
157 result,
158 RESOLVE_STATUS_MAX);
159}
160
[email protected]1d932852012-06-19 19:40:33161bool ResemblesNetBIOSName(const std::string& hostname) {
162 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
163}
164
165// True if |hostname| ends with either ".local" or ".local.".
166bool ResemblesMulticastDNSName(const std::string& hostname) {
167 DCHECK(!hostname.empty());
168 const char kSuffix[] = ".local.";
169 const size_t kSuffixLen = sizeof(kSuffix) - 1;
170 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36171 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33172 return hostname.size() > kSuffixLen &&
173 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
174 }
175 return hostname.size() > kSuffixLenTrimmed &&
176 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
177 kSuffix, kSuffixLenTrimmed);
178}
179
[email protected]51b9a6b2012-06-25 21:50:29180// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21181#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
182 do { \
183 switch (priority) { \
184 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28185 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21186 break; \
187 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28188 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21189 break; \
190 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28191 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21192 break; \
193 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28194 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21195 break; \
196 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28197 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21198 break; \
199 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28200 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21201 break; \
202 } \
203 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29204 } while (0)
205
[email protected]1339a2a22012-10-17 08:39:43206void RecordTTL(base::TimeDelta ttl) {
207 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
208 base::TimeDelta::FromSeconds(1),
209 base::TimeDelta::FromDays(1), 100);
210}
211
[email protected]16c2bd72013-06-28 01:19:22212bool ConfigureAsyncDnsNoFallbackFieldTrial() {
213 const bool kDefault = false;
214
215 // Configure the AsyncDns field trial as follows:
216 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
217 // groups AsyncDnsA and AsyncDnsB: return false,
218 // groups SystemDnsA and SystemDnsB: return false,
219 // otherwise (trial absent): return default.
220 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29221 if (!group_name.empty()) {
222 return base::StartsWith(group_name, "AsyncDnsNoFallback",
223 base::CompareCase::INSENSITIVE_ASCII);
224 }
[email protected]16c2bd72013-06-28 01:19:22225 return kDefault;
226}
227
Maks Orlovich5393c8682018-02-26 16:17:50228const base::FeatureParam<base::TaskPriority>::Option prio_modes[] = {
229 {base::TaskPriority::USER_VISIBLE, "default"},
230 {base::TaskPriority::USER_BLOCKING, "user_blocking"}};
231const base::Feature kSystemResolverPriorityExperiment = {
232 "SystemResolverPriorityExperiment", base::FEATURE_DISABLED_BY_DEFAULT};
233const base::FeatureParam<base::TaskPriority> priority_mode{
234 &kSystemResolverPriorityExperiment, "mode",
235 base::TaskPriority::USER_VISIBLE, &prio_modes};
236
[email protected]d7b9a2b2012-05-31 22:31:19237//-----------------------------------------------------------------------------
238
Avi Drissman13fc8932015-12-20 04:40:46239AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17240 if (list.empty() || list.front().port() == port)
241 return list;
242 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56243}
244
[email protected]ec666ab22013-04-17 20:05:59245// Returns true if |addresses| contains only IPv4 loopback addresses.
246bool IsAllIPv4Loopback(const AddressList& addresses) {
247 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51248 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59249 switch (addresses[i].GetFamily()) {
250 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51251 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59252 return false;
253 break;
254 case ADDRESS_FAMILY_IPV6:
255 return false;
256 default:
257 NOTREACHED();
258 return false;
259 }
260 }
261 return true;
262}
263
tfarinada9e1362017-03-14 16:49:06264// Returns true if it can determine that only loopback addresses are configured.
265// i.e. if only 127.0.0.1 and ::1 are routable.
266// Also returns false if it cannot determine this.
267bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40268 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47269#if defined(OS_WIN)
270 // TODO(wtc): implement with the GetAdaptersAddresses function.
271 NOTIMPLEMENTED();
272 return false;
273#elif defined(OS_ANDROID)
tfarinada9e1362017-03-14 16:49:06274 return android::HaveOnlyLoopbackAddresses();
275#elif defined(OS_NACL)
276 NOTIMPLEMENTED();
277 return false;
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47278#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tfarinada9e1362017-03-14 16:49:06279 struct ifaddrs* interface_addr = NULL;
280 int rv = getifaddrs(&interface_addr);
281 if (rv != 0) {
282 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
283 return false;
284 }
285
286 bool result = true;
287 for (struct ifaddrs* interface = interface_addr;
288 interface != NULL;
289 interface = interface->ifa_next) {
290 if (!(IFF_UP & interface->ifa_flags))
291 continue;
292 if (IFF_LOOPBACK & interface->ifa_flags)
293 continue;
294 const struct sockaddr* addr = interface->ifa_addr;
295 if (!addr)
296 continue;
297 if (addr->sa_family == AF_INET6) {
298 // Safe cast since this is AF_INET6.
299 const struct sockaddr_in6* addr_in6 =
300 reinterpret_cast<const struct sockaddr_in6*>(addr);
301 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
302 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
303 continue;
304 }
305 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
306 continue;
307
308 result = false;
309 break;
310 }
311 freeifaddrs(interface_addr);
312 return result;
tfarinada9e1362017-03-14 16:49:06313#endif // defined(various platforms)
314}
315
[email protected]cd565142012-06-12 16:21:45316// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40317std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46318 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17319 int net_error,
320 int os_error,
321 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40322 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45323 if (attempt_number)
324 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46325
[email protected]cd565142012-06-12 16:21:45326 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16327
[email protected]cd565142012-06-12 16:21:45328 if (os_error) {
329 dict->SetInteger("os_error", os_error);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47330#if defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45331 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04332 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08333 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
334 0, // Use the internal message table.
335 os_error,
336 0, // Use default language.
337 (LPWSTR)&error_string,
338 0, // Buffer size.
339 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01340 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45341 LocalFree(error_string);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47342#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
343 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46344#endif
[email protected]21526002010-05-16 19:42:46345 }
346
dchengc7eeda422015-12-26 03:56:48347 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45348}
[email protected]a9813302012-04-28 09:29:28349
[email protected]cd565142012-06-12 16:21:45350// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40351std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11352 int net_error,
353 int dns_error,
354 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40355 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45356 dict->SetInteger("net_error", net_error);
357 if (dns_error)
358 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48359 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36360}
[email protected]ee094b82010-08-24 15:55:51361
[email protected]cd565142012-06-12 16:21:45362// Creates NetLog parameters containing the information in a RequestInfo object,
Eric Orth70992982018-07-24 00:25:00363// along with the associated NetLogSource. Use NetLogRequestCallback() if the
364// request information is not specified via RequestInfo.
danakj22f90e72016-04-16 01:55:40365std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11366 const HostResolver::RequestInfo* info,
367 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40368 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20369
[email protected]cd565142012-06-12 16:21:45370 dict->SetString("host", info->host_port_pair().ToString());
371 dict->SetInteger("address_family",
372 static_cast<int>(info->address_family()));
373 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
374 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48375 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45376}
[email protected]b3601bc22012-02-21 21:23:20377
Eric Orth70992982018-07-24 00:25:00378// Creates NetLog parameters containing the information of the request. Use
379// NetLogRequestInfoCallback if the request is specified via RequestInfo.
380std::unique_ptr<base::Value> NetLogRequestCallback(
381 const HostPortPair& host,
382 NetLogCaptureMode /* capture_mode */) {
383 auto dict = std::make_unique<base::DictionaryValue>();
384
385 dict->SetString("host", host.ToString());
386 dict->SetInteger("address_family",
387 static_cast<int>(ADDRESS_FAMILY_UNSPECIFIED));
388 dict->SetBoolean("allow_cached_response", true);
389 dict->SetBoolean("is_speculative", false);
390 return std::move(dict);
391}
392
[email protected]cd565142012-06-12 16:21:45393// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40394std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19395 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11396 const std::string* host,
397 NetLogCaptureMode /* capture_mode */) {
Eric Orth70992982018-07-24 00:25:00398 auto dict = std::make_unique<base::DictionaryValue>();
estade5e5529d2015-05-21 20:59:11399 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45400 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48401 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45402}
[email protected]a9813302012-04-28 09:29:28403
[email protected]cd565142012-06-12 16:21:45404// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40405std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19406 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11407 RequestPriority priority,
408 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40409 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11410 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56411 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48412 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45413}
[email protected]b3601bc22012-02-21 21:23:20414
[email protected]cd565142012-06-12 16:21:45415// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40416std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11417 const DnsConfig* config,
418 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08419 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45420}
[email protected]b4481b222012-03-16 17:13:11421
danakj22f90e72016-04-16 01:55:40422std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11423 bool ipv6_available,
424 bool cached,
425 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40426 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37427 dict->SetBoolean("ipv6_available", ipv6_available);
428 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48429 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37430}
431
[email protected]0f292de02012-02-01 22:28:20432// The logging routines are defined here because some requests are resolved
433// without a Request object.
434
Eric Orth70992982018-07-24 00:25:00435// Logs when a request has just been started. Overloads for whether or not the
436// request information is specified via a RequestInfo object.
tfarina428341112016-09-22 13:38:20437void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20438 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00439 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
440 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20441}
Eric Orth70992982018-07-24 00:25:00442void LogStartRequest(const NetLogWithSource& source_net_log,
443 const HostPortPair& host) {
444 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
445 base::BindRepeating(&NetLogRequestCallback, host));
446}
[email protected]0f292de02012-02-01 22:28:20447
448// Logs when a request has just completed (before its callback is run).
Eric Orth70992982018-07-24 00:25:00449void LogFinishRequest(const NetLogWithSource& source_net_log, int net_error) {
xunjieli26f90452014-11-10 16:23:02450 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00451 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20452}
453
454// Logs when a request has been cancelled.
Eric Orth70992982018-07-24 00:25:00455void LogCancelRequest(const NetLogWithSource& source_net_log) {
mikecirone8b85c432016-09-08 19:11:00456 source_net_log.AddEvent(NetLogEventType::CANCELLED);
457 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20458}
459
[email protected]b59ff372009-07-15 22:04:32460//-----------------------------------------------------------------------------
461
[email protected]0f292de02012-02-01 22:28:20462// Keeps track of the highest priority.
463class PriorityTracker {
464 public:
[email protected]8c98d002012-07-18 19:02:27465 explicit PriorityTracker(RequestPriority initial_priority)
466 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20467 memset(counts_, 0, sizeof(counts_));
468 }
469
470 RequestPriority highest_priority() const {
471 return highest_priority_;
472 }
473
474 size_t total_count() const {
475 return total_count_;
476 }
477
478 void Add(RequestPriority req_priority) {
479 ++total_count_;
480 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05481 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20482 highest_priority_ = req_priority;
483 }
484
485 void Remove(RequestPriority req_priority) {
486 DCHECK_GT(total_count_, 0u);
487 DCHECK_GT(counts_[req_priority], 0u);
488 --total_count_;
489 --counts_[req_priority];
490 size_t i;
thestiga74ad2b2016-07-11 20:52:36491 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
492 }
[email protected]0f292de02012-02-01 22:28:20493 highest_priority_ = static_cast<RequestPriority>(i);
494
[email protected]31ae7ab2012-04-24 21:09:05495 // In absence of requests, default to MINIMUM_PRIORITY.
496 if (total_count_ == 0)
497 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20498 }
499
500 private:
501 RequestPriority highest_priority_;
502 size_t total_count_;
503 size_t counts_[NUM_PRIORITIES];
504};
505
juliatuttle9fb7aeb2016-06-06 20:16:33506void MakeNotStale(HostCache::EntryStaleness* stale_info) {
507 if (!stale_info)
508 return;
509 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
510 stale_info->network_changes = 0;
511 stale_info->stale_hits = 0;
512}
513
Paul Jensen41dc3e9f2018-11-06 22:10:10514// Is |dns_server| within the list of known DNS servers that also support
515// DNS-over-HTTPS?
516bool DnsServerSupportsDoh(const IPAddress& dns_server) {
Eric Orth192e3bb2018-11-14 19:30:32517 static const base::NoDestructor<std::unordered_set<std::string>>
Paul Jensen41dc3e9f2018-11-06 22:10:10518 upgradable_servers({
519 // Google Public DNS
520 "8.8.8.8", "8.8.4.4", "2001:4860:4860::8888", "2001:4860:4860::8844",
521 // Cloudflare DNS
522 "1.1.1.1", "1.0.0.1", "2606:4700:4700::1111", "2606:4700:4700::1001",
523 // Quad9 DNS
524 "9.9.9.9", "149.112.112.112", "2620:fe::fe", "2620:fe::9",
525 });
526 return upgradable_servers->find(dns_server.ToString()) !=
527 upgradable_servers->end();
528}
529
[email protected]c54a8912012-10-22 22:09:43530} // namespace
[email protected]0f292de02012-02-01 22:28:20531
532//-----------------------------------------------------------------------------
533
tfarina9ed7f8c52016-02-19 17:50:18534bool ResolveLocalHostname(base::StringPiece host,
535 uint16_t port,
536 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18537 address_list->clear();
538
539 bool is_local6;
540 if (!IsLocalHostname(host, &is_local6))
541 return false;
542
martijna23c8962016-03-04 18:18:51543 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18544 if (!is_local6) {
martijna23c8962016-03-04 18:18:51545 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18546 }
547
548 return true;
549}
550
[email protected]daae1322013-09-05 18:26:50551const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
552
Eric Roman91aab1e62018-04-24 20:31:32553// Holds the callback and request parameters for an outstanding request.
554//
555// The RequestImpl is owned by the end user of host resolution. Deletion prior
556// to the request having completed means the request was cancelled by the
557// caller.
558//
559// Both the RequestImpl and its associated Job hold non-owning pointers to each
560// other. Care must be taken to clear the corresponding pointer when
561// cancellation is initiated by the Job (OnJobCancelled) vs by the end user
562// (~RequestImpl).
David Benjamina5677192018-04-23 23:25:42563class HostResolverImpl::RequestImpl
Eric Orth70992982018-07-24 00:25:00564 : public HostResolver::ResolveHostRequest,
David Benjamina5677192018-04-23 23:25:42565 public base::LinkNode<HostResolverImpl::RequestImpl> {
[email protected]b59ff372009-07-15 22:04:32566 public:
tfarina428341112016-09-22 13:38:20567 RequestImpl(const NetLogWithSource& source_net_log,
Eric Orth70992982018-07-24 00:25:00568 const HostPortPair& request_host,
Eric Orth00fe5a62018-08-15 22:20:00569 const base::Optional<ResolveHostParameters>& optional_parameters,
Eric Orth70992982018-07-24 00:25:00570 base::WeakPtr<HostResolverImpl> resolver)
[email protected]ee094b82010-08-24 15:55:51571 : source_net_log_(source_net_log),
Eric Orth70992982018-07-24 00:25:00572 request_host_(request_host),
Eric Orth00fe5a62018-08-15 22:20:00573 parameters_(optional_parameters ? optional_parameters.value()
574 : ResolveHostParameters()),
Eric Orthdc35748e2018-08-23 22:41:48575 host_resolver_flags_(ParametersToHostResolverFlags(parameters_)),
Eric Orth00fe5a62018-08-15 22:20:00576 priority_(parameters_.initial_priority),
Eric Orth70992982018-07-24 00:25:00577 job_(nullptr),
578 resolver_(resolver),
579 complete_(false) {}
[email protected]b59ff372009-07-15 22:04:32580
maksim.sisov31452af2016-07-27 06:38:10581 ~RequestImpl() override;
582
Eric Orth70992982018-07-24 00:25:00583 int Start(CompletionOnceCallback callback) override {
584 DCHECK(callback);
585 // Start() may only be called once per request.
586 DCHECK(!job_);
587 DCHECK(!complete_);
588 DCHECK(!callback_);
589 // Parent HostResolver must still be alive to call Start().
590 DCHECK(resolver_);
maksim.sisov31452af2016-07-27 06:38:10591
Eric Orth70992982018-07-24 00:25:00592 int rv = resolver_->Resolve(this);
593 DCHECK(!complete_);
594 if (rv == ERR_IO_PENDING) {
595 DCHECK(job_);
596 callback_ = std::move(callback);
597 } else {
598 DCHECK(!job_);
599 complete_ = true;
600 }
601 resolver_ = nullptr;
602
603 return rv;
604 }
605
606 const base::Optional<AddressList>& GetAddressResults() const override {
607 DCHECK(complete_);
608 return address_results_;
609 }
610
611 void set_address_results(const AddressList& address_results) {
612 // Should only be called at most once and before request is marked
613 // completed.
614 DCHECK(!complete_);
615 DCHECK(!address_results_);
Eric Orthb30bc172018-08-17 21:09:57616 DCHECK(!parameters_.is_speculative);
Eric Orth70992982018-07-24 00:25:00617
618 address_results_ = address_results;
619 }
620
621 void ChangeRequestPriority(RequestPriority priority);
622
623 void AssignJob(Job* job) {
624 DCHECK(job);
625 DCHECK(!job_);
626
627 job_ = job;
628 }
629
630 // Unassigns the Job without calling completion callback.
maksim.sisov31452af2016-07-27 06:38:10631 void OnJobCancelled(Job* job) {
632 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04633 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00634 DCHECK(!complete_);
635 DCHECK(callback_);
[email protected]aa22b242011-11-16 18:58:29636 callback_.Reset();
Eric Orth70992982018-07-24 00:25:00637
638 // No results should be set.
639 DCHECK(!address_results_);
[email protected]b59ff372009-07-15 22:04:32640 }
641
Eric Orth70992982018-07-24 00:25:00642 // Cleans up Job assignment, marks request completed, and calls the completion
643 // callback.
644 void OnJobCompleted(Job* job, int error) {
maksim.sisov31452af2016-07-27 06:38:10645 DCHECK_EQ(job_, job);
maksim.sisov31452af2016-07-27 06:38:10646 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00647
648 DCHECK(!complete_);
649 complete_ = true;
650
651 DCHECK(callback_);
Bence Béky0f26a5812018-06-13 03:18:40652 std::move(callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32653 }
654
Eric Orth70992982018-07-24 00:25:00655 Job* job() const { return job_; }
[email protected]b59ff372009-07-15 22:04:32656
[email protected]0f292de02012-02-01 22:28:20657 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20658 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51659
Eric Orth70992982018-07-24 00:25:00660 const HostPortPair& request_host() const { return request_host_; }
661
Eric Orth00fe5a62018-08-15 22:20:00662 const ResolveHostParameters& parameters() const { return parameters_; }
663
Eric Orth322af3e42018-08-20 18:12:59664 HostResolverFlags host_resolver_flags() const { return host_resolver_flags_; }
665
[email protected]5109c1952013-08-20 18:44:10666 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31667 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10668
Eric Orth70992982018-07-24 00:25:00669 bool complete() const { return complete_; }
670
671 base::TimeTicks request_time() const {
672 DCHECK(!request_time_.is_null());
673 return request_time_;
674 }
675 void set_request_time(base::TimeTicks request_time) {
676 DCHECK(request_time_.is_null());
677 DCHECK(!request_time.is_null());
678 request_time_ = request_time;
679 }
[email protected]51b9a6b2012-06-25 21:50:29680
[email protected]b59ff372009-07-15 22:04:32681 private:
tfarina428341112016-09-22 13:38:20682 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09683
Eric Orth70992982018-07-24 00:25:00684 const HostPortPair request_host_;
Eric Orth00fe5a62018-08-15 22:20:00685 const ResolveHostParameters parameters_;
Eric Orth322af3e42018-08-20 18:12:59686 const HostResolverFlags host_resolver_flags_;
[email protected]5109c1952013-08-20 18:44:10687
juliatuttlec53b19a72016-05-05 13:51:31688 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32689
[email protected]0f292de02012-02-01 22:28:20690 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32691 Job* job_;
Eric Orth70992982018-07-24 00:25:00692 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]b59ff372009-07-15 22:04:32693
694 // The user's callback to invoke when the request completes.
Bence Béky0f26a5812018-06-13 03:18:40695 CompletionOnceCallback callback_;
[email protected]b59ff372009-07-15 22:04:32696
Eric Orth70992982018-07-24 00:25:00697 bool complete_;
698 base::Optional<AddressList> address_results_;
[email protected]b59ff372009-07-15 22:04:32699
Eric Orth70992982018-07-24 00:25:00700 base::TimeTicks request_time_;
[email protected]51b9a6b2012-06-25 21:50:29701
maksim.sisov31452af2016-07-27 06:38:10702 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32703};
704
Eric Orth70992982018-07-24 00:25:00705// Wraps a RequestImpl to implement Request objects from the legacy Resolve()
706// API. The wrapped request must not yet have been started.
707//
708// TODO(crbug.com/821021): Delete this class once all usage has been
709// converted to the new CreateRequest() API.
710class HostResolverImpl::LegacyRequestImpl : public HostResolver::Request {
711 public:
712 explicit LegacyRequestImpl(std::unique_ptr<RequestImpl> inner_request)
713 : inner_request_(std::move(inner_request)) {
714 DCHECK(!inner_request_->job());
715 DCHECK(!inner_request_->complete());
716 }
717
718 ~LegacyRequestImpl() override {}
719
720 void ChangeRequestPriority(RequestPriority priority) override {
721 inner_request_->ChangeRequestPriority(priority);
722 }
723
724 int Start() {
725 return inner_request_->Start(base::BindOnce(
726 &LegacyRequestImpl::LegacyApiCallback, base::Unretained(this)));
727 }
728
729 // Do not call to assign the callback until we are running an async job (after
730 // Start() returns ERR_IO_PENDING) and before completion. Until then, the
731 // legacy HostResolverImpl::Resolve() needs to hang onto |callback| to ensure
732 // it stays alive for the duration of the method call, as some callers may be
733 // binding objects, eg the AddressList, with the callback.
734 void AssignCallback(CompletionOnceCallback callback,
735 AddressList* addresses_result_ptr) {
736 DCHECK(callback);
737 DCHECK(addresses_result_ptr);
738 DCHECK(inner_request_->job());
739 DCHECK(!inner_request_->complete());
740
741 callback_ = std::move(callback);
742 addresses_result_ptr_ = addresses_result_ptr;
743 }
744
745 const RequestImpl& inner_request() const { return *inner_request_; }
746
747 private:
748 // Result callback to bridge results handled entirely via ResolveHostRequest
749 // to legacy API styles where AddressList was a separate method out parameter.
750 void LegacyApiCallback(int error) {
751 // Must call AssignCallback() before async results.
752 DCHECK(callback_);
753
Eric Orthb30bc172018-08-17 21:09:57754 if (error == OK && !inner_request_->parameters().is_speculative) {
Eric Orth70992982018-07-24 00:25:00755 // Legacy API does not allow non-address results (eg TXT), so AddressList
756 // is always expected to be present on OK.
757 DCHECK(inner_request_->GetAddressResults());
758 *addresses_result_ptr_ = inner_request_->GetAddressResults().value();
759 }
760 addresses_result_ptr_ = nullptr;
761 std::move(callback_).Run(error);
762 }
763
764 const std::unique_ptr<RequestImpl> inner_request_;
765
766 CompletionOnceCallback callback_;
767 // This is a caller-provided pointer and should not be used once |callback_|
768 // is invoked.
769 AddressList* addresses_result_ptr_;
770
771 DISALLOW_COPY_AND_ASSIGN(LegacyRequestImpl);
772};
773
[email protected]1e9bbd22010-10-15 16:42:45774//------------------------------------------------------------------------------
775
Francois Doraya2d01ba2017-09-25 19:17:40776// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20777//
Miriam Gershenson02592182018-03-22 17:42:37778// In non-test code, the HostResolverProc is always SystemHostResolverProc,
779// which calls a platform API that implements host resolution.
780//
[email protected]0f292de02012-02-01 22:28:20781// Whenever we try to resolve the host, we post a delayed task to check if host
782// resolution (OnLookupComplete) is completed or not. If the original attempt
783// hasn't completed, then we start another attempt for host resolution. We take
784// the results from the first attempt that finishes and ignore the results from
785// all other attempts.
786//
787// TODO(szym): Move to separate source file for testing and mocking.
788//
Eric Orth9a037562018-07-03 21:24:38789class HostResolverImpl::ProcTask {
[email protected]b59ff372009-07-15 22:04:32790 public:
Eric Orth9a037562018-07-03 21:24:38791 typedef base::OnceCallback<void(int net_error, const AddressList& addr_list)>
792 Callback;
[email protected]b59ff372009-07-15 22:04:32793
[email protected]0f292de02012-02-01 22:28:20794 ProcTask(const Key& key,
795 const ProcTaskParams& params,
Eric Orth9a037562018-07-03 21:24:38796 Callback callback,
Miriam Gershensone42adb22017-10-16 16:19:38797 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:02798 const NetLogWithSource& job_net_log,
799 const base::TickClock* tick_clock)
[email protected]0f292de02012-02-01 22:28:20800 : key_(key),
801 params_(params),
Eric Orth9a037562018-07-03 21:24:38802 callback_(std::move(callback)),
mmenke91c17162016-06-02 16:03:23803 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38804 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20805 attempt_number_(0),
Misha Efimovb99e7da2018-05-30 16:59:02806 net_log_(job_net_log),
Eric Orth9a037562018-07-03 21:24:38807 tick_clock_(tick_clock),
808 weak_ptr_factory_(this) {
Eric Orth192e3bb2018-11-14 19:30:32809 // ProcTask only supports resolving addresses.
810 DCHECK(IsAddressType(key_.dns_query_type));
811
Eric Orth9a037562018-07-03 21:24:38812 DCHECK(callback_);
[email protected]90499482013-06-01 00:39:50813 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20814 params_.resolver_proc = HostResolverProc::GetDefault();
815 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50816 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06817 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32818 }
819
Eric Orth9a037562018-07-03 21:24:38820 // Cancels this ProcTask. Any outstanding resolve attempts running on worker
821 // thread will continue running, but they will post back to the network thread
822 // before checking their WeakPtrs to find that this task is cancelled.
823 ~ProcTask() {
824 DCHECK(network_task_runner_->BelongsToCurrentThread());
825
826 // If this is cancellation, log the EndEvent (otherwise this was logged in
827 // OnLookupComplete()).
828 if (!was_completed())
829 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
830 }
831
[email protected]b59ff372009-07-15 22:04:32832 void Start() {
mmenke91c17162016-06-02 16:03:23833 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38834 DCHECK(!was_completed());
mikecirone8b85c432016-09-08 19:11:00835 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54836 StartLookupAttempt();
837 }
[email protected]252b699b2010-02-05 21:38:06838
Eric Orth9a037562018-07-03 21:24:38839 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23840 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20841 return callback_.is_null();
842 }
843
[email protected]0f292de02012-02-01 22:28:20844 private:
Eric Orth9a037562018-07-03 21:24:38845 using AttemptCompletionCallback = base::OnceCallback<
846 void(const AddressList& results, int error, const int os_error)>;
[email protected]a9813302012-04-28 09:29:28847
[email protected]189163e2011-05-11 01:48:54848 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23849 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38850 DCHECK(!was_completed());
Misha Efimovb99e7da2018-05-30 16:59:02851 base::TimeTicks start_time = tick_clock_->NowTicks();
[email protected]189163e2011-05-11 01:48:54852 ++attempt_number_;
853 // Dispatch the lookup attempt to a worker thread.
Eric Orth9a037562018-07-03 21:24:38854 AttemptCompletionCallback completion_callback = base::BindOnce(
855 &ProcTask::OnLookupAttemptComplete, weak_ptr_factory_.GetWeakPtr(),
856 start_time, attempt_number_, tick_clock_);
Miriam Gershensone42adb22017-10-16 16:19:38857 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40858 FROM_HERE,
Eric Orth9a037562018-07-03 21:24:38859 base::BindOnce(&ProcTask::DoLookup, key_, params_.resolver_proc,
860 network_task_runner_, std::move(completion_callback)));
[email protected]13024882011-05-18 23:19:16861
mikecirone8b85c432016-09-08 19:11:00862 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28863 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16864
mmenke91c17162016-06-02 16:03:23865 // If the results aren't received within a given time, RetryIfNotComplete
866 // will start a new attempt if none of the outstanding attempts have
867 // completed yet.
Eric Orth9a037562018-07-03 21:24:38868 // Use a WeakPtr to avoid keeping the ProcTask alive after completion or
869 // cancellation.
[email protected]0f292de02012-02-01 22:28:20870 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23871 network_task_runner_->PostDelayedTask(
Eric Orth9a037562018-07-03 21:24:38872 FROM_HERE,
873 base::BindOnce(&ProcTask::StartLookupAttempt,
874 weak_ptr_factory_.GetWeakPtr()),
875 params_.unresponsive_delay *
876 std::pow(params_.retry_factor, attempt_number_ - 1));
[email protected]06ef6d92011-05-19 04:24:58877 }
[email protected]b59ff372009-07-15 22:04:32878 }
879
Francois Doraya2d01ba2017-09-25 19:17:40880 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
881 // shutdown code cannot wait for it to finish, so this code must be very
882 // careful about using other objects (like MessageLoops, Singletons, etc).
Eric Orth9a037562018-07-03 21:24:38883 // During shutdown these objects may no longer exist.
884 static void DoLookup(
885 Key key,
886 scoped_refptr<HostResolverProc> resolver_proc,
887 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
888 AttemptCompletionCallback completion_callback) {
[email protected]189163e2011-05-11 01:48:54889 AddressList results;
890 int os_error = 0;
Eric Orth192e3bb2018-11-14 19:30:32891 int error = resolver_proc->Resolve(
892 key.hostname, DnsQueryTypeToAddressFamily(key.dns_query_type),
893 key.host_resolver_flags, &results, &os_error);
[email protected]b59ff372009-07-15 22:04:32894
Eric Orth9a037562018-07-03 21:24:38895 network_task_runner->PostTask(
896 FROM_HERE, base::BindOnce(std::move(completion_callback), results,
897 error, os_error));
[email protected]189163e2011-05-11 01:48:54898 }
899
Eric Orth9a037562018-07-03 21:24:38900 // Callback for when DoLookup() completes (runs on task runner thread). Now
901 // that we're back in the network thread, checks that |proc_task| is still
902 // valid, and if so, passes back to the object.
903 static void OnLookupAttemptComplete(base::WeakPtr<ProcTask> proc_task,
904 const base::TimeTicks& start_time,
905 const uint32_t attempt_number,
906 const base::TickClock* tick_clock,
907 const AddressList& results,
908 int error,
909 const int os_error) {
Alexandr Ilin33126632018-11-14 14:48:17910 TRACE_EVENT0(NetTracingCategory(), "ProcTask::OnLookupComplete");
Eric Orth9a037562018-07-03 21:24:38911
[email protected]49b70b222013-05-07 21:24:23912 // If results are empty, we should return an error.
913 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23914 if (empty_list_on_ok)
915 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54916
[email protected]2d3b7762010-10-09 00:35:47917 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20918 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23919 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54920 if (error != OK && NetworkChangeNotifier::IsOffline())
921 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47922
Paul Jensenb7352f92018-11-08 00:02:49923 if (!proc_task)
Luciano Pachecob4426082018-07-02 08:04:18924 return;
Eric Orth9a037562018-07-03 21:24:38925
926 proc_task->OnLookupComplete(results, start_time, attempt_number, error,
927 os_error);
928 }
929
930 void OnLookupComplete(const AddressList& results,
931 const base::TimeTicks& start_time,
932 const uint32_t attempt_number,
933 int error,
934 const int os_error) {
935 DCHECK(network_task_runner_->BelongsToCurrentThread());
936 DCHECK(!was_completed());
937
938 // Invalidate WeakPtrs to cancel handling of all outstanding lookup attempts
939 // and retries.
940 weak_ptr_factory_.InvalidateWeakPtrs();
941
Eric Orthcb8862f2018-06-27 18:08:35942 NetLogParametersCallback net_log_callback;
Eric Orth9a037562018-07-03 21:24:38943 NetLogParametersCallback attempt_net_log_callback;
[email protected]0f292de02012-02-01 22:28:20944 if (error != OK) {
Eric Orth70992982018-07-24 00:25:00945 net_log_callback = base::BindRepeating(&NetLogProcTaskFailedCallback, 0,
946 error, os_error);
947 attempt_net_log_callback = base::BindRepeating(
948 &NetLogProcTaskFailedCallback, attempt_number, error, os_error);
[email protected]ee094b82010-08-24 15:55:51949 } else {
Eric Orth9a037562018-07-03 21:24:38950 net_log_callback = results.CreateNetLogCallback();
951 attempt_net_log_callback =
952 NetLog::IntCallback("attempt_number", attempt_number);
[email protected]ee094b82010-08-24 15:55:51953 }
mikecirone8b85c432016-09-08 19:11:00954 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45955 net_log_callback);
Eric Orth9a037562018-07-03 21:24:38956 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
957 attempt_net_log_callback);
[email protected]ee094b82010-08-24 15:55:51958
Eric Orth9a037562018-07-03 21:24:38959 std::move(callback_).Run(error, results);
[email protected]b59ff372009-07-15 22:04:32960 }
961
[email protected]123ab1e32009-10-21 19:12:57962 Key key_;
[email protected]b59ff372009-07-15 22:04:32963
[email protected]0f292de02012-02-01 22:28:20964 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32965 // This may not be the current resolver procedure by the time we call
966 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
967 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20968 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32969
[email protected]0f292de02012-02-01 22:28:20970 // The listener to the results of this ProcTask.
971 Callback callback_;
972
mmenke91c17162016-06-02 16:03:23973 // Used to post events onto the network thread.
974 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:38975 // Used to post blocking HostResolverProc tasks.
976 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:54977
978 // Keeps track of the number of attempts we have made so far to resolve the
979 // host. Whenever we start an attempt to resolve the host, we increase this
980 // number.
Avi Drissman13fc8932015-12-20 04:40:46981 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54982
tfarina428341112016-09-22 13:38:20983 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51984
Misha Efimovb99e7da2018-05-30 16:59:02985 const base::TickClock* tick_clock_;
986
Eric Orth9a037562018-07-03 21:24:38987 // Used to loop back from the blocking lookup attempt tasks as well as from
988 // delayed retry tasks. Invalidate WeakPtrs on completion and cancellation to
989 // cancel handling of such posted tasks.
990 base::WeakPtrFactory<ProcTask> weak_ptr_factory_;
991
[email protected]0f292de02012-02-01 22:28:20992 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32993};
994
995//-----------------------------------------------------------------------------
996
Miriam Gershenson02592182018-03-22 17:42:37997// Resolves the hostname using DnsTransaction, which is a full implementation of
998// a DNS stub resolver. One DnsTransaction is created for each resolution
999// needed, which for AF_UNSPEC resolutions includes both A and AAAA. The
1000// transactions are scheduled separately and started separately.
1001//
[email protected]b3601bc22012-02-21 21:23:201002// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461003class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201004 public:
[email protected]daae1322013-09-05 18:26:501005 class Delegate {
1006 public:
1007 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1008 int net_error,
1009 const AddressList& addr_list,
1010 base::TimeDelta ttl) = 0;
1011
1012 // Called when the first of two jobs succeeds. If the first completed
1013 // transaction fails, this is not called. Also not called when the DnsTask
1014 // only needs to run one transaction.
1015 virtual void OnFirstDnsTransactionComplete() = 0;
1016
Brad Lassey786929ad2018-02-21 20:54:271017 virtual URLRequestContext* url_request_context() = 0;
1018 virtual RequestPriority priority() const = 0;
1019
[email protected]daae1322013-09-05 18:26:501020 protected:
Chris Watkins68b15032017-12-01 03:07:131021 Delegate() = default;
1022 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:501023 };
[email protected]b3601bc22012-02-21 21:23:201024
[email protected]0adcb2b2012-08-15 21:30:461025 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201026 const Key& key,
Eric Orth60931742018-11-05 23:40:571027 bool allow_fallback_resolution,
[email protected]daae1322013-09-05 18:26:501028 Delegate* delegate,
Misha Efimovb99e7da2018-05-30 16:59:021029 const NetLogWithSource& job_net_log,
1030 const base::TickClock* tick_clock)
[email protected]0adcb2b2012-08-15 21:30:461031 : client_(client),
[email protected]daae1322013-09-05 18:26:501032 key_(key),
Eric Orth60931742018-11-05 23:40:571033 allow_fallback_resolution_(allow_fallback_resolution),
[email protected]daae1322013-09-05 18:26:501034 delegate_(delegate),
1035 net_log_(job_net_log),
1036 num_completed_transactions_(0),
Misha Efimovb99e7da2018-05-30 16:59:021037 tick_clock_(tick_clock),
1038 task_start_time_(tick_clock_->NowTicks()) {
[email protected]0adcb2b2012-08-15 21:30:461039 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501040 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501041 }
1042
Eric Orth60931742018-11-05 23:40:571043 bool allow_fallback_resolution() const { return allow_fallback_resolution_; }
1044
[email protected]daae1322013-09-05 18:26:501045 bool needs_two_transactions() const {
Eric Orth192e3bb2018-11-14 19:30:321046 return key_.dns_query_type == DnsQueryType::UNSPECIFIED;
[email protected]daae1322013-09-05 18:26:501047 }
1048
1049 bool needs_another_transaction() const {
Eric Orth192e3bb2018-11-14 19:30:321050 return needs_two_transactions() && !transaction2_;
[email protected]daae1322013-09-05 18:26:501051 }
1052
1053 void StartFirstTransaction() {
1054 DCHECK_EQ(0u, num_completed_transactions_);
Eric Orth192e3bb2018-11-14 19:30:321055 DCHECK(!transaction1_);
1056
mikecirone8b85c432016-09-08 19:11:001057 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
Eric Orth192e3bb2018-11-14 19:30:321058 if (key_.dns_query_type == DnsQueryType::UNSPECIFIED) {
1059 transaction1_ = CreateTransaction(DnsQueryType::A);
[email protected]daae1322013-09-05 18:26:501060 } else {
Eric Orth192e3bb2018-11-14 19:30:321061 transaction1_ = CreateTransaction(key_.dns_query_type);
[email protected]daae1322013-09-05 18:26:501062 }
Eric Orth192e3bb2018-11-14 19:30:321063 transaction1_->Start();
[email protected]daae1322013-09-05 18:26:501064 }
1065
1066 void StartSecondTransaction() {
Eric Orth192e3bb2018-11-14 19:30:321067 DCHECK(needs_another_transaction());
1068 transaction2_ = CreateTransaction(DnsQueryType::AAAA);
1069 transaction2_->Start();
[email protected]70c04ab2013-08-22 16:05:121070 }
1071
Brad Lassey2e8f185d2018-05-21 22:25:211072 base::TimeDelta ttl() { return ttl_; }
1073
[email protected]70c04ab2013-08-22 16:05:121074 private:
Eric Orth192e3bb2018-11-14 19:30:321075 std::unique_ptr<DnsTransaction> CreateTransaction(
1076 DnsQueryType dns_query_type) {
1077 DCHECK_NE(DnsQueryType::UNSPECIFIED, dns_query_type);
Brad Lassey786929ad2018-02-21 20:54:271078 std::unique_ptr<DnsTransaction> trans =
1079 client_->GetTransactionFactory()->CreateTransaction(
Eric Orth192e3bb2018-11-14 19:30:321080 key_.hostname, DnsQueryTypeToQtype(dns_query_type),
Brad Lasseydba0a84b2018-02-23 22:18:531081 base::BindOnce(&DnsTask::OnTransactionComplete,
Misha Efimovb99e7da2018-05-30 16:59:021082 base::Unretained(this), tick_clock_->NowTicks()),
Brad Lassey786929ad2018-02-21 20:54:271083 net_log_);
1084 trans->SetRequestContext(delegate_->url_request_context());
1085 trans->SetRequestPriority(delegate_->priority());
1086 return trans;
[email protected]daae1322013-09-05 18:26:501087 }
1088
1089 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001090 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201091 int net_error,
1092 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471093 DCHECK(transaction);
Misha Efimovb99e7da2018-05-30 16:59:021094 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Brad Lassey2e8f185d2018-05-21 22:25:211095 if (net_error != OK && !(net_error == ERR_NAME_NOT_RESOLVED && response &&
1096 response->IsValid())) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211097 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461098 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1099 return;
[email protected]6c411902012-08-14 22:36:361100 }
[email protected]0adcb2b2012-08-15 21:30:461101
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211102 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511103 switch (transaction->GetType()) {
1104 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211105 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511106 break;
1107 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211108 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1109 duration);
[email protected]02cd6982013-01-10 20:12:511110 break;
1111 }
[email protected]daae1322013-09-05 18:26:501112
[email protected]0adcb2b2012-08-15 21:30:461113 AddressList addr_list;
1114 base::TimeDelta ttl;
1115 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1116 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1117 result,
1118 DnsResponse::DNS_PARSE_RESULT_MAX);
1119 if (result != DnsResponse::DNS_PARSE_OK) {
1120 // Fail even if the other query succeeds.
1121 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1122 return;
1123 }
1124
[email protected]daae1322013-09-05 18:26:501125 ++num_completed_transactions_;
1126 if (num_completed_transactions_ == 1) {
1127 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461128 } else {
[email protected]daae1322013-09-05 18:26:501129 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461130 }
1131
[email protected]daae1322013-09-05 18:26:501132 if (transaction->GetType() == dns_protocol::kTypeA) {
Eric Orth192e3bb2018-11-14 19:30:321133 DCHECK_EQ(transaction1_.get(), transaction);
[email protected]daae1322013-09-05 18:26:501134 // Place IPv4 addresses after IPv6.
1135 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
Eric Orth192e3bb2018-11-14 19:30:321136 } else if (transaction->GetType() == dns_protocol::kTypeAAAA) {
[email protected]daae1322013-09-05 18:26:501137 // Place IPv6 addresses before IPv4.
1138 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
Eric Orth192e3bb2018-11-14 19:30:321139 } else {
1140 // TODO(crbug.com/846423): Add result parsing for non-address types.
1141 NOTIMPLEMENTED();
[email protected]daae1322013-09-05 18:26:501142 }
1143
Asanka Herath2d0226c2018-10-24 14:35:551144 // If requested via HOST_RESOLVER_CANONNAME, store the canonical name from
1145 // the response. Prefer the name from the AAAA response. Only look at name
1146 // if there is at least one address record.
1147 if ((key_.host_resolver_flags & HOST_RESOLVER_CANONNAME) != 0 &&
1148 !addr_list.empty() &&
1149 (transaction->GetType() == dns_protocol::kTypeAAAA ||
1150 addr_list_.canonical_name().empty())) {
1151 addr_list_.set_canonical_name(addr_list.canonical_name());
1152 }
1153
[email protected]daae1322013-09-05 18:26:501154 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1155 // No need to repeat the suffix search.
1156 key_.hostname = transaction->GetHostname();
1157 delegate_->OnFirstDnsTransactionComplete();
1158 return;
1159 }
1160
1161 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121162 // TODO(szym): Don't fallback to ProcTask in this case.
1163 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461164 return;
1165 }
1166
[email protected]daae1322013-09-05 18:26:501167 // If there are multiple addresses, and at least one is IPv6, need to sort
1168 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1169 // sufficient to just check the family of the first address.
1170 if (addr_list_.size() > 1 &&
1171 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1172 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461173 client_->GetAddressSorter()->Sort(
Bence Békyd5e474c2018-08-02 18:45:081174 addr_list_, base::BindOnce(&DnsTask::OnSortComplete, AsWeakPtr(),
1175 tick_clock_->NowTicks()));
[email protected]0adcb2b2012-08-15 21:30:461176 } else {
[email protected]daae1322013-09-05 18:26:501177 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461178 }
1179 }
1180
1181 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461182 bool success,
1183 const AddressList& addr_list) {
1184 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211185 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
Misha Efimovb99e7da2018-05-30 16:59:021186 tick_clock_->NowTicks() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461187 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1188 return;
1189 }
1190
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211191 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
Misha Efimovb99e7da2018-05-30 16:59:021192 tick_clock_->NowTicks() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461193
1194 // AddressSorter prunes unusable destinations.
1195 if (addr_list.empty()) {
1196 LOG(WARNING) << "Address list empty after RFC3484 sort";
1197 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1198 return;
1199 }
1200
[email protected]daae1322013-09-05 18:26:501201 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461202 }
1203
1204 void OnFailure(int net_error, DnsResponse::Result result) {
1205 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451206 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001207 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451208 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
Brad Lassey2e8f185d2018-05-21 22:25:211209 base::TimeDelta ttl = ttl_ < base::TimeDelta::FromSeconds(
1210 std::numeric_limits<uint32_t>::max()) &&
1211 num_completed_transactions_ > 0
1212 ? ttl_
1213 : base::TimeDelta::FromSeconds(0);
Miriam Gershenson66024d72017-12-05 04:30:321214 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
Brad Lassey2e8f185d2018-05-21 22:25:211215 ttl);
[email protected]b3601bc22012-02-21 21:23:201216 }
1217
[email protected]daae1322013-09-05 18:26:501218 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001219 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461220 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501221 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461222 }
1223
1224 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501225 Key key_;
1226
Eric Orth60931742018-11-05 23:40:571227 // Whether resolution may fallback to other task types (e.g. ProcTask) on
1228 // failure of this task.
1229 bool allow_fallback_resolution_;
1230
[email protected]b3601bc22012-02-21 21:23:201231 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501232 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201233 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201234
Eric Orth192e3bb2018-11-14 19:30:321235 std::unique_ptr<DnsTransaction> transaction1_;
1236 std::unique_ptr<DnsTransaction> transaction2_;
[email protected]0adcb2b2012-08-15 21:30:461237
[email protected]daae1322013-09-05 18:26:501238 unsigned num_completed_transactions_;
1239
1240 // These are updated as each transaction completes.
1241 base::TimeDelta ttl_;
1242 // IPv6 addresses must appear first in the list.
1243 AddressList addr_list_;
1244
Misha Efimovb99e7da2018-05-30 16:59:021245 const base::TickClock* tick_clock_;
[email protected]daae1322013-09-05 18:26:501246 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461247
1248 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201249};
1250
1251//-----------------------------------------------------------------------------
1252
[email protected]0f292de02012-02-01 22:28:201253// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501254class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1255 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391256 public:
[email protected]0f292de02012-02-01 22:28:201257 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351258 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181259 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201260 const Key& key,
[email protected]8c98d002012-07-18 19:02:271261 RequestPriority priority,
Miriam Gershensone42adb22017-10-16 16:19:381262 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:021263 const NetLogWithSource& source_net_log,
1264 const base::TickClock* tick_clock)
[email protected]12faa4c2012-11-06 04:44:181265 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201266 key_(key),
[email protected]8c98d002012-07-18 19:02:271267 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381268 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201269 had_non_speculative_request_(false),
[email protected]daae1322013-09-05 18:26:501270 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331271 dns_task_error_(OK),
Misha Efimovb99e7da2018-05-30 16:59:021272 tick_clock_(tick_clock),
tfarina428341112016-09-22 13:38:201273 net_log_(
1274 NetLogWithSource::Make(source_net_log.net_log(),
Eric Orth60931742018-11-05 23:40:571275 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)),
1276 weak_ptr_factory_(this) {
mikecirone8b85c432016-09-08 19:11:001277 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201278
mikecirone8b85c432016-09-08 19:11:001279 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1280 base::Bind(&NetLogJobCreationCallback,
1281 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391282 }
1283
dchengb03027d2014-10-21 12:00:201284 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201285 if (is_running()) {
1286 // |resolver_| was destroyed with this Job still in flight.
1287 // Clean-up, record in the log, but don't run any callbacks.
Eric Orth9a037562018-07-03 21:24:381288 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351289 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501290 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001291 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201292 ERR_ABORTED);
1293 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551294 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351295 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001296 net_log_.AddEvent(NetLogEventType::CANCELLED);
1297 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391298 }
[email protected]b3601bc22012-02-21 21:23:201299 // else CompleteRequests logged EndEvent.
David Benjamina5677192018-04-23 23:25:421300 while (!requests_.empty()) {
maksim.sisov31452af2016-07-27 06:38:101301 // Log any remaining Requests as cancelled.
David Benjamina5677192018-04-23 23:25:421302 RequestImpl* req = requests_.head()->value();
1303 req->RemoveFromList();
1304 DCHECK_EQ(this, req->job());
Eric Orth70992982018-07-24 00:25:001305 LogCancelRequest(req->source_net_log());
David Benjamina5677192018-04-23 23:25:421306 req->OnJobCancelled(this);
[email protected]b3601bc22012-02-21 21:23:201307 }
[email protected]68ad3ee2010-01-30 03:45:391308 }
1309
[email protected]daae1322013-09-05 18:26:501310 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1311 // of the queue.
1312 void Schedule(bool at_head) {
1313 DCHECK(!is_queued());
1314 PrioritizedDispatcher::Handle handle;
1315 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001316 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501317 } else {
[email protected]106ccd2c2014-06-17 09:21:001318 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501319 }
1320 // The dispatcher could have started |this| in the above call to Add, which
1321 // could have called Schedule again. In that case |handle| will be null,
1322 // but |handle_| may have been set by the other nested call to Schedule.
1323 if (!handle.is_null()) {
1324 DCHECK(handle_.is_null());
1325 handle_ = handle;
1326 }
[email protected]16ee26d2012-03-08 03:34:351327 }
1328
maksim.sisov31452af2016-07-27 06:38:101329 void AddRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001330 DCHECK_EQ(key_.hostname, request->request_host().host());
1331
1332 request->AssignJob(this);
[email protected]0f292de02012-02-01 22:28:201333
maksim.sisov31452af2016-07-27 06:38:101334 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201335
maksim.sisov31452af2016-07-27 06:38:101336 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001337 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451338 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201339
1340 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001341 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101342 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451343 priority()));
[email protected]0f292de02012-02-01 22:28:201344
Eric Orthb30bc172018-08-17 21:09:571345 if (!request->parameters().is_speculative)
[email protected]0f292de02012-02-01 22:28:201346 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201347
David Benjamina5677192018-04-23 23:25:421348 requests_.Append(request);
[email protected]b3601bc22012-02-21 21:23:201349
[email protected]51b9a6b2012-06-25 21:50:291350 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391351 }
1352
maksim.sisov31452af2016-07-27 06:38:101353 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
Eric Orth70992982018-07-24 00:25:001354 DCHECK_EQ(key_.hostname, req->request_host().host());
juliatuttlec53b19a72016-05-05 13:51:311355
1356 priority_tracker_.Remove(req->priority());
1357 req->set_priority(priority);
1358 priority_tracker_.Add(req->priority());
1359 UpdatePriority();
1360 }
1361
maksim.sisov31452af2016-07-27 06:38:101362 // Detach cancelled request. If it was the last active Request, also finishes
1363 // this Job.
1364 void CancelRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001365 DCHECK_EQ(key_.hostname, request->request_host().host());
maksim.sisov31452af2016-07-27 06:38:101366 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351367
Eric Orth70992982018-07-24 00:25:001368 LogCancelRequest(request->source_net_log());
[email protected]16ee26d2012-03-08 03:34:351369
maksim.sisov31452af2016-07-27 06:38:101370 priority_tracker_.Remove(request->priority());
1371 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001372 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101373 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1374 priority()));
[email protected]b3601bc22012-02-21 21:23:201375
[email protected]16ee26d2012-03-08 03:34:351376 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291377 UpdatePriority();
David Benjamina5677192018-04-23 23:25:421378 request->RemoveFromList();
[email protected]16ee26d2012-03-08 03:34:351379 } else {
1380 // If we were called from a Request's callback within CompleteRequests,
1381 // that Request could not have been cancelled, so num_active_requests()
1382 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431383 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201384 }
[email protected]68ad3ee2010-01-30 03:45:391385 }
1386
[email protected]7af985a2012-12-14 22:40:421387 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1388 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111389 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201390 void Abort() {
[email protected]0f292de02012-02-01 22:28:201391 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421392 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201393 }
1394
Eric Orth60931742018-11-05 23:40:571395 // Gets a closure that will abort a DnsTask (see AbortDnsTask()) iff |this| is
1396 // still valid. Useful if aborting a list of Jobs as some may be cancelled
1397 // while aborting others.
1398 base::OnceClosure GetAbortDnsTaskClosure(int error, bool fallback_only) {
1399 return base::BindOnce(&Job::AbortDnsTask, weak_ptr_factory_.GetWeakPtr(),
1400 error, fallback_only);
1401 }
1402
1403 // If DnsTask present, abort it. Depending on task settings, either fall back
1404 // to ProcTask or abort the job entirely. Warning, aborting a job may cause
1405 // other jobs to be aborted, thus |jobs_| may be unpredictably changed by
1406 // calling this method.
1407 //
1408 // |error| is the net error that will be returned to requests if this method
1409 // results in completely aborting the job.
1410 void AbortDnsTask(int error, bool fallback_only) {
[email protected]f0f602bd2012-11-15 18:01:021411 if (dns_task_) {
Eric Orth60931742018-11-05 23:40:571412 if (dns_task_->allow_fallback_resolution()) {
1413 KillDnsTask();
1414 dns_task_error_ = OK;
1415 StartProcTask();
1416 } else if (!fallback_only) {
1417 CompleteRequestsWithError(error);
1418 }
[email protected]f0f602bd2012-11-15 18:01:021419 }
1420 }
1421
[email protected]16ee26d2012-03-08 03:34:351422 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1423 // Completes all requests and destroys the job.
1424 void OnEvicted() {
1425 DCHECK(!is_running());
1426 DCHECK(is_queued());
1427 handle_.Reset();
1428
mikecirone8b85c432016-09-08 19:11:001429 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351430
1431 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431432 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351433 }
1434
[email protected]78eac2a2012-03-14 19:09:271435 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1436 // this Job was destroyed.
1437 bool ServeFromHosts() {
1438 DCHECK_GT(num_active_requests(), 0u);
1439 AddressList addr_list;
Eric Orth70992982018-07-24 00:25:001440 if (resolver_->ServeFromHosts(
1441 key(), requests_.head()->value()->request_host().port(),
1442 &addr_list)) {
[email protected]78eac2a2012-03-14 19:09:271443 // This will destroy the Job.
Rob Percival94f21ad2017-11-14 10:20:241444 CompleteRequests(
1445 MakeCacheEntry(OK, addr_list, HostCache::Entry::SOURCE_HOSTS),
Eric Orth9871aafa2018-10-02 19:59:181446 base::TimeDelta(), true /* allow_cache */);
[email protected]78eac2a2012-03-14 19:09:271447 return true;
1448 }
1449 return false;
1450 }
1451
tanay.c6ddd5f6f2015-08-25 06:34:571452 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111453
1454 bool is_queued() const {
1455 return !handle_.is_null();
1456 }
1457
1458 bool is_running() const {
Eric Orth9871aafa2018-10-02 19:59:181459 return is_dns_running() || is_mdns_running() || is_proc_running();
[email protected]b4481b222012-03-16 17:13:111460 }
1461
[email protected]16ee26d2012-03-08 03:34:351462 private:
[email protected]daae1322013-09-05 18:26:501463 void KillDnsTask() {
1464 if (dns_task_) {
1465 ReduceToOneJobSlot();
1466 dns_task_.reset();
1467 }
1468 }
1469
1470 // Reduce the number of job slots occupied and queued in the dispatcher
1471 // to one. If the second Job slot is queued in the dispatcher, cancels the
1472 // queued job. Otherwise, the second Job has been started by the
1473 // PrioritizedDispatcher, so signals it is complete.
1474 void ReduceToOneJobSlot() {
1475 DCHECK_GE(num_occupied_job_slots_, 1u);
1476 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001477 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501478 handle_.Reset();
1479 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001480 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501481 --num_occupied_job_slots_;
1482 }
1483 DCHECK_EQ(1u, num_occupied_job_slots_);
1484 }
1485
eroman0cd87b62016-12-14 19:13:451486 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1487 // HostCache::Entry(). The address list is omited from the cache entry
1488 // for errors.
1489 HostCache::Entry MakeCacheEntry(int net_error,
Rob Percival94f21ad2017-11-14 10:20:241490 const AddressList& addr_list,
1491 HostCache::Entry::Source source) const {
eroman0cd87b62016-12-14 19:13:451492 return HostCache::Entry(
1493 net_error,
Rob Percival94f21ad2017-11-14 10:20:241494 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1495 source);
eroman0cd87b62016-12-14 19:13:451496 }
1497
1498 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1499 const AddressList& addr_list,
Rob Percival94f21ad2017-11-14 10:20:241500 HostCache::Entry::Source source,
eroman0cd87b62016-12-14 19:13:451501 base::TimeDelta ttl) const {
1502 return HostCache::Entry(
1503 net_error,
1504 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
Rob Percival94f21ad2017-11-14 10:20:241505 source, ttl);
eroman0cd87b62016-12-14 19:13:451506 }
1507
juliatuttlec53b19a72016-05-05 13:51:311508 AddressList MakeAddressListForRequest(const AddressList& list) const {
1509 if (requests_.empty())
1510 return list;
Eric Orth70992982018-07-24 00:25:001511 return AddressList::CopyWithPort(
1512 list, requests_.head()->value()->request_host().port());
juliatuttlec53b19a72016-05-05 13:51:311513 }
1514
[email protected]51b9a6b2012-06-25 21:50:291515 void UpdatePriority() {
Paul Jensenb7352f92018-11-08 00:02:491516 if (is_queued())
[email protected]106ccd2c2014-06-17 09:21:001517 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291518 }
1519
[email protected]16ee26d2012-03-08 03:34:351520 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201521 void Start() override {
[email protected]daae1322013-09-05 18:26:501522 DCHECK_LE(num_occupied_job_slots_, 1u);
1523
[email protected]70c04ab2013-08-22 16:05:121524 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501525 ++num_occupied_job_slots_;
1526
1527 if (num_occupied_job_slots_ == 2) {
1528 StartSecondDnsTransaction();
1529 return;
1530 }
1531
1532 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201533
mikecirone8b85c432016-09-08 19:11:001534 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201535
Misha Efimovb99e7da2018-05-30 16:59:021536 start_time_ = tick_clock_->NowTicks();
[email protected]51b9a6b2012-06-25 21:50:291537
Eric Orthdc35748e2018-08-23 22:41:481538 switch (key_.host_resolver_source) {
1539 case HostResolverSource::ANY:
Eric Orth60931742018-11-05 23:40:571540 if (!ResemblesMulticastDNSName(key_.hostname)) {
1541 StartDnsTask(true /* allow_fallback_resolution */);
Eric Orthdc35748e2018-08-23 22:41:481542 } else {
1543 StartProcTask();
1544 }
1545 break;
1546 case HostResolverSource::SYSTEM:
1547 StartProcTask();
1548 break;
1549 case HostResolverSource::DNS:
Eric Orth60931742018-11-05 23:40:571550 StartDnsTask(false /* allow_fallback_resolution */);
Eric Orthdc35748e2018-08-23 22:41:481551 break;
Eric Orth9871aafa2018-10-02 19:59:181552 case HostResolverSource::MULTICAST_DNS:
1553 StartMdnsTask();
1554 break;
Eric Orthdc35748e2018-08-23 22:41:481555 }
[email protected]443714fad2013-09-19 04:52:011556
[email protected]1d932852012-06-19 19:40:331557 // Caution: Job::Start must not complete synchronously.
[email protected]b3601bc22012-02-21 21:23:201558 }
1559
[email protected]b3601bc22012-02-21 21:23:201560 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401561 // the limits on |dispatcher_|. But in order to keep the number of
1562 // TaskScheduler threads low, we will need to use an "inner"
1563 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201564 void StartProcTask() {
Eric Orth9871aafa2018-10-02 19:59:181565 DCHECK(!is_running());
Eric Orth9a037562018-07-03 21:24:381566 proc_task_ = std::make_unique<ProcTask>(
Misha Efimovb99e7da2018-05-30 16:59:021567 key_, resolver_->proc_params_,
Eric Orth70992982018-07-24 00:25:001568 base::BindOnce(&Job::OnProcTaskComplete, base::Unretained(this),
1569 tick_clock_->NowTicks()),
Misha Efimovb99e7da2018-05-30 16:59:021570 proc_task_runner_, net_log_, tick_clock_);
[email protected]0f292de02012-02-01 22:28:201571
[email protected]0f292de02012-02-01 22:28:201572 // Start() could be called from within Resolve(), hence it must NOT directly
1573 // call OnProcTaskComplete, for example, on synchronous failure.
1574 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391575 }
1576
[email protected]0f292de02012-02-01 22:28:201577 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371578 void OnProcTaskComplete(base::TimeTicks start_time,
1579 int net_error,
1580 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201581 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391582
[email protected]1d932852012-06-19 19:40:331583 if (dns_task_error_ != OK) {
Eric Orth60931742018-11-05 23:40:571584 // This ProcTask was a fallback resolution after a failed DnsTask.
Misha Efimovb99e7da2018-05-30 16:59:021585 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]1def74c2012-03-22 20:07:001586 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211587 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331588 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1589 ResemblesNetBIOSName(key_.hostname)) {
1590 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1591 } else {
1592 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1593 }
Ilya Sherman0eb39802017-12-08 20:58:181594 base::UmaHistogramSparse("Net.DNS.DnsTask.Errors",
1595 std::abs(dns_task_error_));
Eric Orth60931742018-11-05 23:40:571596 resolver_->OnFallbackResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001597 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211598 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001599 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1600 }
1601 }
1602
eroman1efc237c2016-12-14 00:00:451603 if (ContainsIcannNameCollisionIp(addr_list))
1604 net_error = ERR_ICANN_NAME_COLLISION;
1605
[email protected]1339a2a22012-10-17 08:39:431606 base::TimeDelta ttl =
1607 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201608 if (net_error == OK)
1609 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391610
Rob Percival94f21ad2017-11-14 10:20:241611 // Source unknown because the system resolver could have gotten it from a
1612 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171613 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241614 CompleteRequests(
1615 MakeCacheEntry(net_error, addr_list, HostCache::Entry::SOURCE_UNKNOWN),
Eric Orth9871aafa2018-10-02 19:59:181616 ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201617 }
1618
Eric Orth60931742018-11-05 23:40:571619 void StartDnsTask(bool allow_fallback_resolution) {
1620 if ((!resolver_->HaveDnsConfig() || resolver_->use_proctask_by_default_) &&
1621 allow_fallback_resolution) {
1622 // DnsClient or config is not available, but we're allowed to switch to
1623 // ProcTask instead.
1624 StartProcTask();
1625 return;
1626 }
[email protected]b3601bc22012-02-21 21:23:201627
Eric Orth60931742018-11-05 23:40:571628 // Need to create the task even if we're going to post a failure instead of
1629 // running it, as a "started" job needs a task to be properly cleaned up.
1630 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_,
1631 allow_fallback_resolution, this, net_log_,
1632 tick_clock_));
1633
1634 if (resolver_->HaveDnsConfig()) {
1635 dns_task_->StartFirstTransaction();
1636 // Schedule a second transaction, if needed.
1637 if (dns_task_->needs_two_transactions())
1638 Schedule(true);
1639 } else {
1640 // Cannot start a DNS task when DnsClient or config is not available.
1641 // Since we cannot complete synchronously from here, post a failure.
1642 base::SequencedTaskRunnerHandle::Get()->PostTask(
1643 FROM_HERE,
1644 base::BindOnce(&Job::OnDnsTaskFailure, weak_ptr_factory_.GetWeakPtr(),
1645 dns_task_->AsWeakPtr(), base::TimeDelta(),
1646 ERR_FAILED));
1647 }
[email protected]daae1322013-09-05 18:26:501648 }
1649
1650 void StartSecondDnsTransaction() {
1651 DCHECK(dns_task_->needs_two_transactions());
1652 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221653 }
1654
1655 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1656 // deleted before this callback. In this case dns_task is deleted as well,
1657 // so we use it as indicator whether Job is still valid.
1658 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1659 base::TimeDelta duration,
1660 int net_error) {
Miriam Gershenson61604662017-09-28 23:51:111661 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221662
wezb9820d42016-06-22 23:41:041663 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221664 return;
1665
Miriam Gershenson19faef812018-02-07 23:56:441666 if (duration < base::TimeDelta::FromMilliseconds(10)) {
1667 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Fast",
1668 std::abs(net_error));
1669 } else {
1670 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Slow",
1671 std::abs(net_error));
1672 }
[email protected]16c2bd72013-06-28 01:19:221673 dns_task_error_ = net_error;
1674
1675 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1676 // http://crbug.com/117655
1677
1678 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1679 // ProcTask in that case is a waste of time.
Eric Orth60931742018-11-05 23:40:571680 if (resolver_->allow_fallback_to_proctask_ &&
1681 dns_task->allow_fallback_resolution()) {
[email protected]daae1322013-09-05 18:26:501682 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221683 StartProcTask();
1684 } else {
1685 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Brad Lassey2e8f185d2018-05-21 22:25:211686 // If the ttl is max, we didn't get one from the record, so set it to 0
1687 base::TimeDelta ttl =
1688 dns_task->ttl() < base::TimeDelta::FromSeconds(
1689 std::numeric_limits<uint32_t>::max())
1690 ? dns_task->ttl()
1691 : base::TimeDelta::FromSeconds(0);
1692 CompleteRequests(
1693 HostCache::Entry(net_error, AddressList(),
1694 HostCache::Entry::Source::SOURCE_UNKNOWN, ttl),
Eric Orth9871aafa2018-10-02 19:59:181695 ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201696 }
1697 }
1698
[email protected]daae1322013-09-05 18:26:501699 // HostResolverImpl::DnsTask::Delegate implementation:
1700
dchengb03027d2014-10-21 12:00:201701 void OnDnsTaskComplete(base::TimeTicks start_time,
1702 int net_error,
1703 const AddressList& addr_list,
1704 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201705 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201706
Misha Efimovb99e7da2018-05-30 16:59:021707 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]b3601bc22012-02-21 21:23:201708 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221709 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201710 return;
1711 }
Miriam Gershenson61604662017-09-28 23:51:111712
1713 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201714
[email protected]1def74c2012-03-22 20:07:001715 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431716 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461717
Eric Orth60931742018-11-05 23:40:571718 resolver_->OnDnsTaskResolve();
[email protected]f0f602bd2012-11-15 18:01:021719
[email protected]895123222012-10-25 15:21:171720 base::TimeDelta bounded_ttl =
1721 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1722
eroman0cd87b62016-12-14 19:13:451723 if (ContainsIcannNameCollisionIp(addr_list)) {
1724 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1725 } else {
Rob Percival94f21ad2017-11-14 10:20:241726 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list,
1727 HostCache::Entry::SOURCE_DNS, ttl),
Eric Orth9871aafa2018-10-02 19:59:181728 bounded_ttl, true /* allow_cache */);
eroman0cd87b62016-12-14 19:13:451729 }
[email protected]b3601bc22012-02-21 21:23:201730 }
1731
dchengb03027d2014-10-21 12:00:201732 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501733 DCHECK(dns_task_->needs_two_transactions());
1734 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1735 // No longer need to occupy two dispatcher slots.
1736 ReduceToOneJobSlot();
1737
1738 // We already have a job slot at the dispatcher, so if the second
1739 // transaction hasn't started, reuse it now instead of waiting in the queue
1740 // for the second slot.
1741 if (dns_task_->needs_another_transaction())
1742 dns_task_->StartSecondTransaction();
1743 }
1744
Eric Orth9871aafa2018-10-02 19:59:181745 void StartMdnsTask() {
1746 DCHECK(!is_running());
1747
1748 // No flags are supported for MDNS except
1749 // HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6 (which is not actually an
1750 // input flag).
1751 DCHECK_EQ(0, key_.host_resolver_flags &
1752 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
1753
Eric Orth192e3bb2018-11-14 19:30:321754 std::vector<DnsQueryType> query_types;
1755 if (key_.dns_query_type == DnsQueryType::UNSPECIFIED) {
1756 query_types.push_back(DnsQueryType::A);
1757 query_types.push_back(DnsQueryType::AAAA);
1758 } else {
1759 query_types.push_back(key_.dns_query_type);
Eric Orth9871aafa2018-10-02 19:59:181760 }
1761
1762 mdns_task_ = std::make_unique<HostResolverMdnsTask>(
1763 resolver_->GetOrCreateMdnsClient(), key_.hostname, query_types);
1764 mdns_task_->Start(
1765 base::BindOnce(&Job::OnMdnsTaskComplete, base::Unretained(this)));
1766 }
1767
1768 void OnMdnsTaskComplete(int error) {
1769 DCHECK(is_mdns_running());
1770 // TODO(crbug.com/846423): Consider adding MDNS-specific logging.
1771
1772 if (error != OK) {
1773 CompleteRequestsWithError(error);
1774 } else if (ContainsIcannNameCollisionIp(mdns_task_->result_addresses())) {
1775 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1776 } else {
1777 // MDNS uses a separate cache, so skip saving result to cache.
1778 // TODO(crbug.com/846423): Consider merging caches.
1779 CompleteRequestsWithoutCache(error, mdns_task_->result_addresses());
1780 }
1781 }
1782
Brad Lassey786929ad2018-02-21 20:54:271783 URLRequestContext* url_request_context() override {
1784 return resolver_->url_request_context_;
1785 }
1786
Miriam Gershenson61604662017-09-28 23:51:111787 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581788 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1789 // deprecated values.
1790 enum Category {
1791 RESOLVE_SUCCESS = 0,
1792 RESOLVE_FAIL = 1,
1793 RESOLVE_SPECULATIVE_SUCCESS = 2,
1794 RESOLVE_SPECULATIVE_FAIL = 3,
1795 RESOLVE_ABORT = 4,
1796 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111797 RESOLVE_MAX, // Bounding value.
1798 };
1799 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1800
Misha Efimovb99e7da2018-05-30 16:59:021801 base::TimeDelta duration = tick_clock_->NowTicks() - start_time_;
Miriam Gershenson61604662017-09-28 23:51:111802 if (error == OK) {
1803 if (had_non_speculative_request_) {
1804 category = RESOLVE_SUCCESS;
1805 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
Eric Orth192e3bb2018-11-14 19:30:321806 switch (key_.dns_query_type) {
1807 case DnsQueryType::A:
Miriam Gershenson61604662017-09-28 23:51:111808 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1809 duration);
1810 break;
Eric Orth192e3bb2018-11-14 19:30:321811 case DnsQueryType::AAAA:
Miriam Gershenson61604662017-09-28 23:51:111812 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1813 duration);
1814 break;
Eric Orth192e3bb2018-11-14 19:30:321815 case DnsQueryType::UNSPECIFIED:
Miriam Gershenson61604662017-09-28 23:51:111816 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1817 duration);
1818 break;
Eric Orth192e3bb2018-11-14 19:30:321819 default:
1820 // No histogram for other query types.
1821 break;
Miriam Gershenson61604662017-09-28 23:51:111822 }
1823 } else {
1824 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111825 }
Miriam Gershensonc282ab42017-11-20 23:19:581826 } else if (error == ERR_NETWORK_CHANGED ||
1827 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1828 category = had_non_speculative_request_ ? RESOLVE_ABORT
1829 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111830 } else {
1831 if (had_non_speculative_request_) {
1832 category = RESOLVE_FAIL;
1833 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
Eric Orth192e3bb2018-11-14 19:30:321834 switch (key_.dns_query_type) {
1835 case DnsQueryType::A:
Miriam Gershensonc282ab42017-11-20 23:19:581836 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111837 duration);
1838 break;
Eric Orth192e3bb2018-11-14 19:30:321839 case DnsQueryType::AAAA:
Miriam Gershensonc282ab42017-11-20 23:19:581840 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111841 duration);
1842 break;
Eric Orth192e3bb2018-11-14 19:30:321843 case DnsQueryType::UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581844 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111845 duration);
1846 break;
Eric Orth192e3bb2018-11-14 19:30:321847 default:
1848 // No histogram for other query types.
1849 break;
Miriam Gershenson61604662017-09-28 23:51:111850 }
1851 } else {
1852 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111853 }
1854 }
1855 DCHECK_LT(static_cast<int>(category),
1856 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1857 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061858
1859 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1860 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181861 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061862 else
Ilya Sherman0eb39802017-12-08 20:58:181863 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061864 }
Miriam Gershenson61604662017-09-28 23:51:111865 }
1866
[email protected]16ee26d2012-03-08 03:34:351867 // Performs Job's last rites. Completes all Requests. Deletes this.
Eric Orth9871aafa2018-10-02 19:59:181868 //
1869 // If not |allow_cache|, result will not be stored in the host cache, even if
1870 // result would otherwise allow doing so.
[email protected]895123222012-10-25 15:21:171871 void CompleteRequests(const HostCache::Entry& entry,
Eric Orth9871aafa2018-10-02 19:59:181872 base::TimeDelta ttl,
1873 bool allow_cache) {
[email protected]11fbca0b2013-06-02 23:37:211874 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201875
[email protected]16ee26d2012-03-08 03:34:351876 // This job must be removed from resolver's |jobs_| now to make room for a
1877 // new job with the same key in case one of the OnComplete callbacks decides
Eric Orth18544ae2018-06-11 22:57:161878 // to spawn one. Consequently, if the job was owned by |jobs_|, the job
1879 // deletes itself when CompleteRequests is done.
1880 std::unique_ptr<Job> self_deleter = resolver_->RemoveJob(this);
[email protected]16ee26d2012-03-08 03:34:351881
[email protected]16ee26d2012-03-08 03:34:351882 if (is_running()) {
Eric Orth9a037562018-07-03 21:24:381883 proc_task_ = nullptr;
[email protected]daae1322013-09-05 18:26:501884 KillDnsTask();
Eric Orth9871aafa2018-10-02 19:59:181885 mdns_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351886
1887 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001888 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351889 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001890 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351891 handle_.Reset();
1892 }
1893
1894 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001895 net_log_.AddEvent(NetLogEventType::CANCELLED);
1896 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351897 OK);
1898 return;
1899 }
[email protected]b3601bc22012-02-21 21:23:201900
mikecirone8b85c432016-09-08 19:11:001901 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221902 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391903
[email protected]78eac2a2012-03-14 19:09:271904 DCHECK(!requests_.empty());
1905
eroman1efc237c2016-12-14 00:00:451906 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191907 // Record this histogram here, when we know the system has a valid DNS
1908 // configuration.
[email protected]539df6c2012-06-19 21:21:291909 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1910 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191911 }
[email protected]16ee26d2012-03-08 03:34:351912
juliatuttle317860e2016-05-12 14:47:221913 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1914 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Eric Orth9871aafa2018-10-02 19:59:181915 if (did_complete && allow_cache)
[email protected]1339a2a22012-10-17 08:39:431916 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581917
1918 RecordJobHistograms(entry.error());
[email protected]16ee26d2012-03-08 03:34:351919
maksim.sisov31452af2016-07-27 06:38:101920 // Complete all of the requests that were attached to the job and
1921 // detach them.
1922 while (!requests_.empty()) {
David Benjamina5677192018-04-23 23:25:421923 RequestImpl* req = requests_.head()->value();
1924 req->RemoveFromList();
[email protected]0f292de02012-02-01 22:28:201925 DCHECK_EQ(this, req->job());
1926 // Update the net log and notify registered observers.
Eric Orth70992982018-07-24 00:25:001927 LogFinishRequest(req->source_net_log(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291928 if (did_complete) {
1929 // Record effective total time from creation to completion.
Paul Jensen41dc3e9f2018-11-06 22:10:101930 resolver_->RecordTotalTime(
1931 req->parameters().is_speculative, false /* from_cache */,
1932 tick_clock_->NowTicks() - req->request_time());
[email protected]51b9a6b2012-06-25 21:50:291933 }
Eric Orthb30bc172018-08-17 21:09:571934 if (entry.error() == OK && !req->parameters().is_speculative) {
Eric Orth70992982018-07-24 00:25:001935 req->set_address_results(EnsurePortOnAddressList(
1936 entry.addresses(), req->request_host().port()));
1937 }
1938 req->OnJobCompleted(this, entry.error());
[email protected]0f292de02012-02-01 22:28:201939
1940 // Check if the resolver was destroyed as a result of running the
1941 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211942 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201943 return;
1944 }
1945 }
1946
Eric Orth9871aafa2018-10-02 19:59:181947 void CompleteRequestsWithoutCache(int error, const AddressList& addresses) {
1948 CompleteRequests(
1949 MakeCacheEntry(error, addresses, HostCache::Entry::SOURCE_UNKNOWN),
1950 base::TimeDelta(), false /* allow_cache */);
1951 }
1952
[email protected]1339a2a22012-10-17 08:39:431953 // Convenience wrapper for CompleteRequests in case of failure.
1954 void CompleteRequestsWithError(int net_error) {
Rob Percival94f21ad2017-11-14 10:20:241955 CompleteRequests(HostCache::Entry(net_error, AddressList(),
1956 HostCache::Entry::SOURCE_UNKNOWN),
Eric Orth9871aafa2018-10-02 19:59:181957 base::TimeDelta(), true /* allow_cache */);
[email protected]1339a2a22012-10-17 08:39:431958 }
1959
Brad Lassey786929ad2018-02-21 20:54:271960 RequestPriority priority() const override {
[email protected]b4481b222012-03-16 17:13:111961 return priority_tracker_.highest_priority();
1962 }
1963
1964 // Number of non-canceled requests in |requests_|.
1965 size_t num_active_requests() const {
1966 return priority_tracker_.total_count();
1967 }
1968
wezb9820d42016-06-22 23:41:041969 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111970
Eric Orth9871aafa2018-10-02 19:59:181971 bool is_mdns_running() const { return !!mdns_task_; }
1972
wezb9820d42016-06-22 23:41:041973 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111974
[email protected]0f292de02012-02-01 22:28:201975 base::WeakPtr<HostResolverImpl> resolver_;
1976
1977 Key key_;
1978
1979 // Tracks the highest priority across |requests_|.
1980 PriorityTracker priority_tracker_;
1981
Miriam Gershensone42adb22017-10-16 16:19:381982 // Task runner used for HostResolverProc.
1983 scoped_refptr<base::TaskRunner> proc_task_runner_;
1984
[email protected]0f292de02012-02-01 22:28:201985 bool had_non_speculative_request_;
1986
[email protected]daae1322013-09-05 18:26:501987 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1988 unsigned num_occupied_job_slots_;
1989
[email protected]1d932852012-06-19 19:40:331990 // Result of DnsTask.
1991 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001992
Misha Efimovb99e7da2018-05-30 16:59:021993 const base::TickClock* tick_clock_;
Miriam Gershenson61604662017-09-28 23:51:111994 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:291995
tfarina428341112016-09-22 13:38:201996 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201997
[email protected]b3601bc22012-02-21 21:23:201998 // Resolves the host using a HostResolverProc.
Eric Orth9a037562018-07-03 21:24:381999 std::unique_ptr<ProcTask> proc_task_;
[email protected]0f292de02012-02-01 22:28:202000
[email protected]b3601bc22012-02-21 21:23:202001 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:402002 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:202003
Eric Orth9871aafa2018-10-02 19:59:182004 // Resolves the host using MDnsClient.
2005 std::unique_ptr<HostResolverMdnsTask> mdns_task_;
2006
[email protected]0f292de02012-02-01 22:28:202007 // All Requests waiting for the result of this Job. Some can be canceled.
David Benjamina5677192018-04-23 23:25:422008 base::LinkedList<RequestImpl> requests_;
[email protected]0f292de02012-02-01 22:28:202009
[email protected]16ee26d2012-03-08 03:34:352010 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:202011 PrioritizedDispatcher::Handle handle_;
Eric Orth60931742018-11-05 23:40:572012
2013 base::WeakPtrFactory<Job> weak_ptr_factory_;
[email protected]68ad3ee2010-01-30 03:45:392014};
2015
2016//-----------------------------------------------------------------------------
2017
[email protected]0f292de02012-02-01 22:28:202018HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:432019 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:202020 size_t max_retry_attempts)
2021 : resolver_proc(resolver_proc),
2022 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:442023 unresponsive_delay(
2024 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:202025 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:002026 // Maximum of 4 retry attempts for host resolution.
2027 static const size_t kDefaultMaxRetryAttempts = 4u;
2028 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
2029 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:202030}
2031
vmpstracd23b72016-02-26 21:08:552032HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
2033 default;
2034
Chris Watkins68b15032017-12-01 03:07:132035HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:202036
Francois Doraya2d01ba2017-09-25 19:17:402037HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:232038 : max_queued_jobs_(0),
2039 proc_params_(NULL, options.max_retry_attempts),
2040 net_log_(net_log),
2041 received_dns_config_(false),
2042 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:032043 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:232044 use_local_ipv6_(false),
2045 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:232046 additional_resolver_flags_(0),
Eric Orth60931742018-11-05 23:40:572047 use_proctask_by_default_(false),
2048 allow_fallback_to_proctask_(true),
Brad Lassey73e67ee2018-05-31 00:11:592049 url_request_context_(nullptr),
Misha Efimovb99e7da2018-05-30 16:59:022050 tick_clock_(base::DefaultTickClock::GetInstance()),
mmenke91c17162016-06-02 16:03:232051 weak_ptr_factory_(this),
2052 probe_weak_ptr_factory_(this) {
2053 if (options.enable_caching)
2054 cache_ = HostCache::CreateDefaultCache();
2055
2056 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2057 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2058 max_queued_jobs_ = job_limits.total_jobs * 100u;
2059
2060 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2061
Miriam Gershensone42adb22017-10-16 16:19:382062 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
Maks Orlovich5393c8682018-02-26 16:17:502063 {base::MayBlock(), priority_mode.Get(),
2064 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
Miriam Gershensone42adb22017-10-16 16:19:382065
mmenke91c17162016-06-02 16:03:232066#if defined(OS_WIN)
2067 EnsureWinsockInit();
2068#endif
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472069#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2070 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232071 RunLoopbackProbeJob();
2072#endif
Paul Jensenf47bbab2018-09-14 16:34:042073 NetworkChangeNotifier::AddIPAddressObserver(this);
2074 NetworkChangeNotifier::AddConnectionTypeObserver(this);
mmenke91c17162016-06-02 16:03:232075 NetworkChangeNotifier::AddDNSObserver(this);
2076#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Fabrice de Gans-Riberi65421f62018-05-22 23:16:182077 !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232078 EnsureDnsReloaderInit();
2079#endif
2080
Paul Jensenf47bbab2018-09-14 16:34:042081 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
mmenke91c17162016-06-02 16:03:232082
2083 {
Eric Orthe366fe62018-10-24 16:38:312084 DnsConfig dns_config = GetBaseDnsConfig();
mmenke91c17162016-06-02 16:03:232085 received_dns_config_ = dns_config.IsValid();
2086 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2087 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
Paul Jensen41dc3e9f2018-11-06 22:10:102088 UpdateModeForHistogram(dns_config);
mmenke91c17162016-06-02 16:03:232089 }
2090
Eric Orth60931742018-11-05 23:40:572091 allow_fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
mmenke91c17162016-06-02 16:03:232092}
2093
Eric Orth70992982018-07-24 00:25:002094HostResolverImpl::~HostResolverImpl() {
2095 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2096 // Prevent the dispatcher from starting new jobs.
2097 dispatcher_->SetLimitsToZero();
2098 // It's now safe for Jobs to call KillDnsTask on destruction, because
2099 // OnJobComplete will not start any new jobs.
2100 jobs_.clear();
2101
Paul Jensenf47bbab2018-09-14 16:34:042102 NetworkChangeNotifier::RemoveIPAddressObserver(this);
2103 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
Eric Orth70992982018-07-24 00:25:002104 NetworkChangeNotifier::RemoveDNSObserver(this);
mmenke91c17162016-06-02 16:03:232105}
2106
Eric Orth70992982018-07-24 00:25:002107void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
2108 // DnsClient and config must be updated before aborting DnsTasks, since doing
2109 // so may start new jobs.
2110 dns_client_ = std::move(dns_client);
2111 if (dns_client_ && !dns_client_->GetConfig() &&
2112 num_dns_failures_ < kMaximumDnsFailures) {
Eric Orthc823a23d2018-10-30 22:12:482113 DnsConfig dns_config;
2114 // Skip retrieving the base config if all values will be overridden.
2115 if (!dns_config_overrides_.OverridesEverything())
2116 dns_config = GetBaseDnsConfig();
Eric Orthc1eb1292018-10-09 22:07:072117 DnsConfig overridden_config =
2118 dns_config_overrides_.ApplyOverrides(dns_config);
2119 dns_client_->SetConfig(overridden_config);
Eric Orth70992982018-07-24 00:25:002120 num_dns_failures_ = 0;
2121 if (dns_client_->GetConfig())
2122 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2123 }
2124
Eric Orth60931742018-11-05 23:40:572125 AbortDnsTasks(ERR_NETWORK_CHANGED, false /* fallback_only */);
Findite5a94e02018-07-13 21:56:212126}
2127
Eric Orth70992982018-07-24 00:25:002128std::unique_ptr<HostResolver::ResolveHostRequest>
Eric Orth00fe5a62018-08-15 22:20:002129HostResolverImpl::CreateRequest(
2130 const HostPortPair& host,
2131 const NetLogWithSource& net_log,
2132 const base::Optional<ResolveHostParameters>& optional_parameters) {
2133 return std::make_unique<RequestImpl>(net_log, host, optional_parameters,
Eric Orth00fe5a62018-08-15 22:20:002134 weak_ptr_factory_.GetWeakPtr());
Eric Orth70992982018-07-24 00:25:002135}
2136
2137int HostResolverImpl::Resolve(const RequestInfo& info,
2138 RequestPriority priority,
2139 AddressList* addresses,
2140 CompletionOnceCallback callback,
2141 std::unique_ptr<Request>* out_req,
2142 const NetLogWithSource& source_net_log) {
2143 DCHECK(addresses);
2144 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2145 DCHECK(callback);
2146 DCHECK(out_req);
2147
2148 auto request = std::make_unique<RequestImpl>(
Eric Orth00fe5a62018-08-15 22:20:002149 source_net_log, info.host_port_pair(),
2150 RequestInfoToResolveHostParameters(info, priority),
Eric Orthb30bc172018-08-17 21:09:572151 weak_ptr_factory_.GetWeakPtr());
Eric Orth70992982018-07-24 00:25:002152 auto wrapped_request =
2153 std::make_unique<LegacyRequestImpl>(std::move(request));
2154
2155 int rv = wrapped_request->Start();
2156
Eric Orthb30bc172018-08-17 21:09:572157 if (rv == OK && !info.is_speculative()) {
Eric Orth70992982018-07-24 00:25:002158 DCHECK(wrapped_request->inner_request().GetAddressResults());
2159 *addresses = wrapped_request->inner_request().GetAddressResults().value();
2160 } else if (rv == ERR_IO_PENDING) {
2161 wrapped_request->AssignCallback(std::move(callback), addresses);
2162 *out_req = std::move(wrapped_request);
Eric Orthfac527992018-07-13 21:11:162163 }
2164
Eric Orth70992982018-07-24 00:25:002165 return rv;
[email protected]95a214c2011-08-04 21:50:402166}
2167
2168int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2169 AddressList* addresses,
tfarina428341112016-09-22 13:38:202170 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432171 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402172 DCHECK(addresses);
2173
[email protected]95a214c2011-08-04 21:50:402174 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022175 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402176
Matt Menke23b4bbf82017-07-20 19:11:292177 Key key;
Eric Orth70992982018-07-24 00:25:002178 int rv = ResolveLocally(
Eric Orth00fe5a62018-08-15 22:20:002179 info.host_port_pair(), AddressFamilyToDnsQueryType(info.address_family()),
Eric Orthdc35748e2018-08-23 22:41:482180 FlagsToSource(info.host_resolver_flags()), info.host_resolver_flags(),
2181 info.allow_cached_response(), false /* allow_stale */,
2182 nullptr /* stale_info */, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402183
Eric Orth70992982018-07-24 00:25:002184 LogFinishRequest(source_net_log, rv);
2185 return rv;
2186}
2187
2188int HostResolverImpl::ResolveStaleFromCache(
2189 const RequestInfo& info,
2190 AddressList* addresses,
2191 HostCache::EntryStaleness* stale_info,
2192 const NetLogWithSource& source_net_log) {
2193 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2194 DCHECK(addresses);
2195 DCHECK(stale_info);
2196
2197 // Update the net log and notify registered observers.
2198 LogStartRequest(source_net_log, info);
2199
2200 Key key;
Eric Orth00fe5a62018-08-15 22:20:002201 int rv = ResolveLocally(
2202 info.host_port_pair(), AddressFamilyToDnsQueryType(info.address_family()),
Eric Orthdc35748e2018-08-23 22:41:482203 FlagsToSource(info.host_resolver_flags()), info.host_resolver_flags(),
2204 info.allow_cached_response(), true /* allow_stale */, stale_info,
2205 source_net_log, addresses, &key);
Eric Orth70992982018-07-24 00:25:002206 LogFinishRequest(source_net_log, rv);
[email protected]95a214c2011-08-04 21:50:402207 return rv;
2208}
2209
[email protected]a8883e452012-11-17 05:58:062210void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432211 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062212#if defined(ENABLE_BUILT_IN_DNS)
2213 if (enabled && !dns_client_) {
2214 SetDnsClient(DnsClient::CreateClient(net_log_));
2215 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402216 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062217 }
2218#endif
2219}
2220
[email protected]489d1a82011-10-12 03:09:112221HostCache* HostResolverImpl::GetHostCache() {
2222 return cache_.get();
2223}
[email protected]95a214c2011-08-04 21:50:402224
Rob Percivalbc658a22017-12-13 08:24:422225bool HostResolverImpl::HasCached(base::StringPiece hostname,
2226 HostCache::Entry::Source* source_out,
2227 HostCache::EntryStaleness* stale_out) const {
2228 if (!cache_)
2229 return false;
2230
2231 return cache_->HasEntry(hostname, source_out, stale_out);
2232}
2233
danakj22f90e72016-04-16 01:55:402234std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242235 // Check if async DNS is disabled.
2236 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082237 return nullptr;
[email protected]17e92032012-03-29 00:56:242238
2239 // Check if async DNS is enabled, but we currently have no configuration
2240 // for it.
2241 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042242 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192243 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242244
2245 return dns_config->ToValue();
2246}
2247
Miriam Gershenson2839ef112017-08-30 03:25:372248size_t HostResolverImpl::LastRestoredCacheSize() const {
2249 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2250
2251 return cache_ ? cache_->last_restore_size() : 0;
2252}
2253
2254size_t HostResolverImpl::CacheSize() const {
2255 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2256
2257 return cache_ ? cache_->size() : 0;
2258}
2259
mgershaf9a9232017-04-13 20:19:032260void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432261 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032262 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2263}
2264
2265bool HostResolverImpl::GetNoIPv6OnWifi() {
2266 return assume_ipv6_failure_on_wifi_;
2267}
2268
Eric Orthc1eb1292018-10-09 22:07:072269void HostResolverImpl::SetDnsConfigOverrides(
2270 const DnsConfigOverrides& overrides) {
2271 if (dns_config_overrides_ == overrides)
2272 return;
2273
2274 dns_config_overrides_ = overrides;
Eric Orthc823a23d2018-10-30 22:12:482275 if (dns_client_.get())
Eric Orthc1eb1292018-10-09 22:07:072276 UpdateDNSConfig(true);
2277}
2278
Brad Lassey786929ad2018-02-21 20:54:272279void HostResolverImpl::SetRequestContext(URLRequestContext* context) {
2280 if (context != url_request_context_) {
2281 url_request_context_ = context;
2282 }
2283}
2284
Matt Menkeb67c0a8e2018-06-14 22:41:042285const std::vector<DnsConfig::DnsOverHttpsServerConfig>*
2286HostResolverImpl::GetDnsOverHttpsServersForTesting() const {
Eric Orthc1eb1292018-10-09 22:07:072287 if (!dns_config_overrides_.dns_over_https_servers ||
2288 dns_config_overrides_.dns_over_https_servers.value().empty()) {
Matt Menkeb67c0a8e2018-06-14 22:41:042289 return nullptr;
Eric Orthc1eb1292018-10-09 22:07:072290 }
2291 return &dns_config_overrides_.dns_over_https_servers.value();
Matt Menkeb67c0a8e2018-06-14 22:41:042292}
2293
Eric Orth70992982018-07-24 00:25:002294void HostResolverImpl::SetTickClockForTesting(
2295 const base::TickClock* tick_clock) {
2296 tick_clock_ = tick_clock;
2297 cache_->set_tick_clock_for_testing(tick_clock);
2298}
2299
2300void HostResolverImpl::SetMaxQueuedJobsForTesting(size_t value) {
2301 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
2302 DCHECK_GE(value, 0u);
2303 max_queued_jobs_ = value;
2304}
2305
2306void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2307 if (result) {
2308 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2309 } else {
2310 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2311 }
2312}
2313
Eric Orth9871aafa2018-10-02 19:59:182314void HostResolverImpl::SetMdnsSocketFactoryForTesting(
2315 std::unique_ptr<MDnsSocketFactory> socket_factory) {
2316 DCHECK(!mdns_client_);
2317 mdns_socket_factory_ = std::move(socket_factory);
2318}
2319
2320void HostResolverImpl::SetMdnsClientForTesting(
2321 std::unique_ptr<MDnsClient> client) {
2322 mdns_client_ = std::move(client);
2323}
2324
Eric Orthe366fe62018-10-24 16:38:312325void HostResolverImpl::SetBaseDnsConfigForTesting(
2326 const DnsConfig& base_config) {
2327 test_base_config_ = base_config;
2328 UpdateDNSConfig(true);
2329}
2330
Eric Orth70992982018-07-24 00:25:002331void HostResolverImpl::SetTaskRunnerForTesting(
2332 scoped_refptr<base::TaskRunner> task_runner) {
2333 proc_task_runner_ = std::move(task_runner);
2334}
2335
2336int HostResolverImpl::Resolve(RequestImpl* request) {
2337 // Request should not yet have a scheduled Job.
2338 DCHECK(!request->job());
2339 // Request may only be resolved once.
2340 DCHECK(!request->complete());
Eric Orth9871aafa2018-10-02 19:59:182341 // MDNS requests do not support skipping cache.
2342 // TODO(crbug.com/846423): Either add support for skipping the MDNS cache, or
2343 // merge to use the normal host cache for MDNS requests.
2344 DCHECK(request->parameters().source != HostResolverSource::MULTICAST_DNS ||
2345 request->parameters().allow_cached_response);
Eric Orth70992982018-07-24 00:25:002346
2347 request->set_request_time(tick_clock_->NowTicks());
2348
2349 LogStartRequest(request->source_net_log(), request->request_host());
2350
2351 AddressList addresses;
2352 Key key;
Eric Orth00fe5a62018-08-15 22:20:002353 int rv = ResolveLocally(
2354 request->request_host(), request->parameters().dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482355 request->parameters().source, request->host_resolver_flags(),
2356 request->parameters().allow_cached_response, false /* allow_stale */,
2357 nullptr /* stale_info */, request->source_net_log(), &addresses, &key);
Eric Orthb30bc172018-08-17 21:09:572358 if (rv == OK && !request->parameters().is_speculative) {
Eric Orth70992982018-07-24 00:25:002359 request->set_address_results(
2360 EnsurePortOnAddressList(addresses, request->request_host().port()));
2361 }
2362 if (rv != ERR_DNS_CACHE_MISS) {
2363 LogFinishRequest(request->source_net_log(), rv);
Eric Orthb30bc172018-08-17 21:09:572364 RecordTotalTime(request->parameters().is_speculative, true /* from_cache */,
Eric Orth70992982018-07-24 00:25:002365 base::TimeDelta());
2366 return rv;
2367 }
2368
2369 rv = CreateAndStartJob(key, request);
2370 // At this point, expect only async or errors.
2371 DCHECK_NE(OK, rv);
2372
2373 return rv;
2374}
2375
2376int HostResolverImpl::ResolveLocally(const HostPortPair& host,
Eric Orth00fe5a62018-08-15 22:20:002377 DnsQueryType dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482378 HostResolverSource source,
Eric Orth70992982018-07-24 00:25:002379 HostResolverFlags flags,
2380 bool allow_cache,
2381 bool allow_stale,
2382 HostCache::EntryStaleness* stale_info,
2383 const NetLogWithSource& source_net_log,
2384 AddressList* addresses,
2385 Key* key) {
2386 IPAddress ip_address;
2387 IPAddress* ip_address_ptr = nullptr;
2388 if (ip_address.AssignFromIPLiteral(host.host())) {
2389 ip_address_ptr = &ip_address;
2390 } else {
2391 // Check that the caller supplied a valid hostname to resolve.
2392 if (!IsValidDNSDomain(host.host()))
2393 return ERR_NAME_NOT_RESOLVED;
2394 }
2395
2396 // Build a key that identifies the request in the cache and in the
2397 // outstanding jobs map.
Eric Orthdc35748e2018-08-23 22:41:482398 *key = GetEffectiveKeyForRequest(host.host(), dns_query_type, source, flags,
Eric Orth70992982018-07-24 00:25:002399 ip_address_ptr, source_net_log);
2400
2401 DCHECK(allow_stale == !!stale_info);
2402 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2403 // On Windows it gives the default interface's address, whereas on Linux it
2404 // gives an error. We will make it fail on all platforms for consistency.
2405 if (host.host().empty() || host.host().size() > kMaxHostLength) {
2406 MakeNotStale(stale_info);
2407 return ERR_NAME_NOT_RESOLVED;
2408 }
2409
2410 int net_error = ERR_UNEXPECTED;
2411 if (ResolveAsIP(*key, host.port(), ip_address_ptr, &net_error, addresses)) {
2412 MakeNotStale(stale_info);
2413 return net_error;
2414 }
2415
2416 // Special-case localhost names, as per the recommendations in
2417 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2418 if (ServeLocalhost(*key, host.port(), addresses)) {
2419 MakeNotStale(stale_info);
2420 return OK;
2421 }
2422
2423 if (allow_cache && ServeFromCache(*key, host.port(), &net_error, addresses,
2424 allow_stale, stale_info)) {
2425 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2426 addresses->CreateNetLogCallback());
2427 // |ServeFromCache()| will set |*stale_info| as needed.
2428 return net_error;
2429 }
2430
2431 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2432 // http://crbug.com/117655
2433 if (ServeFromHosts(*key, host.port(), addresses)) {
2434 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2435 addresses->CreateNetLogCallback());
2436 MakeNotStale(stale_info);
2437 return OK;
2438 }
2439
2440 return ERR_DNS_CACHE_MISS;
2441}
2442
2443int HostResolverImpl::CreateAndStartJob(const Key& key, RequestImpl* request) {
2444 auto jobit = jobs_.find(key);
2445 Job* job;
2446 if (jobit == jobs_.end()) {
2447 auto new_job = std::make_unique<Job>(
2448 weak_ptr_factory_.GetWeakPtr(), key, request->priority(),
2449 proc_task_runner_, request->source_net_log(), tick_clock_);
2450 job = new_job.get();
2451 new_job->Schedule(false);
2452
2453 // Check for queue overflow.
2454 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
2455 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
2456 DCHECK(evicted);
2457 evicted->OnEvicted();
2458 if (evicted == new_job.get()) {
2459 LogFinishRequest(request->source_net_log(),
2460 ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
2461 return ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
2462 }
2463 }
2464 jobs_[key] = std::move(new_job);
2465 } else {
2466 job = jobit->second.get();
2467 }
2468
2469 // Can't complete synchronously. Attach request and job to each other.
2470 job->AddRequest(request);
2471 return ERR_IO_PENDING;
2472}
2473
[email protected]95a214c2011-08-04 21:50:402474bool HostResolverImpl::ResolveAsIP(const Key& key,
Eric Orth70992982018-07-24 00:25:002475 uint16_t host_port,
martijna23c8962016-03-04 18:18:512476 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402477 int* net_error,
2478 AddressList* addresses) {
2479 DCHECK(addresses);
2480 DCHECK(net_error);
Eric Orth192e3bb2018-11-14 19:30:322481 if (ip_address == nullptr || !IsAddressType(key.dns_query_type))
[email protected]95a214c2011-08-04 21:50:402482 return false;
2483
[email protected]95a214c2011-08-04 21:50:402484 *net_error = OK;
martijna23c8962016-03-04 18:18:512485 AddressFamily family = GetAddressFamily(*ip_address);
Eric Orth192e3bb2018-11-14 19:30:322486 if (key.dns_query_type != DnsQueryType::UNSPECIFIED &&
2487 key.dns_query_type != AddressFamilyToDnsQueryType(family)) {
[email protected]1c7cf3f82014-08-07 21:33:482488 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402489 *net_error = ERR_NAME_NOT_RESOLVED;
2490 } else {
Eric Orth70992982018-07-24 00:25:002491 *addresses = AddressList::CreateFromIPAddress(*ip_address, host_port);
[email protected]7054e78f2012-05-07 21:44:562492 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2493 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402494 }
2495 return true;
2496}
2497
2498bool HostResolverImpl::ServeFromCache(const Key& key,
Eric Orth70992982018-07-24 00:25:002499 uint16_t host_port,
[email protected]95a214c2011-08-04 21:50:402500 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332501 AddressList* addresses,
2502 bool allow_stale,
2503 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402504 DCHECK(addresses);
2505 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332506 DCHECK(allow_stale == !!stale_info);
Eric Orth70992982018-07-24 00:25:002507 if (!cache_.get())
[email protected]95a214c2011-08-04 21:50:402508 return false;
2509
juliatuttle9fb7aeb2016-06-06 20:16:332510 const HostCache::Entry* cache_entry;
2511 if (allow_stale)
Misha Efimovb99e7da2018-05-30 16:59:022512 cache_entry = cache_->LookupStale(key, tick_clock_->NowTicks(), stale_info);
juliatuttle9fb7aeb2016-06-06 20:16:332513 else
Misha Efimovb99e7da2018-05-30 16:59:022514 cache_entry = cache_->Lookup(key, tick_clock_->NowTicks());
[email protected]95a214c2011-08-04 21:50:402515 if (!cache_entry)
2516 return false;
2517
juliatuttle317860e2016-05-12 14:47:222518 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562519 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432520 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222521 RecordTTL(cache_entry->ttl());
Eric Orth70992982018-07-24 00:25:002522 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), host_port);
[email protected]7054e78f2012-05-07 21:44:562523 }
[email protected]95a214c2011-08-04 21:50:402524 return true;
2525}
2526
[email protected]78eac2a2012-03-14 19:09:272527bool HostResolverImpl::ServeFromHosts(const Key& key,
Eric Orth70992982018-07-24 00:25:002528 uint16_t host_port,
[email protected]78eac2a2012-03-14 19:09:272529 AddressList* addresses) {
2530 DCHECK(addresses);
2531 if (!HaveDnsConfig())
2532 return false;
[email protected]05a79d42013-03-28 07:30:092533 addresses->clear();
2534
[email protected]cb507622012-03-23 16:17:062535 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222536 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062537
[email protected]05a79d42013-03-28 07:30:092538 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2539
[email protected]78eac2a2012-03-14 19:09:272540 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2541 // (glibc and c-ares) return the first matching line. We have more
2542 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092543 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2544 // necessary.
Eric Orth192e3bb2018-11-14 19:30:322545 if (key.dns_query_type == DnsQueryType::AAAA ||
2546 key.dns_query_type == DnsQueryType::UNSPECIFIED) {
jdoerrie22a91d8b92018-10-05 08:43:262547 auto it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
[email protected]05a79d42013-03-28 07:30:092548 if (it != hosts.end())
Eric Orth70992982018-07-24 00:25:002549 addresses->push_back(IPEndPoint(it->second, host_port));
[email protected]78eac2a2012-03-14 19:09:272550 }
2551
Eric Orth192e3bb2018-11-14 19:30:322552 if (key.dns_query_type == DnsQueryType::A ||
2553 key.dns_query_type == DnsQueryType::UNSPECIFIED) {
jdoerrie22a91d8b92018-10-05 08:43:262554 auto it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
[email protected]05a79d42013-03-28 07:30:092555 if (it != hosts.end())
Eric Orth70992982018-07-24 00:25:002556 addresses->push_back(IPEndPoint(it->second, host_port));
[email protected]05a79d42013-03-28 07:30:092557 }
2558
[email protected]ec666ab22013-04-17 20:05:592559 // If got only loopback addresses and the family was restricted, resolve
2560 // again, without restrictions. See SystemHostResolverCall for rationale.
2561 if ((key.host_resolver_flags &
2562 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2563 IsAllIPv4Loopback(*addresses)) {
2564 Key new_key(key);
Eric Orth192e3bb2018-11-14 19:30:322565 new_key.dns_query_type = DnsQueryType::UNSPECIFIED;
[email protected]ec666ab22013-04-17 20:05:592566 new_key.host_resolver_flags &=
2567 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Eric Orth70992982018-07-24 00:25:002568 return ServeFromHosts(new_key, host_port, addresses);
[email protected]ec666ab22013-04-17 20:05:592569 }
[email protected]05a79d42013-03-28 07:30:092570 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272571}
2572
estarkd1bc206e2015-06-20 00:44:392573bool HostResolverImpl::ServeLocalhost(const Key& key,
Eric Orth70992982018-07-24 00:25:002574 uint16_t host_port,
estarkd1bc206e2015-06-20 00:44:392575 AddressList* addresses) {
2576 AddressList resolved_addresses;
Eric Orth70992982018-07-24 00:25:002577 if (!ResolveLocalHostname(key.hostname, host_port, &resolved_addresses))
estarkd1bc206e2015-06-20 00:44:392578 return false;
2579
2580 addresses->clear();
2581
Eric Orth192e3bb2018-11-14 19:30:322582 if (IsAddressType(key.dns_query_type)) {
2583 for (const auto& address : resolved_addresses) {
2584 // Include the address if:
2585 // - caller didn't specify an address family, or
2586 // - caller specifically asked for the address family of this address, or
2587 // - this is an IPv6 address and caller specifically asked for IPv4 due
2588 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2589 // rationale).
2590 if (key.dns_query_type == DnsQueryType::UNSPECIFIED ||
2591 DnsQueryTypeToAddressFamily(key.dns_query_type) ==
2592 address.GetFamily() ||
2593 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2594 key.dns_query_type == DnsQueryType::A &&
2595 (key.host_resolver_flags &
2596 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2597 addresses->push_back(address);
2598 }
estarkd1bc206e2015-06-20 00:44:392599 }
2600 }
2601
2602 return true;
2603}
2604
[email protected]16ee26d2012-03-08 03:34:352605void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432606 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352607 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052608 // Don't cache an error unless it has a positive TTL.
2609 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
Misha Efimovb99e7da2018-05-30 16:59:022610 cache_->Set(key, entry, tick_clock_->NowTicks(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032611}
2612
Paul Jensen41dc3e9f2018-11-06 22:10:102613// Record time from Request creation until a valid DNS response.
2614void HostResolverImpl::RecordTotalTime(bool speculative,
2615 bool from_cache,
2616 base::TimeDelta duration) const {
2617 if (!speculative) {
2618 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
2619
2620 switch (mode_for_histogram_) {
2621 case MODE_FOR_HISTOGRAM_SYSTEM:
2622 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.System", duration);
2623 break;
2624 case MODE_FOR_HISTOGRAM_SYSTEM_SUPPORTS_DOH:
2625 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.SystemSupportsDoh",
2626 duration);
2627 break;
2628 case MODE_FOR_HISTOGRAM_SYSTEM_PRIVATE_DNS:
2629 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.SystemPrivate",
2630 duration);
2631 break;
2632 case MODE_FOR_HISTOGRAM_ASYNC_DNS:
2633 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.Async", duration);
2634 break;
2635 case MODE_FOR_HISTOGRAM_ASYNC_DNS_PRIVATE_SUPPORTS_DOH:
2636 UMA_HISTOGRAM_MEDIUM_TIMES(
2637 "Net.DNS.TotalTimeTyped.AsyncPrivateSupportsDoh", duration);
2638 break;
2639 }
2640
2641 if (!from_cache)
2642 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
2643 }
2644}
2645
Eric Orth18544ae2018-06-11 22:57:162646std::unique_ptr<HostResolverImpl::Job> HostResolverImpl::RemoveJob(Job* job) {
[email protected]0f292de02012-02-01 22:28:202647 DCHECK(job);
Eric Orth18544ae2018-06-11 22:57:162648 std::unique_ptr<Job> retval;
avi9e72eb482016-12-09 21:10:542649 auto it = jobs_.find(job->key());
2650 if (it != jobs_.end() && it->second.get() == job) {
Eric Orth18544ae2018-06-11 22:57:162651 it->second.swap(retval);
[email protected]16ee26d2012-03-08 03:34:352652 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542653 }
Eric Orth18544ae2018-06-11 22:57:162654 return retval;
[email protected]b59ff372009-07-15 22:04:322655}
2656
[email protected]137af622010-02-05 02:14:352657HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
Eric Orth70992982018-07-24 00:25:002658 const std::string& hostname,
Eric Orth00fe5a62018-08-15 22:20:002659 DnsQueryType dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482660 HostResolverSource source,
Eric Orth70992982018-07-24 00:25:002661 HostResolverFlags flags,
martijna23c8962016-03-04 18:18:512662 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202663 const NetLogWithSource& net_log) {
Eric Orth70992982018-07-24 00:25:002664 HostResolverFlags effective_flags = flags | additional_resolver_flags_;
Eric Orth00fe5a62018-08-15 22:20:002665
Eric Orth192e3bb2018-11-14 19:30:322666 DnsQueryType effective_query_type = dns_query_type;
[email protected]9db6f702013-04-10 18:10:512667
Eric Orth192e3bb2018-11-14 19:30:322668 if (effective_query_type == DnsQueryType::UNSPECIFIED &&
mgersh3eba057d2017-02-28 18:50:562669 // When resolving IPv4 literals, there's no need to probe for IPv6.
2670 // When resolving IPv6 literals, there's no benefit to artificially
2671 // limiting our resolution based on a probe. Prior logic ensures
Eric Orth192e3bb2018-11-14 19:30:322672 // that this query is UNSPECIFIED (see effective_query_type check above)
2673 // so the code requesting the resolution should be amenable to receiving a
2674 // IPv6 resolution.
mgersh3eba057d2017-02-28 18:50:562675 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
Eric Orth192e3bb2018-11-14 19:30:322676 effective_query_type = DnsQueryType::A;
mgersh3eba057d2017-02-28 18:50:562677 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512678 }
2679
Eric Orth192e3bb2018-11-14 19:30:322680 return Key(hostname, effective_query_type, effective_flags, source);
[email protected]137af622010-02-05 02:14:352681}
2682
tfarina428341112016-09-22 13:38:202683bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032684 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2685 // work on WiFi.
2686 if (assume_ipv6_failure_on_wifi_ &&
2687 NetworkChangeNotifier::GetConnectionType() ==
2688 NetworkChangeNotifier::CONNECTION_WIFI) {
2689 return false;
2690 }
2691
eroman1a17ef32016-12-14 01:06:092692 // Cache the result for kIPv6ProbePeriodMs (measured from after
2693 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372694 bool cached = true;
Misha Efimovb99e7da2018-05-30 16:59:022695 if ((tick_clock_->NowTicks() - last_ipv6_probe_time_).InMilliseconds() >
eroman1a17ef32016-12-14 01:06:092696 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512697 last_ipv6_probe_result_ =
2698 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
Misha Efimovb99e7da2018-05-30 16:59:022699 last_ipv6_probe_time_ = tick_clock_->NowTicks();
sergeyub8cdc212015-05-14 18:50:372700 cached = false;
2701 }
mikecirone8b85c432016-09-08 19:11:002702 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372703 base::Bind(&NetLogIPv6AvailableCallback,
2704 last_ipv6_probe_result_, cached));
2705 return last_ipv6_probe_result_;
2706}
2707
mgershaf9a9232017-04-13 20:19:032708bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2709 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032710 std::unique_ptr<DatagramClientSocket> socket(
2711 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
Sergey Ulanovcbdfc8852018-03-16 20:13:282712 DatagramSocket::DEFAULT_BIND, net_log.net_log(), net_log.source()));
mgershaf9a9232017-04-13 20:19:032713 int rv = socket->Connect(IPEndPoint(dest, 53));
2714 if (rv != OK)
2715 return false;
2716 IPEndPoint endpoint;
2717 rv = socket->GetLocalAddress(&endpoint);
2718 if (rv != OK)
2719 return false;
2720 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2721 const IPAddress& address = endpoint.address();
2722
2723 bool is_link_local =
2724 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2725 if (is_link_local)
2726 return false;
2727
2728 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2729 if (IPAddressStartsWith(address, kTeredoPrefix))
2730 return false;
2731
2732 return true;
2733}
2734
mmenke91c17162016-06-02 16:03:232735void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402736 // Run this asynchronously as it can take 40-100ms and should not block
2737 // initialization.
2738 base::PostTaskWithTraitsAndReplyWithResult(
2739 FROM_HERE,
2740 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2741 base::BindOnce(&HaveOnlyLoopbackAddresses),
2742 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2743 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232744}
2745
[email protected]35ddc282010-09-21 23:42:062746void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202747 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2748 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402749 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542750 for (auto it = jobs_.begin(); it != jobs_.end();) {
2751 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202752 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542753 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202754 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202755 } else {
[email protected]b3601bc22012-02-21 21:23:202756 DCHECK(job->is_queued());
2757 ++it;
[email protected]0f292de02012-02-01 22:28:202758 }
[email protected]ef4c40c2010-09-01 14:42:032759 }
[email protected]b3601bc22012-02-21 21:23:202760
[email protected]daae1322013-09-05 18:26:502761 // Pause the dispatcher so it won't start any new dispatcher jobs while
2762 // aborting the old ones. This is needed so that it won't start the second
2763 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2764 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002765 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2766 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502767 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122768
[email protected]57a48d32012-03-03 00:04:552769 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072770 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552771
[email protected]16ee26d2012-03-08 03:34:352772 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212773 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552774 jobs_to_abort[i]->Abort();
[email protected]b3601bc22012-02-21 21:23:202775 }
[email protected]daae1322013-09-05 18:26:502776
2777 if (self)
[email protected]106ccd2c2014-06-17 09:21:002778 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502779}
2780
Eric Orth60931742018-11-05 23:40:572781void HostResolverImpl::AbortDnsTasks(int error, bool fallback_only) {
2782 // Aborting jobs potentially modifies |jobs_| and may even delete some jobs.
2783 // Create safe closures of all current jobs.
2784 std::vector<base::OnceClosure> job_abort_closures;
2785 for (auto& job : jobs_) {
2786 job_abort_closures.push_back(
2787 job.second->GetAbortDnsTaskClosure(error, fallback_only));
2788 }
2789
[email protected]daae1322013-09-05 18:26:502790 // Pause the dispatcher so it won't start any new dispatcher jobs while
2791 // aborting the old ones. This is needed so that it won't start the second
2792 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002793 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2794 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502795 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2796
Eric Orth60931742018-11-05 23:40:572797 for (base::OnceClosure& closure : job_abort_closures)
2798 std::move(closure).Run();
2799
[email protected]106ccd2c2014-06-17 09:21:002800 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032801}
2802
[email protected]78eac2a2012-03-14 19:09:272803void HostResolverImpl::TryServingAllJobsFromHosts() {
2804 if (!HaveDnsConfig())
2805 return;
2806
2807 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2808 // http://crbug.com/117655
2809
2810 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072811 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272812
avi9e72eb482016-12-09 21:10:542813 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2814 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272815 ++it;
2816 // This could remove |job| from |jobs_|, but iterator will remain valid.
2817 job->ServeFromHosts();
2818 }
2819}
2820
Paul Jensenf47bbab2018-09-14 16:34:042821void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372822 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182823 // Abandon all ProbeJobs.
2824 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172825 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102826 cache_->OnNetworkChange();
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472827#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2828 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232829 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132830#endif
2831 AbortAllInProgressJobs();
2832 // |this| may be deleted inside AbortAllInProgressJobs().
2833}
2834
Paul Jensenf47bbab2018-09-14 16:34:042835void HostResolverImpl::OnConnectionTypeChanged(
ttuttlecf1158bf2016-03-18 16:37:442836 NetworkChangeNotifier::ConnectionType type) {
2837 proc_params_.unresponsive_delay =
2838 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2839 "DnsUnresponsiveDelayMsByConnectionType",
2840 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2841 type);
2842}
2843
pauljensen101ed372015-04-17 00:11:422844void HostResolverImpl::OnInitialDNSConfigRead() {
2845 UpdateDNSConfig(false);
2846}
2847
[email protected]bb0e34542012-08-31 19:52:402848void HostResolverImpl::OnDNSChanged() {
Eric Orthc823a23d2018-10-30 22:12:482849 // Ignore changes if we're using a test config or if we have overriding
2850 // configuration that overrides everything from the base config.
2851 if (test_base_config_ || dns_config_overrides_.OverridesEverything())
Eric Orthe366fe62018-10-24 16:38:312852 return;
2853
pauljensen101ed372015-04-17 00:11:422854 UpdateDNSConfig(true);
2855}
2856
Eric Orthe366fe62018-10-24 16:38:312857DnsConfig HostResolverImpl::GetBaseDnsConfig() const {
[email protected]bb0e34542012-08-31 19:52:402858 DnsConfig dns_config;
Eric Orthe366fe62018-10-24 16:38:312859 if (test_base_config_)
2860 dns_config = test_base_config_.value();
2861 else
2862 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2863 return dns_config;
2864}
2865
2866void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
Eric Orthc823a23d2018-10-30 22:12:482867 DnsConfig dns_config;
[email protected]ec666ab22013-04-17 20:05:592868
Eric Orthc823a23d2018-10-30 22:12:482869 // Skip retrieving the base config if all values will be overridden.
2870 if (!dns_config_overrides_.OverridesEverything()) {
2871 dns_config = GetBaseDnsConfig();
2872
2873 if (net_log_) {
2874 net_log_->AddGlobalEntry(
2875 NetLogEventType::DNS_CONFIG_CHANGED,
2876 base::BindRepeating(&NetLogDnsConfigCallback, &dns_config));
2877 }
2878
2879 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
2880 received_dns_config_ = dns_config.IsValid();
[email protected]b4481b222012-03-16 17:13:112881 }
2882
Eric Orthc1eb1292018-10-09 22:07:072883 dns_config = dns_config_overrides_.ApplyOverrides(dns_config);
2884
[email protected]c9fa8f312013-09-17 12:24:522885 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2886 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272887
[email protected]a8883e452012-11-17 05:58:062888 num_dns_failures_ = 0;
2889
[email protected]01b3b9d2012-08-13 16:18:142890 // We want a new DnsSession in place, before we Abort running Jobs, so that
2891 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022892 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252893 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532894 // wasn't already a DnsConfig or it's the same one.
2895 DCHECK(config_changed || !dns_client_->GetConfig() ||
2896 dns_client_->GetConfig()->Equals(dns_config));
[email protected]d7b9a2b2012-05-31 22:31:192897 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252898 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022899 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022900 }
Eric Orth60931742018-11-05 23:40:572901 use_proctask_by_default_ = false;
[email protected]01b3b9d2012-08-13 16:18:142902
pauljensen101ed372015-04-17 00:11:422903 if (config_changed) {
2904 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232905 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422906 // as NSCD's cache should be dropped automatically by the OS when
2907 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172908 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232909 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142910
pauljensen101ed372015-04-17 00:11:422911 // Life check to bail once |this| is deleted.
2912 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022913
pauljensen101ed372015-04-17 00:11:422914 // Existing jobs will have been sent to the original server so they need to
2915 // be aborted.
2916 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142917
pauljensen101ed372015-04-17 00:11:422918 // |this| may be deleted inside AbortAllInProgressJobs().
2919 if (self.get())
2920 TryServingAllJobsFromHosts();
2921 }
Paul Jensen41dc3e9f2018-11-06 22:10:102922
2923 UpdateModeForHistogram(dns_config);
[email protected]78eac2a2012-03-14 19:09:272924}
2925
2926bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252927 // Use DnsClient only if it's fully configured and there is no override by
2928 // ScopedDefaultHostResolverProc.
2929 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2930 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042931 return dns_client_ && dns_client_->GetConfig() &&
2932 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202933}
2934
Eric Orth60931742018-11-05 23:40:572935void HostResolverImpl::OnDnsTaskResolve() {
[email protected]f0f602bd2012-11-15 18:01:022936 DCHECK(dns_client_);
Eric Orth60931742018-11-05 23:40:572937 num_dns_failures_ = 0;
2938}
2939
2940void HostResolverImpl::OnFallbackResolve(int dns_task_error) {
2941 DCHECK(dns_client_);
2942 DCHECK_NE(OK, dns_task_error);
2943
[email protected]f0f602bd2012-11-15 18:01:022944 ++num_dns_failures_;
2945 if (num_dns_failures_ < kMaximumDnsFailures)
2946 return;
[email protected]daae1322013-09-05 18:26:502947
Eric Orth60931742018-11-05 23:40:572948 // Force fallback until the next DNS change. Must be done before aborting
2949 // DnsTasks, since doing so may start new jobs. Do not fully clear out or
2950 // disable the DnsClient as some requests (e.g. those specifying DNS source)
2951 // are not allowed to fallback and will continue using DnsTask.
2952 use_proctask_by_default_ = true;
[email protected]daae1322013-09-05 18:26:502953
Eric Orth60931742018-11-05 23:40:572954 // Fallback all fallback-allowed DnsTasks to ProcTasks.
2955 AbortDnsTasks(ERR_FAILED, true /* fallback_only */);
[email protected]daae1322013-09-05 18:26:502956
[email protected]f0f602bd2012-11-15 18:01:022957 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:182958 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
Eric Orth60931742018-11-05 23:40:572959 std::abs(dns_task_error));
[email protected]f0f602bd2012-11-15 18:01:022960}
2961
Eric Orth9871aafa2018-10-02 19:59:182962MDnsClient* HostResolverImpl::GetOrCreateMdnsClient() {
2963#if BUILDFLAG(ENABLE_MDNS)
2964 if (!mdns_client_) {
2965 if (!mdns_socket_factory_)
2966 mdns_socket_factory_ = std::make_unique<MDnsSocketFactoryImpl>(net_log_);
2967
2968 mdns_client_ = MDnsClient::CreateDefault();
2969 mdns_client_->StartListening(mdns_socket_factory_.get());
2970 }
2971
2972 DCHECK(mdns_client_->IsListening());
2973 return mdns_client_.get();
2974#else
2975 // Should not request MDNS resoltuion unless MDNS is enabled.
2976 NOTREACHED();
2977 return nullptr;
2978#endif
2979}
2980
Paul Jensen41dc3e9f2018-11-06 22:10:102981void HostResolverImpl::UpdateModeForHistogram(const DnsConfig& dns_config) {
2982 // Resolving with Async DNS resolver?
2983 if (HaveDnsConfig()) {
2984 mode_for_histogram_ = MODE_FOR_HISTOGRAM_ASYNC_DNS;
2985 for (const auto& dns_server : dns_client_->GetConfig()->nameservers) {
2986 if (DnsServerSupportsDoh(dns_server.address())) {
2987 mode_for_histogram_ = MODE_FOR_HISTOGRAM_ASYNC_DNS_PRIVATE_SUPPORTS_DOH;
2988 break;
2989 }
2990 }
2991 } else {
2992 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM;
2993 for (const auto& dns_server : dns_config.nameservers) {
2994 if (DnsServerSupportsDoh(dns_server.address())) {
2995 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM_SUPPORTS_DOH;
2996 break;
2997 }
2998 }
2999#if defined(OS_ANDROID)
3000 if (base::android::BuildInfo::GetInstance()->sdk_int() >=
3001 base::android::SDK_VERSION_P) {
3002 std::vector<IPEndPoint> dns_servers;
3003 if (net::android::GetDnsServers(&dns_servers) ==
3004 internal::CONFIG_PARSE_POSIX_PRIVATE_DNS_ACTIVE) {
3005 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM_PRIVATE_DNS;
3006 }
3007 }
3008#endif // defined(OS_ANDROID)
3009 }
3010}
3011
maksim.sisov31452af2016-07-27 06:38:103012HostResolverImpl::RequestImpl::~RequestImpl() {
3013 if (job_)
3014 job_->CancelRequest(this);
3015}
3016
3017void HostResolverImpl::RequestImpl::ChangeRequestPriority(
3018 RequestPriority priority) {
3019 job_->ChangeRequestPriority(this, priority);
3020}
3021
[email protected]b59ff372009-07-15 22:04:323022} // namespace net