1 // Copyright (c) 2010 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 #include "net/base/host_resolver_proc.h"
6
7 #include "build/build_config.h"
8
9 #if defined(OS_POSIX) && !defined(OS_MACOSX)
10 #include <resolv.h>
11 #endif
12
13 #include "base/logging.h"
14 #include "base/time.h"
15 #include "net/base/address_list.h"
16 #include "net/base/net_errors.h"
17 #include "net/base/sys_addrinfo.h"
18
19 #if defined(OS_POSIX) && !defined(OS_MACOSX)
20 #include "base/singleton.h"
21 #include "base/thread_local_storage.h"
22 #endif
23
24 namespace net {
25
26 HostResolverProc* HostResolverProc::default_proc_ = NULL;
27
HostResolverProc(HostResolverProc * previous)28 HostResolverProc::HostResolverProc(HostResolverProc* previous) {
29 SetPreviousProc(previous);
30
31 // Implicitly fall-back to the global default procedure.
32 if (!previous)
33 SetPreviousProc(default_proc_);
34 }
35
SetPreviousProc(HostResolverProc * proc)36 void HostResolverProc::SetPreviousProc(HostResolverProc* proc) {
37 HostResolverProc* current_previous = previous_proc_;
38 previous_proc_ = NULL;
39 // Now that we've guaranteed |this| is the last proc in a chain, we can
40 // detect potential cycles using GetLastProc().
41 previous_proc_ = (GetLastProc(proc) == this) ? current_previous : proc;
42 }
43
SetLastProc(HostResolverProc * proc)44 void HostResolverProc::SetLastProc(HostResolverProc* proc) {
45 GetLastProc(this)->SetPreviousProc(proc);
46 }
47
48 // static
GetLastProc(HostResolverProc * proc)49 HostResolverProc* HostResolverProc::GetLastProc(HostResolverProc* proc) {
50 if (proc == NULL)
51 return NULL;
52 HostResolverProc* last_proc = proc;
53 while (last_proc->previous_proc_ != NULL)
54 last_proc = last_proc->previous_proc_;
55 return last_proc;
56 }
57
58 // static
SetDefault(HostResolverProc * proc)59 HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) {
60 HostResolverProc* old = default_proc_;
61 default_proc_ = proc;
62 return old;
63 }
64
65 // static
GetDefault()66 HostResolverProc* HostResolverProc::GetDefault() {
67 return default_proc_;
68 }
69
ResolveUsingPrevious(const std::string & host,AddressFamily address_family,AddressList * addrlist)70 int HostResolverProc::ResolveUsingPrevious(const std::string& host,
71 AddressFamily address_family,
72 AddressList* addrlist) {
73 if (previous_proc_)
74 return previous_proc_->Resolve(host, address_family, addrlist);
75
76 // Final fallback is the system resolver.
77 return SystemHostResolverProc(host, address_family, addrlist);
78 }
79
80 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
81 // On Linux/BSD, changes to /etc/resolv.conf can go unnoticed thus resulting
82 // in DNS queries failing either because nameservers are unknown on startup
83 // or because nameserver info has changed as a result of e.g. connecting to
84 // a new network. Some distributions patch glibc to stat /etc/resolv.conf
85 // to try to automatically detect such changes but these patches are not
86 // universal and even patched systems such as Jaunty appear to need calls
87 // to res_ninit to reload the nameserver information in different threads.
88 //
89 // We adopt the Mozilla solution here which is to call res_ninit when
90 // lookups fail and to rate limit the reloading to once per second per
91 // thread.
92 //
93 // OpenBSD does not have thread-safe res_ninit/res_nclose so we can't do
94 // the same trick there.
95
96 // Keep a timer per calling thread to rate limit the calling of res_ninit.
97 class DnsReloadTimer {
98 public:
99 // Check if the timer for the calling thread has expired. When no
100 // timer exists for the calling thread, create one.
Expired()101 bool Expired() {
102 const base::TimeDelta kRetryTime = base::TimeDelta::FromSeconds(1);
103 base::TimeTicks now = base::TimeTicks::Now();
104 base::TimeTicks* timer_ptr =
105 static_cast<base::TimeTicks*>(tls_index_.Get());
106
107 if (!timer_ptr) {
108 timer_ptr = new base::TimeTicks();
109 *timer_ptr = base::TimeTicks::Now();
110 tls_index_.Set(timer_ptr);
111 // Return true to reload dns info on the first call for each thread.
112 return true;
113 } else if (now - *timer_ptr > kRetryTime) {
114 *timer_ptr = now;
115 return true;
116 } else {
117 return false;
118 }
119 }
120
121 // Free the allocated timer.
SlotReturnFunction(void * data)122 static void SlotReturnFunction(void* data) {
123 base::TimeTicks* tls_data = static_cast<base::TimeTicks*>(data);
124 delete tls_data;
125 }
126
127 private:
128 friend struct DefaultSingletonTraits<DnsReloadTimer>;
129
DnsReloadTimer()130 DnsReloadTimer() {
131 // During testing the DnsReloadTimer Singleton may be created and destroyed
132 // multiple times. Initialize the ThreadLocalStorage slot only once.
133 if (!tls_index_.initialized())
134 tls_index_.Initialize(SlotReturnFunction);
135 }
136
~DnsReloadTimer()137 ~DnsReloadTimer() {
138 }
139
140 // We use thread local storage to identify which base::TimeTicks to
141 // interact with.
142 static ThreadLocalStorage::Slot tls_index_ ;
143
144 DISALLOW_COPY_AND_ASSIGN(DnsReloadTimer);
145 };
146
147 // A TLS slot to the TimeTicks for the current thread.
148 // static
149 ThreadLocalStorage::Slot DnsReloadTimer::tls_index_(base::LINKER_INITIALIZED);
150
151 #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
152
SystemHostResolverProc(const std::string & host,AddressFamily address_family,AddressList * addrlist)153 int SystemHostResolverProc(const std::string& host,
154 AddressFamily address_family,
155 AddressList* addrlist) {
156 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
157 // On Windows it gives the default interface's address, whereas on Linux it
158 // gives an error. We will make it fail on all platforms for consistency.
159 if (host.empty())
160 return ERR_NAME_NOT_RESOLVED;
161
162 struct addrinfo* ai = NULL;
163 struct addrinfo hints = {0};
164
165 switch (address_family) {
166 case ADDRESS_FAMILY_IPV4:
167 hints.ai_family = AF_INET;
168 break;
169 case ADDRESS_FAMILY_IPV6:
170 hints.ai_family = AF_INET6;
171 break;
172 case ADDRESS_FAMILY_UNSPECIFIED:
173 hints.ai_family = AF_UNSPEC;
174 break;
175 default:
176 NOTREACHED();
177 hints.ai_family = AF_UNSPEC;
178 }
179
180 #if defined(OS_WIN) || defined(OS_OPENBSD)
181 // DO NOT USE AI_ADDRCONFIG ON WINDOWS.
182 //
183 // The following comment in <winsock2.h> is the best documentation I found
184 // on AI_ADDRCONFIG for Windows:
185 // Flags used in "hints" argument to getaddrinfo()
186 // - AI_ADDRCONFIG is supported starting with Vista
187 // - default is AI_ADDRCONFIG ON whether the flag is set or not
188 // because the performance penalty in not having ADDRCONFIG in
189 // the multi-protocol stack environment is severe;
190 // this defaulting may be disabled by specifying the AI_ALL flag,
191 // in that case AI_ADDRCONFIG must be EXPLICITLY specified to
192 // enable ADDRCONFIG behavior
193 //
194 // Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the
195 // computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo
196 // to fail with WSANO_DATA (11004) for "localhost", probably because of the
197 // following note on AI_ADDRCONFIG in the MSDN getaddrinfo page:
198 // The IPv4 or IPv6 loopback address is not considered a valid global
199 // address.
200 // See http://crbug.com/5234.
201 //
202 // OpenBSD does not support it, either.
203 hints.ai_flags = 0;
204 #else
205 hints.ai_flags = AI_ADDRCONFIG;
206 #endif
207
208 // Restrict result set to only this socket type to avoid duplicates.
209 hints.ai_socktype = SOCK_STREAM;
210
211 int err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
212 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
213 net::DnsReloadTimer* dns_timer = Singleton<net::DnsReloadTimer>::get();
214 // If we fail, re-initialise the resolver just in case there have been any
215 // changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info.
216 if (err && dns_timer->Expired()) {
217 res_nclose(&_res);
218 if (!res_ninit(&_res))
219 err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
220 }
221 #endif
222
223 if (err)
224 return ERR_NAME_NOT_RESOLVED;
225
226 addrlist->Adopt(ai);
227 return OK;
228 }
229
230 } // namespace net
231