blob: 95e03ba7a912a857586e0ceaf1c6845a4679820d [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]ee094b82010-08-24 15:55:5136#include "net/base/host_port_pair.h"
[email protected]2bb04442010-08-18 18:01:1537#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5138#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0339#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4640#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2741#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2042#include "net/dns/dns_config_service.h"
43#include "net/dns/dns_protocol.h"
44#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2045#include "net/dns/dns_transaction.h"
[email protected]f2cb3cf2013-03-21 01:40:5346#include "net/dns/host_resolver_proc.h"
[email protected]9db6f702013-04-10 18:10:5147#include "net/socket/client_socket_factory.h"
48#include "net/udp/datagram_client_socket.h"
[email protected]b59ff372009-07-15 22:04:3249
50#if defined(OS_WIN)
51#include "net/base/winsock_init.h"
52#endif
53
54namespace net {
55
[email protected]e95d3aca2010-01-11 22:47:4356namespace {
57
[email protected]6e78dfb2011-07-28 21:34:4758// Limit the size of hostnames that will be resolved to combat issues in
59// some platform's resolvers.
60const size_t kMaxHostLength = 4096;
61
[email protected]a2730882012-01-21 00:56:2762// Default TTL for successful resolutions with ProcTask.
63const unsigned kCacheEntryTTLSeconds = 60;
64
[email protected]b3601bc22012-02-21 21:23:2065// Default TTL for unsuccessful resolutions with ProcTask.
66const unsigned kNegativeCacheEntryTTLSeconds = 0;
67
[email protected]895123222012-10-25 15:21:1768// Minimum TTL for successful resolutions with DnsTask.
69const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
70
[email protected]f0f602bd2012-11-15 18:01:0271// Number of consecutive failures of DnsTask (with successful fallback) before
72// the DnsClient is disabled until the next DNS change.
73const unsigned kMaximumDnsFailures = 16;
74
[email protected]24f4bab2010-10-15 01:27:1175// We use a separate histogram name for each platform to facilitate the
76// display of error codes by their symbolic name (since each platform has
77// different mappings).
78const char kOSErrorsForGetAddrinfoHistogramName[] =
79#if defined(OS_WIN)
80 "Net.OSErrorsForGetAddrinfo_Win";
81#elif defined(OS_MACOSX)
82 "Net.OSErrorsForGetAddrinfo_Mac";
83#elif defined(OS_LINUX)
84 "Net.OSErrorsForGetAddrinfo_Linux";
85#else
86 "Net.OSErrorsForGetAddrinfo";
87#endif
88
[email protected]c89b2442011-05-26 14:28:2789// Gets a list of the likely error codes that getaddrinfo() can return
90// (non-exhaustive). These are the error codes that we will track via
91// a histogram.
92std::vector<int> GetAllGetAddrinfoOSErrors() {
93 int os_errors[] = {
94#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:5195#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:3796#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:4597 // EAI_ADDRFAMILY has been declared obsolete in Android's and
98 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:2799 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37100#endif
[email protected]c48aef92011-11-22 23:41:45101 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51102 EAI_NODATA,
103#endif
[email protected]c89b2442011-05-26 14:28:27104 EAI_AGAIN,
105 EAI_BADFLAGS,
106 EAI_FAIL,
107 EAI_FAMILY,
108 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27109 EAI_NONAME,
110 EAI_SERVICE,
111 EAI_SOCKTYPE,
112 EAI_SYSTEM,
113#elif defined(OS_WIN)
114 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
115 WSA_NOT_ENOUGH_MEMORY,
116 WSAEAFNOSUPPORT,
117 WSAEINVAL,
118 WSAESOCKTNOSUPPORT,
119 WSAHOST_NOT_FOUND,
120 WSANO_DATA,
121 WSANO_RECOVERY,
122 WSANOTINITIALISED,
123 WSATRY_AGAIN,
124 WSATYPE_NOT_FOUND,
125 // The following are not in doc, but might be to appearing in results :-(.
126 WSA_INVALID_HANDLE,
127#endif
128 };
129
130 // Ensure all errors are positive, as histogram only tracks positive values.
131 for (size_t i = 0; i < arraysize(os_errors); ++i) {
132 os_errors[i] = std::abs(os_errors[i]);
133 }
134
135 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
136 arraysize(os_errors));
137}
138
[email protected]1def74c2012-03-22 20:07:00139enum DnsResolveStatus {
140 RESOLVE_STATUS_DNS_SUCCESS = 0,
141 RESOLVE_STATUS_PROC_SUCCESS,
142 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33143 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00144 RESOLVE_STATUS_MAX
145};
146
147void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
148 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
149 result,
150 RESOLVE_STATUS_MAX);
151}
152
[email protected]1d932852012-06-19 19:40:33153bool ResemblesNetBIOSName(const std::string& hostname) {
154 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
155}
156
157// True if |hostname| ends with either ".local" or ".local.".
158bool ResemblesMulticastDNSName(const std::string& hostname) {
159 DCHECK(!hostname.empty());
160 const char kSuffix[] = ".local.";
161 const size_t kSuffixLen = sizeof(kSuffix) - 1;
162 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
163 if (hostname[hostname.size() - 1] == '.') {
164 return hostname.size() > kSuffixLen &&
165 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
166 }
167 return hostname.size() > kSuffixLenTrimmed &&
168 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
169 kSuffix, kSuffixLenTrimmed);
170}
171
[email protected]9db6f702013-04-10 18:10:51172// Attempts to connect a UDP socket to |dest|:80.
[email protected]e9051722013-04-12 21:58:18173bool IsGloballyReachable(const IPAddressNumber& dest) {
[email protected]9db6f702013-04-10 18:10:51174 scoped_ptr<DatagramClientSocket> socket(
175 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
176 DatagramSocket::DEFAULT_BIND,
177 RandIntCallback(),
178 NULL,
179 NetLog::Source()));
[email protected]e9051722013-04-12 21:58:18180 int rv = socket->Connect(IPEndPoint(dest, 80));
181 if (rv != OK)
182 return false;
183 IPEndPoint endpoint;
184 rv = socket->GetLocalAddress(&endpoint);
185 if (rv != OK)
186 return false;
187 DCHECK(endpoint.GetFamily() == ADDRESS_FAMILY_IPV6);
188 const IPAddressNumber& address = endpoint.address();
189 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
190 if (is_link_local)
191 return false;
192 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
193 bool is_teredo = std::equal(kTeredoPrefix,
194 kTeredoPrefix + arraysize(kTeredoPrefix),
195 address.begin());
196 if (is_teredo)
197 return false;
198 return true;
[email protected]9db6f702013-04-10 18:10:51199}
200
[email protected]51b9a6b2012-06-25 21:50:29201// Provide a common macro to simplify code and readability. We must use a
202// macro as the underlying HISTOGRAM macro creates static variables.
203#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
204 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
205
206// A macro to simplify code and readability.
207#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
208 do { \
209 switch (priority) { \
210 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
211 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
212 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
213 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
214 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
215 default: NOTREACHED(); break; \
216 } \
217 DNS_HISTOGRAM(basename, time); \
218 } while (0)
219
220// Record time from Request creation until a valid DNS response.
221void RecordTotalTime(bool had_dns_config,
222 bool speculative,
223 base::TimeDelta duration) {
224 if (had_dns_config) {
225 if (speculative) {
226 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
227 } else {
228 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
229 }
230 } else {
231 if (speculative) {
232 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
233 } else {
234 DNS_HISTOGRAM("DNS.TotalTime", duration);
235 }
236 }
237}
238
[email protected]1339a2a22012-10-17 08:39:43239void RecordTTL(base::TimeDelta ttl) {
240 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
241 base::TimeDelta::FromSeconds(1),
242 base::TimeDelta::FromDays(1), 100);
243}
244
[email protected]d7b9a2b2012-05-31 22:31:19245//-----------------------------------------------------------------------------
246
[email protected]895123222012-10-25 15:21:17247AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
248 if (list.empty() || list.front().port() == port)
249 return list;
250 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56251}
252
[email protected]ec666ab22013-04-17 20:05:59253// Returns true if |addresses| contains only IPv4 loopback addresses.
254bool IsAllIPv4Loopback(const AddressList& addresses) {
255 for (unsigned i = 0; i < addresses.size(); ++i) {
256 const IPAddressNumber& address = addresses[i].address();
257 switch (addresses[i].GetFamily()) {
258 case ADDRESS_FAMILY_IPV4:
259 if (address[0] != 127)
260 return false;
261 break;
262 case ADDRESS_FAMILY_IPV6:
263 return false;
264 default:
265 NOTREACHED();
266 return false;
267 }
268 }
269 return true;
270}
271
[email protected]cd565142012-06-12 16:21:45272// Creates NetLog parameters when the resolve failed.
273base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
274 int net_error,
275 int os_error,
276 NetLog::LogLevel /* log_level */) {
277 DictionaryValue* dict = new DictionaryValue();
278 if (attempt_number)
279 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46280
[email protected]cd565142012-06-12 16:21:45281 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16282
[email protected]cd565142012-06-12 16:21:45283 if (os_error) {
284 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46285#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45286 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46287#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45288 // Map the error code to a human-readable string.
289 LPWSTR error_string = NULL;
290 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
291 FORMAT_MESSAGE_FROM_SYSTEM,
292 0, // Use the internal message table.
293 os_error,
294 0, // Use default language.
295 (LPWSTR)&error_string,
296 0, // Buffer size.
297 0); // Arguments (unused).
298 dict->SetString("os_error_string", WideToUTF8(error_string));
299 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46300#endif
[email protected]21526002010-05-16 19:42:46301 }
302
[email protected]cd565142012-06-12 16:21:45303 return dict;
304}
[email protected]a9813302012-04-28 09:29:28305
[email protected]cd565142012-06-12 16:21:45306// Creates NetLog parameters when the DnsTask failed.
307base::Value* NetLogDnsTaskFailedCallback(int net_error,
308 int dns_error,
309 NetLog::LogLevel /* log_level */) {
310 DictionaryValue* dict = new DictionaryValue();
311 dict->SetInteger("net_error", net_error);
312 if (dns_error)
313 dict->SetInteger("dns_error", dns_error);
314 return dict;
[email protected]ee094b82010-08-24 15:55:51315};
316
[email protected]cd565142012-06-12 16:21:45317// Creates NetLog parameters containing the information in a RequestInfo object,
318// along with the associated NetLog::Source.
319base::Value* NetLogRequestInfoCallback(const NetLog::Source& source,
320 const HostResolver::RequestInfo* info,
321 NetLog::LogLevel /* log_level */) {
322 DictionaryValue* dict = new DictionaryValue();
323 source.AddToEventParameters(dict);
[email protected]b3601bc22012-02-21 21:23:20324
[email protected]cd565142012-06-12 16:21:45325 dict->SetString("host", info->host_port_pair().ToString());
326 dict->SetInteger("address_family",
327 static_cast<int>(info->address_family()));
328 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
329 dict->SetBoolean("is_speculative", info->is_speculative());
330 dict->SetInteger("priority", info->priority());
331 return dict;
332}
[email protected]b3601bc22012-02-21 21:23:20333
[email protected]cd565142012-06-12 16:21:45334// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
335base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
336 const std::string* host,
337 NetLog::LogLevel /* log_level */) {
338 DictionaryValue* dict = new DictionaryValue();
339 source.AddToEventParameters(dict);
340 dict->SetString("host", *host);
341 return dict;
342}
[email protected]a9813302012-04-28 09:29:28343
[email protected]cd565142012-06-12 16:21:45344// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
345base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
346 RequestPriority priority,
347 NetLog::LogLevel /* log_level */) {
348 DictionaryValue* dict = new DictionaryValue();
349 source.AddToEventParameters(dict);
350 dict->SetInteger("priority", priority);
351 return dict;
352}
[email protected]b3601bc22012-02-21 21:23:20353
[email protected]cd565142012-06-12 16:21:45354// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
355base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
356 NetLog::LogLevel /* log_level */) {
357 return config->ToValue();
358}
[email protected]b4481b222012-03-16 17:13:11359
[email protected]0f292de02012-02-01 22:28:20360// The logging routines are defined here because some requests are resolved
361// without a Request object.
362
363// Logs when a request has just been started.
364void LogStartRequest(const BoundNetLog& source_net_log,
365 const BoundNetLog& request_net_log,
366 const HostResolver::RequestInfo& info) {
367 source_net_log.BeginEvent(
368 NetLog::TYPE_HOST_RESOLVER_IMPL,
[email protected]cd565142012-06-12 16:21:45369 request_net_log.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:20370
371 request_net_log.BeginEvent(
372 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
[email protected]cd565142012-06-12 16:21:45373 base::Bind(&NetLogRequestInfoCallback, source_net_log.source(), &info));
[email protected]0f292de02012-02-01 22:28:20374}
375
376// Logs when a request has just completed (before its callback is run).
377void LogFinishRequest(const BoundNetLog& source_net_log,
378 const BoundNetLog& request_net_log,
379 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20380 int net_error) {
381 request_net_log.EndEventWithNetErrorCode(
382 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]4da911f2012-06-14 19:45:20383 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20384}
385
386// Logs when a request has been cancelled.
387void LogCancelRequest(const BoundNetLog& source_net_log,
388 const BoundNetLog& request_net_log,
389 const HostResolverImpl::RequestInfo& info) {
[email protected]4da911f2012-06-14 19:45:20390 request_net_log.AddEvent(NetLog::TYPE_CANCELLED);
391 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
392 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20393}
394
[email protected]b59ff372009-07-15 22:04:32395//-----------------------------------------------------------------------------
396
[email protected]0f292de02012-02-01 22:28:20397// Keeps track of the highest priority.
398class PriorityTracker {
399 public:
[email protected]8c98d002012-07-18 19:02:27400 explicit PriorityTracker(RequestPriority initial_priority)
401 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20402 memset(counts_, 0, sizeof(counts_));
403 }
404
405 RequestPriority highest_priority() const {
406 return highest_priority_;
407 }
408
409 size_t total_count() const {
410 return total_count_;
411 }
412
413 void Add(RequestPriority req_priority) {
414 ++total_count_;
415 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05416 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20417 highest_priority_ = req_priority;
418 }
419
420 void Remove(RequestPriority req_priority) {
421 DCHECK_GT(total_count_, 0u);
422 DCHECK_GT(counts_[req_priority], 0u);
423 --total_count_;
424 --counts_[req_priority];
425 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05426 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20427 highest_priority_ = static_cast<RequestPriority>(i);
428
[email protected]31ae7ab2012-04-24 21:09:05429 // In absence of requests, default to MINIMUM_PRIORITY.
430 if (total_count_ == 0)
431 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20432 }
433
434 private:
435 RequestPriority highest_priority_;
436 size_t total_count_;
437 size_t counts_[NUM_PRIORITIES];
438};
439
[email protected]c54a8912012-10-22 22:09:43440} // namespace
[email protected]0f292de02012-02-01 22:28:20441
442//-----------------------------------------------------------------------------
443
444// Holds the data for a request that could not be completed synchronously.
445// It is owned by a Job. Canceled Requests are only marked as canceled rather
446// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32447class HostResolverImpl::Request {
448 public:
[email protected]ee094b82010-08-24 15:55:51449 Request(const BoundNetLog& source_net_log,
450 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09451 const RequestInfo& info,
[email protected]aa22b242011-11-16 18:58:29452 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32453 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51454 : source_net_log_(source_net_log),
455 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09456 info_(info),
457 job_(NULL),
458 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29459 addresses_(addresses),
460 request_time_(base::TimeTicks::Now()) {
[email protected]54e13772009-08-14 03:01:09461 }
[email protected]b59ff372009-07-15 22:04:32462
[email protected]0f292de02012-02-01 22:28:20463 // Mark the request as canceled.
464 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32465 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32466 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29467 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32468 }
469
[email protected]0f292de02012-02-01 22:28:20470 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29471 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32472 }
473
474 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20475 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32476 // Identify which job the request is waiting on.
477 job_ = job;
478 }
479
[email protected]0f292de02012-02-01 22:28:20480 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20481 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29482 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17483 if (error == OK)
484 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29485 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20486 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29487 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32488 }
489
[email protected]b59ff372009-07-15 22:04:32490 Job* job() const {
491 return job_;
492 }
493
[email protected]0f292de02012-02-01 22:28:20494 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51495 const BoundNetLog& source_net_log() {
496 return source_net_log_;
497 }
498
[email protected]0f292de02012-02-01 22:28:20499 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51500 const BoundNetLog& request_net_log() {
501 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09502 }
503
[email protected]b59ff372009-07-15 22:04:32504 const RequestInfo& info() const {
505 return info_;
506 }
507
[email protected]51b9a6b2012-06-25 21:50:29508 base::TimeTicks request_time() const {
509 return request_time_;
510 }
511
[email protected]b59ff372009-07-15 22:04:32512 private:
[email protected]ee094b82010-08-24 15:55:51513 BoundNetLog source_net_log_;
514 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09515
[email protected]b59ff372009-07-15 22:04:32516 // The request info that started the request.
517 RequestInfo info_;
518
[email protected]0f292de02012-02-01 22:28:20519 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32520 Job* job_;
521
522 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29523 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32524
525 // The address list to save result into.
526 AddressList* addresses_;
527
[email protected]51b9a6b2012-06-25 21:50:29528 const base::TimeTicks request_time_;
529
[email protected]b59ff372009-07-15 22:04:32530 DISALLOW_COPY_AND_ASSIGN(Request);
531};
532
[email protected]1e9bbd22010-10-15 16:42:45533//------------------------------------------------------------------------------
534
[email protected]0f292de02012-02-01 22:28:20535// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
536//
537// Whenever we try to resolve the host, we post a delayed task to check if host
538// resolution (OnLookupComplete) is completed or not. If the original attempt
539// hasn't completed, then we start another attempt for host resolution. We take
540// the results from the first attempt that finishes and ignore the results from
541// all other attempts.
542//
543// TODO(szym): Move to separate source file for testing and mocking.
544//
545class HostResolverImpl::ProcTask
546 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32547 public:
[email protected]b3601bc22012-02-21 21:23:20548 typedef base::Callback<void(int net_error,
549 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32550
[email protected]0f292de02012-02-01 22:28:20551 ProcTask(const Key& key,
552 const ProcTaskParams& params,
553 const Callback& callback,
554 const BoundNetLog& job_net_log)
555 : key_(key),
556 params_(params),
557 callback_(callback),
558 origin_loop_(base::MessageLoopProxy::current()),
559 attempt_number_(0),
560 completed_attempt_number_(0),
561 completed_attempt_error_(ERR_UNEXPECTED),
562 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20563 net_log_(job_net_log) {
[email protected]0f292de02012-02-01 22:28:20564 if (!params_.resolver_proc)
565 params_.resolver_proc = HostResolverProc::GetDefault();
566 // If default is unset, use the system proc.
567 if (!params_.resolver_proc)
[email protected]1ee9afa12013-04-16 14:18:06568 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32569 }
570
[email protected]b59ff372009-07-15 22:04:32571 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15572 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20573 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54574 StartLookupAttempt();
575 }
[email protected]252b699b2010-02-05 21:38:06576
[email protected]0f292de02012-02-01 22:28:20577 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
578 // attempts running on worker threads will continue running. Only once all the
579 // attempts complete will the final reference to this ProcTask be released.
580 void Cancel() {
581 DCHECK(origin_loop_->BelongsToCurrentThread());
582
[email protected]0adcb2b2012-08-15 21:30:46583 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20584 return;
585
[email protected]0f292de02012-02-01 22:28:20586 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20587 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20588 }
589
590 void set_had_non_speculative_request() {
591 DCHECK(origin_loop_->BelongsToCurrentThread());
592 had_non_speculative_request_ = true;
593 }
594
595 bool was_canceled() const {
596 DCHECK(origin_loop_->BelongsToCurrentThread());
597 return callback_.is_null();
598 }
599
600 bool was_completed() const {
601 DCHECK(origin_loop_->BelongsToCurrentThread());
602 return completed_attempt_number_ > 0;
603 }
604
605 private:
[email protected]a9813302012-04-28 09:29:28606 friend class base::RefCountedThreadSafe<ProcTask>;
607 ~ProcTask() {}
608
[email protected]189163e2011-05-11 01:48:54609 void StartLookupAttempt() {
610 DCHECK(origin_loop_->BelongsToCurrentThread());
611 base::TimeTicks start_time = base::TimeTicks::Now();
612 ++attempt_number_;
613 // Dispatch the lookup attempt to a worker thread.
614 if (!base::WorkerPool::PostTask(
615 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20616 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54617 true)) {
[email protected]b59ff372009-07-15 22:04:32618 NOTREACHED();
619
620 // Since we could be running within Resolve() right now, we can't just
621 // call OnLookupComplete(). Instead we must wait until Resolve() has
622 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15623 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54624 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20625 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12626 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54627 return;
[email protected]b59ff372009-07-15 22:04:32628 }
[email protected]13024882011-05-18 23:19:16629
630 net_log_.AddEvent(
631 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45632 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16633
[email protected]0f292de02012-02-01 22:28:20634 // If we don't get the results within a given time, RetryIfNotComplete
635 // will start a new attempt on a different worker thread if none of our
636 // outstanding attempts have completed yet.
637 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58638 origin_loop_->PostDelayedTask(
639 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20640 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42641 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58642 }
[email protected]b59ff372009-07-15 22:04:32643 }
644
[email protected]6c710ee2010-05-07 07:51:16645 // WARNING: This code runs inside a worker pool. The shutdown code cannot
646 // wait for it to finish, so we must be very careful here about using other
647 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54648 // may no longer exist. Multiple DoLookups() could be running in parallel, so
649 // any state inside of |this| must not mutate .
650 void DoLookup(const base::TimeTicks& start_time,
651 const uint32 attempt_number) {
652 AddressList results;
653 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32654 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20655 int error = params_.resolver_proc->Resolve(key_.hostname,
656 key_.address_family,
657 key_.host_resolver_flags,
658 &results,
659 &os_error);
[email protected]b59ff372009-07-15 22:04:32660
[email protected]189163e2011-05-11 01:48:54661 origin_loop_->PostTask(
662 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20663 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12664 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54665 }
666
[email protected]0f292de02012-02-01 22:28:20667 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
668 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54669 DCHECK(origin_loop_->BelongsToCurrentThread());
670
[email protected]0f292de02012-02-01 22:28:20671 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54672 return;
673
[email protected]0f292de02012-02-01 22:28:20674 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54675 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32676 }
677
678 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54679 void OnLookupComplete(const AddressList& results,
680 const base::TimeTicks& start_time,
681 const uint32 attempt_number,
682 int error,
683 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15684 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23685 // If results are empty, we should return an error.
686 bool empty_list_on_ok = (error == OK && results.empty());
687 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
688 if (empty_list_on_ok)
689 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54690
691 bool was_retry_attempt = attempt_number > 1;
692
[email protected]2d3b7762010-10-09 00:35:47693 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20694 // however it isn't safe to call NetworkChangeNotifier from worker threads.
695 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54696 if (error != OK && NetworkChangeNotifier::IsOffline())
697 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47698
[email protected]b3601bc22012-02-21 21:23:20699 // If this is the first attempt that is finishing later, then record data
700 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54701 if (!was_retry_attempt)
702 RecordPerformanceHistograms(start_time, error, os_error);
703
704 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35705
[email protected]0f292de02012-02-01 22:28:20706 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32707 return;
708
[email protected]cd565142012-06-12 16:21:45709 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20710 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45711 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
712 attempt_number,
713 error,
714 os_error);
[email protected]0f292de02012-02-01 22:28:20715 } else {
[email protected]cd565142012-06-12 16:21:45716 net_log_callback = NetLog::IntegerCallback("attempt_number",
717 attempt_number);
[email protected]0f292de02012-02-01 22:28:20718 }
[email protected]cd565142012-06-12 16:21:45719 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
720 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20721
722 if (was_completed())
723 return;
724
725 // Copy the results from the first worker thread that resolves the host.
726 results_ = results;
727 completed_attempt_number_ = attempt_number;
728 completed_attempt_error_ = error;
729
[email protected]e87b8b512011-06-14 22:12:52730 if (was_retry_attempt) {
731 // If retry attempt finishes before 1st attempt, then get stats on how
732 // much time is saved by having spawned an extra attempt.
733 retry_attempt_finished_time_ = base::TimeTicks::Now();
734 }
735
[email protected]189163e2011-05-11 01:48:54736 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45737 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
738 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51739 } else {
[email protected]cd565142012-06-12 16:21:45740 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51741 }
[email protected]cd565142012-06-12 16:21:45742 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
743 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51744
[email protected]b3601bc22012-02-21 21:23:20745 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32746 }
747
[email protected]189163e2011-05-11 01:48:54748 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
749 const int error,
750 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15751 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]1e9bbd22010-10-15 16:42:45752 enum Category { // Used in HISTOGRAM_ENUMERATION.
753 RESOLVE_SUCCESS,
754 RESOLVE_FAIL,
755 RESOLVE_SPECULATIVE_SUCCESS,
756 RESOLVE_SPECULATIVE_FAIL,
757 RESOLVE_MAX, // Bounding value.
758 };
759 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
760
[email protected]189163e2011-05-11 01:48:54761 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
762 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45763 if (had_non_speculative_request_) {
764 category = RESOLVE_SUCCESS;
765 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
766 } else {
767 category = RESOLVE_SPECULATIVE_SUCCESS;
768 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
769 }
[email protected]7e96d792011-06-10 17:08:23770
[email protected]78eac2a2012-03-14 19:09:27771 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23772 // if IPv4 or IPv4/6 lookups are faster or slower.
773 switch(key_.address_family) {
774 case ADDRESS_FAMILY_IPV4:
775 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
776 break;
777 case ADDRESS_FAMILY_IPV6:
778 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
779 break;
780 case ADDRESS_FAMILY_UNSPECIFIED:
781 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
782 break;
783 }
[email protected]1e9bbd22010-10-15 16:42:45784 } else {
785 if (had_non_speculative_request_) {
786 category = RESOLVE_FAIL;
787 DNS_HISTOGRAM("DNS.ResolveFail", duration);
788 } else {
789 category = RESOLVE_SPECULATIVE_FAIL;
790 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
791 }
[email protected]78eac2a2012-03-14 19:09:27792 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23793 // if IPv4 or IPv4/6 lookups are faster or slower.
794 switch(key_.address_family) {
795 case ADDRESS_FAMILY_IPV4:
796 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
797 break;
798 case ADDRESS_FAMILY_IPV6:
799 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
800 break;
801 case ADDRESS_FAMILY_UNSPECIFIED:
802 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
803 break;
804 }
[email protected]c833e322010-10-16 23:51:36805 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54806 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45807 GetAllGetAddrinfoOSErrors());
808 }
[email protected]051b6ab2010-10-18 16:50:46809 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45810
811 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45812 }
813
[email protected]189163e2011-05-11 01:48:54814 void RecordAttemptHistograms(const base::TimeTicks& start_time,
815 const uint32 attempt_number,
816 const int error,
817 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20818 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54819 bool first_attempt_to_complete =
820 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52821 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45822
[email protected]189163e2011-05-11 01:48:54823 if (first_attempt_to_complete) {
824 // If this was first attempt to complete, then record the resolution
825 // status of the attempt.
826 if (completed_attempt_error_ == OK) {
827 UMA_HISTOGRAM_ENUMERATION(
828 "DNS.AttemptFirstSuccess", attempt_number, 100);
829 } else {
830 UMA_HISTOGRAM_ENUMERATION(
831 "DNS.AttemptFirstFailure", attempt_number, 100);
832 }
833 }
834
835 if (error == OK)
836 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
837 else
838 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
839
[email protected]e87b8b512011-06-14 22:12:52840 // If first attempt didn't finish before retry attempt, then calculate stats
841 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20842 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52843 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
844 base::TimeTicks::Now() - retry_attempt_finished_time_);
845 }
846
[email protected]0f292de02012-02-01 22:28:20847 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54848 // Count those attempts which completed after the job was already canceled
849 // OR after the job was already completed by an earlier attempt (so in
850 // effect).
851 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
852
[email protected]0f292de02012-02-01 22:28:20853 // Record if job is canceled.
854 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54855 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
856 }
857
858 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
859 if (error == OK)
860 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
861 else
862 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
863 }
[email protected]1e9bbd22010-10-15 16:42:45864
[email protected]b59ff372009-07-15 22:04:32865 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57866 Key key_;
[email protected]b59ff372009-07-15 22:04:32867
[email protected]0f292de02012-02-01 22:28:20868 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32869 // This may not be the current resolver procedure by the time we call
870 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
871 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20872 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32873
[email protected]0f292de02012-02-01 22:28:20874 // The listener to the results of this ProcTask.
875 Callback callback_;
876
877 // Used to post ourselves onto the origin thread.
878 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54879
880 // Keeps track of the number of attempts we have made so far to resolve the
881 // host. Whenever we start an attempt to resolve the host, we increase this
882 // number.
883 uint32 attempt_number_;
884
885 // The index of the attempt which finished first (or 0 if the job is still in
886 // progress).
887 uint32 completed_attempt_number_;
888
889 // The result (a net error code) from the first attempt to complete.
890 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06891
[email protected]e87b8b512011-06-14 22:12:52892 // The time when retry attempt was finished.
893 base::TimeTicks retry_attempt_finished_time_;
894
[email protected]252b699b2010-02-05 21:38:06895 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20896 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06897 // This boolean is used for histogramming the duration of jobs used to
898 // service non-speculative requests.
899 bool had_non_speculative_request_;
900
[email protected]b59ff372009-07-15 22:04:32901 AddressList results_;
902
[email protected]ee094b82010-08-24 15:55:51903 BoundNetLog net_log_;
904
[email protected]0f292de02012-02-01 22:28:20905 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32906};
907
908//-----------------------------------------------------------------------------
909
[email protected]12faa4c2012-11-06 04:44:18910// Wraps a call to TestIPv6Support to be executed on the WorkerPool as it takes
911// 40-100ms.
[email protected]9db6f702013-04-10 18:10:51912// TODO(szym): Remove altogether, if IPv6ActiveProbe works.
[email protected]12faa4c2012-11-06 04:44:18913class HostResolverImpl::IPv6ProbeJob {
[email protected]0f8f1b432010-03-16 19:06:03914 public:
[email protected]12faa4c2012-11-06 04:44:18915 IPv6ProbeJob(const base::WeakPtr<HostResolverImpl>& resolver, NetLog* net_log)
[email protected]0f8f1b432010-03-16 19:06:03916 : resolver_(resolver),
[email protected]12faa4c2012-11-06 04:44:18917 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_IPV6_PROBE_JOB)),
918 result_(false, IPV6_SUPPORT_MAX, OK) {
[email protected]3e9d9cc2011-05-03 21:08:15919 DCHECK(resolver);
[email protected]ae8e80f2012-07-19 21:08:33920 net_log_.BeginEvent(NetLog::TYPE_IPV6_PROBE_RUNNING);
[email protected]f092e64b2010-03-17 00:39:18921 const bool kIsSlow = true;
[email protected]12faa4c2012-11-06 04:44:18922 base::WorkerPool::PostTaskAndReply(
923 FROM_HERE,
924 base::Bind(&IPv6ProbeJob::DoProbe, base::Unretained(this)),
925 base::Bind(&IPv6ProbeJob::OnProbeComplete, base::Owned(this)),
926 kIsSlow);
[email protected]0f8f1b432010-03-16 19:06:03927 }
928
[email protected]12faa4c2012-11-06 04:44:18929 virtual ~IPv6ProbeJob() {}
[email protected]0f8f1b432010-03-16 19:06:03930
[email protected]0f8f1b432010-03-16 19:06:03931 private:
[email protected]12faa4c2012-11-06 04:44:18932 // Runs on worker thread.
[email protected]0f8f1b432010-03-16 19:06:03933 void DoProbe() {
[email protected]12faa4c2012-11-06 04:44:18934 result_ = TestIPv6Support();
[email protected]0f8f1b432010-03-16 19:06:03935 }
936
[email protected]12faa4c2012-11-06 04:44:18937 void OnProbeComplete() {
938 net_log_.EndEvent(NetLog::TYPE_IPV6_PROBE_RUNNING,
939 base::Bind(&IPv6SupportResult::ToNetLogValue,
940 base::Unretained(&result_)));
941 if (!resolver_)
[email protected]a9af7112010-05-08 00:56:01942 return;
[email protected]12faa4c2012-11-06 04:44:18943 resolver_->IPv6ProbeSetDefaultAddressFamily(
944 result_.ipv6_supported ? ADDRESS_FAMILY_UNSPECIFIED
[email protected]ae8e80f2012-07-19 21:08:33945 : ADDRESS_FAMILY_IPV4);
[email protected]0f8f1b432010-03-16 19:06:03946 }
947
[email protected]0f8f1b432010-03-16 19:06:03948 // Used/set only on origin thread.
[email protected]12faa4c2012-11-06 04:44:18949 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]0f8f1b432010-03-16 19:06:03950
[email protected]ae8e80f2012-07-19 21:08:33951 BoundNetLog net_log_;
952
[email protected]12faa4c2012-11-06 04:44:18953 IPv6SupportResult result_;
954
[email protected]0f8f1b432010-03-16 19:06:03955 DISALLOW_COPY_AND_ASSIGN(IPv6ProbeJob);
956};
957
[email protected]12faa4c2012-11-06 04:44:18958// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
959// it takes 40-100ms and should not block initialization.
960class HostResolverImpl::LoopbackProbeJob {
961 public:
962 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
963 : resolver_(resolver),
964 result_(false) {
965 DCHECK(resolver);
966 const bool kIsSlow = true;
967 base::WorkerPool::PostTaskAndReply(
968 FROM_HERE,
969 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
970 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
971 kIsSlow);
972 }
973
974 virtual ~LoopbackProbeJob() {}
975
976 private:
977 // Runs on worker thread.
978 void DoProbe() {
979 result_ = HaveOnlyLoopbackAddresses();
980 }
981
982 void OnProbeComplete() {
983 if (!resolver_)
984 return;
985 resolver_->SetHaveOnlyLoopbackAddresses(result_);
986 }
987
988 // Used/set only on origin thread.
989 base::WeakPtr<HostResolverImpl> resolver_;
990
991 bool result_;
992
993 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
994};
995
[email protected]0f8f1b432010-03-16 19:06:03996//-----------------------------------------------------------------------------
997
[email protected]b3601bc22012-02-21 21:23:20998// Resolves the hostname using DnsTransaction.
999// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461000class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201001 public:
1002 typedef base::Callback<void(int net_error,
1003 const AddressList& addr_list,
1004 base::TimeDelta ttl)> Callback;
1005
[email protected]0adcb2b2012-08-15 21:30:461006 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201007 const Key& key,
1008 const Callback& callback,
1009 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461010 : client_(client),
1011 family_(key.address_family),
1012 callback_(callback),
1013 net_log_(job_net_log) {
1014 DCHECK(client);
[email protected]b3601bc22012-02-21 21:23:201015 DCHECK(!callback.is_null());
1016
[email protected]0adcb2b2012-08-15 21:30:461017 // If unspecified, do IPv4 first, because suffix search will be faster.
1018 uint16 qtype = (family_ == ADDRESS_FAMILY_IPV6) ?
1019 dns_protocol::kTypeAAAA :
1020 dns_protocol::kTypeA;
1021 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
[email protected]b3601bc22012-02-21 21:23:201022 key.hostname,
1023 qtype,
[email protected]1def74c2012-03-22 20:07:001024 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
[email protected]0adcb2b2012-08-15 21:30:461025 true /* first_query */, base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201026 net_log_);
[email protected]b3601bc22012-02-21 21:23:201027 }
1028
1029 int Start() {
[email protected]4da911f2012-06-14 19:45:201030 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]b3601bc22012-02-21 21:23:201031 return transaction_->Start();
1032 }
1033
[email protected]0adcb2b2012-08-15 21:30:461034 private:
1035 void OnTransactionComplete(bool first_query,
1036 const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001037 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201038 int net_error,
1039 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471040 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511041 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201042 // Run |callback_| last since the owning Job will then delete this DnsTask.
[email protected]0adcb2b2012-08-15 21:30:461043 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511044 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461045 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1046 return;
[email protected]6c411902012-08-14 22:36:361047 }
[email protected]0adcb2b2012-08-15 21:30:461048
1049 CHECK(response);
[email protected]02cd6982013-01-10 20:12:511050 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1051 switch (transaction->GetType()) {
1052 case dns_protocol::kTypeA:
1053 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1054 break;
1055 case dns_protocol::kTypeAAAA:
1056 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1057 break;
1058 }
[email protected]0adcb2b2012-08-15 21:30:461059 AddressList addr_list;
1060 base::TimeDelta ttl;
1061 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1062 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1063 result,
1064 DnsResponse::DNS_PARSE_RESULT_MAX);
1065 if (result != DnsResponse::DNS_PARSE_OK) {
1066 // Fail even if the other query succeeds.
1067 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1068 return;
1069 }
1070
1071 bool needs_sort = false;
1072 if (first_query) {
1073 DCHECK(client_->GetConfig()) <<
1074 "Transaction should have been aborted when config changed!";
1075 if (family_ == ADDRESS_FAMILY_IPV6) {
1076 needs_sort = (addr_list.size() > 1);
1077 } else if (family_ == ADDRESS_FAMILY_UNSPECIFIED) {
1078 first_addr_list_ = addr_list;
1079 first_ttl_ = ttl;
1080 // Use fully-qualified domain name to avoid search.
1081 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
1082 response->GetDottedName() + ".",
1083 dns_protocol::kTypeAAAA,
1084 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1085 false /* first_query */, base::TimeTicks::Now()),
1086 net_log_);
1087 net_error = transaction_->Start();
1088 if (net_error != ERR_IO_PENDING)
1089 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1090 return;
1091 }
1092 } else {
1093 DCHECK_EQ(ADDRESS_FAMILY_UNSPECIFIED, family_);
1094 bool has_ipv6_addresses = !addr_list.empty();
1095 if (!first_addr_list_.empty()) {
1096 ttl = std::min(ttl, first_ttl_);
1097 // Place IPv4 addresses after IPv6.
1098 addr_list.insert(addr_list.end(), first_addr_list_.begin(),
1099 first_addr_list_.end());
1100 }
1101 needs_sort = (has_ipv6_addresses && addr_list.size() > 1);
1102 }
1103
1104 if (addr_list.empty()) {
1105 // TODO(szym): Don't fallback to ProcTask in this case.
1106 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1107 return;
1108 }
1109
1110 if (needs_sort) {
1111 // Sort could complete synchronously.
1112 client_->GetAddressSorter()->Sort(
1113 addr_list,
[email protected]4589a3a2012-09-20 20:57:071114 base::Bind(&DnsTask::OnSortComplete,
1115 AsWeakPtr(),
[email protected]0adcb2b2012-08-15 21:30:461116 base::TimeTicks::Now(),
1117 ttl));
1118 } else {
1119 OnSuccess(addr_list, ttl);
1120 }
1121 }
1122
1123 void OnSortComplete(base::TimeTicks start_time,
1124 base::TimeDelta ttl,
1125 bool success,
1126 const AddressList& addr_list) {
1127 if (!success) {
1128 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1129 base::TimeTicks::Now() - start_time);
1130 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1131 return;
1132 }
1133
1134 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1135 base::TimeTicks::Now() - start_time);
1136
1137 // AddressSorter prunes unusable destinations.
1138 if (addr_list.empty()) {
1139 LOG(WARNING) << "Address list empty after RFC3484 sort";
1140 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1141 return;
1142 }
1143
1144 OnSuccess(addr_list, ttl);
1145 }
1146
1147 void OnFailure(int net_error, DnsResponse::Result result) {
1148 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451149 net_log_.EndEvent(
1150 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1151 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]b3601bc22012-02-21 21:23:201152 callback_.Run(net_error, AddressList(), base::TimeDelta());
1153 }
1154
[email protected]0adcb2b2012-08-15 21:30:461155 void OnSuccess(const AddressList& addr_list, base::TimeDelta ttl) {
1156 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1157 addr_list.CreateNetLogCallback());
1158 callback_.Run(OK, addr_list, ttl);
1159 }
1160
1161 DnsClient* client_;
1162 AddressFamily family_;
[email protected]b3601bc22012-02-21 21:23:201163 // The listener to the results of this DnsTask.
1164 Callback callback_;
[email protected]b3601bc22012-02-21 21:23:201165 const BoundNetLog net_log_;
1166
1167 scoped_ptr<DnsTransaction> transaction_;
[email protected]0adcb2b2012-08-15 21:30:461168
1169 // Results from the first transaction. Used only if |family_| is unspecified.
1170 AddressList first_addr_list_;
1171 base::TimeDelta first_ttl_;
1172
1173 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201174};
1175
1176//-----------------------------------------------------------------------------
1177
[email protected]0f292de02012-02-01 22:28:201178// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201179class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391180 public:
[email protected]0f292de02012-02-01 22:28:201181 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351182 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181183 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201184 const Key& key,
[email protected]8c98d002012-07-18 19:02:271185 RequestPriority priority,
[email protected]16ee26d2012-03-08 03:34:351186 const BoundNetLog& request_net_log)
[email protected]12faa4c2012-11-06 04:44:181187 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201188 key_(key),
[email protected]8c98d002012-07-18 19:02:271189 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201190 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291191 had_dns_config_(false),
[email protected]1d932852012-06-19 19:40:331192 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291193 creation_time_(base::TimeTicks::Now()),
1194 priority_change_time_(creation_time_),
[email protected]0f292de02012-02-01 22:28:201195 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201196 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]4da911f2012-06-14 19:45:201197 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201198
1199 net_log_.BeginEvent(
1200 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451201 base::Bind(&NetLogJobCreationCallback,
1202 request_net_log.source(),
1203 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391204 }
1205
[email protected]0f292de02012-02-01 22:28:201206 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201207 if (is_running()) {
1208 // |resolver_| was destroyed with this Job still in flight.
1209 // Clean-up, record in the log, but don't run any callbacks.
1210 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201211 proc_task_->Cancel();
1212 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201213 }
[email protected]16ee26d2012-03-08 03:34:351214 // Clean up now for nice NetLog.
1215 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201216 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1217 ERR_ABORTED);
1218 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551219 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351220 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201221 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1222 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391223 }
[email protected]b3601bc22012-02-21 21:23:201224 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391225
[email protected]b3601bc22012-02-21 21:23:201226 // Log any remaining Requests as cancelled.
1227 for (RequestsList::const_iterator it = requests_.begin();
1228 it != requests_.end(); ++it) {
1229 Request* req = *it;
1230 if (req->was_canceled())
1231 continue;
1232 DCHECK_EQ(this, req->job());
1233 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1234 req->info());
1235 }
[email protected]68ad3ee2010-01-30 03:45:391236 }
1237
[email protected]16ee26d2012-03-08 03:34:351238 // Add this job to the dispatcher.
[email protected]8c98d002012-07-18 19:02:271239 void Schedule() {
1240 handle_ = resolver_->dispatcher_.Add(this, priority());
[email protected]16ee26d2012-03-08 03:34:351241 }
1242
[email protected]b3601bc22012-02-21 21:23:201243 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201244 DCHECK_EQ(key_.hostname, req->info().hostname());
1245
1246 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201247 priority_tracker_.Add(req->info().priority());
1248
1249 req->request_net_log().AddEvent(
1250 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451251 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201252
1253 net_log_.AddEvent(
1254 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451255 base::Bind(&NetLogJobAttachCallback,
1256 req->request_net_log().source(),
1257 priority()));
[email protected]0f292de02012-02-01 22:28:201258
1259 // TODO(szym): Check if this is still needed.
1260 if (!req->info().is_speculative()) {
1261 had_non_speculative_request_ = true;
1262 if (proc_task_)
1263 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391264 }
[email protected]b3601bc22012-02-21 21:23:201265
1266 requests_.push_back(req.release());
1267
[email protected]51b9a6b2012-06-25 21:50:291268 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391269 }
1270
[email protected]16ee26d2012-03-08 03:34:351271 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461272 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201273 void CancelRequest(Request* req) {
1274 DCHECK_EQ(key_.hostname, req->info().hostname());
1275 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351276
[email protected]0f292de02012-02-01 22:28:201277 // Don't remove it from |requests_| just mark it canceled.
1278 req->MarkAsCanceled();
1279 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1280 req->info());
[email protected]16ee26d2012-03-08 03:34:351281
[email protected]0f292de02012-02-01 22:28:201282 priority_tracker_.Remove(req->info().priority());
1283 net_log_.AddEvent(
1284 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
[email protected]cd565142012-06-12 16:21:451285 base::Bind(&NetLogJobAttachCallback,
1286 req->request_net_log().source(),
1287 priority()));
[email protected]b3601bc22012-02-21 21:23:201288
[email protected]16ee26d2012-03-08 03:34:351289 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291290 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351291 } else {
1292 // If we were called from a Request's callback within CompleteRequests,
1293 // that Request could not have been cancelled, so num_active_requests()
1294 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431295 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201296 }
[email protected]68ad3ee2010-01-30 03:45:391297 }
1298
[email protected]7af985a2012-12-14 22:40:421299 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1300 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201301 void Abort() {
[email protected]0f292de02012-02-01 22:28:201302 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421303 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201304 }
1305
[email protected]f0f602bd2012-11-15 18:01:021306 // If DnsTask present, abort it and fall back to ProcTask.
1307 void AbortDnsTask() {
1308 if (dns_task_) {
1309 dns_task_.reset();
1310 dns_task_error_ = OK;
1311 StartProcTask();
1312 }
1313 }
1314
[email protected]16ee26d2012-03-08 03:34:351315 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1316 // Completes all requests and destroys the job.
1317 void OnEvicted() {
1318 DCHECK(!is_running());
1319 DCHECK(is_queued());
1320 handle_.Reset();
1321
[email protected]4da911f2012-06-14 19:45:201322 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351323
1324 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431325 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351326 }
1327
[email protected]78eac2a2012-03-14 19:09:271328 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1329 // this Job was destroyed.
1330 bool ServeFromHosts() {
1331 DCHECK_GT(num_active_requests(), 0u);
1332 AddressList addr_list;
1333 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031334 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271335 &addr_list)) {
1336 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171337 CompleteRequests(
1338 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1339 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271340 return true;
1341 }
1342 return false;
1343 }
1344
[email protected]b4481b222012-03-16 17:13:111345 const Key key() const {
1346 return key_;
1347 }
1348
1349 bool is_queued() const {
1350 return !handle_.is_null();
1351 }
1352
1353 bool is_running() const {
1354 return is_dns_running() || is_proc_running();
1355 }
1356
[email protected]16ee26d2012-03-08 03:34:351357 private:
[email protected]51b9a6b2012-06-25 21:50:291358 void UpdatePriority() {
1359 if (is_queued()) {
1360 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1361 priority_change_time_ = base::TimeTicks::Now();
1362 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
1363 }
1364 }
1365
[email protected]895123222012-10-25 15:21:171366 AddressList MakeAddressListForRequest(const AddressList& list) const {
1367 if (requests_.empty())
1368 return list;
1369 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1370 }
1371
[email protected]16ee26d2012-03-08 03:34:351372 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201373 virtual void Start() OVERRIDE {
1374 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201375 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201376
[email protected]4da911f2012-06-14 19:45:201377 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201378
[email protected]51b9a6b2012-06-25 21:50:291379 had_dns_config_ = resolver_->HaveDnsConfig();
1380
1381 base::TimeTicks now = base::TimeTicks::Now();
1382 base::TimeDelta queue_time = now - creation_time_;
1383 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1384
1385 if (had_dns_config_) {
1386 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1387 queue_time);
1388 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1389 queue_time_after_change);
1390 } else {
1391 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1392 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1393 queue_time_after_change);
1394 }
1395
[email protected]1d932852012-06-19 19:40:331396 // Caution: Job::Start must not complete synchronously.
[email protected]51b9a6b2012-06-25 21:50:291397 if (had_dns_config_ && !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201398 StartDnsTask();
1399 } else {
1400 StartProcTask();
1401 }
1402 }
1403
[email protected]b3601bc22012-02-21 21:23:201404 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1405 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1406 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1407 // tighter limits.
1408 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351409 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201410 proc_task_ = new ProcTask(
1411 key_,
1412 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371413 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1414 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201415 net_log_);
1416
1417 if (had_non_speculative_request_)
1418 proc_task_->set_had_non_speculative_request();
1419 // Start() could be called from within Resolve(), hence it must NOT directly
1420 // call OnProcTaskComplete, for example, on synchronous failure.
1421 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391422 }
1423
[email protected]0f292de02012-02-01 22:28:201424 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371425 void OnProcTaskComplete(base::TimeTicks start_time,
1426 int net_error,
1427 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201428 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391429
[email protected]62e86ba2013-01-29 18:59:161430 if (!resolver_->resolved_known_ipv6_hostname_ &&
1431 net_error == OK &&
1432 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1433 if (key_.hostname == "www.google.com") {
1434 resolver_->resolved_known_ipv6_hostname_ = true;
1435 bool got_ipv6_address = false;
1436 for (size_t i = 0; i < addr_list.size(); ++i) {
1437 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6)
1438 got_ipv6_address = true;
1439 }
1440 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1441 }
1442 }
1443
[email protected]1d932852012-06-19 19:40:331444 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371445 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001446 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371447 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331448 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1449 ResemblesNetBIOSName(key_.hostname)) {
1450 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1451 } else {
1452 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1453 }
1454 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1455 std::abs(dns_task_error_),
1456 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221457 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001458 } else {
[email protected]e3bd4822012-10-23 18:01:371459 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001460 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1461 }
1462 }
1463
[email protected]1339a2a22012-10-17 08:39:431464 base::TimeDelta ttl =
1465 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201466 if (net_error == OK)
1467 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391468
[email protected]895123222012-10-25 15:21:171469 // Don't store the |ttl| in cache since it's not obtained from the server.
1470 CompleteRequests(
1471 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1472 ttl);
[email protected]b3601bc22012-02-21 21:23:201473 }
1474
1475 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271476 DCHECK(resolver_->HaveDnsConfig());
[email protected]b3601bc22012-02-21 21:23:201477 dns_task_.reset(new DnsTask(
[email protected]0adcb2b2012-08-15 21:30:461478 resolver_->dns_client_.get(),
[email protected]b3601bc22012-02-21 21:23:201479 key_,
[email protected]e3bd4822012-10-23 18:01:371480 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this),
1481 base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201482 net_log_));
1483
1484 int rv = dns_task_->Start();
1485 if (rv != ERR_IO_PENDING) {
1486 DCHECK_NE(OK, rv);
[email protected]51b9a6b2012-06-25 21:50:291487 dns_task_error_ = rv;
[email protected]b3601bc22012-02-21 21:23:201488 dns_task_.reset();
1489 StartProcTask();
1490 }
1491 }
1492
1493 // Called by DnsTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371494 void OnDnsTaskComplete(base::TimeTicks start_time,
1495 int net_error,
[email protected]b3601bc22012-02-21 21:23:201496 const AddressList& addr_list,
1497 base::TimeDelta ttl) {
1498 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201499
[email protected]e3bd4822012-10-23 18:01:371500 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201501 if (net_error != OK) {
[email protected]e3bd4822012-10-23 18:01:371502 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1503
[email protected]1d932852012-06-19 19:40:331504 dns_task_error_ = net_error;
[email protected]16ee26d2012-03-08 03:34:351505 dns_task_.reset();
[email protected]78eac2a2012-03-14 19:09:271506
1507 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1508 // http://crbug.com/117655
1509
[email protected]b3601bc22012-02-21 21:23:201510 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1511 // ProcTask in that case is a waste of time.
1512 StartProcTask();
1513 return;
1514 }
[email protected]e3bd4822012-10-23 18:01:371515 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511516 // Log DNS lookups based on |address_family|.
1517 switch(key_.address_family) {
1518 case ADDRESS_FAMILY_IPV4:
1519 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1520 break;
1521 case ADDRESS_FAMILY_IPV6:
1522 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1523 break;
1524 case ADDRESS_FAMILY_UNSPECIFIED:
1525 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1526 break;
1527 }
[email protected]b3601bc22012-02-21 21:23:201528
[email protected]1def74c2012-03-22 20:07:001529 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431530 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461531
[email protected]1ffdda82012-12-12 23:04:221532 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021533
[email protected]895123222012-10-25 15:21:171534 base::TimeDelta bounded_ttl =
1535 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1536
1537 CompleteRequests(
1538 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1539 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201540 }
1541
[email protected]16ee26d2012-03-08 03:34:351542 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171543 void CompleteRequests(const HostCache::Entry& entry,
1544 base::TimeDelta ttl) {
[email protected]b3601bc22012-02-21 21:23:201545 CHECK(resolver_);
[email protected]b3601bc22012-02-21 21:23:201546
[email protected]16ee26d2012-03-08 03:34:351547 // This job must be removed from resolver's |jobs_| now to make room for a
1548 // new job with the same key in case one of the OnComplete callbacks decides
1549 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1550 // is done.
1551 scoped_ptr<Job> self_deleter(this);
1552
1553 resolver_->RemoveJob(this);
1554
[email protected]16ee26d2012-03-08 03:34:351555 if (is_running()) {
1556 DCHECK(!is_queued());
1557 if (is_proc_running()) {
1558 proc_task_->Cancel();
1559 proc_task_ = NULL;
1560 }
1561 dns_task_.reset();
1562
1563 // Signal dispatcher that a slot has opened.
1564 resolver_->dispatcher_.OnJobFinished();
1565 } else if (is_queued()) {
1566 resolver_->dispatcher_.Cancel(handle_);
1567 handle_.Reset();
1568 }
1569
1570 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201571 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351572 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1573 OK);
1574 return;
1575 }
[email protected]b3601bc22012-02-21 21:23:201576
1577 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171578 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391579
[email protected]78eac2a2012-03-14 19:09:271580 DCHECK(!requests_.empty());
1581
[email protected]895123222012-10-25 15:21:171582 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191583 // Record this histogram here, when we know the system has a valid DNS
1584 // configuration.
[email protected]539df6c2012-06-19 21:21:291585 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1586 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191587 }
[email protected]16ee26d2012-03-08 03:34:351588
[email protected]7af985a2012-12-14 22:40:421589 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171590 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1591 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431592 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351593
[email protected]0f292de02012-02-01 22:28:201594 // Complete all of the requests that were attached to the job.
1595 for (RequestsList::const_iterator it = requests_.begin();
1596 it != requests_.end(); ++it) {
1597 Request* req = *it;
1598
1599 if (req->was_canceled())
1600 continue;
1601
1602 DCHECK_EQ(this, req->job());
1603 // Update the net log and notify registered observers.
1604 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]895123222012-10-25 15:21:171605 req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291606 if (did_complete) {
1607 // Record effective total time from creation to completion.
1608 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1609 base::TimeTicks::Now() - req->request_time());
1610 }
[email protected]895123222012-10-25 15:21:171611 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201612
1613 // Check if the resolver was destroyed as a result of running the
1614 // callback. If it was, we could continue, but we choose to bail.
1615 if (!resolver_)
1616 return;
1617 }
1618 }
1619
[email protected]1339a2a22012-10-17 08:39:431620 // Convenience wrapper for CompleteRequests in case of failure.
1621 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171622 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1623 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431624 }
1625
[email protected]b4481b222012-03-16 17:13:111626 RequestPriority priority() const {
1627 return priority_tracker_.highest_priority();
1628 }
1629
1630 // Number of non-canceled requests in |requests_|.
1631 size_t num_active_requests() const {
1632 return priority_tracker_.total_count();
1633 }
1634
1635 bool is_dns_running() const {
1636 return dns_task_.get() != NULL;
1637 }
1638
1639 bool is_proc_running() const {
1640 return proc_task_.get() != NULL;
1641 }
1642
[email protected]0f292de02012-02-01 22:28:201643 base::WeakPtr<HostResolverImpl> resolver_;
1644
1645 Key key_;
1646
1647 // Tracks the highest priority across |requests_|.
1648 PriorityTracker priority_tracker_;
1649
1650 bool had_non_speculative_request_;
1651
[email protected]51b9a6b2012-06-25 21:50:291652 // Distinguishes measurements taken while DnsClient was fully configured.
1653 bool had_dns_config_;
1654
[email protected]1d932852012-06-19 19:40:331655 // Result of DnsTask.
1656 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001657
[email protected]51b9a6b2012-06-25 21:50:291658 const base::TimeTicks creation_time_;
1659 base::TimeTicks priority_change_time_;
1660
[email protected]0f292de02012-02-01 22:28:201661 BoundNetLog net_log_;
1662
[email protected]b3601bc22012-02-21 21:23:201663 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201664 scoped_refptr<ProcTask> proc_task_;
1665
[email protected]b3601bc22012-02-21 21:23:201666 // Resolves the host using a DnsTransaction.
1667 scoped_ptr<DnsTask> dns_task_;
1668
[email protected]0f292de02012-02-01 22:28:201669 // All Requests waiting for the result of this Job. Some can be canceled.
1670 RequestsList requests_;
1671
[email protected]16ee26d2012-03-08 03:34:351672 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201673 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391674};
1675
1676//-----------------------------------------------------------------------------
1677
[email protected]0f292de02012-02-01 22:28:201678HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431679 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201680 size_t max_retry_attempts)
1681 : resolver_proc(resolver_proc),
1682 max_retry_attempts(max_retry_attempts),
1683 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1684 retry_factor(2) {
1685}
1686
1687HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1688
1689HostResolverImpl::HostResolverImpl(
[email protected]c54a8912012-10-22 22:09:431690 scoped_ptr<HostCache> cache,
[email protected]0f292de02012-02-01 22:28:201691 const PrioritizedDispatcher::Limits& job_limits,
1692 const ProcTaskParams& proc_params,
[email protected]ee094b82010-08-24 15:55:511693 NetLog* net_log)
[email protected]c54a8912012-10-22 22:09:431694 : cache_(cache.Pass()),
[email protected]0f292de02012-02-01 22:28:201695 dispatcher_(job_limits),
1696 max_queued_jobs_(job_limits.total_jobs * 100u),
1697 proc_params_(proc_params),
[email protected]62e86ba2013-01-29 18:59:161698 net_log_(net_log),
[email protected]0c7798452009-10-26 17:59:511699 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]4589a3a2012-09-20 20:57:071700 weak_ptr_factory_(this),
[email protected]12faa4c2012-11-06 04:44:181701 probe_weak_ptr_factory_(this),
[email protected]d7b9a2b2012-05-31 22:31:191702 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021703 num_dns_failures_(0),
[email protected]2f3bc65c2010-07-23 17:47:101704 ipv6_probe_monitoring_(false),
[email protected]62e86ba2013-01-29 18:59:161705 resolved_known_ipv6_hostname_(false),
1706 additional_resolver_flags_(0) {
[email protected]0f292de02012-02-01 22:28:201707
1708 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391709
[email protected]06ef6d92011-05-19 04:24:581710 // Maximum of 4 retry attempts for host resolution.
1711 static const size_t kDefaultMaxRetryAttempts = 4u;
1712
[email protected]0f292de02012-02-01 22:28:201713 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1714 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391715
[email protected]b59ff372009-07-15 22:04:321716#if defined(OS_WIN)
1717 EnsureWinsockInit();
1718#endif
[email protected]23f771162011-06-02 18:37:511719#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:181720 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101721#endif
[email protected]232a5812011-03-04 22:42:081722 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401723 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191724#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1725 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191726 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341727#endif
[email protected]2ac22db2012-11-28 19:50:041728
1729 // TODO(szym): Remove when received_dns_config_ is removed, once
1730 // http://crbug.com/137914 is resolved.
1731 {
1732 DnsConfig dns_config;
1733 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1734 received_dns_config_ = dns_config.IsValid();
1735 }
[email protected]b59ff372009-07-15 22:04:321736}
1737
1738HostResolverImpl::~HostResolverImpl() {
[email protected]0f292de02012-02-01 22:28:201739 // This will also cancel all outstanding requests.
1740 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431741
[email protected]232a5812011-03-04 22:42:081742 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401743 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321744}
1745
[email protected]0f292de02012-02-01 22:28:201746void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1747 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1748 DCHECK_GT(value, 0u);
1749 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131750}
1751
[email protected]684970b2009-08-14 04:54:461752int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321753 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291754 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461755 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511756 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401757 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141758 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291759 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141760
[email protected]ee094b82010-08-24 15:55:511761 // Make a log item for the request.
1762 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1763 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1764
[email protected]0f292de02012-02-01 22:28:201765 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321766
[email protected]123ab1e32009-10-21 19:12:571767 // Build a key that identifies the request in the cache and in the
1768 // outstanding jobs map.
[email protected]137af622010-02-05 02:14:351769 Key key = GetEffectiveKeyForRequest(info);
[email protected]123ab1e32009-10-21 19:12:571770
[email protected]287d7c22011-11-15 17:34:251771 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401772 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201773 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291774 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401775 return rv;
[email protected]38368712011-03-02 08:09:401776 }
1777
[email protected]0f292de02012-02-01 22:28:201778 // Next we need to attach our request to a "job". This job is responsible for
1779 // calling "getaddrinfo(hostname)" on a worker thread.
1780
1781 JobMap::iterator jobit = jobs_.find(key);
1782 Job* job;
1783 if (jobit == jobs_.end()) {
[email protected]12faa4c2012-11-06 04:44:181784 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, info.priority(),
1785 request_net_log);
[email protected]8c98d002012-07-18 19:02:271786 job->Schedule();
[email protected]0f292de02012-02-01 22:28:201787
1788 // Check for queue overflow.
1789 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1790 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1791 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351792 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201793 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201794 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201795 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201796 return rv;
1797 }
[email protected]0f292de02012-02-01 22:28:201798 }
[email protected]0f292de02012-02-01 22:28:201799 jobs_.insert(jobit, std::make_pair(key, job));
1800 } else {
1801 job = jobit->second;
1802 }
1803
1804 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201805 scoped_ptr<Request> req(new Request(source_net_log,
1806 request_net_log,
1807 info,
1808 callback,
1809 addresses));
[email protected]b59ff372009-07-15 22:04:321810 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201811 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321812
[email protected]b3601bc22012-02-21 21:23:201813 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201814 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321815 return ERR_IO_PENDING;
1816}
1817
[email protected]287d7c22011-11-15 17:34:251818int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401819 const RequestInfo& info,
1820 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001821 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401822 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1823 // On Windows it gives the default interface's address, whereas on Linux it
1824 // gives an error. We will make it fail on all platforms for consistency.
1825 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1826 return ERR_NAME_NOT_RESOLVED;
1827
1828 int net_error = ERR_UNEXPECTED;
1829 if (ResolveAsIP(key, info, &net_error, addresses))
1830 return net_error;
[email protected]78eac2a2012-03-14 19:09:271831 if (ServeFromCache(key, info, &net_error, addresses)) {
[email protected]4da911f2012-06-14 19:45:201832 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271833 return net_error;
1834 }
1835 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1836 // http://crbug.com/117655
1837 if (ServeFromHosts(key, info, addresses)) {
[email protected]4da911f2012-06-14 19:45:201838 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271839 return OK;
1840 }
1841 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401842}
1843
1844int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1845 AddressList* addresses,
1846 const BoundNetLog& source_net_log) {
1847 DCHECK(CalledOnValidThread());
1848 DCHECK(addresses);
1849
[email protected]95a214c2011-08-04 21:50:401850 // Make a log item for the request.
1851 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1852 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1853
1854 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201855 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401856
[email protected]95a214c2011-08-04 21:50:401857 Key key = GetEffectiveKeyForRequest(info);
1858
[email protected]287d7c22011-11-15 17:34:251859 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201860 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401861 return rv;
1862}
1863
[email protected]b59ff372009-07-15 22:04:321864void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141865 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321866 Request* req = reinterpret_cast<Request*>(req_handle);
1867 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201868 Job* job = req->job();
1869 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201870 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321871}
1872
[email protected]0f8f1b432010-03-16 19:06:031873void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141874 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031875 default_address_family_ = address_family;
[email protected]12faa4c2012-11-06 04:44:181876 ipv6_probe_monitoring_ = false;
[email protected]0f8f1b432010-03-16 19:06:031877}
1878
[email protected]f7d310e2010-10-07 16:25:111879AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1880 return default_address_family_;
1881}
1882
[email protected]9db6f702013-04-10 18:10:511883// TODO(szym): Remove this API altogether if IPv6ActiveProbe works.
[email protected]a78f4272011-10-21 19:16:331884void HostResolverImpl::ProbeIPv6Support() {
1885 DCHECK(CalledOnValidThread());
1886 DCHECK(!ipv6_probe_monitoring_);
1887 ipv6_probe_monitoring_ = true;
[email protected]12faa4c2012-11-06 04:44:181888 OnIPAddressChanged();
[email protected]ddb1e5a2010-12-13 20:10:451889}
1890
[email protected]a8883e452012-11-17 05:58:061891void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
1892 DCHECK(CalledOnValidThread());
1893#if defined(ENABLE_BUILT_IN_DNS)
1894 if (enabled && !dns_client_) {
1895 SetDnsClient(DnsClient::CreateClient(net_log_));
1896 } else if (!enabled && dns_client_) {
1897 SetDnsClient(scoped_ptr<DnsClient>());
1898 }
1899#endif
1900}
1901
[email protected]489d1a82011-10-12 03:09:111902HostCache* HostResolverImpl::GetHostCache() {
1903 return cache_.get();
1904}
[email protected]95a214c2011-08-04 21:50:401905
[email protected]17e92032012-03-29 00:56:241906base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
1907 // Check if async DNS is disabled.
1908 if (!dns_client_.get())
1909 return NULL;
1910
1911 // Check if async DNS is enabled, but we currently have no configuration
1912 // for it.
1913 const DnsConfig* dns_config = dns_client_->GetConfig();
1914 if (dns_config == NULL)
1915 return new DictionaryValue();
1916
1917 return dns_config->ToValue();
1918}
1919
[email protected]95a214c2011-08-04 21:50:401920bool HostResolverImpl::ResolveAsIP(const Key& key,
1921 const RequestInfo& info,
1922 int* net_error,
1923 AddressList* addresses) {
1924 DCHECK(addresses);
1925 DCHECK(net_error);
1926 IPAddressNumber ip_number;
1927 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1928 return false;
1929
1930 DCHECK_EQ(key.host_resolver_flags &
1931 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1932 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1933 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201934 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
1935 !ipv6_probe_monitoring_;
[email protected]95a214c2011-08-04 21:50:401936 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201937 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401938 *net_error = ERR_NAME_NOT_RESOLVED;
1939 } else {
[email protected]7054e78f2012-05-07 21:44:561940 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
1941 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
1942 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:401943 }
1944 return true;
1945}
1946
1947bool HostResolverImpl::ServeFromCache(const Key& key,
1948 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401949 int* net_error,
1950 AddressList* addresses) {
1951 DCHECK(addresses);
1952 DCHECK(net_error);
1953 if (!info.allow_cached_response() || !cache_.get())
1954 return false;
1955
[email protected]407a30ab2012-08-15 17:16:101956 const HostCache::Entry* cache_entry = cache_->Lookup(
1957 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:401958 if (!cache_entry)
1959 return false;
1960
[email protected]95a214c2011-08-04 21:50:401961 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:561962 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:431963 if (cache_entry->has_ttl())
1964 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:171965 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:561966 }
[email protected]95a214c2011-08-04 21:50:401967 return true;
1968}
1969
[email protected]78eac2a2012-03-14 19:09:271970bool HostResolverImpl::ServeFromHosts(const Key& key,
1971 const RequestInfo& info,
1972 AddressList* addresses) {
1973 DCHECK(addresses);
1974 if (!HaveDnsConfig())
1975 return false;
[email protected]05a79d42013-03-28 07:30:091976 addresses->clear();
1977
[email protected]cb507622012-03-23 16:17:061978 // HOSTS lookups are case-insensitive.
1979 std::string hostname = StringToLowerASCII(key.hostname);
1980
[email protected]05a79d42013-03-28 07:30:091981 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1982
[email protected]78eac2a2012-03-14 19:09:271983 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1984 // (glibc and c-ares) return the first matching line. We have more
1985 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:091986 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
1987 // necessary.
1988 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
1989 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1990 DnsHosts::const_iterator it = hosts.find(
1991 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
1992 if (it != hosts.end())
1993 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:271994 }
1995
[email protected]05a79d42013-03-28 07:30:091996 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
1997 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1998 DnsHosts::const_iterator it = hosts.find(
1999 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2000 if (it != hosts.end())
2001 addresses->push_back(IPEndPoint(it->second, info.port()));
2002 }
2003
[email protected]ec666ab22013-04-17 20:05:592004 // If got only loopback addresses and the family was restricted, resolve
2005 // again, without restrictions. See SystemHostResolverCall for rationale.
2006 if ((key.host_resolver_flags &
2007 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2008 IsAllIPv4Loopback(*addresses)) {
2009 Key new_key(key);
2010 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2011 new_key.host_resolver_flags &=
2012 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2013 return ServeFromHosts(new_key, info, addresses);
2014 }
[email protected]05a79d42013-03-28 07:30:092015 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272016}
2017
[email protected]16ee26d2012-03-08 03:34:352018void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432019 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352020 base::TimeDelta ttl) {
2021 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432022 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032023}
2024
[email protected]0f292de02012-02-01 22:28:202025void HostResolverImpl::RemoveJob(Job* job) {
2026 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352027 JobMap::iterator it = jobs_.find(job->key());
2028 if (it != jobs_.end() && it->second == job)
2029 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322030}
2031
[email protected]0f8f1b432010-03-16 19:06:032032void HostResolverImpl::IPv6ProbeSetDefaultAddressFamily(
2033 AddressFamily address_family) {
2034 DCHECK(address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2035 address_family == ADDRESS_FAMILY_IPV4);
[email protected]12faa4c2012-11-06 04:44:182036 if (!ipv6_probe_monitoring_)
2037 return;
[email protected]f092e64b2010-03-17 00:39:182038 if (default_address_family_ != address_family) {
[email protected]b30a3f52010-10-16 01:05:462039 VLOG(1) << "IPv6Probe forced AddressFamily setting to "
2040 << ((address_family == ADDRESS_FAMILY_UNSPECIFIED) ?
2041 "ADDRESS_FAMILY_UNSPECIFIED" : "ADDRESS_FAMILY_IPV4");
[email protected]f092e64b2010-03-17 00:39:182042 }
[email protected]0f8f1b432010-03-16 19:06:032043 default_address_family_ = address_family;
[email protected]e95d3aca2010-01-11 22:47:432044}
2045
[email protected]9936a7862012-10-26 04:44:022046void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2047 if (result) {
2048 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2049 } else {
2050 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2051 }
2052}
2053
[email protected]137af622010-02-05 02:14:352054HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
2055 const RequestInfo& info) const {
[email protected]eaf3a3b2010-09-03 20:34:272056 HostResolverFlags effective_flags =
2057 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352058 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512059
2060 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]ac0b52e2013-04-21 01:26:162061 if (ipv6_probe_monitoring_) {
2062 base::TimeTicks start_time = base::TimeTicks::Now();
2063 // Google DNS address.
2064 const uint8 kIPv6Address[] =
2065 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2066 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
2067 IPAddressNumber address(kIPv6Address,
2068 kIPv6Address + arraysize(kIPv6Address));
2069 bool rv6 = IsGloballyReachable(address);
[email protected]9db6f702013-04-10 18:10:512070
[email protected]ac0b52e2013-04-21 01:26:162071 UMA_HISTOGRAM_TIMES("Net.IPv6ConnectDuration",
2072 base::TimeTicks::Now() - start_time);
2073 if (rv6) {
2074 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch",
2075 default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED);
2076 } else {
2077 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch",
2078 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED);
2079
2080 effective_address_family = ADDRESS_FAMILY_IPV4;
2081 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2082 }
[email protected]9db6f702013-04-10 18:10:512083 } else {
[email protected]ac0b52e2013-04-21 01:26:162084 effective_address_family = default_address_family_;
[email protected]9db6f702013-04-10 18:10:512085 }
2086 }
2087
[email protected]eaf3a3b2010-09-03 20:34:272088 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352089}
2090
[email protected]35ddc282010-09-21 23:42:062091void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202092 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2093 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542094 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202095 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2096 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202097 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202098 jobs_to_abort.push_back(job);
2099 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202100 } else {
[email protected]b3601bc22012-02-21 21:23:202101 DCHECK(job->is_queued());
2102 ++it;
[email protected]0f292de02012-02-01 22:28:202103 }
[email protected]ef4c40c2010-09-01 14:42:032104 }
[email protected]b3601bc22012-02-21 21:23:202105
[email protected]57a48d32012-03-03 00:04:552106 // Check if no dispatcher slots leaked out.
2107 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
2108
2109 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072110 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552111
[email protected]16ee26d2012-03-08 03:34:352112 // Then Abort them.
[email protected]57a48d32012-03-03 00:04:552113 for (size_t i = 0; self && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552114 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542115 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202116 }
[email protected]ef4c40c2010-09-01 14:42:032117}
2118
[email protected]78eac2a2012-03-14 19:09:272119void HostResolverImpl::TryServingAllJobsFromHosts() {
2120 if (!HaveDnsConfig())
2121 return;
2122
2123 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2124 // http://crbug.com/117655
2125
2126 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072127 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272128
2129 for (JobMap::iterator it = jobs_.begin(); self && it != jobs_.end(); ) {
2130 Job* job = it->second;
2131 ++it;
2132 // This could remove |job| from |jobs_|, but iterator will remain valid.
2133 job->ServeFromHosts();
2134 }
2135}
2136
[email protected]be1a48b2011-01-20 00:12:132137void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162138 resolved_known_ipv6_hostname_ = false;
[email protected]12faa4c2012-11-06 04:44:182139 // Abandon all ProbeJobs.
2140 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132141 if (cache_.get())
2142 cache_->clear();
[email protected]12faa4c2012-11-06 04:44:182143 if (ipv6_probe_monitoring_)
2144 new IPv6ProbeJob(probe_weak_ptr_factory_.GetWeakPtr(), net_log_);
[email protected]23f771162011-06-02 18:37:512145#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:182146 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132147#endif
2148 AbortAllInProgressJobs();
2149 // |this| may be deleted inside AbortAllInProgressJobs().
2150}
2151
[email protected]bb0e34542012-08-31 19:52:402152void HostResolverImpl::OnDNSChanged() {
2153 DnsConfig dns_config;
2154 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592155
[email protected]b4481b222012-03-16 17:13:112156 if (net_log_) {
2157 net_log_->AddGlobalEntry(
2158 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452159 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112160 }
2161
[email protected]01b3b9d2012-08-13 16:18:142162 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192163 received_dns_config_ = dns_config.IsValid();
[email protected]78eac2a2012-03-14 19:09:272164
[email protected]a8883e452012-11-17 05:58:062165 num_dns_failures_ = 0;
2166
[email protected]01b3b9d2012-08-13 16:18:142167 // We want a new DnsSession in place, before we Abort running Jobs, so that
2168 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022169 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192170 dns_client_->SetConfig(dns_config);
[email protected]a8883e452012-11-17 05:58:062171 if (dns_config.IsValid())
[email protected]f0f602bd2012-11-15 18:01:022172 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022173 }
[email protected]01b3b9d2012-08-13 16:18:142174
2175 // If the DNS server has changed, existing cached info could be wrong so we
2176 // have to drop our internal cache :( Note that OS level DNS caches, such
2177 // as NSCD's cache should be dropped automatically by the OS when
2178 // resolv.conf changes so we don't need to do anything to clear that cache.
2179 if (cache_.get())
2180 cache_->clear();
2181
[email protected]f0f602bd2012-11-15 18:01:022182 // Life check to bail once |this| is deleted.
2183 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2184
[email protected]01b3b9d2012-08-13 16:18:142185 // Existing jobs will have been sent to the original server so they need to
2186 // be aborted.
2187 AbortAllInProgressJobs();
2188
2189 // |this| may be deleted inside AbortAllInProgressJobs().
2190 if (self)
2191 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272192}
2193
2194bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252195 // Use DnsClient only if it's fully configured and there is no override by
2196 // ScopedDefaultHostResolverProc.
2197 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2198 // but that would introduce construction order requirements for NCN and SDHRP.
2199 return (dns_client_.get() != NULL) &&
2200 (dns_client_->GetConfig() != NULL) &&
2201 !(proc_params_.resolver_proc == NULL &&
2202 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202203}
2204
[email protected]1ffdda82012-12-12 23:04:222205void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022206 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222207 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022208 num_dns_failures_ = 0;
2209 return;
2210 }
2211 ++num_dns_failures_;
2212 if (num_dns_failures_ < kMaximumDnsFailures)
2213 return;
2214 // Disable DnsClient until the next DNS change.
2215 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2216 it->second->AbortDnsTask();
2217 dns_client_->SetConfig(DnsConfig());
2218 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222219 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2220 std::abs(net_error),
2221 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022222}
2223
[email protected]a8883e452012-11-17 05:58:062224void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
2225 if (HaveDnsConfig()) {
2226 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2227 it->second->AbortDnsTask();
2228 }
2229 dns_client_ = dns_client.Pass();
2230 if (!dns_client_ || dns_client_->GetConfig() ||
2231 num_dns_failures_ >= kMaximumDnsFailures) {
2232 return;
2233 }
2234 DnsConfig dns_config;
2235 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2236 dns_client_->SetConfig(dns_config);
2237 num_dns_failures_ = 0;
2238 if (dns_config.IsValid())
2239 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2240}
2241
[email protected]b59ff372009-07-15 22:04:322242} // namespace net