Home | History | Annotate | Download | only in dns
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef NET_DNS_HOST_RESOLVER_IMPL_H_
      6 #define NET_DNS_HOST_RESOLVER_IMPL_H_
      7 
      8 #include <map>
      9 
     10 #include "base/basictypes.h"
     11 #include "base/gtest_prod_util.h"
     12 #include "base/memory/scoped_ptr.h"
     13 #include "base/memory/scoped_vector.h"
     14 #include "base/memory/weak_ptr.h"
     15 #include "base/threading/non_thread_safe.h"
     16 #include "base/time/time.h"
     17 #include "net/base/net_export.h"
     18 #include "net/base/network_change_notifier.h"
     19 #include "net/dns/host_cache.h"
     20 #include "net/dns/host_resolver.h"
     21 #include "net/dns/host_resolver_proc.h"
     22 
     23 namespace net {
     24 
     25 class BoundNetLog;
     26 class DnsClient;
     27 class NetLog;
     28 
     29 // For each hostname that is requested, HostResolver creates a
     30 // HostResolverImpl::Job. When this job gets dispatched it creates a ProcTask
     31 // which runs the given HostResolverProc on a WorkerPool thread. If requests for
     32 // that same host are made during the job's lifetime, they are attached to the
     33 // existing job rather than creating a new one. This avoids doing parallel
     34 // resolves for the same host.
     35 //
     36 // The way these classes fit together is illustrated by:
     37 //
     38 //
     39 //            +----------- HostResolverImpl -------------+
     40 //            |                    |                     |
     41 //           Job                  Job                   Job
     42 //    (for host1, fam1)    (for host2, fam2)     (for hostx, famx)
     43 //       /    |   |            /   |   |             /   |   |
     44 //   Request ... Request  Request ... Request   Request ... Request
     45 //  (port1)     (port2)  (port3)      (port4)  (port5)      (portX)
     46 //
     47 // When a HostResolverImpl::Job finishes, the callbacks of each waiting request
     48 // are run on the origin thread.
     49 //
     50 // Thread safety: This class is not threadsafe, and must only be called
     51 // from one thread!
     52 //
     53 // The HostResolverImpl enforces limits on the maximum number of concurrent
     54 // threads using PrioritizedDispatcher::Limits.
     55 //
     56 // Jobs are ordered in the queue based on their priority and order of arrival.
     57 class NET_EXPORT HostResolverImpl
     58     : public HostResolver,
     59       NON_EXPORTED_BASE(public base::NonThreadSafe),
     60       public NetworkChangeNotifier::IPAddressObserver,
     61       public NetworkChangeNotifier::DNSObserver {
     62  public:
     63   // Parameters for ProcTask which resolves hostnames using HostResolveProc.
     64   //
     65   // |resolver_proc| is used to perform the actual resolves; it must be
     66   // thread-safe since it is run from multiple worker threads. If
     67   // |resolver_proc| is NULL then the default host resolver procedure is
     68   // used (which is SystemHostResolverProc except if overridden).
     69   //
     70   // For each attempt, we could start another attempt if host is not resolved
     71   // within |unresponsive_delay| time. We keep attempting to resolve the host
     72   // for |max_retry_attempts|. For every retry attempt, we grow the
     73   // |unresponsive_delay| by the |retry_factor| amount (that is retry interval
     74   // is multiplied by the retry factor each time). Once we have retried
     75   // |max_retry_attempts|, we give up on additional attempts.
     76   //
     77   struct NET_EXPORT_PRIVATE ProcTaskParams {
     78     // Sets up defaults.
     79     ProcTaskParams(HostResolverProc* resolver_proc, size_t max_retry_attempts);
     80 
     81     ~ProcTaskParams();
     82 
     83     // The procedure to use for resolving host names. This will be NULL, except
     84     // in the case of unit-tests which inject custom host resolving behaviors.
     85     scoped_refptr<HostResolverProc> resolver_proc;
     86 
     87     // Maximum number retry attempts to resolve the hostname.
     88     // Pass HostResolver::kDefaultRetryAttempts to choose a default value.
     89     size_t max_retry_attempts;
     90 
     91     // This is the limit after which we make another attempt to resolve the host
     92     // if the worker thread has not responded yet.
     93     base::TimeDelta unresponsive_delay;
     94 
     95     // Factor to grow |unresponsive_delay| when we re-re-try.
     96     uint32 retry_factor;
     97   };
     98 
     99   // Creates a HostResolver as specified by |options|.
    100   //
    101   // If Options.enable_caching is true, a cache is created using
    102   // HostCache::CreateDefaultCache(). Otherwise no cache is used.
    103   //
    104   // Options.GetDispatcherLimits() determines the maximum number of jobs that
    105   // the resolver will run at once. This upper-bounds the total number of
    106   // outstanding DNS transactions (not counting retransmissions and retries).
    107   //
    108   // |net_log| must remain valid for the life of the HostResolverImpl.
    109   HostResolverImpl(const Options& options, NetLog* net_log);
    110 
    111   // If any completion callbacks are pending when the resolver is destroyed,
    112   // the host resolutions are cancelled, and the completion callbacks will not
    113   // be called.
    114   virtual ~HostResolverImpl();
    115 
    116   // Configures maximum number of Jobs in the queue. Exposed for testing.
    117   // Only allowed when the queue is empty.
    118   void SetMaxQueuedJobs(size_t value);
    119 
    120   // Set the DnsClient to be used for resolution. In case of failure, the
    121   // HostResolverProc from ProcTaskParams will be queried. If the DnsClient is
    122   // not pre-configured with a valid DnsConfig, a new config is fetched from
    123   // NetworkChangeNotifier.
    124   void SetDnsClient(scoped_ptr<DnsClient> dns_client);
    125 
    126   // HostResolver methods:
    127   virtual int Resolve(const RequestInfo& info,
    128                       RequestPriority priority,
    129                       AddressList* addresses,
    130                       const CompletionCallback& callback,
    131                       RequestHandle* out_req,
    132                       const BoundNetLog& source_net_log) OVERRIDE;
    133   virtual int ResolveFromCache(const RequestInfo& info,
    134                                AddressList* addresses,
    135                                const BoundNetLog& source_net_log) OVERRIDE;
    136   virtual void CancelRequest(RequestHandle req) OVERRIDE;
    137   virtual void SetDefaultAddressFamily(AddressFamily address_family) OVERRIDE;
    138   virtual AddressFamily GetDefaultAddressFamily() const OVERRIDE;
    139   virtual void SetDnsClientEnabled(bool enabled) OVERRIDE;
    140   virtual HostCache* GetHostCache() OVERRIDE;
    141   virtual base::Value* GetDnsConfigAsValue() const OVERRIDE;
    142 
    143   void set_proc_params_for_test(const ProcTaskParams& proc_params) {
    144     proc_params_ = proc_params;
    145   }
    146 
    147  private:
    148   friend class HostResolverImplTest;
    149   class Job;
    150   class ProcTask;
    151   class LoopbackProbeJob;
    152   class DnsTask;
    153   class Request;
    154   typedef HostCache::Key Key;
    155   typedef std::map<Key, Job*> JobMap;
    156   typedef ScopedVector<Request> RequestsList;
    157 
    158   // Number of consecutive failures of DnsTask (with successful fallback to
    159   // ProcTask) before the DnsClient is disabled until the next DNS change.
    160   static const unsigned kMaximumDnsFailures;
    161 
    162   // Helper used by |Resolve()| and |ResolveFromCache()|.  Performs IP
    163   // literal, cache and HOSTS lookup (if enabled), returns OK if successful,
    164   // ERR_NAME_NOT_RESOLVED if either hostname is invalid or IP literal is
    165   // incompatible, ERR_DNS_CACHE_MISS if entry was not found in cache and HOSTS.
    166   int ResolveHelper(const Key& key,
    167                     const RequestInfo& info,
    168                     AddressList* addresses,
    169                     const BoundNetLog& request_net_log);
    170 
    171   // Tries to resolve |key| as an IP, returns true and sets |net_error| if
    172   // succeeds, returns false otherwise.
    173   bool ResolveAsIP(const Key& key,
    174                    const RequestInfo& info,
    175                    int* net_error,
    176                    AddressList* addresses);
    177 
    178   // If |key| is not found in cache returns false, otherwise returns
    179   // true, sets |net_error| to the cached error code and fills |addresses|
    180   // if it is a positive entry.
    181   bool ServeFromCache(const Key& key,
    182                       const RequestInfo& info,
    183                       int* net_error,
    184                       AddressList* addresses);
    185 
    186   // If we have a DnsClient with a valid DnsConfig, and |key| is found in the
    187   // HOSTS file, returns true and fills |addresses|. Otherwise returns false.
    188   bool ServeFromHosts(const Key& key,
    189                       const RequestInfo& info,
    190                       AddressList* addresses);
    191 
    192   // Callback from HaveOnlyLoopbackAddresses probe.
    193   void SetHaveOnlyLoopbackAddresses(bool result);
    194 
    195   // Returns the (hostname, address_family) key to use for |info|, choosing an
    196   // "effective" address family by inheriting the resolver's default address
    197   // family when the request leaves it unspecified.
    198   Key GetEffectiveKeyForRequest(const RequestInfo& info,
    199                                 const BoundNetLog& net_log) const;
    200 
    201   // Records the result in cache if cache is present.
    202   void CacheResult(const Key& key,
    203                    const HostCache::Entry& entry,
    204                    base::TimeDelta ttl);
    205 
    206   // Removes |job| from |jobs_|, only if it exists.
    207   void RemoveJob(Job* job);
    208 
    209   // Aborts all in progress jobs with ERR_NETWORK_CHANGED and notifies their
    210   // requests. Might start new jobs.
    211   void AbortAllInProgressJobs();
    212 
    213   // Aborts all in progress DnsTasks. In-progress jobs will fall back to
    214   // ProcTasks. Might start new jobs, if any jobs were taking up two dispatcher
    215   // slots.
    216   void AbortDnsTasks();
    217 
    218   // Attempts to serve each Job in |jobs_| from the HOSTS file if we have
    219   // a DnsClient with a valid DnsConfig.
    220   void TryServingAllJobsFromHosts();
    221 
    222   // NetworkChangeNotifier::IPAddressObserver:
    223   virtual void OnIPAddressChanged() OVERRIDE;
    224 
    225   // NetworkChangeNotifier::DNSObserver:
    226   virtual void OnDNSChanged() OVERRIDE;
    227 
    228   // True if have a DnsClient with a valid DnsConfig.
    229   bool HaveDnsConfig() const;
    230 
    231   // Called when a host name is successfully resolved and DnsTask was run on it
    232   // and resulted in |net_error|.
    233   void OnDnsTaskResolve(int net_error);
    234 
    235   // Allows the tests to catch slots leaking out of the dispatcher.  One
    236   // HostResolverImpl::Job could occupy multiple PrioritizedDispatcher job
    237   // slots.
    238   size_t num_running_dispatcher_jobs_for_tests() const {
    239     return dispatcher_->num_running_jobs();
    240   }
    241 
    242   // Cache of host resolution results.
    243   scoped_ptr<HostCache> cache_;
    244 
    245   // Map from HostCache::Key to a Job.
    246   JobMap jobs_;
    247 
    248   // Starts Jobs according to their priority and the configured limits.
    249   scoped_ptr<PrioritizedDispatcher> dispatcher_;
    250 
    251   // Limit on the maximum number of jobs queued in |dispatcher_|.
    252   size_t max_queued_jobs_;
    253 
    254   // Parameters for ProcTask.
    255   ProcTaskParams proc_params_;
    256 
    257   NetLog* net_log_;
    258 
    259   // Address family to use when the request doesn't specify one.
    260   AddressFamily default_address_family_;
    261 
    262   // If present, used by DnsTask and ServeFromHosts to resolve requests.
    263   scoped_ptr<DnsClient> dns_client_;
    264 
    265   // True if received valid config from |dns_config_service_|. Temporary, used
    266   // to measure performance of DnsConfigService: http://crbug.com/125599
    267   bool received_dns_config_;
    268 
    269   // Number of consecutive failures of DnsTask, counted when fallback succeeds.
    270   unsigned num_dns_failures_;
    271 
    272   // True if probing is done for each Request to set address family. When false,
    273   // explicit setting in |default_address_family_| is used.
    274   bool probe_ipv6_support_;
    275 
    276   // True if DnsConfigService detected that system configuration depends on
    277   // local IPv6 connectivity. Disables probing.
    278   bool use_local_ipv6_;
    279 
    280   // True iff ProcTask has successfully resolved a hostname known to have IPv6
    281   // addresses using ADDRESS_FAMILY_UNSPECIFIED. Reset on IP address change.
    282   bool resolved_known_ipv6_hostname_;
    283 
    284   // Any resolver flags that should be added to a request by default.
    285   HostResolverFlags additional_resolver_flags_;
    286 
    287   // Allow fallback to ProcTask if DnsTask fails.
    288   bool fallback_to_proctask_;
    289 
    290   base::WeakPtrFactory<HostResolverImpl> weak_ptr_factory_;
    291 
    292   base::WeakPtrFactory<HostResolverImpl> probe_weak_ptr_factory_;
    293 
    294   DISALLOW_COPY_AND_ASSIGN(HostResolverImpl);
    295 };
    296 
    297 }  // namespace net
    298 
    299 #endif  // NET_DNS_HOST_RESOLVER_IMPL_H_
    300