blob: 2a511535dd0a1630b63ee9848023538c55dcc2ca [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
5#include "net/base/host_resolver_impl.h"
6
[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]ee094b82010-08-24 15:55:5135#include "net/base/address_list_net_log_param.h"
[email protected]46018c9d2011-09-06 03:42:3436#include "net/base/dns_reloader.h"
[email protected]ee094b82010-08-24 15:55:5137#include "net/base/host_port_pair.h"
[email protected]b59ff372009-07-15 22:04:3238#include "net/base/host_resolver_proc.h"
[email protected]2bb04442010-08-18 18:01:1539#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5140#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0341#include "net/base/net_util.h"
[email protected]78eac2a2012-03-14 19:09:2742#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2043#include "net/dns/dns_config_service.h"
44#include "net/dns/dns_protocol.h"
45#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2046#include "net/dns/dns_transaction.h"
[email protected]b59ff372009-07-15 22:04:3247
48#if defined(OS_WIN)
49#include "net/base/winsock_init.h"
50#endif
51
52namespace net {
53
[email protected]e95d3aca2010-01-11 22:47:4354namespace {
55
[email protected]6e78dfb2011-07-28 21:34:4756// Limit the size of hostnames that will be resolved to combat issues in
57// some platform's resolvers.
58const size_t kMaxHostLength = 4096;
59
[email protected]a2730882012-01-21 00:56:2760// Default TTL for successful resolutions with ProcTask.
61const unsigned kCacheEntryTTLSeconds = 60;
62
[email protected]b3601bc22012-02-21 21:23:2063// Default TTL for unsuccessful resolutions with ProcTask.
64const unsigned kNegativeCacheEntryTTLSeconds = 0;
65
[email protected]0f292de02012-02-01 22:28:2066// Maximum of 8 concurrent resolver threads (excluding retries).
67// Some routers (or resolvers) appear to start to provide host-not-found if
68// too many simultaneous resolutions are pending. This number needs to be
69// further optimized, but 8 is what FF currently does.
70static const size_t kDefaultMaxProcTasks = 8u;
71
[email protected]fe89ea72011-05-12 02:02:4072// Helper to mutate the linked list contained by AddressList to the given
73// port. Note that in general this is dangerous since the AddressList's
74// data might be shared (and you should use AddressList::SetPort).
75//
76// However since we allocated the AddressList ourselves we can safely
77// do this optimization and avoid reallocating the list.
[email protected]b3601bc22012-02-21 21:23:2078void MutableSetPort(int port, AddressList* addr_list) {
[email protected]fe89ea72011-05-12 02:02:4079 struct addrinfo* mutable_head =
[email protected]b3601bc22012-02-21 21:23:2080 const_cast<struct addrinfo*>(addr_list->head());
[email protected]fe89ea72011-05-12 02:02:4081 SetPortForAllAddrinfos(mutable_head, port);
82}
83
[email protected]24f4bab2010-10-15 01:27:1184// We use a separate histogram name for each platform to facilitate the
85// display of error codes by their symbolic name (since each platform has
86// different mappings).
87const char kOSErrorsForGetAddrinfoHistogramName[] =
88#if defined(OS_WIN)
89 "Net.OSErrorsForGetAddrinfo_Win";
90#elif defined(OS_MACOSX)
91 "Net.OSErrorsForGetAddrinfo_Mac";
92#elif defined(OS_LINUX)
93 "Net.OSErrorsForGetAddrinfo_Linux";
94#else
95 "Net.OSErrorsForGetAddrinfo";
96#endif
97
[email protected]c89b2442011-05-26 14:28:2798// Gets a list of the likely error codes that getaddrinfo() can return
99// (non-exhaustive). These are the error codes that we will track via
100// a histogram.
101std::vector<int> GetAllGetAddrinfoOSErrors() {
102 int os_errors[] = {
103#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51104#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37105#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45106 // EAI_ADDRFAMILY has been declared obsolete in Android's and
107 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27108 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37109#endif
[email protected]c48aef92011-11-22 23:41:45110 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51111 EAI_NODATA,
112#endif
[email protected]c89b2442011-05-26 14:28:27113 EAI_AGAIN,
114 EAI_BADFLAGS,
115 EAI_FAIL,
116 EAI_FAMILY,
117 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27118 EAI_NONAME,
119 EAI_SERVICE,
120 EAI_SOCKTYPE,
121 EAI_SYSTEM,
122#elif defined(OS_WIN)
123 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
124 WSA_NOT_ENOUGH_MEMORY,
125 WSAEAFNOSUPPORT,
126 WSAEINVAL,
127 WSAESOCKTNOSUPPORT,
128 WSAHOST_NOT_FOUND,
129 WSANO_DATA,
130 WSANO_RECOVERY,
131 WSANOTINITIALISED,
132 WSATRY_AGAIN,
133 WSATYPE_NOT_FOUND,
134 // The following are not in doc, but might be to appearing in results :-(.
135 WSA_INVALID_HANDLE,
136#endif
137 };
138
139 // Ensure all errors are positive, as histogram only tracks positive values.
140 for (size_t i = 0; i < arraysize(os_errors); ++i) {
141 os_errors[i] = std::abs(os_errors[i]);
142 }
143
144 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
145 arraysize(os_errors));
146}
147
[email protected]0f292de02012-02-01 22:28:20148// Wraps call to SystemHostResolverProc as an instance of HostResolverProc.
149// TODO(szym): This should probably be declared in host_resolver_proc.h.
150class CallSystemHostResolverProc : public HostResolverProc {
151 public:
152 CallSystemHostResolverProc() : HostResolverProc(NULL) {}
153 virtual int Resolve(const std::string& hostname,
154 AddressFamily address_family,
155 HostResolverFlags host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20156 AddressList* addr_list,
[email protected]0f292de02012-02-01 22:28:20157 int* os_error) OVERRIDE {
158 return SystemHostResolverProc(hostname,
159 address_family,
160 host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20161 addr_list,
[email protected]0f292de02012-02-01 22:28:20162 os_error);
[email protected]b59ff372009-07-15 22:04:32163 }
[email protected]0f292de02012-02-01 22:28:20164};
[email protected]b59ff372009-07-15 22:04:32165
[email protected]21526002010-05-16 19:42:46166// Extra parameters to attach to the NetLog when the resolve failed.
[email protected]b3601bc22012-02-21 21:23:20167class ProcTaskFailedParams : public NetLog::EventParameters {
[email protected]21526002010-05-16 19:42:46168 public:
[email protected]b3601bc22012-02-21 21:23:20169 ProcTaskFailedParams(uint32 attempt_number, int net_error, int os_error)
[email protected]13024882011-05-18 23:19:16170 : attempt_number_(attempt_number),
171 net_error_(net_error),
[email protected]ee094b82010-08-24 15:55:51172 os_error_(os_error) {
[email protected]21526002010-05-16 19:42:46173 }
174
[email protected]0f292de02012-02-01 22:28:20175 virtual Value* ToValue() const OVERRIDE {
[email protected]21526002010-05-16 19:42:46176 DictionaryValue* dict = new DictionaryValue();
[email protected]13024882011-05-18 23:19:16177 if (attempt_number_)
178 dict->SetInteger("attempt_number", attempt_number_);
179
[email protected]ccaff652010-07-31 06:28:20180 dict->SetInteger("net_error", net_error_);
[email protected]21526002010-05-16 19:42:46181
182 if (os_error_) {
[email protected]ccaff652010-07-31 06:28:20183 dict->SetInteger("os_error", os_error_);
[email protected]21526002010-05-16 19:42:46184#if defined(OS_POSIX)
[email protected]ccaff652010-07-31 06:28:20185 dict->SetString("os_error_string", gai_strerror(os_error_));
[email protected]21526002010-05-16 19:42:46186#elif defined(OS_WIN)
187 // Map the error code to a human-readable string.
188 LPWSTR error_string = NULL;
189 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
190 FORMAT_MESSAGE_FROM_SYSTEM,
191 0, // Use the internal message table.
192 os_error_,
193 0, // Use default language.
194 (LPWSTR)&error_string,
195 0, // Buffer size.
196 0); // Arguments (unused).
[email protected]ccaff652010-07-31 06:28:20197 dict->SetString("os_error_string", WideToUTF8(error_string));
[email protected]21526002010-05-16 19:42:46198 LocalFree(error_string);
199#endif
200 }
201
202 return dict;
203 }
204
205 private:
[email protected]13024882011-05-18 23:19:16206 const uint32 attempt_number_;
[email protected]21526002010-05-16 19:42:46207 const int net_error_;
208 const int os_error_;
[email protected]ee094b82010-08-24 15:55:51209};
210
[email protected]b3601bc22012-02-21 21:23:20211// Extra parameters to attach to the NetLog when the DnsTask failed.
212class DnsTaskFailedParams : public NetLog::EventParameters {
213 public:
214 DnsTaskFailedParams(int net_error, int dns_error)
215 : net_error_(net_error), dns_error_(dns_error) {
216 }
217
218 virtual Value* ToValue() const OVERRIDE {
219 DictionaryValue* dict = new DictionaryValue();
220 dict->SetInteger("net_error", net_error_);
221 if (dns_error_)
222 dict->SetInteger("dns_error", dns_error_);
223 return dict;
224 }
225
226 private:
227 const int net_error_;
228 const int dns_error_;
229};
230
[email protected]ee094b82010-08-24 15:55:51231// Parameters representing the information in a RequestInfo object, along with
232// the associated NetLog::Source.
233class RequestInfoParameters : public NetLog::EventParameters {
234 public:
235 RequestInfoParameters(const HostResolver::RequestInfo& info,
236 const NetLog::Source& source)
237 : info_(info), source_(source) {}
238
[email protected]0f292de02012-02-01 22:28:20239 virtual Value* ToValue() const OVERRIDE {
[email protected]ee094b82010-08-24 15:55:51240 DictionaryValue* dict = new DictionaryValue();
[email protected]930cc742010-09-15 22:54:10241 dict->SetString("host", info_.host_port_pair().ToString());
[email protected]ee094b82010-08-24 15:55:51242 dict->SetInteger("address_family",
243 static_cast<int>(info_.address_family()));
244 dict->SetBoolean("allow_cached_response", info_.allow_cached_response());
245 dict->SetBoolean("is_speculative", info_.is_speculative());
246 dict->SetInteger("priority", info_.priority());
247
248 if (source_.is_valid())
249 dict->Set("source_dependency", source_.ToValue());
250
251 return dict;
252 }
253
254 private:
255 const HostResolver::RequestInfo info_;
256 const NetLog::Source source_;
257};
258
[email protected]b3601bc22012-02-21 21:23:20259// Parameters associated with the creation of a HostResolverImpl::Job.
[email protected]ee094b82010-08-24 15:55:51260class JobCreationParameters : public NetLog::EventParameters {
261 public:
[email protected]0f292de02012-02-01 22:28:20262 JobCreationParameters(const std::string& host,
263 const NetLog::Source& source)
[email protected]ee094b82010-08-24 15:55:51264 : host_(host), source_(source) {}
265
[email protected]0f292de02012-02-01 22:28:20266 virtual Value* ToValue() const OVERRIDE {
[email protected]ee094b82010-08-24 15:55:51267 DictionaryValue* dict = new DictionaryValue();
268 dict->SetString("host", host_);
269 dict->Set("source_dependency", source_.ToValue());
270 return dict;
271 }
272
273 private:
274 const std::string host_;
275 const NetLog::Source source_;
[email protected]21526002010-05-16 19:42:46276};
277
[email protected]0f292de02012-02-01 22:28:20278// Parameters of the HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH event.
279class JobAttachParameters : public NetLog::EventParameters {
280 public:
281 JobAttachParameters(const NetLog::Source& source,
282 RequestPriority priority)
283 : source_(source), priority_(priority) {}
284
285 virtual Value* ToValue() const OVERRIDE {
286 DictionaryValue* dict = new DictionaryValue();
287 dict->Set("source_dependency", source_.ToValue());
288 dict->SetInteger("priority", priority_);
289 return dict;
290 }
291
292 private:
293 const NetLog::Source source_;
294 const RequestPriority priority_;
295};
296
297// The logging routines are defined here because some requests are resolved
298// without a Request object.
299
300// Logs when a request has just been started.
301void LogStartRequest(const BoundNetLog& source_net_log,
302 const BoundNetLog& request_net_log,
303 const HostResolver::RequestInfo& info) {
304 source_net_log.BeginEvent(
305 NetLog::TYPE_HOST_RESOLVER_IMPL,
306 make_scoped_refptr(new NetLogSourceParameter(
307 "source_dependency", request_net_log.source())));
308
309 request_net_log.BeginEvent(
310 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
311 make_scoped_refptr(new RequestInfoParameters(
312 info, source_net_log.source())));
313}
314
315// Logs when a request has just completed (before its callback is run).
316void LogFinishRequest(const BoundNetLog& source_net_log,
317 const BoundNetLog& request_net_log,
318 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20319 int net_error) {
320 request_net_log.EndEventWithNetErrorCode(
321 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20322 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL, NULL);
323}
324
325// Logs when a request has been cancelled.
326void LogCancelRequest(const BoundNetLog& source_net_log,
327 const BoundNetLog& request_net_log,
328 const HostResolverImpl::RequestInfo& info) {
329 request_net_log.AddEvent(NetLog::TYPE_CANCELLED, NULL);
330 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, NULL);
331 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL, NULL);
332}
333
[email protected]b59ff372009-07-15 22:04:32334//-----------------------------------------------------------------------------
335
[email protected]0f292de02012-02-01 22:28:20336// Keeps track of the highest priority.
337class PriorityTracker {
338 public:
[email protected]16ee26d2012-03-08 03:34:35339 PriorityTracker()
340 : highest_priority_(IDLE), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20341 memset(counts_, 0, sizeof(counts_));
342 }
343
344 RequestPriority highest_priority() const {
345 return highest_priority_;
346 }
347
348 size_t total_count() const {
349 return total_count_;
350 }
351
352 void Add(RequestPriority req_priority) {
353 ++total_count_;
354 ++counts_[req_priority];
355 if (highest_priority_ > req_priority)
356 highest_priority_ = req_priority;
357 }
358
359 void Remove(RequestPriority req_priority) {
360 DCHECK_GT(total_count_, 0u);
361 DCHECK_GT(counts_[req_priority], 0u);
362 --total_count_;
363 --counts_[req_priority];
364 size_t i;
365 for (i = highest_priority_; i < NUM_PRIORITIES && !counts_[i]; ++i);
366 highest_priority_ = static_cast<RequestPriority>(i);
367
368 // In absence of requests set default.
369 if (highest_priority_ == NUM_PRIORITIES) {
370 DCHECK_EQ(0u, total_count_);
371 highest_priority_ = IDLE;
372 }
373 }
374
375 private:
376 RequestPriority highest_priority_;
377 size_t total_count_;
378 size_t counts_[NUM_PRIORITIES];
379};
380
381//-----------------------------------------------------------------------------
382
383HostResolver* CreateHostResolver(size_t max_concurrent_resolves,
384 size_t max_retry_attempts,
[email protected]b3601bc22012-02-21 21:23:20385 HostCache* cache,
386 scoped_ptr<DnsConfigService> config_service,
[email protected]0f292de02012-02-01 22:28:20387 NetLog* net_log) {
388 if (max_concurrent_resolves == HostResolver::kDefaultParallelism)
389 max_concurrent_resolves = kDefaultMaxProcTasks;
390
391 // TODO(szym): Add experiments with reserved slots for higher priority
392 // requests.
393
394 PrioritizedDispatcher::Limits limits(NUM_PRIORITIES, max_concurrent_resolves);
395
396 HostResolverImpl* resolver = new HostResolverImpl(
[email protected]b3601bc22012-02-21 21:23:20397 cache,
[email protected]0f292de02012-02-01 22:28:20398 limits,
399 HostResolverImpl::ProcTaskParams(NULL, max_retry_attempts),
[email protected]b3601bc22012-02-21 21:23:20400 config_service.Pass(),
[email protected]0f292de02012-02-01 22:28:20401 net_log);
402
403 return resolver;
404}
405
406} // anonymous namespace
407
408//-----------------------------------------------------------------------------
409
410HostResolver* CreateSystemHostResolver(size_t max_concurrent_resolves,
411 size_t max_retry_attempts,
412 NetLog* net_log) {
413 return CreateHostResolver(max_concurrent_resolves,
414 max_retry_attempts,
[email protected]b3601bc22012-02-21 21:23:20415 HostCache::CreateDefaultCache(),
416 scoped_ptr<DnsConfigService>(NULL),
[email protected]0f292de02012-02-01 22:28:20417 net_log);
418}
419
420HostResolver* CreateNonCachingSystemHostResolver(size_t max_concurrent_resolves,
421 size_t max_retry_attempts,
422 NetLog* net_log) {
423 return CreateHostResolver(max_concurrent_resolves,
424 max_retry_attempts,
[email protected]b3601bc22012-02-21 21:23:20425 NULL,
426 scoped_ptr<DnsConfigService>(NULL),
427 net_log);
428}
429
430HostResolver* CreateAsyncHostResolver(size_t max_concurrent_resolves,
431 size_t max_retry_attempts,
432 NetLog* net_log) {
433 scoped_ptr<DnsConfigService> config_service =
434 DnsConfigService::CreateSystemService();
435 config_service->Watch();
436 return CreateHostResolver(max_concurrent_resolves,
437 max_retry_attempts,
438 HostCache::CreateDefaultCache(),
439 config_service.Pass(),
[email protected]0f292de02012-02-01 22:28:20440 net_log);
441}
442
443//-----------------------------------------------------------------------------
444
445// Holds the data for a request that could not be completed synchronously.
446// It is owned by a Job. Canceled Requests are only marked as canceled rather
447// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32448class HostResolverImpl::Request {
449 public:
[email protected]ee094b82010-08-24 15:55:51450 Request(const BoundNetLog& source_net_log,
451 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09452 const RequestInfo& info,
[email protected]aa22b242011-11-16 18:58:29453 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32454 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51455 : source_net_log_(source_net_log),
456 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09457 info_(info),
458 job_(NULL),
459 callback_(callback),
460 addresses_(addresses) {
461 }
[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]b59ff372009-07-15 22:04:32482 if (error == OK)
[email protected]b3601bc22012-02-21 21:23:20483 *addresses_ = CreateAddressListUsingPort(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29484 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20485 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29486 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32487 }
488
[email protected]b59ff372009-07-15 22:04:32489 Job* job() const {
490 return job_;
491 }
492
[email protected]0f292de02012-02-01 22:28:20493 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51494 const BoundNetLog& source_net_log() {
495 return source_net_log_;
496 }
497
[email protected]0f292de02012-02-01 22:28:20498 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51499 const BoundNetLog& request_net_log() {
500 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09501 }
502
[email protected]b59ff372009-07-15 22:04:32503 const RequestInfo& info() const {
504 return info_;
505 }
506
507 private:
[email protected]ee094b82010-08-24 15:55:51508 BoundNetLog source_net_log_;
509 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09510
[email protected]b59ff372009-07-15 22:04:32511 // The request info that started the request.
512 RequestInfo info_;
513
[email protected]0f292de02012-02-01 22:28:20514 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32515 Job* job_;
516
517 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29518 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32519
520 // The address list to save result into.
521 AddressList* addresses_;
522
523 DISALLOW_COPY_AND_ASSIGN(Request);
524};
525
[email protected]1e9bbd22010-10-15 16:42:45526//------------------------------------------------------------------------------
527
528// Provide a common macro to simplify code and readability. We must use a
529// macros as the underlying HISTOGRAM macro creates static varibles.
530#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
531 base::TimeDelta::FromMicroseconds(1), base::TimeDelta::FromHours(1), 100)
[email protected]b59ff372009-07-15 22:04:32532
[email protected]0f292de02012-02-01 22:28:20533// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
534//
535// Whenever we try to resolve the host, we post a delayed task to check if host
536// resolution (OnLookupComplete) is completed or not. If the original attempt
537// hasn't completed, then we start another attempt for host resolution. We take
538// the results from the first attempt that finishes and ignore the results from
539// all other attempts.
540//
541// TODO(szym): Move to separate source file for testing and mocking.
542//
543class HostResolverImpl::ProcTask
544 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32545 public:
[email protected]b3601bc22012-02-21 21:23:20546 typedef base::Callback<void(int net_error,
547 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32548
[email protected]0f292de02012-02-01 22:28:20549 ProcTask(const Key& key,
550 const ProcTaskParams& params,
551 const Callback& callback,
552 const BoundNetLog& job_net_log)
553 : key_(key),
554 params_(params),
555 callback_(callback),
556 origin_loop_(base::MessageLoopProxy::current()),
557 attempt_number_(0),
558 completed_attempt_number_(0),
559 completed_attempt_error_(ERR_UNEXPECTED),
560 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20561 net_log_(job_net_log) {
[email protected]0f292de02012-02-01 22:28:20562 if (!params_.resolver_proc)
563 params_.resolver_proc = HostResolverProc::GetDefault();
564 // If default is unset, use the system proc.
565 if (!params_.resolver_proc)
566 params_.resolver_proc = new CallSystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32567 }
568
[email protected]b59ff372009-07-15 22:04:32569 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15570 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]9c571762012-02-27 19:12:40571 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK, NULL);
[email protected]189163e2011-05-11 01:48:54572 StartLookupAttempt();
573 }
[email protected]252b699b2010-02-05 21:38:06574
[email protected]0f292de02012-02-01 22:28:20575 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
576 // attempts running on worker threads will continue running. Only once all the
577 // attempts complete will the final reference to this ProcTask be released.
578 void Cancel() {
579 DCHECK(origin_loop_->BelongsToCurrentThread());
580
581 if (was_canceled())
582 return;
583
[email protected]0f292de02012-02-01 22:28:20584 callback_.Reset();
[email protected]0f292de02012-02-01 22:28:20585 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK, NULL);
586 }
587
588 void set_had_non_speculative_request() {
589 DCHECK(origin_loop_->BelongsToCurrentThread());
590 had_non_speculative_request_ = true;
591 }
592
593 bool was_canceled() const {
594 DCHECK(origin_loop_->BelongsToCurrentThread());
595 return callback_.is_null();
596 }
597
598 bool was_completed() const {
599 DCHECK(origin_loop_->BelongsToCurrentThread());
600 return completed_attempt_number_ > 0;
601 }
602
603 private:
[email protected]189163e2011-05-11 01:48:54604 void StartLookupAttempt() {
605 DCHECK(origin_loop_->BelongsToCurrentThread());
606 base::TimeTicks start_time = base::TimeTicks::Now();
607 ++attempt_number_;
608 // Dispatch the lookup attempt to a worker thread.
609 if (!base::WorkerPool::PostTask(
610 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20611 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54612 true)) {
[email protected]b59ff372009-07-15 22:04:32613 NOTREACHED();
614
615 // Since we could be running within Resolve() right now, we can't just
616 // call OnLookupComplete(). Instead we must wait until Resolve() has
617 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15618 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54619 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20620 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12621 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54622 return;
[email protected]b59ff372009-07-15 22:04:32623 }
[email protected]13024882011-05-18 23:19:16624
625 net_log_.AddEvent(
626 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
627 make_scoped_refptr(new NetLogIntegerParameter(
628 "attempt_number", attempt_number_)));
629
[email protected]0f292de02012-02-01 22:28:20630 // If we don't get the results within a given time, RetryIfNotComplete
631 // will start a new attempt on a different worker thread if none of our
632 // outstanding attempts have completed yet.
633 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58634 origin_loop_->PostDelayedTask(
635 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20636 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42637 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58638 }
[email protected]b59ff372009-07-15 22:04:32639 }
640
[email protected]6c710ee2010-05-07 07:51:16641 // WARNING: This code runs inside a worker pool. The shutdown code cannot
642 // wait for it to finish, so we must be very careful here about using other
643 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54644 // may no longer exist. Multiple DoLookups() could be running in parallel, so
645 // any state inside of |this| must not mutate .
646 void DoLookup(const base::TimeTicks& start_time,
647 const uint32 attempt_number) {
648 AddressList results;
649 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32650 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20651 int error = params_.resolver_proc->Resolve(key_.hostname,
652 key_.address_family,
653 key_.host_resolver_flags,
654 &results,
655 &os_error);
[email protected]b59ff372009-07-15 22:04:32656
[email protected]189163e2011-05-11 01:48:54657 origin_loop_->PostTask(
658 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20659 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12660 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54661 }
662
[email protected]0f292de02012-02-01 22:28:20663 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
664 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54665 DCHECK(origin_loop_->BelongsToCurrentThread());
666
[email protected]0f292de02012-02-01 22:28:20667 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54668 return;
669
[email protected]0f292de02012-02-01 22:28:20670 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54671 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32672 }
673
674 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54675 void OnLookupComplete(const AddressList& results,
676 const base::TimeTicks& start_time,
677 const uint32 attempt_number,
678 int error,
679 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15680 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54681 DCHECK(error || results.head());
682
683 bool was_retry_attempt = attempt_number > 1;
684
[email protected]2d3b7762010-10-09 00:35:47685 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20686 // however it isn't safe to call NetworkChangeNotifier from worker threads.
687 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54688 if (error != OK && NetworkChangeNotifier::IsOffline())
689 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47690
[email protected]b3601bc22012-02-21 21:23:20691 // If this is the first attempt that is finishing later, then record data
692 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54693 if (!was_retry_attempt)
694 RecordPerformanceHistograms(start_time, error, os_error);
695
696 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35697
[email protected]0f292de02012-02-01 22:28:20698 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32699 return;
700
[email protected]0f292de02012-02-01 22:28:20701 scoped_refptr<NetLog::EventParameters> params;
702 if (error != OK) {
[email protected]b3601bc22012-02-21 21:23:20703 params = new ProcTaskFailedParams(attempt_number, error, os_error);
[email protected]0f292de02012-02-01 22:28:20704 } else {
[email protected]53b583b2012-02-09 00:10:47705 params = new NetLogIntegerParameter("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20706 }
707 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED, params);
708
709 if (was_completed())
710 return;
711
712 // Copy the results from the first worker thread that resolves the host.
713 results_ = results;
714 completed_attempt_number_ = attempt_number;
715 completed_attempt_error_ = error;
716
[email protected]e87b8b512011-06-14 22:12:52717 if (was_retry_attempt) {
718 // If retry attempt finishes before 1st attempt, then get stats on how
719 // much time is saved by having spawned an extra attempt.
720 retry_attempt_finished_time_ = base::TimeTicks::Now();
721 }
722
[email protected]189163e2011-05-11 01:48:54723 if (error != OK) {
[email protected]b3601bc22012-02-21 21:23:20724 params = new ProcTaskFailedParams(0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51725 } else {
726 params = new AddressListNetLogParam(results_);
727 }
[email protected]0f292de02012-02-01 22:28:20728 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK, params);
[email protected]ee094b82010-08-24 15:55:51729
[email protected]b3601bc22012-02-21 21:23:20730 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32731 }
732
[email protected]189163e2011-05-11 01:48:54733 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
734 const int error,
735 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15736 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]1e9bbd22010-10-15 16:42:45737 enum Category { // Used in HISTOGRAM_ENUMERATION.
738 RESOLVE_SUCCESS,
739 RESOLVE_FAIL,
740 RESOLVE_SPECULATIVE_SUCCESS,
741 RESOLVE_SPECULATIVE_FAIL,
742 RESOLVE_MAX, // Bounding value.
743 };
744 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
745
[email protected]189163e2011-05-11 01:48:54746 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
747 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45748 if (had_non_speculative_request_) {
749 category = RESOLVE_SUCCESS;
750 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
751 } else {
752 category = RESOLVE_SPECULATIVE_SUCCESS;
753 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
754 }
[email protected]7e96d792011-06-10 17:08:23755
[email protected]78eac2a2012-03-14 19:09:27756 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23757 // if IPv4 or IPv4/6 lookups are faster or slower.
758 switch(key_.address_family) {
759 case ADDRESS_FAMILY_IPV4:
760 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
761 break;
762 case ADDRESS_FAMILY_IPV6:
763 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
764 break;
765 case ADDRESS_FAMILY_UNSPECIFIED:
766 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
767 break;
768 }
[email protected]1e9bbd22010-10-15 16:42:45769 } else {
770 if (had_non_speculative_request_) {
771 category = RESOLVE_FAIL;
772 DNS_HISTOGRAM("DNS.ResolveFail", duration);
773 } else {
774 category = RESOLVE_SPECULATIVE_FAIL;
775 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
776 }
[email protected]78eac2a2012-03-14 19:09:27777 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23778 // if IPv4 or IPv4/6 lookups are faster or slower.
779 switch(key_.address_family) {
780 case ADDRESS_FAMILY_IPV4:
781 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
782 break;
783 case ADDRESS_FAMILY_IPV6:
784 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
785 break;
786 case ADDRESS_FAMILY_UNSPECIFIED:
787 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
788 break;
789 }
[email protected]c833e322010-10-16 23:51:36790 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54791 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45792 GetAllGetAddrinfoOSErrors());
793 }
[email protected]051b6ab2010-10-18 16:50:46794 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45795
796 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
797
[email protected]edafd4c2011-05-10 17:18:53798 static const bool show_speculative_experiment_histograms =
799 base::FieldTrialList::TrialExists("DnsImpact");
[email protected]ecd95ae2010-10-20 23:58:17800 if (show_speculative_experiment_histograms) {
[email protected]1e9bbd22010-10-15 16:42:45801 UMA_HISTOGRAM_ENUMERATION(
802 base::FieldTrial::MakeName("DNS.ResolveCategory", "DnsImpact"),
803 category, RESOLVE_MAX);
804 if (RESOLVE_SUCCESS == category) {
805 DNS_HISTOGRAM(base::FieldTrial::MakeName("DNS.ResolveSuccess",
806 "DnsImpact"), duration);
807 }
808 }
[email protected]edafd4c2011-05-10 17:18:53809 static const bool show_parallelism_experiment_histograms =
810 base::FieldTrialList::TrialExists("DnsParallelism");
[email protected]ecd95ae2010-10-20 23:58:17811 if (show_parallelism_experiment_histograms) {
812 UMA_HISTOGRAM_ENUMERATION(
813 base::FieldTrial::MakeName("DNS.ResolveCategory", "DnsParallelism"),
814 category, RESOLVE_MAX);
815 if (RESOLVE_SUCCESS == category) {
816 DNS_HISTOGRAM(base::FieldTrial::MakeName("DNS.ResolveSuccess",
817 "DnsParallelism"), duration);
818 }
819 }
[email protected]1e9bbd22010-10-15 16:42:45820 }
821
[email protected]189163e2011-05-11 01:48:54822 void RecordAttemptHistograms(const base::TimeTicks& start_time,
823 const uint32 attempt_number,
824 const int error,
825 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20826 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54827 bool first_attempt_to_complete =
828 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52829 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45830
[email protected]189163e2011-05-11 01:48:54831 if (first_attempt_to_complete) {
832 // If this was first attempt to complete, then record the resolution
833 // status of the attempt.
834 if (completed_attempt_error_ == OK) {
835 UMA_HISTOGRAM_ENUMERATION(
836 "DNS.AttemptFirstSuccess", attempt_number, 100);
837 } else {
838 UMA_HISTOGRAM_ENUMERATION(
839 "DNS.AttemptFirstFailure", attempt_number, 100);
840 }
841 }
842
843 if (error == OK)
844 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
845 else
846 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
847
[email protected]e87b8b512011-06-14 22:12:52848 // If first attempt didn't finish before retry attempt, then calculate stats
849 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20850 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52851 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
852 base::TimeTicks::Now() - retry_attempt_finished_time_);
853 }
854
[email protected]0f292de02012-02-01 22:28:20855 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54856 // Count those attempts which completed after the job was already canceled
857 // OR after the job was already completed by an earlier attempt (so in
858 // effect).
859 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
860
[email protected]0f292de02012-02-01 22:28:20861 // Record if job is canceled.
862 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54863 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
864 }
865
866 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
867 if (error == OK)
868 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
869 else
870 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
871 }
[email protected]1e9bbd22010-10-15 16:42:45872
[email protected]b59ff372009-07-15 22:04:32873 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57874 Key key_;
[email protected]b59ff372009-07-15 22:04:32875
[email protected]0f292de02012-02-01 22:28:20876 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32877 // This may not be the current resolver procedure by the time we call
878 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
879 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20880 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32881
[email protected]0f292de02012-02-01 22:28:20882 // The listener to the results of this ProcTask.
883 Callback callback_;
884
885 // Used to post ourselves onto the origin thread.
886 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54887
888 // Keeps track of the number of attempts we have made so far to resolve the
889 // host. Whenever we start an attempt to resolve the host, we increase this
890 // number.
891 uint32 attempt_number_;
892
893 // The index of the attempt which finished first (or 0 if the job is still in
894 // progress).
895 uint32 completed_attempt_number_;
896
897 // The result (a net error code) from the first attempt to complete.
898 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06899
[email protected]e87b8b512011-06-14 22:12:52900 // The time when retry attempt was finished.
901 base::TimeTicks retry_attempt_finished_time_;
902
[email protected]252b699b2010-02-05 21:38:06903 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20904 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06905 // This boolean is used for histogramming the duration of jobs used to
906 // service non-speculative requests.
907 bool had_non_speculative_request_;
908
[email protected]b59ff372009-07-15 22:04:32909 AddressList results_;
910
[email protected]ee094b82010-08-24 15:55:51911 BoundNetLog net_log_;
912
[email protected]0f292de02012-02-01 22:28:20913 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32914};
915
916//-----------------------------------------------------------------------------
917
[email protected]0f292de02012-02-01 22:28:20918// Represents a request to the worker pool for a "probe for IPv6 support" call.
[email protected]b3601bc22012-02-21 21:23:20919//
920// TODO(szym): This could also be replaced with PostTaskAndReply and Callbacks.
[email protected]0f8f1b432010-03-16 19:06:03921class HostResolverImpl::IPv6ProbeJob
922 : public base::RefCountedThreadSafe<HostResolverImpl::IPv6ProbeJob> {
923 public:
924 explicit IPv6ProbeJob(HostResolverImpl* resolver)
925 : resolver_(resolver),
[email protected]edd685f2011-08-15 20:33:46926 origin_loop_(base::MessageLoopProxy::current()) {
[email protected]3e9d9cc2011-05-03 21:08:15927 DCHECK(resolver);
[email protected]0f8f1b432010-03-16 19:06:03928 }
929
930 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15931 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20932 if (was_canceled())
[email protected]a9af7112010-05-08 00:56:01933 return;
[email protected]f092e64b2010-03-17 00:39:18934 const bool kIsSlow = true;
[email protected]ac9ba8fe2010-12-30 18:08:36935 base::WorkerPool::PostTask(
[email protected]33152acc2011-10-20 23:37:12936 FROM_HERE, base::Bind(&IPv6ProbeJob::DoProbe, this), kIsSlow);
[email protected]0f8f1b432010-03-16 19:06:03937 }
938
939 // Cancels the current job.
940 void Cancel() {
[email protected]3e9d9cc2011-05-03 21:08:15941 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20942 if (was_canceled())
[email protected]a9af7112010-05-08 00:56:01943 return;
[email protected]0f8f1b432010-03-16 19:06:03944 resolver_ = NULL; // Read/write ONLY on origin thread.
[email protected]0f8f1b432010-03-16 19:06:03945 }
946
[email protected]0f8f1b432010-03-16 19:06:03947 private:
948 friend class base::RefCountedThreadSafe<HostResolverImpl::IPv6ProbeJob>;
949
950 ~IPv6ProbeJob() {
951 }
952
[email protected]0f292de02012-02-01 22:28:20953 bool was_canceled() const {
[email protected]3e9d9cc2011-05-03 21:08:15954 DCHECK(origin_loop_->BelongsToCurrentThread());
955 return !resolver_;
[email protected]a9af7112010-05-08 00:56:01956 }
957
[email protected]0f8f1b432010-03-16 19:06:03958 // Run on worker thread.
959 void DoProbe() {
960 // Do actual testing on this thread, as it takes 40-100ms.
961 AddressFamily family = IPv6Supported() ? ADDRESS_FAMILY_UNSPECIFIED
962 : ADDRESS_FAMILY_IPV4;
963
[email protected]3e9d9cc2011-05-03 21:08:15964 origin_loop_->PostTask(
965 FROM_HERE,
[email protected]33152acc2011-10-20 23:37:12966 base::Bind(&IPv6ProbeJob::OnProbeComplete, this, family));
[email protected]0f8f1b432010-03-16 19:06:03967 }
968
[email protected]3e9d9cc2011-05-03 21:08:15969 // Callback for when DoProbe() completes.
[email protected]0f8f1b432010-03-16 19:06:03970 void OnProbeComplete(AddressFamily address_family) {
[email protected]3e9d9cc2011-05-03 21:08:15971 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20972 if (was_canceled())
[email protected]a9af7112010-05-08 00:56:01973 return;
[email protected]a9af7112010-05-08 00:56:01974 resolver_->IPv6ProbeSetDefaultAddressFamily(address_family);
[email protected]0f8f1b432010-03-16 19:06:03975 }
976
[email protected]0f8f1b432010-03-16 19:06:03977 // Used/set only on origin thread.
978 HostResolverImpl* resolver_;
979
980 // Used to post ourselves onto the origin thread.
[email protected]3e9d9cc2011-05-03 21:08:15981 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]0f8f1b432010-03-16 19:06:03982
983 DISALLOW_COPY_AND_ASSIGN(IPv6ProbeJob);
984};
985
986//-----------------------------------------------------------------------------
987
[email protected]b3601bc22012-02-21 21:23:20988// Resolves the hostname using DnsTransaction.
989// TODO(szym): This could be moved to separate source file as well.
990class HostResolverImpl::DnsTask {
991 public:
992 typedef base::Callback<void(int net_error,
993 const AddressList& addr_list,
994 base::TimeDelta ttl)> Callback;
995
996 DnsTask(DnsTransactionFactory* factory,
997 const Key& key,
998 const Callback& callback,
999 const BoundNetLog& job_net_log)
1000 : callback_(callback), net_log_(job_net_log) {
1001 DCHECK(factory);
1002 DCHECK(!callback.is_null());
1003
1004 // For now we treat ADDRESS_FAMILY_UNSPEC as if it was IPV4.
1005 uint16 qtype = (key.address_family == ADDRESS_FAMILY_IPV6)
1006 ? dns_protocol::kTypeAAAA
1007 : dns_protocol::kTypeA;
1008 // TODO(szym): Implement "happy eyeballs".
1009 transaction_ = factory->CreateTransaction(
1010 key.hostname,
1011 qtype,
1012 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this)),
1013 net_log_);
1014 DCHECK(transaction_.get());
1015 }
1016
1017 int Start() {
1018 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK, NULL);
1019 return transaction_->Start();
1020 }
1021
1022 void OnTransactionComplete(DnsTransaction* transaction,
1023 int net_error,
1024 const DnsResponse* response) {
1025 // TODO(szym): Record performance histograms.
1026 // Run |callback_| last since the owning Job will then delete this DnsTask.
1027 DnsResponse::Result result = DnsResponse::DNS_SUCCESS;
1028 if (net_error == OK) {
1029 AddressList addr_list;
1030 base::TimeDelta ttl;
1031 result = response->ParseToAddressList(&addr_list, &ttl);
1032 if (result == DnsResponse::DNS_SUCCESS) {
1033 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1034 new AddressListNetLogParam(addr_list));
1035 callback_.Run(net_error, addr_list, ttl);
1036 return;
1037 }
1038 net_error = ERR_DNS_MALFORMED_RESPONSE;
1039 }
1040 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1041 new DnsTaskFailedParams(net_error, result));
1042 callback_.Run(net_error, AddressList(), base::TimeDelta());
1043 }
1044
1045 private:
1046 // The listener to the results of this DnsTask.
1047 Callback callback_;
1048
1049 const BoundNetLog net_log_;
1050
1051 scoped_ptr<DnsTransaction> transaction_;
1052};
1053
1054//-----------------------------------------------------------------------------
1055
[email protected]0f292de02012-02-01 22:28:201056// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201057class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391058 public:
[email protected]0f292de02012-02-01 22:28:201059 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351060 // request that spawned it.
[email protected]0f292de02012-02-01 22:28:201061 Job(HostResolverImpl* resolver,
1062 const Key& key,
[email protected]16ee26d2012-03-08 03:34:351063 const BoundNetLog& request_net_log)
[email protected]0f292de02012-02-01 22:28:201064 : resolver_(resolver->AsWeakPtr()),
1065 key_(key),
1066 had_non_speculative_request_(false),
1067 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201068 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]0f292de02012-02-01 22:28:201069 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB, NULL);
1070
1071 net_log_.BeginEvent(
1072 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1073 make_scoped_refptr(new JobCreationParameters(
1074 key_.hostname, request_net_log.source())));
[email protected]68ad3ee2010-01-30 03:45:391075 }
1076
[email protected]0f292de02012-02-01 22:28:201077 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201078 if (is_running()) {
1079 // |resolver_| was destroyed with this Job still in flight.
1080 // Clean-up, record in the log, but don't run any callbacks.
1081 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201082 proc_task_->Cancel();
1083 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201084 }
[email protected]16ee26d2012-03-08 03:34:351085 // Clean up now for nice NetLog.
1086 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201087 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1088 ERR_ABORTED);
1089 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551090 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351091 // TODO(szym): is there any benefit in having this distinction?
[email protected]b3601bc22012-02-21 21:23:201092 net_log_.AddEvent(NetLog::TYPE_CANCELLED, NULL);
1093 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB, NULL);
[email protected]68ad3ee2010-01-30 03:45:391094 }
[email protected]b3601bc22012-02-21 21:23:201095 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391096
[email protected]b3601bc22012-02-21 21:23:201097 // Log any remaining Requests as cancelled.
1098 for (RequestsList::const_iterator it = requests_.begin();
1099 it != requests_.end(); ++it) {
1100 Request* req = *it;
1101 if (req->was_canceled())
1102 continue;
1103 DCHECK_EQ(this, req->job());
1104 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1105 req->info());
1106 }
1107 STLDeleteElements(&requests_);
[email protected]68ad3ee2010-01-30 03:45:391108 }
1109
[email protected]16ee26d2012-03-08 03:34:351110 const Key key() const {
[email protected]0f292de02012-02-01 22:28:201111 return key_;
1112 }
1113
[email protected]b3601bc22012-02-21 21:23:201114 bool is_queued() const {
1115 return !handle_.is_null();
[email protected]0f292de02012-02-01 22:28:201116 }
1117
[email protected]16ee26d2012-03-08 03:34:351118 bool is_running() const {
1119 return is_dns_running() || is_proc_running();
1120 }
1121
1122 // Add this job to the dispatcher.
1123 void Schedule(RequestPriority priority) {
1124 handle_ = resolver_->dispatcher_.Add(this, priority);
1125 }
1126
[email protected]b3601bc22012-02-21 21:23:201127 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201128 DCHECK_EQ(key_.hostname, req->info().hostname());
1129
1130 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201131 priority_tracker_.Add(req->info().priority());
1132
1133 req->request_net_log().AddEvent(
1134 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
1135 make_scoped_refptr(new NetLogSourceParameter(
1136 "source_dependency", net_log_.source())));
1137
1138 net_log_.AddEvent(
1139 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
1140 make_scoped_refptr(new JobAttachParameters(
1141 req->request_net_log().source(), priority())));
1142
1143 // TODO(szym): Check if this is still needed.
1144 if (!req->info().is_speculative()) {
1145 had_non_speculative_request_ = true;
1146 if (proc_task_)
1147 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391148 }
[email protected]b3601bc22012-02-21 21:23:201149
1150 requests_.push_back(req.release());
1151
[email protected]16ee26d2012-03-08 03:34:351152 if (is_queued())
[email protected]b3601bc22012-02-21 21:23:201153 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
[email protected]68ad3ee2010-01-30 03:45:391154 }
1155
[email protected]16ee26d2012-03-08 03:34:351156 // Marks |req| as cancelled. If it was the last active Request, also finishes
1157 // this Job marking it either as aborted or cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201158 void CancelRequest(Request* req) {
1159 DCHECK_EQ(key_.hostname, req->info().hostname());
1160 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351161
[email protected]0f292de02012-02-01 22:28:201162 // Don't remove it from |requests_| just mark it canceled.
1163 req->MarkAsCanceled();
1164 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1165 req->info());
[email protected]16ee26d2012-03-08 03:34:351166
[email protected]0f292de02012-02-01 22:28:201167 priority_tracker_.Remove(req->info().priority());
1168 net_log_.AddEvent(
1169 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1170 make_scoped_refptr(new JobAttachParameters(
1171 req->request_net_log().source(), priority())));
[email protected]b3601bc22012-02-21 21:23:201172
[email protected]16ee26d2012-03-08 03:34:351173 if (num_active_requests() > 0) {
1174 if (is_queued())
[email protected]b3601bc22012-02-21 21:23:201175 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
[email protected]16ee26d2012-03-08 03:34:351176 } else {
1177 // If we were called from a Request's callback within CompleteRequests,
1178 // that Request could not have been cancelled, so num_active_requests()
1179 // could not be 0. Therefore, we are not in CompleteRequests().
1180 CompleteRequests(OK, AddressList(), base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201181 }
[email protected]68ad3ee2010-01-30 03:45:391182 }
1183
[email protected]16ee26d2012-03-08 03:34:351184 // Called from AbortAllInProgressJobs. Completes all requests as aborted
1185 // and destroys the job.
[email protected]0f292de02012-02-01 22:28:201186 void Abort() {
[email protected]0f292de02012-02-01 22:28:201187 DCHECK(is_running());
[email protected]b3601bc22012-02-21 21:23:201188 CompleteRequests(ERR_ABORTED, AddressList(), base::TimeDelta());
1189 }
1190
[email protected]16ee26d2012-03-08 03:34:351191 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1192 // Completes all requests and destroys the job.
1193 void OnEvicted() {
1194 DCHECK(!is_running());
1195 DCHECK(is_queued());
1196 handle_.Reset();
1197
1198 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED, NULL);
1199
1200 // This signals to CompleteRequests that this job never ran.
1201 CompleteRequests(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE,
1202 AddressList(),
1203 base::TimeDelta());
1204 }
1205
[email protected]78eac2a2012-03-14 19:09:271206 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1207 // this Job was destroyed.
1208 bool ServeFromHosts() {
1209 DCHECK_GT(num_active_requests(), 0u);
1210 AddressList addr_list;
1211 if (resolver_->ServeFromHosts(key(),
1212 requests_.front()->info(),
1213 &addr_list)) {
1214 // This will destroy the Job.
1215 CompleteRequests(OK, addr_list, base::TimeDelta());
1216 return true;
1217 }
1218 return false;
1219 }
1220
[email protected]16ee26d2012-03-08 03:34:351221 private:
1222 RequestPriority priority() const {
1223 return priority_tracker_.highest_priority();
1224 }
1225
1226 // Number of non-canceled requests in |requests_|.
1227 size_t num_active_requests() const {
1228 return priority_tracker_.total_count();
1229 }
1230
[email protected]b3601bc22012-02-21 21:23:201231 bool is_dns_running() const {
1232 return dns_task_.get() != NULL;
1233 }
1234
1235 bool is_proc_running() const {
1236 return proc_task_.get() != NULL;
[email protected]35ddc282010-09-21 23:42:061237 }
1238
[email protected]16ee26d2012-03-08 03:34:351239 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201240 virtual void Start() OVERRIDE {
1241 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201242 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201243
1244 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED, NULL);
1245
[email protected]16ee26d2012-03-08 03:34:351246 // Job::Start must not complete synchronously.
[email protected]78eac2a2012-03-14 19:09:271247 if (resolver_->HaveDnsConfig()) {
[email protected]b3601bc22012-02-21 21:23:201248 StartDnsTask();
1249 } else {
1250 StartProcTask();
1251 }
1252 }
1253
[email protected]b3601bc22012-02-21 21:23:201254 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1255 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1256 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1257 // tighter limits.
1258 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351259 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201260 proc_task_ = new ProcTask(
1261 key_,
1262 resolver_->proc_params_,
1263 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this)),
1264 net_log_);
1265
1266 if (had_non_speculative_request_)
1267 proc_task_->set_had_non_speculative_request();
1268 // Start() could be called from within Resolve(), hence it must NOT directly
1269 // call OnProcTaskComplete, for example, on synchronous failure.
1270 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391271 }
1272
[email protected]0f292de02012-02-01 22:28:201273 // Called by ProcTask when it completes.
[email protected]b3601bc22012-02-21 21:23:201274 void OnProcTaskComplete(int net_error, const AddressList& addr_list) {
1275 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391276
[email protected]b3601bc22012-02-21 21:23:201277 base::TimeDelta ttl = base::TimeDelta::FromSeconds(
1278 kNegativeCacheEntryTTLSeconds);
1279 if (net_error == OK)
1280 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391281
[email protected]16ee26d2012-03-08 03:34:351282 CompleteRequests(net_error, addr_list, ttl);
[email protected]b3601bc22012-02-21 21:23:201283 }
1284
1285 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271286 DCHECK(resolver_->HaveDnsConfig());
[email protected]b3601bc22012-02-21 21:23:201287 dns_task_.reset(new DnsTask(
[email protected]78eac2a2012-03-14 19:09:271288 resolver_->dns_client_->GetTransactionFactory(),
[email protected]b3601bc22012-02-21 21:23:201289 key_,
1290 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this)),
1291 net_log_));
1292
1293 int rv = dns_task_->Start();
1294 if (rv != ERR_IO_PENDING) {
1295 DCHECK_NE(OK, rv);
1296 dns_task_.reset();
1297 StartProcTask();
1298 }
1299 }
1300
1301 // Called by DnsTask when it completes.
1302 void OnDnsTaskComplete(int net_error,
1303 const AddressList& addr_list,
1304 base::TimeDelta ttl) {
1305 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201306
1307 if (net_error != OK) {
[email protected]16ee26d2012-03-08 03:34:351308 dns_task_.reset();
[email protected]78eac2a2012-03-14 19:09:271309
1310 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1311 // http://crbug.com/117655
1312
[email protected]b3601bc22012-02-21 21:23:201313 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1314 // ProcTask in that case is a waste of time.
1315 StartProcTask();
1316 return;
1317 }
1318
[email protected]16ee26d2012-03-08 03:34:351319 CompleteRequests(net_error, addr_list, ttl);
[email protected]b3601bc22012-02-21 21:23:201320 }
1321
[email protected]16ee26d2012-03-08 03:34:351322 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]b3601bc22012-02-21 21:23:201323 void CompleteRequests(int net_error,
1324 const AddressList& addr_list,
1325 base::TimeDelta ttl) {
1326 CHECK(resolver_);
[email protected]b3601bc22012-02-21 21:23:201327
[email protected]16ee26d2012-03-08 03:34:351328 // This job must be removed from resolver's |jobs_| now to make room for a
1329 // new job with the same key in case one of the OnComplete callbacks decides
1330 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1331 // is done.
1332 scoped_ptr<Job> self_deleter(this);
1333
1334 resolver_->RemoveJob(this);
1335
1336 // |addr_list| will be destroyed once we destroy |proc_task_| and
1337 // |dns_task_|.
[email protected]b3601bc22012-02-21 21:23:201338 AddressList list = addr_list;
[email protected]16ee26d2012-03-08 03:34:351339
1340 if (is_running()) {
1341 DCHECK(!is_queued());
1342 if (is_proc_running()) {
1343 proc_task_->Cancel();
1344 proc_task_ = NULL;
1345 }
1346 dns_task_.reset();
1347
1348 // Signal dispatcher that a slot has opened.
1349 resolver_->dispatcher_.OnJobFinished();
1350 } else if (is_queued()) {
1351 resolver_->dispatcher_.Cancel(handle_);
1352 handle_.Reset();
1353 }
1354
1355 if (num_active_requests() == 0) {
1356 net_log_.AddEvent(NetLog::TYPE_CANCELLED, NULL);
1357 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1358 OK);
1359 return;
1360 }
[email protected]b3601bc22012-02-21 21:23:201361
1362 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1363 net_error);
[email protected]68ad3ee2010-01-30 03:45:391364
[email protected]78eac2a2012-03-14 19:09:271365 DCHECK(!requests_.empty());
1366
[email protected]16ee26d2012-03-08 03:34:351367 // We are the only consumer of |list|, so we can safely change the port
1368 // without copy-on-write. This pays off, when job has only one request.
[email protected]78eac2a2012-03-14 19:09:271369 if (net_error == OK)
[email protected]16ee26d2012-03-08 03:34:351370 MutableSetPort(requests_.front()->info().port(), &list);
1371
1372 if ((net_error != ERR_ABORTED) &&
1373 (net_error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE)) {
1374 resolver_->CacheResult(key_, net_error, list, ttl);
1375 }
1376
[email protected]0f292de02012-02-01 22:28:201377 // Complete all of the requests that were attached to the job.
1378 for (RequestsList::const_iterator it = requests_.begin();
1379 it != requests_.end(); ++it) {
1380 Request* req = *it;
1381
1382 if (req->was_canceled())
1383 continue;
1384
1385 DCHECK_EQ(this, req->job());
1386 // Update the net log and notify registered observers.
1387 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]b3601bc22012-02-21 21:23:201388 req->info(), net_error);
[email protected]0f292de02012-02-01 22:28:201389
[email protected]b3601bc22012-02-21 21:23:201390 req->OnComplete(net_error, list);
[email protected]0f292de02012-02-01 22:28:201391
1392 // Check if the resolver was destroyed as a result of running the
1393 // callback. If it was, we could continue, but we choose to bail.
1394 if (!resolver_)
1395 return;
1396 }
1397 }
1398
[email protected]0f292de02012-02-01 22:28:201399 base::WeakPtr<HostResolverImpl> resolver_;
1400
1401 Key key_;
1402
1403 // Tracks the highest priority across |requests_|.
1404 PriorityTracker priority_tracker_;
1405
1406 bool had_non_speculative_request_;
1407
1408 BoundNetLog net_log_;
1409
[email protected]b3601bc22012-02-21 21:23:201410 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201411 scoped_refptr<ProcTask> proc_task_;
1412
[email protected]b3601bc22012-02-21 21:23:201413 // Resolves the host using a DnsTransaction.
1414 scoped_ptr<DnsTask> dns_task_;
1415
[email protected]0f292de02012-02-01 22:28:201416 // All Requests waiting for the result of this Job. Some can be canceled.
1417 RequestsList requests_;
1418
[email protected]16ee26d2012-03-08 03:34:351419 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201420 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391421};
1422
1423//-----------------------------------------------------------------------------
1424
[email protected]0f292de02012-02-01 22:28:201425HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431426 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201427 size_t max_retry_attempts)
1428 : resolver_proc(resolver_proc),
1429 max_retry_attempts(max_retry_attempts),
1430 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1431 retry_factor(2) {
1432}
1433
1434HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1435
1436HostResolverImpl::HostResolverImpl(
[email protected]e95d3aca2010-01-11 22:47:431437 HostCache* cache,
[email protected]0f292de02012-02-01 22:28:201438 const PrioritizedDispatcher::Limits& job_limits,
1439 const ProcTaskParams& proc_params,
[email protected]b3601bc22012-02-21 21:23:201440 scoped_ptr<DnsConfigService> dns_config_service,
[email protected]ee094b82010-08-24 15:55:511441 NetLog* net_log)
[email protected]112bd462009-12-10 07:23:401442 : cache_(cache),
[email protected]0f292de02012-02-01 22:28:201443 dispatcher_(job_limits),
1444 max_queued_jobs_(job_limits.total_jobs * 100u),
1445 proc_params_(proc_params),
[email protected]0c7798452009-10-26 17:59:511446 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]78eac2a2012-03-14 19:09:271447 dns_client_(NULL),
[email protected]b3601bc22012-02-21 21:23:201448 dns_config_service_(dns_config_service.Pass()),
[email protected]2f3bc65c2010-07-23 17:47:101449 ipv6_probe_monitoring_(false),
[email protected]ee094b82010-08-24 15:55:511450 additional_resolver_flags_(0),
1451 net_log_(net_log) {
[email protected]0f292de02012-02-01 22:28:201452
1453 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391454
[email protected]06ef6d92011-05-19 04:24:581455 // Maximum of 4 retry attempts for host resolution.
1456 static const size_t kDefaultMaxRetryAttempts = 4u;
1457
[email protected]0f292de02012-02-01 22:28:201458 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1459 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391460
[email protected]b59ff372009-07-15 22:04:321461#if defined(OS_WIN)
1462 EnsureWinsockInit();
1463#endif
[email protected]23f771162011-06-02 18:37:511464#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]2f3bc65c2010-07-23 17:47:101465 if (HaveOnlyLoopbackAddresses())
1466 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
1467#endif
[email protected]232a5812011-03-04 22:42:081468 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]46018c9d2011-09-06 03:42:341469#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
[email protected]ae7c9f42011-11-21 11:41:161470#if !defined(OS_ANDROID)
[email protected]46018c9d2011-09-06 03:42:341471 EnsureDnsReloaderInit();
[email protected]ae7c9f42011-11-21 11:41:161472#endif
[email protected]46018c9d2011-09-06 03:42:341473 NetworkChangeNotifier::AddDNSObserver(this);
1474#endif
[email protected]b3601bc22012-02-21 21:23:201475
[email protected]78eac2a2012-03-14 19:09:271476 if (dns_config_service_.get()) {
[email protected]b3601bc22012-02-21 21:23:201477 dns_config_service_->AddObserver(this);
[email protected]78eac2a2012-03-14 19:09:271478 dns_client_ = DnsClient::CreateClient(net_log_);
1479 }
[email protected]b59ff372009-07-15 22:04:321480}
1481
1482HostResolverImpl::~HostResolverImpl() {
[email protected]0f8f1b432010-03-16 19:06:031483 DiscardIPv6ProbeJob();
1484
[email protected]0f292de02012-02-01 22:28:201485 // This will also cancel all outstanding requests.
1486 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431487
[email protected]232a5812011-03-04 22:42:081488 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]46018c9d2011-09-06 03:42:341489#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
1490 NetworkChangeNotifier::RemoveDNSObserver(this);
1491#endif
[email protected]b59ff372009-07-15 22:04:321492}
1493
[email protected]0f292de02012-02-01 22:28:201494void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1495 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1496 DCHECK_GT(value, 0u);
1497 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131498}
1499
[email protected]684970b2009-08-14 04:54:461500int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321501 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291502 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461503 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511504 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401505 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141506 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291507 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141508
[email protected]ee094b82010-08-24 15:55:511509 // Make a log item for the request.
1510 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1511 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1512
[email protected]0f292de02012-02-01 22:28:201513 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321514
[email protected]123ab1e32009-10-21 19:12:571515 // Build a key that identifies the request in the cache and in the
1516 // outstanding jobs map.
[email protected]137af622010-02-05 02:14:351517 Key key = GetEffectiveKeyForRequest(info);
[email protected]123ab1e32009-10-21 19:12:571518
[email protected]287d7c22011-11-15 17:34:251519 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401520 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201521 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401522 return rv;
[email protected]38368712011-03-02 08:09:401523 }
1524
[email protected]0f292de02012-02-01 22:28:201525 // Next we need to attach our request to a "job". This job is responsible for
1526 // calling "getaddrinfo(hostname)" on a worker thread.
1527
1528 JobMap::iterator jobit = jobs_.find(key);
1529 Job* job;
1530 if (jobit == jobs_.end()) {
1531 // Create new Job.
[email protected]16ee26d2012-03-08 03:34:351532 job = new Job(this, key, request_net_log);
1533 job->Schedule(info.priority());
[email protected]0f292de02012-02-01 22:28:201534
1535 // Check for queue overflow.
1536 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1537 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1538 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351539 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201540 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201541 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201542 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201543 return rv;
1544 }
[email protected]0f292de02012-02-01 22:28:201545 }
[email protected]0f292de02012-02-01 22:28:201546 jobs_.insert(jobit, std::make_pair(key, job));
1547 } else {
1548 job = jobit->second;
1549 }
1550
1551 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201552 scoped_ptr<Request> req(new Request(source_net_log,
1553 request_net_log,
1554 info,
1555 callback,
1556 addresses));
[email protected]b59ff372009-07-15 22:04:321557 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201558 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321559
[email protected]b3601bc22012-02-21 21:23:201560 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201561 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321562 return ERR_IO_PENDING;
1563}
1564
[email protected]287d7c22011-11-15 17:34:251565int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401566 const RequestInfo& info,
1567 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001568 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401569 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1570 // On Windows it gives the default interface's address, whereas on Linux it
1571 // gives an error. We will make it fail on all platforms for consistency.
1572 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1573 return ERR_NAME_NOT_RESOLVED;
1574
1575 int net_error = ERR_UNEXPECTED;
1576 if (ResolveAsIP(key, info, &net_error, addresses))
1577 return net_error;
[email protected]78eac2a2012-03-14 19:09:271578 if (ServeFromCache(key, info, &net_error, addresses)) {
1579 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT, NULL);
1580 return net_error;
1581 }
1582 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1583 // http://crbug.com/117655
1584 if (ServeFromHosts(key, info, addresses)) {
1585 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT, NULL);
1586 return OK;
1587 }
1588 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401589}
1590
1591int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1592 AddressList* addresses,
1593 const BoundNetLog& source_net_log) {
1594 DCHECK(CalledOnValidThread());
1595 DCHECK(addresses);
1596
[email protected]95a214c2011-08-04 21:50:401597 // Make a log item for the request.
1598 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1599 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1600
1601 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201602 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401603
[email protected]95a214c2011-08-04 21:50:401604 Key key = GetEffectiveKeyForRequest(info);
1605
[email protected]287d7c22011-11-15 17:34:251606 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201607 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401608 return rv;
1609}
1610
[email protected]b59ff372009-07-15 22:04:321611void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141612 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321613 Request* req = reinterpret_cast<Request*>(req_handle);
1614 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201615 Job* job = req->job();
1616 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201617 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321618}
1619
[email protected]0f8f1b432010-03-16 19:06:031620void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141621 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031622 ipv6_probe_monitoring_ = false;
1623 DiscardIPv6ProbeJob();
1624 default_address_family_ = address_family;
1625}
1626
[email protected]f7d310e2010-10-07 16:25:111627AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1628 return default_address_family_;
1629}
1630
[email protected]a78f4272011-10-21 19:16:331631void HostResolverImpl::ProbeIPv6Support() {
1632 DCHECK(CalledOnValidThread());
1633 DCHECK(!ipv6_probe_monitoring_);
1634 ipv6_probe_monitoring_ = true;
1635 OnIPAddressChanged(); // Give initial setup call.
[email protected]ddb1e5a2010-12-13 20:10:451636}
1637
[email protected]489d1a82011-10-12 03:09:111638HostCache* HostResolverImpl::GetHostCache() {
1639 return cache_.get();
1640}
[email protected]95a214c2011-08-04 21:50:401641
1642bool HostResolverImpl::ResolveAsIP(const Key& key,
1643 const RequestInfo& info,
1644 int* net_error,
1645 AddressList* addresses) {
1646 DCHECK(addresses);
1647 DCHECK(net_error);
1648 IPAddressNumber ip_number;
1649 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1650 return false;
1651
1652 DCHECK_EQ(key.host_resolver_flags &
1653 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1654 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1655 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201656 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
1657 !ipv6_probe_monitoring_;
[email protected]95a214c2011-08-04 21:50:401658 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201659 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401660 *net_error = ERR_NAME_NOT_RESOLVED;
1661 } else {
1662 *addresses = AddressList::CreateFromIPAddressWithCname(
1663 ip_number, info.port(),
1664 (key.host_resolver_flags & HOST_RESOLVER_CANONNAME));
1665 }
1666 return true;
1667}
1668
1669bool HostResolverImpl::ServeFromCache(const Key& key,
1670 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401671 int* net_error,
1672 AddressList* addresses) {
1673 DCHECK(addresses);
1674 DCHECK(net_error);
1675 if (!info.allow_cached_response() || !cache_.get())
1676 return false;
1677
1678 const HostCache::Entry* cache_entry = cache_->Lookup(
1679 key, base::TimeTicks::Now());
1680 if (!cache_entry)
1681 return false;
1682
[email protected]78eac2a2012-03-14 19:09:271683
[email protected]95a214c2011-08-04 21:50:401684 *net_error = cache_entry->error;
1685 if (*net_error == OK)
1686 *addresses = CreateAddressListUsingPort(cache_entry->addrlist, info.port());
1687 return true;
1688}
1689
[email protected]78eac2a2012-03-14 19:09:271690bool HostResolverImpl::ServeFromHosts(const Key& key,
1691 const RequestInfo& info,
1692 AddressList* addresses) {
1693 DCHECK(addresses);
1694 if (!HaveDnsConfig())
1695 return false;
1696
1697 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1698 // (glibc and c-ares) return the first matching line. We have more
1699 // flexibility, but lose implicit ordering.
1700 // TODO(szym) http://crbug.com/117850
1701 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1702 DnsHosts::const_iterator it = hosts.find(
1703 DnsHostsKey(key.hostname,
1704 key.address_family == ADDRESS_FAMILY_UNSPECIFIED ?
1705 ADDRESS_FAMILY_IPV4 : key.address_family));
1706
1707 if (it == hosts.end()) {
1708 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED)
1709 return false;
1710
1711 it = hosts.find(DnsHostsKey(key.hostname, ADDRESS_FAMILY_IPV6));
1712 if (it == hosts.end())
1713 return false;
1714 }
1715
1716 *addresses = AddressList::CreateFromIPAddress(it->second, info.port());
1717 return true;
1718}
1719
[email protected]16ee26d2012-03-08 03:34:351720void HostResolverImpl::CacheResult(const Key& key,
1721 int net_error,
1722 const AddressList& addr_list,
1723 base::TimeDelta ttl) {
1724 if (cache_.get())
1725 cache_->Set(key, net_error, addr_list, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:031726}
1727
[email protected]0f292de02012-02-01 22:28:201728void HostResolverImpl::RemoveJob(Job* job) {
1729 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:351730 JobMap::iterator it = jobs_.find(job->key());
1731 if (it != jobs_.end() && it->second == job)
1732 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:321733}
1734
[email protected]0f8f1b432010-03-16 19:06:031735void HostResolverImpl::DiscardIPv6ProbeJob() {
1736 if (ipv6_probe_job_.get()) {
1737 ipv6_probe_job_->Cancel();
1738 ipv6_probe_job_ = NULL;
1739 }
1740}
1741
1742void HostResolverImpl::IPv6ProbeSetDefaultAddressFamily(
1743 AddressFamily address_family) {
1744 DCHECK(address_family == ADDRESS_FAMILY_UNSPECIFIED ||
1745 address_family == ADDRESS_FAMILY_IPV4);
[email protected]f092e64b2010-03-17 00:39:181746 if (default_address_family_ != address_family) {
[email protected]b30a3f52010-10-16 01:05:461747 VLOG(1) << "IPv6Probe forced AddressFamily setting to "
1748 << ((address_family == ADDRESS_FAMILY_UNSPECIFIED) ?
1749 "ADDRESS_FAMILY_UNSPECIFIED" : "ADDRESS_FAMILY_IPV4");
[email protected]f092e64b2010-03-17 00:39:181750 }
[email protected]0f8f1b432010-03-16 19:06:031751 default_address_family_ = address_family;
1752 // Drop reference since the job has called us back.
1753 DiscardIPv6ProbeJob();
[email protected]e95d3aca2010-01-11 22:47:431754}
1755
[email protected]137af622010-02-05 02:14:351756HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
1757 const RequestInfo& info) const {
[email protected]eaf3a3b2010-09-03 20:34:271758 HostResolverFlags effective_flags =
1759 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:351760 AddressFamily effective_address_family = info.address_family();
[email protected]eaf3a3b2010-09-03 20:34:271761 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
1762 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]137af622010-02-05 02:14:351763 effective_address_family = default_address_family_;
[email protected]eaf3a3b2010-09-03 20:34:271764 if (ipv6_probe_monitoring_)
1765 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
1766 }
1767 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:351768}
1769
[email protected]35ddc282010-09-21 23:42:061770void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:201771 // In Abort, a Request callback could spawn new Jobs with matching keys, so
1772 // first collect and remove all running jobs from |jobs_|.
1773 std::vector<Job*> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:201774 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
1775 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:201776 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:201777 jobs_to_abort.push_back(job);
1778 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:201779 } else {
[email protected]b3601bc22012-02-21 21:23:201780 DCHECK(job->is_queued());
1781 ++it;
[email protected]0f292de02012-02-01 22:28:201782 }
[email protected]ef4c40c2010-09-01 14:42:031783 }
[email protected]b3601bc22012-02-21 21:23:201784
[email protected]57a48d32012-03-03 00:04:551785 // Check if no dispatcher slots leaked out.
1786 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
1787
1788 // Life check to bail once |this| is deleted.
1789 base::WeakPtr<HostResolverImpl> self = AsWeakPtr();
1790
[email protected]16ee26d2012-03-08 03:34:351791 // Then Abort them.
[email protected]57a48d32012-03-03 00:04:551792 for (size_t i = 0; self && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:551793 jobs_to_abort[i]->Abort();
[email protected]b3601bc22012-02-21 21:23:201794 }
[email protected]ef4c40c2010-09-01 14:42:031795}
1796
[email protected]78eac2a2012-03-14 19:09:271797void HostResolverImpl::TryServingAllJobsFromHosts() {
1798 if (!HaveDnsConfig())
1799 return;
1800
1801 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1802 // http://crbug.com/117655
1803
1804 // Life check to bail once |this| is deleted.
1805 base::WeakPtr<HostResolverImpl> self = AsWeakPtr();
1806
1807 for (JobMap::iterator it = jobs_.begin(); self && it != jobs_.end(); ) {
1808 Job* job = it->second;
1809 ++it;
1810 // This could remove |job| from |jobs_|, but iterator will remain valid.
1811 job->ServeFromHosts();
1812 }
1813}
1814
[email protected]be1a48b2011-01-20 00:12:131815void HostResolverImpl::OnIPAddressChanged() {
1816 if (cache_.get())
1817 cache_->clear();
1818 if (ipv6_probe_monitoring_) {
[email protected]be1a48b2011-01-20 00:12:131819 DiscardIPv6ProbeJob();
1820 ipv6_probe_job_ = new IPv6ProbeJob(this);
1821 ipv6_probe_job_->Start();
1822 }
[email protected]23f771162011-06-02 18:37:511823#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]be1a48b2011-01-20 00:12:131824 if (HaveOnlyLoopbackAddresses()) {
1825 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
1826 } else {
1827 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
1828 }
1829#endif
1830 AbortAllInProgressJobs();
1831 // |this| may be deleted inside AbortAllInProgressJobs().
1832}
1833
[email protected]446df2952012-02-28 07:22:511834void HostResolverImpl::OnDNSChanged(unsigned detail) {
[email protected]46018c9d2011-09-06 03:42:341835 // If the DNS server has changed, existing cached info could be wrong so we
1836 // have to drop our internal cache :( Note that OS level DNS caches, such
1837 // as NSCD's cache should be dropped automatically by the OS when
1838 // resolv.conf changes so we don't need to do anything to clear that cache.
1839 if (cache_.get())
1840 cache_->clear();
1841 // Existing jobs will have been sent to the original server so they need to
1842 // be aborted. TODO(Craig): Should these jobs be restarted?
1843 AbortAllInProgressJobs();
1844 // |this| may be deleted inside AbortAllInProgressJobs().
1845}
1846
[email protected]b3601bc22012-02-21 21:23:201847void HostResolverImpl::OnConfigChanged(const DnsConfig& dns_config) {
1848 // We want a new factory in place, before we Abort running Jobs, so that the
1849 // newly started jobs use the new factory.
[email protected]78eac2a2012-03-14 19:09:271850 DCHECK(dns_client_.get());
1851
1852 // Life check to bail once |this| is deleted.
1853 base::WeakPtr<HostResolverImpl> self = AsWeakPtr();
1854
1855 bool had_factory = (dns_client_->GetConfig() != NULL);
1856 dns_client_->SetConfig(dns_config);
1857
[email protected]b3601bc22012-02-21 21:23:201858 // Don't Abort running Jobs unless they were running on DnsTransaction.
1859 // TODO(szym): This will change once http://crbug.com/114827 is fixed.
1860 if (had_factory)
[email protected]446df2952012-02-28 07:22:511861 OnDNSChanged(NetworkChangeNotifier::CHANGE_DNS_SETTINGS);
[email protected]78eac2a2012-03-14 19:09:271862
1863 if (self && dns_config.IsValid())
1864 TryServingAllJobsFromHosts();
1865}
1866
1867bool HostResolverImpl::HaveDnsConfig() const {
1868 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL);
[email protected]b3601bc22012-02-21 21:23:201869}
1870
[email protected]b59ff372009-07-15 22:04:321871} // namespace net