blob: 7845e0bee8e6cfebc494f84f746a3d93e69fa0ec [file] [log] [blame]
[email protected]a2730882012-01-21 00:56:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]b59ff372009-07-15 22:04:322// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f2cb3cf2013-03-21 01:40:535#include "net/dns/host_resolver_impl.h"
[email protected]b59ff372009-07-15 22:04:326
[email protected]21526002010-05-16 19:42:467#if defined(OS_WIN)
8#include <Winsock2.h>
9#elif defined(OS_POSIX)
10#include <netdb.h>
11#endif
12
[email protected]68ad3ee2010-01-30 03:45:3913#include <cmath>
[email protected]0f292de02012-02-01 22:28:2014#include <utility>
[email protected]21526002010-05-16 19:42:4615#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3916
17#include "base/basictypes.h"
[email protected]33152acc2011-10-20 23:37:1218#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2919#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2020#include "base/callback.h"
[email protected]b59ff372009-07-15 22:04:3221#include "base/compiler_specific.h"
[email protected]58580352010-10-26 04:07:5022#include "base/debug/debugger.h"
23#include "base/debug/stack_trace.h"
[email protected]3e9d9cc2011-05-03 21:08:1524#include "base/message_loop_proxy.h"
[email protected]1e9bbd22010-10-15 16:42:4525#include "base/metrics/field_trial.h"
[email protected]835d7c82010-10-14 04:38:3826#include "base/metrics/histogram.h"
[email protected]7286e3fc2011-07-19 22:13:2427#include "base/stl_util.h"
[email protected]b59ff372009-07-15 22:04:3228#include "base/string_util.h"
[email protected]ac9ba8fe2010-12-30 18:08:3629#include "base/threading/worker_pool.h"
[email protected]b59ff372009-07-15 22:04:3230#include "base/time.h"
[email protected]ccaff652010-07-31 06:28:2031#include "base/utf_string_conversions.h"
[email protected]21526002010-05-16 19:42:4632#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2033#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3234#include "net/base/address_list.h"
[email protected]46018c9d2011-09-06 03:42:3435#include "net/base/dns_reloader.h"
[email protected]e806cd72013-05-17 02:08:4336#include "net/base/dns_util.h"
[email protected]ee094b82010-08-24 15:55:5137#include "net/base/host_port_pair.h"
[email protected]2bb04442010-08-18 18:01:1538#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5139#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0340#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4641#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2742#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2043#include "net/dns/dns_config_service.h"
44#include "net/dns/dns_protocol.h"
45#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2046#include "net/dns/dns_transaction.h"
[email protected]f2cb3cf2013-03-21 01:40:5347#include "net/dns/host_resolver_proc.h"
[email protected]9db6f702013-04-10 18:10:5148#include "net/socket/client_socket_factory.h"
49#include "net/udp/datagram_client_socket.h"
[email protected]b59ff372009-07-15 22:04:3250
51#if defined(OS_WIN)
52#include "net/base/winsock_init.h"
53#endif
54
55namespace net {
56
[email protected]e95d3aca2010-01-11 22:47:4357namespace {
58
[email protected]6e78dfb2011-07-28 21:34:4759// Limit the size of hostnames that will be resolved to combat issues in
60// some platform's resolvers.
61const size_t kMaxHostLength = 4096;
62
[email protected]a2730882012-01-21 00:56:2763// Default TTL for successful resolutions with ProcTask.
64const unsigned kCacheEntryTTLSeconds = 60;
65
[email protected]b3601bc22012-02-21 21:23:2066// Default TTL for unsuccessful resolutions with ProcTask.
67const unsigned kNegativeCacheEntryTTLSeconds = 0;
68
[email protected]895123222012-10-25 15:21:1769// Minimum TTL for successful resolutions with DnsTask.
70const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
71
[email protected]f0f602bd2012-11-15 18:01:0272// Number of consecutive failures of DnsTask (with successful fallback) before
73// the DnsClient is disabled until the next DNS change.
74const unsigned kMaximumDnsFailures = 16;
75
[email protected]24f4bab2010-10-15 01:27:1176// We use a separate histogram name for each platform to facilitate the
77// display of error codes by their symbolic name (since each platform has
78// different mappings).
79const char kOSErrorsForGetAddrinfoHistogramName[] =
80#if defined(OS_WIN)
81 "Net.OSErrorsForGetAddrinfo_Win";
82#elif defined(OS_MACOSX)
83 "Net.OSErrorsForGetAddrinfo_Mac";
84#elif defined(OS_LINUX)
85 "Net.OSErrorsForGetAddrinfo_Linux";
86#else
87 "Net.OSErrorsForGetAddrinfo";
88#endif
89
[email protected]c89b2442011-05-26 14:28:2790// Gets a list of the likely error codes that getaddrinfo() can return
91// (non-exhaustive). These are the error codes that we will track via
92// a histogram.
93std::vector<int> GetAllGetAddrinfoOSErrors() {
94 int os_errors[] = {
95#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:5196#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:3797#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:4598 // EAI_ADDRFAMILY has been declared obsolete in Android's and
99 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27100 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37101#endif
[email protected]c48aef92011-11-22 23:41:45102 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51103 EAI_NODATA,
104#endif
[email protected]c89b2442011-05-26 14:28:27105 EAI_AGAIN,
106 EAI_BADFLAGS,
107 EAI_FAIL,
108 EAI_FAMILY,
109 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27110 EAI_NONAME,
111 EAI_SERVICE,
112 EAI_SOCKTYPE,
113 EAI_SYSTEM,
114#elif defined(OS_WIN)
115 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
116 WSA_NOT_ENOUGH_MEMORY,
117 WSAEAFNOSUPPORT,
118 WSAEINVAL,
119 WSAESOCKTNOSUPPORT,
120 WSAHOST_NOT_FOUND,
121 WSANO_DATA,
122 WSANO_RECOVERY,
123 WSANOTINITIALISED,
124 WSATRY_AGAIN,
125 WSATYPE_NOT_FOUND,
126 // The following are not in doc, but might be to appearing in results :-(.
127 WSA_INVALID_HANDLE,
128#endif
129 };
130
131 // Ensure all errors are positive, as histogram only tracks positive values.
132 for (size_t i = 0; i < arraysize(os_errors); ++i) {
133 os_errors[i] = std::abs(os_errors[i]);
134 }
135
136 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
137 arraysize(os_errors));
138}
139
[email protected]1def74c2012-03-22 20:07:00140enum DnsResolveStatus {
141 RESOLVE_STATUS_DNS_SUCCESS = 0,
142 RESOLVE_STATUS_PROC_SUCCESS,
143 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33144 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00145 RESOLVE_STATUS_MAX
146};
147
148void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
149 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
150 result,
151 RESOLVE_STATUS_MAX);
152}
153
[email protected]1d932852012-06-19 19:40:33154bool ResemblesNetBIOSName(const std::string& hostname) {
155 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
156}
157
158// True if |hostname| ends with either ".local" or ".local.".
159bool ResemblesMulticastDNSName(const std::string& hostname) {
160 DCHECK(!hostname.empty());
161 const char kSuffix[] = ".local.";
162 const size_t kSuffixLen = sizeof(kSuffix) - 1;
163 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
164 if (hostname[hostname.size() - 1] == '.') {
165 return hostname.size() > kSuffixLen &&
166 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
167 }
168 return hostname.size() > kSuffixLenTrimmed &&
169 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
170 kSuffix, kSuffixLenTrimmed);
171}
172
[email protected]9db6f702013-04-10 18:10:51173// Attempts to connect a UDP socket to |dest|:80.
[email protected]e9051722013-04-12 21:58:18174bool IsGloballyReachable(const IPAddressNumber& dest) {
[email protected]9db6f702013-04-10 18:10:51175 scoped_ptr<DatagramClientSocket> socket(
176 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
177 DatagramSocket::DEFAULT_BIND,
178 RandIntCallback(),
179 NULL,
180 NetLog::Source()));
[email protected]e9051722013-04-12 21:58:18181 int rv = socket->Connect(IPEndPoint(dest, 80));
182 if (rv != OK)
183 return false;
184 IPEndPoint endpoint;
185 rv = socket->GetLocalAddress(&endpoint);
186 if (rv != OK)
187 return false;
188 DCHECK(endpoint.GetFamily() == ADDRESS_FAMILY_IPV6);
189 const IPAddressNumber& address = endpoint.address();
190 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
191 if (is_link_local)
192 return false;
193 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
194 bool is_teredo = std::equal(kTeredoPrefix,
195 kTeredoPrefix + arraysize(kTeredoPrefix),
196 address.begin());
197 if (is_teredo)
198 return false;
199 return true;
[email protected]9db6f702013-04-10 18:10:51200}
201
[email protected]51b9a6b2012-06-25 21:50:29202// Provide a common macro to simplify code and readability. We must use a
203// macro as the underlying HISTOGRAM macro creates static variables.
204#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
205 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
206
207// A macro to simplify code and readability.
208#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
209 do { \
210 switch (priority) { \
211 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
212 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
213 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
214 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
215 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
216 default: NOTREACHED(); break; \
217 } \
218 DNS_HISTOGRAM(basename, time); \
219 } while (0)
220
221// Record time from Request creation until a valid DNS response.
222void RecordTotalTime(bool had_dns_config,
223 bool speculative,
224 base::TimeDelta duration) {
225 if (had_dns_config) {
226 if (speculative) {
227 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
228 } else {
229 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
230 }
231 } else {
232 if (speculative) {
233 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
234 } else {
235 DNS_HISTOGRAM("DNS.TotalTime", duration);
236 }
237 }
238}
239
[email protected]1339a2a22012-10-17 08:39:43240void RecordTTL(base::TimeDelta ttl) {
241 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
242 base::TimeDelta::FromSeconds(1),
243 base::TimeDelta::FromDays(1), 100);
244}
245
[email protected]d7b9a2b2012-05-31 22:31:19246//-----------------------------------------------------------------------------
247
[email protected]895123222012-10-25 15:21:17248AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
249 if (list.empty() || list.front().port() == port)
250 return list;
251 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56252}
253
[email protected]ec666ab22013-04-17 20:05:59254// Returns true if |addresses| contains only IPv4 loopback addresses.
255bool IsAllIPv4Loopback(const AddressList& addresses) {
256 for (unsigned i = 0; i < addresses.size(); ++i) {
257 const IPAddressNumber& address = addresses[i].address();
258 switch (addresses[i].GetFamily()) {
259 case ADDRESS_FAMILY_IPV4:
260 if (address[0] != 127)
261 return false;
262 break;
263 case ADDRESS_FAMILY_IPV6:
264 return false;
265 default:
266 NOTREACHED();
267 return false;
268 }
269 }
270 return true;
271}
272
[email protected]cd565142012-06-12 16:21:45273// Creates NetLog parameters when the resolve failed.
274base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
275 int net_error,
276 int os_error,
277 NetLog::LogLevel /* log_level */) {
278 DictionaryValue* dict = new DictionaryValue();
279 if (attempt_number)
280 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46281
[email protected]cd565142012-06-12 16:21:45282 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16283
[email protected]cd565142012-06-12 16:21:45284 if (os_error) {
285 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46286#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45287 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46288#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45289 // Map the error code to a human-readable string.
290 LPWSTR error_string = NULL;
291 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
292 FORMAT_MESSAGE_FROM_SYSTEM,
293 0, // Use the internal message table.
294 os_error,
295 0, // Use default language.
296 (LPWSTR)&error_string,
297 0, // Buffer size.
298 0); // Arguments (unused).
299 dict->SetString("os_error_string", WideToUTF8(error_string));
300 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46301#endif
[email protected]21526002010-05-16 19:42:46302 }
303
[email protected]cd565142012-06-12 16:21:45304 return dict;
305}
[email protected]a9813302012-04-28 09:29:28306
[email protected]cd565142012-06-12 16:21:45307// Creates NetLog parameters when the DnsTask failed.
308base::Value* NetLogDnsTaskFailedCallback(int net_error,
309 int dns_error,
310 NetLog::LogLevel /* log_level */) {
311 DictionaryValue* dict = new DictionaryValue();
312 dict->SetInteger("net_error", net_error);
313 if (dns_error)
314 dict->SetInteger("dns_error", dns_error);
315 return dict;
[email protected]ee094b82010-08-24 15:55:51316};
317
[email protected]cd565142012-06-12 16:21:45318// Creates NetLog parameters containing the information in a RequestInfo object,
319// along with the associated NetLog::Source.
320base::Value* NetLogRequestInfoCallback(const NetLog::Source& source,
321 const HostResolver::RequestInfo* info,
322 NetLog::LogLevel /* log_level */) {
323 DictionaryValue* dict = new DictionaryValue();
324 source.AddToEventParameters(dict);
[email protected]b3601bc22012-02-21 21:23:20325
[email protected]cd565142012-06-12 16:21:45326 dict->SetString("host", info->host_port_pair().ToString());
327 dict->SetInteger("address_family",
328 static_cast<int>(info->address_family()));
329 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
330 dict->SetBoolean("is_speculative", info->is_speculative());
331 dict->SetInteger("priority", info->priority());
332 return dict;
333}
[email protected]b3601bc22012-02-21 21:23:20334
[email protected]cd565142012-06-12 16:21:45335// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
336base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
337 const std::string* host,
338 NetLog::LogLevel /* log_level */) {
339 DictionaryValue* dict = new DictionaryValue();
340 source.AddToEventParameters(dict);
341 dict->SetString("host", *host);
342 return dict;
343}
[email protected]a9813302012-04-28 09:29:28344
[email protected]cd565142012-06-12 16:21:45345// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
346base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
347 RequestPriority priority,
348 NetLog::LogLevel /* log_level */) {
349 DictionaryValue* dict = new DictionaryValue();
350 source.AddToEventParameters(dict);
351 dict->SetInteger("priority", priority);
352 return dict;
353}
[email protected]b3601bc22012-02-21 21:23:20354
[email protected]cd565142012-06-12 16:21:45355// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
356base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
357 NetLog::LogLevel /* log_level */) {
358 return config->ToValue();
359}
[email protected]b4481b222012-03-16 17:13:11360
[email protected]0f292de02012-02-01 22:28:20361// The logging routines are defined here because some requests are resolved
362// without a Request object.
363
364// Logs when a request has just been started.
365void LogStartRequest(const BoundNetLog& source_net_log,
366 const BoundNetLog& request_net_log,
367 const HostResolver::RequestInfo& info) {
368 source_net_log.BeginEvent(
369 NetLog::TYPE_HOST_RESOLVER_IMPL,
[email protected]cd565142012-06-12 16:21:45370 request_net_log.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:20371
372 request_net_log.BeginEvent(
373 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
[email protected]cd565142012-06-12 16:21:45374 base::Bind(&NetLogRequestInfoCallback, source_net_log.source(), &info));
[email protected]0f292de02012-02-01 22:28:20375}
376
377// Logs when a request has just completed (before its callback is run).
378void LogFinishRequest(const BoundNetLog& source_net_log,
379 const BoundNetLog& request_net_log,
380 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20381 int net_error) {
382 request_net_log.EndEventWithNetErrorCode(
383 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]4da911f2012-06-14 19:45:20384 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20385}
386
387// Logs when a request has been cancelled.
388void LogCancelRequest(const BoundNetLog& source_net_log,
389 const BoundNetLog& request_net_log,
390 const HostResolverImpl::RequestInfo& info) {
[email protected]4da911f2012-06-14 19:45:20391 request_net_log.AddEvent(NetLog::TYPE_CANCELLED);
392 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
393 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20394}
395
[email protected]b59ff372009-07-15 22:04:32396//-----------------------------------------------------------------------------
397
[email protected]0f292de02012-02-01 22:28:20398// Keeps track of the highest priority.
399class PriorityTracker {
400 public:
[email protected]8c98d002012-07-18 19:02:27401 explicit PriorityTracker(RequestPriority initial_priority)
402 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20403 memset(counts_, 0, sizeof(counts_));
404 }
405
406 RequestPriority highest_priority() const {
407 return highest_priority_;
408 }
409
410 size_t total_count() const {
411 return total_count_;
412 }
413
414 void Add(RequestPriority req_priority) {
415 ++total_count_;
416 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05417 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20418 highest_priority_ = req_priority;
419 }
420
421 void Remove(RequestPriority req_priority) {
422 DCHECK_GT(total_count_, 0u);
423 DCHECK_GT(counts_[req_priority], 0u);
424 --total_count_;
425 --counts_[req_priority];
426 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05427 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20428 highest_priority_ = static_cast<RequestPriority>(i);
429
[email protected]31ae7ab2012-04-24 21:09:05430 // In absence of requests, default to MINIMUM_PRIORITY.
431 if (total_count_ == 0)
432 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20433 }
434
435 private:
436 RequestPriority highest_priority_;
437 size_t total_count_;
438 size_t counts_[NUM_PRIORITIES];
439};
440
[email protected]c54a8912012-10-22 22:09:43441} // namespace
[email protected]0f292de02012-02-01 22:28:20442
443//-----------------------------------------------------------------------------
444
445// Holds the data for a request that could not be completed synchronously.
446// It is owned by a Job. Canceled Requests are only marked as canceled rather
447// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32448class HostResolverImpl::Request {
449 public:
[email protected]ee094b82010-08-24 15:55:51450 Request(const BoundNetLog& source_net_log,
451 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09452 const RequestInfo& info,
[email protected]aa22b242011-11-16 18:58:29453 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32454 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51455 : source_net_log_(source_net_log),
456 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09457 info_(info),
458 job_(NULL),
459 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29460 addresses_(addresses),
461 request_time_(base::TimeTicks::Now()) {
[email protected]54e13772009-08-14 03:01:09462 }
[email protected]b59ff372009-07-15 22:04:32463
[email protected]0f292de02012-02-01 22:28:20464 // Mark the request as canceled.
465 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32466 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32467 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29468 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32469 }
470
[email protected]0f292de02012-02-01 22:28:20471 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29472 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32473 }
474
475 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20476 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32477 // Identify which job the request is waiting on.
478 job_ = job;
479 }
480
[email protected]0f292de02012-02-01 22:28:20481 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20482 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29483 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17484 if (error == OK)
485 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29486 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20487 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29488 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32489 }
490
[email protected]b59ff372009-07-15 22:04:32491 Job* job() const {
492 return job_;
493 }
494
[email protected]0f292de02012-02-01 22:28:20495 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51496 const BoundNetLog& source_net_log() {
497 return source_net_log_;
498 }
499
[email protected]0f292de02012-02-01 22:28:20500 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51501 const BoundNetLog& request_net_log() {
502 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09503 }
504
[email protected]b59ff372009-07-15 22:04:32505 const RequestInfo& info() const {
506 return info_;
507 }
508
[email protected]51b9a6b2012-06-25 21:50:29509 base::TimeTicks request_time() const {
510 return request_time_;
511 }
512
[email protected]b59ff372009-07-15 22:04:32513 private:
[email protected]ee094b82010-08-24 15:55:51514 BoundNetLog source_net_log_;
515 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09516
[email protected]b59ff372009-07-15 22:04:32517 // The request info that started the request.
518 RequestInfo info_;
519
[email protected]0f292de02012-02-01 22:28:20520 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32521 Job* job_;
522
523 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29524 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32525
526 // The address list to save result into.
527 AddressList* addresses_;
528
[email protected]51b9a6b2012-06-25 21:50:29529 const base::TimeTicks request_time_;
530
[email protected]b59ff372009-07-15 22:04:32531 DISALLOW_COPY_AND_ASSIGN(Request);
532};
533
[email protected]1e9bbd22010-10-15 16:42:45534//------------------------------------------------------------------------------
535
[email protected]0f292de02012-02-01 22:28:20536// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
537//
538// Whenever we try to resolve the host, we post a delayed task to check if host
539// resolution (OnLookupComplete) is completed or not. If the original attempt
540// hasn't completed, then we start another attempt for host resolution. We take
541// the results from the first attempt that finishes and ignore the results from
542// all other attempts.
543//
544// TODO(szym): Move to separate source file for testing and mocking.
545//
546class HostResolverImpl::ProcTask
547 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32548 public:
[email protected]b3601bc22012-02-21 21:23:20549 typedef base::Callback<void(int net_error,
550 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32551
[email protected]0f292de02012-02-01 22:28:20552 ProcTask(const Key& key,
553 const ProcTaskParams& params,
554 const Callback& callback,
555 const BoundNetLog& job_net_log)
556 : key_(key),
557 params_(params),
558 callback_(callback),
559 origin_loop_(base::MessageLoopProxy::current()),
560 attempt_number_(0),
561 completed_attempt_number_(0),
562 completed_attempt_error_(ERR_UNEXPECTED),
563 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20564 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50565 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20566 params_.resolver_proc = HostResolverProc::GetDefault();
567 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50568 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06569 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32570 }
571
[email protected]b59ff372009-07-15 22:04:32572 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15573 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20574 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54575 StartLookupAttempt();
576 }
[email protected]252b699b2010-02-05 21:38:06577
[email protected]0f292de02012-02-01 22:28:20578 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
579 // attempts running on worker threads will continue running. Only once all the
580 // attempts complete will the final reference to this ProcTask be released.
581 void Cancel() {
582 DCHECK(origin_loop_->BelongsToCurrentThread());
583
[email protected]0adcb2b2012-08-15 21:30:46584 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20585 return;
586
[email protected]0f292de02012-02-01 22:28:20587 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20588 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20589 }
590
591 void set_had_non_speculative_request() {
592 DCHECK(origin_loop_->BelongsToCurrentThread());
593 had_non_speculative_request_ = true;
594 }
595
596 bool was_canceled() const {
597 DCHECK(origin_loop_->BelongsToCurrentThread());
598 return callback_.is_null();
599 }
600
601 bool was_completed() const {
602 DCHECK(origin_loop_->BelongsToCurrentThread());
603 return completed_attempt_number_ > 0;
604 }
605
606 private:
[email protected]a9813302012-04-28 09:29:28607 friend class base::RefCountedThreadSafe<ProcTask>;
608 ~ProcTask() {}
609
[email protected]189163e2011-05-11 01:48:54610 void StartLookupAttempt() {
611 DCHECK(origin_loop_->BelongsToCurrentThread());
612 base::TimeTicks start_time = base::TimeTicks::Now();
613 ++attempt_number_;
614 // Dispatch the lookup attempt to a worker thread.
615 if (!base::WorkerPool::PostTask(
616 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20617 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54618 true)) {
[email protected]b59ff372009-07-15 22:04:32619 NOTREACHED();
620
621 // Since we could be running within Resolve() right now, we can't just
622 // call OnLookupComplete(). Instead we must wait until Resolve() has
623 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15624 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54625 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20626 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12627 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54628 return;
[email protected]b59ff372009-07-15 22:04:32629 }
[email protected]13024882011-05-18 23:19:16630
631 net_log_.AddEvent(
632 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45633 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16634
[email protected]0f292de02012-02-01 22:28:20635 // If we don't get the results within a given time, RetryIfNotComplete
636 // will start a new attempt on a different worker thread if none of our
637 // outstanding attempts have completed yet.
638 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58639 origin_loop_->PostDelayedTask(
640 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20641 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42642 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58643 }
[email protected]b59ff372009-07-15 22:04:32644 }
645
[email protected]6c710ee2010-05-07 07:51:16646 // WARNING: This code runs inside a worker pool. The shutdown code cannot
647 // wait for it to finish, so we must be very careful here about using other
648 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54649 // may no longer exist. Multiple DoLookups() could be running in parallel, so
650 // any state inside of |this| must not mutate .
651 void DoLookup(const base::TimeTicks& start_time,
652 const uint32 attempt_number) {
653 AddressList results;
654 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32655 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20656 int error = params_.resolver_proc->Resolve(key_.hostname,
657 key_.address_family,
658 key_.host_resolver_flags,
659 &results,
660 &os_error);
[email protected]b59ff372009-07-15 22:04:32661
[email protected]189163e2011-05-11 01:48:54662 origin_loop_->PostTask(
663 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20664 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12665 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54666 }
667
[email protected]0f292de02012-02-01 22:28:20668 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
669 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54670 DCHECK(origin_loop_->BelongsToCurrentThread());
671
[email protected]0f292de02012-02-01 22:28:20672 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54673 return;
674
[email protected]0f292de02012-02-01 22:28:20675 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54676 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32677 }
678
679 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54680 void OnLookupComplete(const AddressList& results,
681 const base::TimeTicks& start_time,
682 const uint32 attempt_number,
683 int error,
684 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15685 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23686 // If results are empty, we should return an error.
687 bool empty_list_on_ok = (error == OK && results.empty());
688 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
689 if (empty_list_on_ok)
690 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54691
692 bool was_retry_attempt = attempt_number > 1;
693
[email protected]2d3b7762010-10-09 00:35:47694 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20695 // however it isn't safe to call NetworkChangeNotifier from worker threads.
696 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54697 if (error != OK && NetworkChangeNotifier::IsOffline())
698 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47699
[email protected]b3601bc22012-02-21 21:23:20700 // If this is the first attempt that is finishing later, then record data
701 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54702 if (!was_retry_attempt)
703 RecordPerformanceHistograms(start_time, error, os_error);
704
705 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35706
[email protected]0f292de02012-02-01 22:28:20707 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32708 return;
709
[email protected]cd565142012-06-12 16:21:45710 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20711 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45712 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
713 attempt_number,
714 error,
715 os_error);
[email protected]0f292de02012-02-01 22:28:20716 } else {
[email protected]cd565142012-06-12 16:21:45717 net_log_callback = NetLog::IntegerCallback("attempt_number",
718 attempt_number);
[email protected]0f292de02012-02-01 22:28:20719 }
[email protected]cd565142012-06-12 16:21:45720 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
721 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20722
723 if (was_completed())
724 return;
725
726 // Copy the results from the first worker thread that resolves the host.
727 results_ = results;
728 completed_attempt_number_ = attempt_number;
729 completed_attempt_error_ = error;
730
[email protected]e87b8b512011-06-14 22:12:52731 if (was_retry_attempt) {
732 // If retry attempt finishes before 1st attempt, then get stats on how
733 // much time is saved by having spawned an extra attempt.
734 retry_attempt_finished_time_ = base::TimeTicks::Now();
735 }
736
[email protected]189163e2011-05-11 01:48:54737 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45738 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
739 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51740 } else {
[email protected]cd565142012-06-12 16:21:45741 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51742 }
[email protected]cd565142012-06-12 16:21:45743 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
744 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51745
[email protected]b3601bc22012-02-21 21:23:20746 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32747 }
748
[email protected]189163e2011-05-11 01:48:54749 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
750 const int error,
751 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15752 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]1e9bbd22010-10-15 16:42:45753 enum Category { // Used in HISTOGRAM_ENUMERATION.
754 RESOLVE_SUCCESS,
755 RESOLVE_FAIL,
756 RESOLVE_SPECULATIVE_SUCCESS,
757 RESOLVE_SPECULATIVE_FAIL,
758 RESOLVE_MAX, // Bounding value.
759 };
760 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
761
[email protected]189163e2011-05-11 01:48:54762 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
763 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45764 if (had_non_speculative_request_) {
765 category = RESOLVE_SUCCESS;
766 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
767 } else {
768 category = RESOLVE_SPECULATIVE_SUCCESS;
769 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
770 }
[email protected]7e96d792011-06-10 17:08:23771
[email protected]78eac2a2012-03-14 19:09:27772 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23773 // if IPv4 or IPv4/6 lookups are faster or slower.
774 switch(key_.address_family) {
775 case ADDRESS_FAMILY_IPV4:
776 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
777 break;
778 case ADDRESS_FAMILY_IPV6:
779 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
780 break;
781 case ADDRESS_FAMILY_UNSPECIFIED:
782 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
783 break;
784 }
[email protected]1e9bbd22010-10-15 16:42:45785 } else {
786 if (had_non_speculative_request_) {
787 category = RESOLVE_FAIL;
788 DNS_HISTOGRAM("DNS.ResolveFail", duration);
789 } else {
790 category = RESOLVE_SPECULATIVE_FAIL;
791 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
792 }
[email protected]78eac2a2012-03-14 19:09:27793 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23794 // if IPv4 or IPv4/6 lookups are faster or slower.
795 switch(key_.address_family) {
796 case ADDRESS_FAMILY_IPV4:
797 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
798 break;
799 case ADDRESS_FAMILY_IPV6:
800 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
801 break;
802 case ADDRESS_FAMILY_UNSPECIFIED:
803 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
804 break;
805 }
[email protected]c833e322010-10-16 23:51:36806 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54807 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45808 GetAllGetAddrinfoOSErrors());
809 }
[email protected]051b6ab2010-10-18 16:50:46810 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45811
812 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45813 }
814
[email protected]189163e2011-05-11 01:48:54815 void RecordAttemptHistograms(const base::TimeTicks& start_time,
816 const uint32 attempt_number,
817 const int error,
818 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20819 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54820 bool first_attempt_to_complete =
821 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52822 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45823
[email protected]189163e2011-05-11 01:48:54824 if (first_attempt_to_complete) {
825 // If this was first attempt to complete, then record the resolution
826 // status of the attempt.
827 if (completed_attempt_error_ == OK) {
828 UMA_HISTOGRAM_ENUMERATION(
829 "DNS.AttemptFirstSuccess", attempt_number, 100);
830 } else {
831 UMA_HISTOGRAM_ENUMERATION(
832 "DNS.AttemptFirstFailure", attempt_number, 100);
833 }
834 }
835
836 if (error == OK)
837 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
838 else
839 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
840
[email protected]e87b8b512011-06-14 22:12:52841 // If first attempt didn't finish before retry attempt, then calculate stats
842 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20843 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52844 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
845 base::TimeTicks::Now() - retry_attempt_finished_time_);
846 }
847
[email protected]0f292de02012-02-01 22:28:20848 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54849 // Count those attempts which completed after the job was already canceled
850 // OR after the job was already completed by an earlier attempt (so in
851 // effect).
852 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
853
[email protected]0f292de02012-02-01 22:28:20854 // Record if job is canceled.
855 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54856 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
857 }
858
859 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
860 if (error == OK)
861 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
862 else
863 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
864 }
[email protected]1e9bbd22010-10-15 16:42:45865
[email protected]b59ff372009-07-15 22:04:32866 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57867 Key key_;
[email protected]b59ff372009-07-15 22:04:32868
[email protected]0f292de02012-02-01 22:28:20869 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32870 // This may not be the current resolver procedure by the time we call
871 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
872 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20873 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32874
[email protected]0f292de02012-02-01 22:28:20875 // The listener to the results of this ProcTask.
876 Callback callback_;
877
878 // Used to post ourselves onto the origin thread.
879 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54880
881 // Keeps track of the number of attempts we have made so far to resolve the
882 // host. Whenever we start an attempt to resolve the host, we increase this
883 // number.
884 uint32 attempt_number_;
885
886 // The index of the attempt which finished first (or 0 if the job is still in
887 // progress).
888 uint32 completed_attempt_number_;
889
890 // The result (a net error code) from the first attempt to complete.
891 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06892
[email protected]e87b8b512011-06-14 22:12:52893 // The time when retry attempt was finished.
894 base::TimeTicks retry_attempt_finished_time_;
895
[email protected]252b699b2010-02-05 21:38:06896 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20897 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06898 // This boolean is used for histogramming the duration of jobs used to
899 // service non-speculative requests.
900 bool had_non_speculative_request_;
901
[email protected]b59ff372009-07-15 22:04:32902 AddressList results_;
903
[email protected]ee094b82010-08-24 15:55:51904 BoundNetLog net_log_;
905
[email protected]0f292de02012-02-01 22:28:20906 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32907};
908
909//-----------------------------------------------------------------------------
910
[email protected]12faa4c2012-11-06 04:44:18911// Wraps a call to TestIPv6Support to be executed on the WorkerPool as it takes
912// 40-100ms.
[email protected]9db6f702013-04-10 18:10:51913// TODO(szym): Remove altogether, if IPv6ActiveProbe works.
[email protected]12faa4c2012-11-06 04:44:18914class HostResolverImpl::IPv6ProbeJob {
[email protected]0f8f1b432010-03-16 19:06:03915 public:
[email protected]12faa4c2012-11-06 04:44:18916 IPv6ProbeJob(const base::WeakPtr<HostResolverImpl>& resolver, NetLog* net_log)
[email protected]0f8f1b432010-03-16 19:06:03917 : resolver_(resolver),
[email protected]12faa4c2012-11-06 04:44:18918 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_IPV6_PROBE_JOB)),
919 result_(false, IPV6_SUPPORT_MAX, OK) {
[email protected]3e9d9cc2011-05-03 21:08:15920 DCHECK(resolver);
[email protected]ae8e80f2012-07-19 21:08:33921 net_log_.BeginEvent(NetLog::TYPE_IPV6_PROBE_RUNNING);
[email protected]f092e64b2010-03-17 00:39:18922 const bool kIsSlow = true;
[email protected]12faa4c2012-11-06 04:44:18923 base::WorkerPool::PostTaskAndReply(
924 FROM_HERE,
925 base::Bind(&IPv6ProbeJob::DoProbe, base::Unretained(this)),
926 base::Bind(&IPv6ProbeJob::OnProbeComplete, base::Owned(this)),
927 kIsSlow);
[email protected]0f8f1b432010-03-16 19:06:03928 }
929
[email protected]12faa4c2012-11-06 04:44:18930 virtual ~IPv6ProbeJob() {}
[email protected]0f8f1b432010-03-16 19:06:03931
[email protected]0f8f1b432010-03-16 19:06:03932 private:
[email protected]12faa4c2012-11-06 04:44:18933 // Runs on worker thread.
[email protected]0f8f1b432010-03-16 19:06:03934 void DoProbe() {
[email protected]12faa4c2012-11-06 04:44:18935 result_ = TestIPv6Support();
[email protected]0f8f1b432010-03-16 19:06:03936 }
937
[email protected]12faa4c2012-11-06 04:44:18938 void OnProbeComplete() {
939 net_log_.EndEvent(NetLog::TYPE_IPV6_PROBE_RUNNING,
940 base::Bind(&IPv6SupportResult::ToNetLogValue,
941 base::Unretained(&result_)));
942 if (!resolver_)
[email protected]a9af7112010-05-08 00:56:01943 return;
[email protected]12faa4c2012-11-06 04:44:18944 resolver_->IPv6ProbeSetDefaultAddressFamily(
945 result_.ipv6_supported ? ADDRESS_FAMILY_UNSPECIFIED
[email protected]ae8e80f2012-07-19 21:08:33946 : ADDRESS_FAMILY_IPV4);
[email protected]0f8f1b432010-03-16 19:06:03947 }
948
[email protected]0f8f1b432010-03-16 19:06:03949 // Used/set only on origin thread.
[email protected]12faa4c2012-11-06 04:44:18950 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]0f8f1b432010-03-16 19:06:03951
[email protected]ae8e80f2012-07-19 21:08:33952 BoundNetLog net_log_;
953
[email protected]12faa4c2012-11-06 04:44:18954 IPv6SupportResult result_;
955
[email protected]0f8f1b432010-03-16 19:06:03956 DISALLOW_COPY_AND_ASSIGN(IPv6ProbeJob);
957};
958
[email protected]12faa4c2012-11-06 04:44:18959// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
960// it takes 40-100ms and should not block initialization.
961class HostResolverImpl::LoopbackProbeJob {
962 public:
963 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
964 : resolver_(resolver),
965 result_(false) {
966 DCHECK(resolver);
967 const bool kIsSlow = true;
968 base::WorkerPool::PostTaskAndReply(
969 FROM_HERE,
970 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
971 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
972 kIsSlow);
973 }
974
975 virtual ~LoopbackProbeJob() {}
976
977 private:
978 // Runs on worker thread.
979 void DoProbe() {
980 result_ = HaveOnlyLoopbackAddresses();
981 }
982
983 void OnProbeComplete() {
984 if (!resolver_)
985 return;
986 resolver_->SetHaveOnlyLoopbackAddresses(result_);
987 }
988
989 // Used/set only on origin thread.
990 base::WeakPtr<HostResolverImpl> resolver_;
991
992 bool result_;
993
994 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
995};
996
[email protected]0f8f1b432010-03-16 19:06:03997//-----------------------------------------------------------------------------
998
[email protected]b3601bc22012-02-21 21:23:20999// Resolves the hostname using DnsTransaction.
1000// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461001class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201002 public:
1003 typedef base::Callback<void(int net_error,
1004 const AddressList& addr_list,
1005 base::TimeDelta ttl)> Callback;
1006
[email protected]0adcb2b2012-08-15 21:30:461007 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201008 const Key& key,
1009 const Callback& callback,
1010 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461011 : client_(client),
1012 family_(key.address_family),
1013 callback_(callback),
1014 net_log_(job_net_log) {
1015 DCHECK(client);
[email protected]b3601bc22012-02-21 21:23:201016 DCHECK(!callback.is_null());
1017
[email protected]0adcb2b2012-08-15 21:30:461018 // If unspecified, do IPv4 first, because suffix search will be faster.
1019 uint16 qtype = (family_ == ADDRESS_FAMILY_IPV6) ?
1020 dns_protocol::kTypeAAAA :
1021 dns_protocol::kTypeA;
1022 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
[email protected]b3601bc22012-02-21 21:23:201023 key.hostname,
1024 qtype,
[email protected]1def74c2012-03-22 20:07:001025 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
[email protected]0adcb2b2012-08-15 21:30:461026 true /* first_query */, base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201027 net_log_);
[email protected]b3601bc22012-02-21 21:23:201028 }
1029
1030 int Start() {
[email protected]4da911f2012-06-14 19:45:201031 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]b3601bc22012-02-21 21:23:201032 return transaction_->Start();
1033 }
1034
[email protected]0adcb2b2012-08-15 21:30:461035 private:
1036 void OnTransactionComplete(bool first_query,
1037 const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001038 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201039 int net_error,
1040 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471041 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511042 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201043 // Run |callback_| last since the owning Job will then delete this DnsTask.
[email protected]0adcb2b2012-08-15 21:30:461044 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511045 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461046 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1047 return;
[email protected]6c411902012-08-14 22:36:361048 }
[email protected]0adcb2b2012-08-15 21:30:461049
1050 CHECK(response);
[email protected]02cd6982013-01-10 20:12:511051 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1052 switch (transaction->GetType()) {
1053 case dns_protocol::kTypeA:
1054 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1055 break;
1056 case dns_protocol::kTypeAAAA:
1057 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1058 break;
1059 }
[email protected]0adcb2b2012-08-15 21:30:461060 AddressList addr_list;
1061 base::TimeDelta ttl;
1062 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1063 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1064 result,
1065 DnsResponse::DNS_PARSE_RESULT_MAX);
1066 if (result != DnsResponse::DNS_PARSE_OK) {
1067 // Fail even if the other query succeeds.
1068 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1069 return;
1070 }
1071
1072 bool needs_sort = false;
1073 if (first_query) {
1074 DCHECK(client_->GetConfig()) <<
1075 "Transaction should have been aborted when config changed!";
1076 if (family_ == ADDRESS_FAMILY_IPV6) {
1077 needs_sort = (addr_list.size() > 1);
1078 } else if (family_ == ADDRESS_FAMILY_UNSPECIFIED) {
1079 first_addr_list_ = addr_list;
1080 first_ttl_ = ttl;
1081 // Use fully-qualified domain name to avoid search.
1082 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
1083 response->GetDottedName() + ".",
1084 dns_protocol::kTypeAAAA,
1085 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1086 false /* first_query */, base::TimeTicks::Now()),
1087 net_log_);
1088 net_error = transaction_->Start();
1089 if (net_error != ERR_IO_PENDING)
1090 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1091 return;
1092 }
1093 } else {
1094 DCHECK_EQ(ADDRESS_FAMILY_UNSPECIFIED, family_);
1095 bool has_ipv6_addresses = !addr_list.empty();
1096 if (!first_addr_list_.empty()) {
1097 ttl = std::min(ttl, first_ttl_);
1098 // Place IPv4 addresses after IPv6.
1099 addr_list.insert(addr_list.end(), first_addr_list_.begin(),
1100 first_addr_list_.end());
1101 }
1102 needs_sort = (has_ipv6_addresses && addr_list.size() > 1);
1103 }
1104
1105 if (addr_list.empty()) {
1106 // TODO(szym): Don't fallback to ProcTask in this case.
1107 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1108 return;
1109 }
1110
1111 if (needs_sort) {
1112 // Sort could complete synchronously.
1113 client_->GetAddressSorter()->Sort(
1114 addr_list,
[email protected]4589a3a2012-09-20 20:57:071115 base::Bind(&DnsTask::OnSortComplete,
1116 AsWeakPtr(),
[email protected]0adcb2b2012-08-15 21:30:461117 base::TimeTicks::Now(),
1118 ttl));
1119 } else {
1120 OnSuccess(addr_list, ttl);
1121 }
1122 }
1123
1124 void OnSortComplete(base::TimeTicks start_time,
1125 base::TimeDelta ttl,
1126 bool success,
1127 const AddressList& addr_list) {
1128 if (!success) {
1129 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1130 base::TimeTicks::Now() - start_time);
1131 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1132 return;
1133 }
1134
1135 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1136 base::TimeTicks::Now() - start_time);
1137
1138 // AddressSorter prunes unusable destinations.
1139 if (addr_list.empty()) {
1140 LOG(WARNING) << "Address list empty after RFC3484 sort";
1141 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1142 return;
1143 }
1144
1145 OnSuccess(addr_list, ttl);
1146 }
1147
1148 void OnFailure(int net_error, DnsResponse::Result result) {
1149 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451150 net_log_.EndEvent(
1151 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1152 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]b3601bc22012-02-21 21:23:201153 callback_.Run(net_error, AddressList(), base::TimeDelta());
1154 }
1155
[email protected]0adcb2b2012-08-15 21:30:461156 void OnSuccess(const AddressList& addr_list, base::TimeDelta ttl) {
1157 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1158 addr_list.CreateNetLogCallback());
1159 callback_.Run(OK, addr_list, ttl);
1160 }
1161
1162 DnsClient* client_;
1163 AddressFamily family_;
[email protected]b3601bc22012-02-21 21:23:201164 // The listener to the results of this DnsTask.
1165 Callback callback_;
[email protected]b3601bc22012-02-21 21:23:201166 const BoundNetLog net_log_;
1167
1168 scoped_ptr<DnsTransaction> transaction_;
[email protected]0adcb2b2012-08-15 21:30:461169
1170 // Results from the first transaction. Used only if |family_| is unspecified.
1171 AddressList first_addr_list_;
1172 base::TimeDelta first_ttl_;
1173
1174 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201175};
1176
1177//-----------------------------------------------------------------------------
1178
[email protected]0f292de02012-02-01 22:28:201179// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201180class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391181 public:
[email protected]0f292de02012-02-01 22:28:201182 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351183 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181184 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201185 const Key& key,
[email protected]8c98d002012-07-18 19:02:271186 RequestPriority priority,
[email protected]16ee26d2012-03-08 03:34:351187 const BoundNetLog& request_net_log)
[email protected]12faa4c2012-11-06 04:44:181188 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201189 key_(key),
[email protected]8c98d002012-07-18 19:02:271190 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201191 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291192 had_dns_config_(false),
[email protected]1d932852012-06-19 19:40:331193 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291194 creation_time_(base::TimeTicks::Now()),
1195 priority_change_time_(creation_time_),
[email protected]0f292de02012-02-01 22:28:201196 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201197 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]4da911f2012-06-14 19:45:201198 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201199
1200 net_log_.BeginEvent(
1201 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451202 base::Bind(&NetLogJobCreationCallback,
1203 request_net_log.source(),
1204 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391205 }
1206
[email protected]0f292de02012-02-01 22:28:201207 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201208 if (is_running()) {
1209 // |resolver_| was destroyed with this Job still in flight.
1210 // Clean-up, record in the log, but don't run any callbacks.
1211 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201212 proc_task_->Cancel();
1213 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201214 }
[email protected]16ee26d2012-03-08 03:34:351215 // Clean up now for nice NetLog.
1216 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201217 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1218 ERR_ABORTED);
1219 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551220 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351221 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201222 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1223 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391224 }
[email protected]b3601bc22012-02-21 21:23:201225 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391226
[email protected]b3601bc22012-02-21 21:23:201227 // Log any remaining Requests as cancelled.
1228 for (RequestsList::const_iterator it = requests_.begin();
1229 it != requests_.end(); ++it) {
1230 Request* req = *it;
1231 if (req->was_canceled())
1232 continue;
1233 DCHECK_EQ(this, req->job());
1234 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1235 req->info());
1236 }
[email protected]68ad3ee2010-01-30 03:45:391237 }
1238
[email protected]16ee26d2012-03-08 03:34:351239 // Add this job to the dispatcher.
[email protected]8c98d002012-07-18 19:02:271240 void Schedule() {
1241 handle_ = resolver_->dispatcher_.Add(this, priority());
[email protected]16ee26d2012-03-08 03:34:351242 }
1243
[email protected]b3601bc22012-02-21 21:23:201244 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201245 DCHECK_EQ(key_.hostname, req->info().hostname());
1246
1247 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201248 priority_tracker_.Add(req->info().priority());
1249
1250 req->request_net_log().AddEvent(
1251 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451252 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201253
1254 net_log_.AddEvent(
1255 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451256 base::Bind(&NetLogJobAttachCallback,
1257 req->request_net_log().source(),
1258 priority()));
[email protected]0f292de02012-02-01 22:28:201259
1260 // TODO(szym): Check if this is still needed.
1261 if (!req->info().is_speculative()) {
1262 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501263 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201264 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391265 }
[email protected]b3601bc22012-02-21 21:23:201266
1267 requests_.push_back(req.release());
1268
[email protected]51b9a6b2012-06-25 21:50:291269 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391270 }
1271
[email protected]16ee26d2012-03-08 03:34:351272 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461273 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201274 void CancelRequest(Request* req) {
1275 DCHECK_EQ(key_.hostname, req->info().hostname());
1276 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351277
[email protected]0f292de02012-02-01 22:28:201278 // Don't remove it from |requests_| just mark it canceled.
1279 req->MarkAsCanceled();
1280 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1281 req->info());
[email protected]16ee26d2012-03-08 03:34:351282
[email protected]0f292de02012-02-01 22:28:201283 priority_tracker_.Remove(req->info().priority());
1284 net_log_.AddEvent(
1285 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
[email protected]cd565142012-06-12 16:21:451286 base::Bind(&NetLogJobAttachCallback,
1287 req->request_net_log().source(),
1288 priority()));
[email protected]b3601bc22012-02-21 21:23:201289
[email protected]16ee26d2012-03-08 03:34:351290 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291291 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351292 } else {
1293 // If we were called from a Request's callback within CompleteRequests,
1294 // that Request could not have been cancelled, so num_active_requests()
1295 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431296 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201297 }
[email protected]68ad3ee2010-01-30 03:45:391298 }
1299
[email protected]7af985a2012-12-14 22:40:421300 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1301 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201302 void Abort() {
[email protected]0f292de02012-02-01 22:28:201303 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421304 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201305 }
1306
[email protected]f0f602bd2012-11-15 18:01:021307 // If DnsTask present, abort it and fall back to ProcTask.
1308 void AbortDnsTask() {
1309 if (dns_task_) {
1310 dns_task_.reset();
1311 dns_task_error_ = OK;
1312 StartProcTask();
1313 }
1314 }
1315
[email protected]16ee26d2012-03-08 03:34:351316 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1317 // Completes all requests and destroys the job.
1318 void OnEvicted() {
1319 DCHECK(!is_running());
1320 DCHECK(is_queued());
1321 handle_.Reset();
1322
[email protected]4da911f2012-06-14 19:45:201323 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351324
1325 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431326 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351327 }
1328
[email protected]78eac2a2012-03-14 19:09:271329 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1330 // this Job was destroyed.
1331 bool ServeFromHosts() {
1332 DCHECK_GT(num_active_requests(), 0u);
1333 AddressList addr_list;
1334 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031335 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271336 &addr_list)) {
1337 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171338 CompleteRequests(
1339 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1340 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271341 return true;
1342 }
1343 return false;
1344 }
1345
[email protected]b4481b222012-03-16 17:13:111346 const Key key() const {
1347 return key_;
1348 }
1349
1350 bool is_queued() const {
1351 return !handle_.is_null();
1352 }
1353
1354 bool is_running() const {
1355 return is_dns_running() || is_proc_running();
1356 }
1357
[email protected]16ee26d2012-03-08 03:34:351358 private:
[email protected]51b9a6b2012-06-25 21:50:291359 void UpdatePriority() {
1360 if (is_queued()) {
1361 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1362 priority_change_time_ = base::TimeTicks::Now();
1363 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
1364 }
1365 }
1366
[email protected]895123222012-10-25 15:21:171367 AddressList MakeAddressListForRequest(const AddressList& list) const {
1368 if (requests_.empty())
1369 return list;
1370 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1371 }
1372
[email protected]16ee26d2012-03-08 03:34:351373 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201374 virtual void Start() OVERRIDE {
1375 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201376 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201377
[email protected]4da911f2012-06-14 19:45:201378 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201379
[email protected]51b9a6b2012-06-25 21:50:291380 had_dns_config_ = resolver_->HaveDnsConfig();
1381
1382 base::TimeTicks now = base::TimeTicks::Now();
1383 base::TimeDelta queue_time = now - creation_time_;
1384 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1385
1386 if (had_dns_config_) {
1387 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1388 queue_time);
1389 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1390 queue_time_after_change);
1391 } else {
1392 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1393 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1394 queue_time_after_change);
1395 }
1396
[email protected]1d932852012-06-19 19:40:331397 // Caution: Job::Start must not complete synchronously.
[email protected]51b9a6b2012-06-25 21:50:291398 if (had_dns_config_ && !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201399 StartDnsTask();
1400 } else {
1401 StartProcTask();
1402 }
1403 }
1404
[email protected]b3601bc22012-02-21 21:23:201405 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1406 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1407 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1408 // tighter limits.
1409 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351410 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201411 proc_task_ = new ProcTask(
1412 key_,
1413 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371414 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1415 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201416 net_log_);
1417
1418 if (had_non_speculative_request_)
1419 proc_task_->set_had_non_speculative_request();
1420 // Start() could be called from within Resolve(), hence it must NOT directly
1421 // call OnProcTaskComplete, for example, on synchronous failure.
1422 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391423 }
1424
[email protected]0f292de02012-02-01 22:28:201425 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371426 void OnProcTaskComplete(base::TimeTicks start_time,
1427 int net_error,
1428 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201429 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391430
[email protected]62e86ba2013-01-29 18:59:161431 if (!resolver_->resolved_known_ipv6_hostname_ &&
1432 net_error == OK &&
1433 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1434 if (key_.hostname == "www.google.com") {
1435 resolver_->resolved_known_ipv6_hostname_ = true;
1436 bool got_ipv6_address = false;
1437 for (size_t i = 0; i < addr_list.size(); ++i) {
1438 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6)
1439 got_ipv6_address = true;
1440 }
1441 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1442 }
1443 }
1444
[email protected]1d932852012-06-19 19:40:331445 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371446 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001447 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371448 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331449 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1450 ResemblesNetBIOSName(key_.hostname)) {
1451 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1452 } else {
1453 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1454 }
1455 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1456 std::abs(dns_task_error_),
1457 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221458 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001459 } else {
[email protected]e3bd4822012-10-23 18:01:371460 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001461 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1462 }
1463 }
1464
[email protected]1339a2a22012-10-17 08:39:431465 base::TimeDelta ttl =
1466 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201467 if (net_error == OK)
1468 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391469
[email protected]895123222012-10-25 15:21:171470 // Don't store the |ttl| in cache since it's not obtained from the server.
1471 CompleteRequests(
1472 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1473 ttl);
[email protected]b3601bc22012-02-21 21:23:201474 }
1475
1476 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271477 DCHECK(resolver_->HaveDnsConfig());
[email protected]b3601bc22012-02-21 21:23:201478 dns_task_.reset(new DnsTask(
[email protected]0adcb2b2012-08-15 21:30:461479 resolver_->dns_client_.get(),
[email protected]b3601bc22012-02-21 21:23:201480 key_,
[email protected]e3bd4822012-10-23 18:01:371481 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this),
1482 base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201483 net_log_));
1484
1485 int rv = dns_task_->Start();
1486 if (rv != ERR_IO_PENDING) {
1487 DCHECK_NE(OK, rv);
[email protected]51b9a6b2012-06-25 21:50:291488 dns_task_error_ = rv;
[email protected]b3601bc22012-02-21 21:23:201489 dns_task_.reset();
1490 StartProcTask();
1491 }
1492 }
1493
1494 // Called by DnsTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371495 void OnDnsTaskComplete(base::TimeTicks start_time,
1496 int net_error,
[email protected]b3601bc22012-02-21 21:23:201497 const AddressList& addr_list,
1498 base::TimeDelta ttl) {
1499 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201500
[email protected]e3bd4822012-10-23 18:01:371501 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201502 if (net_error != OK) {
[email protected]e3bd4822012-10-23 18:01:371503 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1504
[email protected]1d932852012-06-19 19:40:331505 dns_task_error_ = net_error;
[email protected]16ee26d2012-03-08 03:34:351506 dns_task_.reset();
[email protected]78eac2a2012-03-14 19:09:271507
1508 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1509 // http://crbug.com/117655
1510
[email protected]b3601bc22012-02-21 21:23:201511 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1512 // ProcTask in that case is a waste of time.
1513 StartProcTask();
1514 return;
1515 }
[email protected]e3bd4822012-10-23 18:01:371516 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511517 // Log DNS lookups based on |address_family|.
1518 switch(key_.address_family) {
1519 case ADDRESS_FAMILY_IPV4:
1520 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1521 break;
1522 case ADDRESS_FAMILY_IPV6:
1523 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1524 break;
1525 case ADDRESS_FAMILY_UNSPECIFIED:
1526 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1527 break;
1528 }
[email protected]b3601bc22012-02-21 21:23:201529
[email protected]1def74c2012-03-22 20:07:001530 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431531 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461532
[email protected]1ffdda82012-12-12 23:04:221533 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021534
[email protected]895123222012-10-25 15:21:171535 base::TimeDelta bounded_ttl =
1536 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1537
1538 CompleteRequests(
1539 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1540 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201541 }
1542
[email protected]16ee26d2012-03-08 03:34:351543 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171544 void CompleteRequests(const HostCache::Entry& entry,
1545 base::TimeDelta ttl) {
[email protected]b3601bc22012-02-21 21:23:201546 CHECK(resolver_);
[email protected]b3601bc22012-02-21 21:23:201547
[email protected]16ee26d2012-03-08 03:34:351548 // This job must be removed from resolver's |jobs_| now to make room for a
1549 // new job with the same key in case one of the OnComplete callbacks decides
1550 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1551 // is done.
1552 scoped_ptr<Job> self_deleter(this);
1553
1554 resolver_->RemoveJob(this);
1555
[email protected]16ee26d2012-03-08 03:34:351556 if (is_running()) {
1557 DCHECK(!is_queued());
1558 if (is_proc_running()) {
1559 proc_task_->Cancel();
1560 proc_task_ = NULL;
1561 }
1562 dns_task_.reset();
1563
1564 // Signal dispatcher that a slot has opened.
1565 resolver_->dispatcher_.OnJobFinished();
1566 } else if (is_queued()) {
1567 resolver_->dispatcher_.Cancel(handle_);
1568 handle_.Reset();
1569 }
1570
1571 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201572 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351573 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1574 OK);
1575 return;
1576 }
[email protected]b3601bc22012-02-21 21:23:201577
1578 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171579 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391580
[email protected]78eac2a2012-03-14 19:09:271581 DCHECK(!requests_.empty());
1582
[email protected]895123222012-10-25 15:21:171583 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191584 // Record this histogram here, when we know the system has a valid DNS
1585 // configuration.
[email protected]539df6c2012-06-19 21:21:291586 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1587 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191588 }
[email protected]16ee26d2012-03-08 03:34:351589
[email protected]7af985a2012-12-14 22:40:421590 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171591 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1592 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431593 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351594
[email protected]0f292de02012-02-01 22:28:201595 // Complete all of the requests that were attached to the job.
1596 for (RequestsList::const_iterator it = requests_.begin();
1597 it != requests_.end(); ++it) {
1598 Request* req = *it;
1599
1600 if (req->was_canceled())
1601 continue;
1602
1603 DCHECK_EQ(this, req->job());
1604 // Update the net log and notify registered observers.
1605 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]895123222012-10-25 15:21:171606 req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291607 if (did_complete) {
1608 // Record effective total time from creation to completion.
1609 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1610 base::TimeTicks::Now() - req->request_time());
1611 }
[email protected]895123222012-10-25 15:21:171612 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201613
1614 // Check if the resolver was destroyed as a result of running the
1615 // callback. If it was, we could continue, but we choose to bail.
1616 if (!resolver_)
1617 return;
1618 }
1619 }
1620
[email protected]1339a2a22012-10-17 08:39:431621 // Convenience wrapper for CompleteRequests in case of failure.
1622 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171623 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1624 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431625 }
1626
[email protected]b4481b222012-03-16 17:13:111627 RequestPriority priority() const {
1628 return priority_tracker_.highest_priority();
1629 }
1630
1631 // Number of non-canceled requests in |requests_|.
1632 size_t num_active_requests() const {
1633 return priority_tracker_.total_count();
1634 }
1635
1636 bool is_dns_running() const {
1637 return dns_task_.get() != NULL;
1638 }
1639
1640 bool is_proc_running() const {
1641 return proc_task_.get() != NULL;
1642 }
1643
[email protected]0f292de02012-02-01 22:28:201644 base::WeakPtr<HostResolverImpl> resolver_;
1645
1646 Key key_;
1647
1648 // Tracks the highest priority across |requests_|.
1649 PriorityTracker priority_tracker_;
1650
1651 bool had_non_speculative_request_;
1652
[email protected]51b9a6b2012-06-25 21:50:291653 // Distinguishes measurements taken while DnsClient was fully configured.
1654 bool had_dns_config_;
1655
[email protected]1d932852012-06-19 19:40:331656 // Result of DnsTask.
1657 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001658
[email protected]51b9a6b2012-06-25 21:50:291659 const base::TimeTicks creation_time_;
1660 base::TimeTicks priority_change_time_;
1661
[email protected]0f292de02012-02-01 22:28:201662 BoundNetLog net_log_;
1663
[email protected]b3601bc22012-02-21 21:23:201664 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201665 scoped_refptr<ProcTask> proc_task_;
1666
[email protected]b3601bc22012-02-21 21:23:201667 // Resolves the host using a DnsTransaction.
1668 scoped_ptr<DnsTask> dns_task_;
1669
[email protected]0f292de02012-02-01 22:28:201670 // All Requests waiting for the result of this Job. Some can be canceled.
1671 RequestsList requests_;
1672
[email protected]16ee26d2012-03-08 03:34:351673 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201674 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391675};
1676
1677//-----------------------------------------------------------------------------
1678
[email protected]0f292de02012-02-01 22:28:201679HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431680 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201681 size_t max_retry_attempts)
1682 : resolver_proc(resolver_proc),
1683 max_retry_attempts(max_retry_attempts),
1684 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1685 retry_factor(2) {
1686}
1687
1688HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1689
1690HostResolverImpl::HostResolverImpl(
[email protected]c54a8912012-10-22 22:09:431691 scoped_ptr<HostCache> cache,
[email protected]0f292de02012-02-01 22:28:201692 const PrioritizedDispatcher::Limits& job_limits,
1693 const ProcTaskParams& proc_params,
[email protected]ee094b82010-08-24 15:55:511694 NetLog* net_log)
[email protected]c54a8912012-10-22 22:09:431695 : cache_(cache.Pass()),
[email protected]0f292de02012-02-01 22:28:201696 dispatcher_(job_limits),
1697 max_queued_jobs_(job_limits.total_jobs * 100u),
1698 proc_params_(proc_params),
[email protected]62e86ba2013-01-29 18:59:161699 net_log_(net_log),
[email protected]0c7798452009-10-26 17:59:511700 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]4589a3a2012-09-20 20:57:071701 weak_ptr_factory_(this),
[email protected]12faa4c2012-11-06 04:44:181702 probe_weak_ptr_factory_(this),
[email protected]d7b9a2b2012-05-31 22:31:191703 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021704 num_dns_failures_(0),
[email protected]2f3bc65c2010-07-23 17:47:101705 ipv6_probe_monitoring_(false),
[email protected]62e86ba2013-01-29 18:59:161706 resolved_known_ipv6_hostname_(false),
1707 additional_resolver_flags_(0) {
[email protected]0f292de02012-02-01 22:28:201708
1709 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391710
[email protected]06ef6d92011-05-19 04:24:581711 // Maximum of 4 retry attempts for host resolution.
1712 static const size_t kDefaultMaxRetryAttempts = 4u;
1713
[email protected]0f292de02012-02-01 22:28:201714 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1715 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391716
[email protected]b59ff372009-07-15 22:04:321717#if defined(OS_WIN)
1718 EnsureWinsockInit();
1719#endif
[email protected]23f771162011-06-02 18:37:511720#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:181721 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101722#endif
[email protected]232a5812011-03-04 22:42:081723 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401724 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191725#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1726 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191727 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341728#endif
[email protected]2ac22db2012-11-28 19:50:041729
1730 // TODO(szym): Remove when received_dns_config_ is removed, once
1731 // http://crbug.com/137914 is resolved.
1732 {
1733 DnsConfig dns_config;
1734 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1735 received_dns_config_ = dns_config.IsValid();
1736 }
[email protected]b59ff372009-07-15 22:04:321737}
1738
1739HostResolverImpl::~HostResolverImpl() {
[email protected]0f292de02012-02-01 22:28:201740 // This will also cancel all outstanding requests.
1741 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431742
[email protected]232a5812011-03-04 22:42:081743 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401744 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321745}
1746
[email protected]0f292de02012-02-01 22:28:201747void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1748 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1749 DCHECK_GT(value, 0u);
1750 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131751}
1752
[email protected]684970b2009-08-14 04:54:461753int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321754 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291755 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461756 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511757 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401758 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141759 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291760 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141761
[email protected]e806cd72013-05-17 02:08:431762 // Check that the caller supplied a valid hostname to resolve.
1763 std::string labeled_hostname;
1764 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1765 return ERR_NAME_NOT_RESOLVED;
1766
[email protected]ee094b82010-08-24 15:55:511767 // Make a log item for the request.
1768 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1769 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1770
[email protected]0f292de02012-02-01 22:28:201771 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321772
[email protected]123ab1e32009-10-21 19:12:571773 // Build a key that identifies the request in the cache and in the
1774 // outstanding jobs map.
[email protected]137af622010-02-05 02:14:351775 Key key = GetEffectiveKeyForRequest(info);
[email protected]123ab1e32009-10-21 19:12:571776
[email protected]287d7c22011-11-15 17:34:251777 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401778 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201779 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291780 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401781 return rv;
[email protected]38368712011-03-02 08:09:401782 }
1783
[email protected]0f292de02012-02-01 22:28:201784 // Next we need to attach our request to a "job". This job is responsible for
1785 // calling "getaddrinfo(hostname)" on a worker thread.
1786
1787 JobMap::iterator jobit = jobs_.find(key);
1788 Job* job;
1789 if (jobit == jobs_.end()) {
[email protected]12faa4c2012-11-06 04:44:181790 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, info.priority(),
1791 request_net_log);
[email protected]8c98d002012-07-18 19:02:271792 job->Schedule();
[email protected]0f292de02012-02-01 22:28:201793
1794 // Check for queue overflow.
1795 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1796 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1797 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351798 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201799 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201800 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201801 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201802 return rv;
1803 }
[email protected]0f292de02012-02-01 22:28:201804 }
[email protected]0f292de02012-02-01 22:28:201805 jobs_.insert(jobit, std::make_pair(key, job));
1806 } else {
1807 job = jobit->second;
1808 }
1809
1810 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201811 scoped_ptr<Request> req(new Request(source_net_log,
1812 request_net_log,
1813 info,
1814 callback,
1815 addresses));
[email protected]b59ff372009-07-15 22:04:321816 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201817 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321818
[email protected]b3601bc22012-02-21 21:23:201819 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201820 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321821 return ERR_IO_PENDING;
1822}
1823
[email protected]287d7c22011-11-15 17:34:251824int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401825 const RequestInfo& info,
1826 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001827 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401828 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1829 // On Windows it gives the default interface's address, whereas on Linux it
1830 // gives an error. We will make it fail on all platforms for consistency.
1831 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1832 return ERR_NAME_NOT_RESOLVED;
1833
1834 int net_error = ERR_UNEXPECTED;
1835 if (ResolveAsIP(key, info, &net_error, addresses))
1836 return net_error;
[email protected]78eac2a2012-03-14 19:09:271837 if (ServeFromCache(key, info, &net_error, addresses)) {
[email protected]4da911f2012-06-14 19:45:201838 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271839 return net_error;
1840 }
1841 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1842 // http://crbug.com/117655
1843 if (ServeFromHosts(key, info, addresses)) {
[email protected]4da911f2012-06-14 19:45:201844 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271845 return OK;
1846 }
1847 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401848}
1849
1850int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1851 AddressList* addresses,
1852 const BoundNetLog& source_net_log) {
1853 DCHECK(CalledOnValidThread());
1854 DCHECK(addresses);
1855
[email protected]95a214c2011-08-04 21:50:401856 // Make a log item for the request.
1857 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1858 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1859
1860 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201861 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401862
[email protected]95a214c2011-08-04 21:50:401863 Key key = GetEffectiveKeyForRequest(info);
1864
[email protected]287d7c22011-11-15 17:34:251865 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201866 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401867 return rv;
1868}
1869
[email protected]b59ff372009-07-15 22:04:321870void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141871 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321872 Request* req = reinterpret_cast<Request*>(req_handle);
1873 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201874 Job* job = req->job();
1875 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201876 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321877}
1878
[email protected]0f8f1b432010-03-16 19:06:031879void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141880 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031881 default_address_family_ = address_family;
[email protected]12faa4c2012-11-06 04:44:181882 ipv6_probe_monitoring_ = false;
[email protected]0f8f1b432010-03-16 19:06:031883}
1884
[email protected]f7d310e2010-10-07 16:25:111885AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1886 return default_address_family_;
1887}
1888
[email protected]9db6f702013-04-10 18:10:511889// TODO(szym): Remove this API altogether if IPv6ActiveProbe works.
[email protected]a78f4272011-10-21 19:16:331890void HostResolverImpl::ProbeIPv6Support() {
1891 DCHECK(CalledOnValidThread());
1892 DCHECK(!ipv6_probe_monitoring_);
1893 ipv6_probe_monitoring_ = true;
[email protected]12faa4c2012-11-06 04:44:181894 OnIPAddressChanged();
[email protected]ddb1e5a2010-12-13 20:10:451895}
1896
[email protected]a8883e452012-11-17 05:58:061897void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
1898 DCHECK(CalledOnValidThread());
1899#if defined(ENABLE_BUILT_IN_DNS)
1900 if (enabled && !dns_client_) {
1901 SetDnsClient(DnsClient::CreateClient(net_log_));
1902 } else if (!enabled && dns_client_) {
1903 SetDnsClient(scoped_ptr<DnsClient>());
1904 }
1905#endif
1906}
1907
[email protected]489d1a82011-10-12 03:09:111908HostCache* HostResolverImpl::GetHostCache() {
1909 return cache_.get();
1910}
[email protected]95a214c2011-08-04 21:50:401911
[email protected]17e92032012-03-29 00:56:241912base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
1913 // Check if async DNS is disabled.
1914 if (!dns_client_.get())
1915 return NULL;
1916
1917 // Check if async DNS is enabled, but we currently have no configuration
1918 // for it.
1919 const DnsConfig* dns_config = dns_client_->GetConfig();
1920 if (dns_config == NULL)
1921 return new DictionaryValue();
1922
1923 return dns_config->ToValue();
1924}
1925
[email protected]95a214c2011-08-04 21:50:401926bool HostResolverImpl::ResolveAsIP(const Key& key,
1927 const RequestInfo& info,
1928 int* net_error,
1929 AddressList* addresses) {
1930 DCHECK(addresses);
1931 DCHECK(net_error);
1932 IPAddressNumber ip_number;
1933 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1934 return false;
1935
1936 DCHECK_EQ(key.host_resolver_flags &
1937 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1938 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1939 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201940 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
1941 !ipv6_probe_monitoring_;
[email protected]95a214c2011-08-04 21:50:401942 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201943 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401944 *net_error = ERR_NAME_NOT_RESOLVED;
1945 } else {
[email protected]7054e78f2012-05-07 21:44:561946 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
1947 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
1948 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:401949 }
1950 return true;
1951}
1952
1953bool HostResolverImpl::ServeFromCache(const Key& key,
1954 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401955 int* net_error,
1956 AddressList* addresses) {
1957 DCHECK(addresses);
1958 DCHECK(net_error);
1959 if (!info.allow_cached_response() || !cache_.get())
1960 return false;
1961
[email protected]407a30ab2012-08-15 17:16:101962 const HostCache::Entry* cache_entry = cache_->Lookup(
1963 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:401964 if (!cache_entry)
1965 return false;
1966
[email protected]95a214c2011-08-04 21:50:401967 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:561968 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:431969 if (cache_entry->has_ttl())
1970 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:171971 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:561972 }
[email protected]95a214c2011-08-04 21:50:401973 return true;
1974}
1975
[email protected]78eac2a2012-03-14 19:09:271976bool HostResolverImpl::ServeFromHosts(const Key& key,
1977 const RequestInfo& info,
1978 AddressList* addresses) {
1979 DCHECK(addresses);
1980 if (!HaveDnsConfig())
1981 return false;
[email protected]05a79d42013-03-28 07:30:091982 addresses->clear();
1983
[email protected]cb507622012-03-23 16:17:061984 // HOSTS lookups are case-insensitive.
1985 std::string hostname = StringToLowerASCII(key.hostname);
1986
[email protected]05a79d42013-03-28 07:30:091987 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1988
[email protected]78eac2a2012-03-14 19:09:271989 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1990 // (glibc and c-ares) return the first matching line. We have more
1991 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:091992 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
1993 // necessary.
1994 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
1995 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1996 DnsHosts::const_iterator it = hosts.find(
1997 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
1998 if (it != hosts.end())
1999 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272000 }
2001
[email protected]05a79d42013-03-28 07:30:092002 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2003 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2004 DnsHosts::const_iterator it = hosts.find(
2005 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2006 if (it != hosts.end())
2007 addresses->push_back(IPEndPoint(it->second, info.port()));
2008 }
2009
[email protected]ec666ab22013-04-17 20:05:592010 // If got only loopback addresses and the family was restricted, resolve
2011 // again, without restrictions. See SystemHostResolverCall for rationale.
2012 if ((key.host_resolver_flags &
2013 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2014 IsAllIPv4Loopback(*addresses)) {
2015 Key new_key(key);
2016 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2017 new_key.host_resolver_flags &=
2018 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2019 return ServeFromHosts(new_key, info, addresses);
2020 }
[email protected]05a79d42013-03-28 07:30:092021 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272022}
2023
[email protected]16ee26d2012-03-08 03:34:352024void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432025 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352026 base::TimeDelta ttl) {
2027 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432028 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032029}
2030
[email protected]0f292de02012-02-01 22:28:202031void HostResolverImpl::RemoveJob(Job* job) {
2032 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352033 JobMap::iterator it = jobs_.find(job->key());
2034 if (it != jobs_.end() && it->second == job)
2035 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322036}
2037
[email protected]0f8f1b432010-03-16 19:06:032038void HostResolverImpl::IPv6ProbeSetDefaultAddressFamily(
2039 AddressFamily address_family) {
2040 DCHECK(address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2041 address_family == ADDRESS_FAMILY_IPV4);
[email protected]12faa4c2012-11-06 04:44:182042 if (!ipv6_probe_monitoring_)
2043 return;
[email protected]f092e64b2010-03-17 00:39:182044 if (default_address_family_ != address_family) {
[email protected]b30a3f52010-10-16 01:05:462045 VLOG(1) << "IPv6Probe forced AddressFamily setting to "
2046 << ((address_family == ADDRESS_FAMILY_UNSPECIFIED) ?
2047 "ADDRESS_FAMILY_UNSPECIFIED" : "ADDRESS_FAMILY_IPV4");
[email protected]f092e64b2010-03-17 00:39:182048 }
[email protected]0f8f1b432010-03-16 19:06:032049 default_address_family_ = address_family;
[email protected]e95d3aca2010-01-11 22:47:432050}
2051
[email protected]9936a7862012-10-26 04:44:022052void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2053 if (result) {
2054 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2055 } else {
2056 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2057 }
2058}
2059
[email protected]137af622010-02-05 02:14:352060HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
2061 const RequestInfo& info) const {
[email protected]eaf3a3b2010-09-03 20:34:272062 HostResolverFlags effective_flags =
2063 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352064 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512065
2066 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]ac0b52e2013-04-21 01:26:162067 if (ipv6_probe_monitoring_) {
2068 base::TimeTicks start_time = base::TimeTicks::Now();
2069 // Google DNS address.
2070 const uint8 kIPv6Address[] =
2071 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2072 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
2073 IPAddressNumber address(kIPv6Address,
2074 kIPv6Address + arraysize(kIPv6Address));
2075 bool rv6 = IsGloballyReachable(address);
[email protected]9db6f702013-04-10 18:10:512076
[email protected]ac0b52e2013-04-21 01:26:162077 UMA_HISTOGRAM_TIMES("Net.IPv6ConnectDuration",
2078 base::TimeTicks::Now() - start_time);
2079 if (rv6) {
2080 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch",
2081 default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED);
2082 } else {
2083 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch",
2084 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED);
2085
2086 effective_address_family = ADDRESS_FAMILY_IPV4;
2087 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2088 }
[email protected]9db6f702013-04-10 18:10:512089 } else {
[email protected]ac0b52e2013-04-21 01:26:162090 effective_address_family = default_address_family_;
[email protected]9db6f702013-04-10 18:10:512091 }
2092 }
2093
[email protected]eaf3a3b2010-09-03 20:34:272094 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352095}
2096
[email protected]35ddc282010-09-21 23:42:062097void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202098 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2099 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542100 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202101 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2102 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202103 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202104 jobs_to_abort.push_back(job);
2105 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202106 } else {
[email protected]b3601bc22012-02-21 21:23:202107 DCHECK(job->is_queued());
2108 ++it;
[email protected]0f292de02012-02-01 22:28:202109 }
[email protected]ef4c40c2010-09-01 14:42:032110 }
[email protected]b3601bc22012-02-21 21:23:202111
[email protected]57a48d32012-03-03 00:04:552112 // Check if no dispatcher slots leaked out.
2113 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
2114
2115 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072116 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552117
[email protected]16ee26d2012-03-08 03:34:352118 // Then Abort them.
[email protected]57a48d32012-03-03 00:04:552119 for (size_t i = 0; self && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552120 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542121 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202122 }
[email protected]ef4c40c2010-09-01 14:42:032123}
2124
[email protected]78eac2a2012-03-14 19:09:272125void HostResolverImpl::TryServingAllJobsFromHosts() {
2126 if (!HaveDnsConfig())
2127 return;
2128
2129 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2130 // http://crbug.com/117655
2131
2132 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072133 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272134
2135 for (JobMap::iterator it = jobs_.begin(); self && it != jobs_.end(); ) {
2136 Job* job = it->second;
2137 ++it;
2138 // This could remove |job| from |jobs_|, but iterator will remain valid.
2139 job->ServeFromHosts();
2140 }
2141}
2142
[email protected]be1a48b2011-01-20 00:12:132143void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162144 resolved_known_ipv6_hostname_ = false;
[email protected]12faa4c2012-11-06 04:44:182145 // Abandon all ProbeJobs.
2146 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132147 if (cache_.get())
2148 cache_->clear();
[email protected]12faa4c2012-11-06 04:44:182149 if (ipv6_probe_monitoring_)
2150 new IPv6ProbeJob(probe_weak_ptr_factory_.GetWeakPtr(), net_log_);
[email protected]23f771162011-06-02 18:37:512151#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:182152 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132153#endif
2154 AbortAllInProgressJobs();
2155 // |this| may be deleted inside AbortAllInProgressJobs().
2156}
2157
[email protected]bb0e34542012-08-31 19:52:402158void HostResolverImpl::OnDNSChanged() {
2159 DnsConfig dns_config;
2160 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592161
[email protected]b4481b222012-03-16 17:13:112162 if (net_log_) {
2163 net_log_->AddGlobalEntry(
2164 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452165 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112166 }
2167
[email protected]01b3b9d2012-08-13 16:18:142168 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192169 received_dns_config_ = dns_config.IsValid();
[email protected]78eac2a2012-03-14 19:09:272170
[email protected]a8883e452012-11-17 05:58:062171 num_dns_failures_ = 0;
2172
[email protected]01b3b9d2012-08-13 16:18:142173 // We want a new DnsSession in place, before we Abort running Jobs, so that
2174 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022175 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192176 dns_client_->SetConfig(dns_config);
[email protected]a8883e452012-11-17 05:58:062177 if (dns_config.IsValid())
[email protected]f0f602bd2012-11-15 18:01:022178 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022179 }
[email protected]01b3b9d2012-08-13 16:18:142180
2181 // If the DNS server has changed, existing cached info could be wrong so we
2182 // have to drop our internal cache :( Note that OS level DNS caches, such
2183 // as NSCD's cache should be dropped automatically by the OS when
2184 // resolv.conf changes so we don't need to do anything to clear that cache.
2185 if (cache_.get())
2186 cache_->clear();
2187
[email protected]f0f602bd2012-11-15 18:01:022188 // Life check to bail once |this| is deleted.
2189 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2190
[email protected]01b3b9d2012-08-13 16:18:142191 // Existing jobs will have been sent to the original server so they need to
2192 // be aborted.
2193 AbortAllInProgressJobs();
2194
2195 // |this| may be deleted inside AbortAllInProgressJobs().
2196 if (self)
2197 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272198}
2199
2200bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252201 // Use DnsClient only if it's fully configured and there is no override by
2202 // ScopedDefaultHostResolverProc.
2203 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2204 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502205 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2206 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252207 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202208}
2209
[email protected]1ffdda82012-12-12 23:04:222210void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022211 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222212 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022213 num_dns_failures_ = 0;
2214 return;
2215 }
2216 ++num_dns_failures_;
2217 if (num_dns_failures_ < kMaximumDnsFailures)
2218 return;
2219 // Disable DnsClient until the next DNS change.
2220 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2221 it->second->AbortDnsTask();
2222 dns_client_->SetConfig(DnsConfig());
2223 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222224 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2225 std::abs(net_error),
2226 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022227}
2228
[email protected]a8883e452012-11-17 05:58:062229void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
2230 if (HaveDnsConfig()) {
2231 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2232 it->second->AbortDnsTask();
2233 }
2234 dns_client_ = dns_client.Pass();
2235 if (!dns_client_ || dns_client_->GetConfig() ||
2236 num_dns_failures_ >= kMaximumDnsFailures) {
2237 return;
2238 }
2239 DnsConfig dns_config;
2240 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2241 dns_client_->SetConfig(dns_config);
2242 num_dns_failures_ = 0;
2243 if (dns_config.IsValid())
2244 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2245}
2246
[email protected]b59ff372009-07-15 22:04:322247} // namespace net