Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / net / dns / dns_config_service_win.cc
blobb0da34ef4bfd7569592710c39c5fc734add082dd
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.
5 #include "net/dns/dns_config_service_win.h"
7 #include <algorithm>
8 #include <string>
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/compiler_specific.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_path_watcher.h"
15 #include "base/logging.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/metrics/histogram.h"
18 #include "base/profiler/scoped_tracker.h"
19 #include "base/strings/string_split.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/synchronization/lock.h"
23 #include "base/threading/non_thread_safe.h"
24 #include "base/threading/thread_restrictions.h"
25 #include "base/time/time.h"
26 #include "base/win/registry.h"
27 #include "base/win/scoped_handle.h"
28 #include "base/win/windows_version.h"
29 #include "net/base/net_util.h"
30 #include "net/base/network_change_notifier.h"
31 #include "net/dns/dns_hosts.h"
32 #include "net/dns/dns_protocol.h"
33 #include "net/dns/serial_worker.h"
34 #include "url/url_canon.h"
36 #pragma comment(lib, "iphlpapi.lib")
38 namespace net {
40 namespace internal {
42 namespace {
44 // Interval between retries to parse config. Used only until parsing succeeds.
45 const int kRetryIntervalSeconds = 5;
47 // Registry key paths.
48 const wchar_t* const kTcpipPath =
49 L"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters";
50 const wchar_t* const kTcpip6Path =
51 L"SYSTEM\\CurrentControlSet\\Services\\Tcpip6\\Parameters";
52 const wchar_t* const kDnscachePath =
53 L"SYSTEM\\CurrentControlSet\\Services\\Dnscache\\Parameters";
54 const wchar_t* const kPolicyPath =
55 L"SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient";
56 const wchar_t* const kPrimaryDnsSuffixPath =
57 L"SOFTWARE\\Policies\\Microsoft\\System\\DNSClient";
58 const wchar_t* const kNRPTPath =
59 L"SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient\\DnsPolicyConfig";
61 enum HostsParseWinResult {
62 HOSTS_PARSE_WIN_OK = 0,
63 HOSTS_PARSE_WIN_UNREADABLE_HOSTS_FILE,
64 HOSTS_PARSE_WIN_COMPUTER_NAME_FAILED,
65 HOSTS_PARSE_WIN_IPHELPER_FAILED,
66 HOSTS_PARSE_WIN_BAD_ADDRESS,
67 HOSTS_PARSE_WIN_MAX // Bounding values for enumeration.
70 // Convenience for reading values using RegKey.
71 class RegistryReader : public base::NonThreadSafe {
72 public:
73 explicit RegistryReader(const wchar_t* key) {
74 // Ignoring the result. |key_.Valid()| will catch failures.
75 key_.Open(HKEY_LOCAL_MACHINE, key, KEY_QUERY_VALUE);
78 bool ReadString(const wchar_t* name,
79 DnsSystemSettings::RegString* out) const {
80 DCHECK(CalledOnValidThread());
81 out->set = false;
82 if (!key_.Valid()) {
83 // Assume that if the |key_| is invalid then the key is missing.
84 return true;
86 LONG result = key_.ReadValue(name, &out->value);
87 if (result == ERROR_SUCCESS) {
88 out->set = true;
89 return true;
91 return (result == ERROR_FILE_NOT_FOUND);
94 bool ReadDword(const wchar_t* name,
95 DnsSystemSettings::RegDword* out) const {
96 DCHECK(CalledOnValidThread());
97 out->set = false;
98 if (!key_.Valid()) {
99 // Assume that if the |key_| is invalid then the key is missing.
100 return true;
102 LONG result = key_.ReadValueDW(name, &out->value);
103 if (result == ERROR_SUCCESS) {
104 out->set = true;
105 return true;
107 return (result == ERROR_FILE_NOT_FOUND);
110 private:
111 base::win::RegKey key_;
113 DISALLOW_COPY_AND_ASSIGN(RegistryReader);
116 // Wrapper for GetAdaptersAddresses. Returns NULL if failed.
117 scoped_ptr<IP_ADAPTER_ADDRESSES, base::FreeDeleter> ReadIpHelper(ULONG flags) {
118 base::ThreadRestrictions::AssertIOAllowed();
120 scoped_ptr<IP_ADAPTER_ADDRESSES, base::FreeDeleter> out;
121 ULONG len = 15000; // As recommended by MSDN for GetAdaptersAddresses.
122 UINT rv = ERROR_BUFFER_OVERFLOW;
123 // Try up to three times.
124 for (unsigned tries = 0; (tries < 3) && (rv == ERROR_BUFFER_OVERFLOW);
125 tries++) {
126 out.reset(static_cast<PIP_ADAPTER_ADDRESSES>(malloc(len)));
127 memset(out.get(), 0, len);
128 rv = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, out.get(), &len);
130 if (rv != NO_ERROR)
131 out.reset();
132 return out.Pass();
135 // Converts a base::string16 domain name to ASCII, possibly using punycode.
136 // Returns true if the conversion succeeds and output is not empty. In case of
137 // failure, |domain| might become dirty.
138 bool ParseDomainASCII(const base::string16& widestr, std::string* domain) {
139 DCHECK(domain);
140 if (widestr.empty())
141 return false;
143 // Check if already ASCII.
144 if (base::IsStringASCII(widestr)) {
145 *domain = base::UTF16ToASCII(widestr);
146 return true;
149 // Otherwise try to convert it from IDN to punycode.
150 const int kInitialBufferSize = 256;
151 url::RawCanonOutputT<base::char16, kInitialBufferSize> punycode;
152 if (!url::IDNToASCII(widestr.data(), widestr.length(), &punycode))
153 return false;
155 // |punycode_output| should now be ASCII; convert it to a std::string.
156 // (We could use UTF16ToASCII() instead, but that requires an extra string
157 // copy. Since ASCII is a subset of UTF8 the following is equivalent).
158 bool success = base::UTF16ToUTF8(punycode.data(), punycode.length(), domain);
159 DCHECK(success);
160 DCHECK(base::IsStringASCII(*domain));
161 return success && !domain->empty();
164 bool ReadDevolutionSetting(const RegistryReader& reader,
165 DnsSystemSettings::DevolutionSetting* setting) {
166 return reader.ReadDword(L"UseDomainNameDevolution", &setting->enabled) &&
167 reader.ReadDword(L"DomainNameDevolutionLevel", &setting->level);
170 // Reads DnsSystemSettings from IpHelper and registry.
171 ConfigParseWinResult ReadSystemSettings(DnsSystemSettings* settings) {
172 settings->addresses = ReadIpHelper(GAA_FLAG_SKIP_ANYCAST |
173 GAA_FLAG_SKIP_UNICAST |
174 GAA_FLAG_SKIP_MULTICAST |
175 GAA_FLAG_SKIP_FRIENDLY_NAME);
176 if (!settings->addresses.get())
177 return CONFIG_PARSE_WIN_READ_IPHELPER;
179 RegistryReader tcpip_reader(kTcpipPath);
180 RegistryReader tcpip6_reader(kTcpip6Path);
181 RegistryReader dnscache_reader(kDnscachePath);
182 RegistryReader policy_reader(kPolicyPath);
183 RegistryReader primary_dns_suffix_reader(kPrimaryDnsSuffixPath);
185 if (!policy_reader.ReadString(L"SearchList",
186 &settings->policy_search_list)) {
187 return CONFIG_PARSE_WIN_READ_POLICY_SEARCHLIST;
190 if (!tcpip_reader.ReadString(L"SearchList", &settings->tcpip_search_list))
191 return CONFIG_PARSE_WIN_READ_TCPIP_SEARCHLIST;
193 if (!tcpip_reader.ReadString(L"Domain", &settings->tcpip_domain))
194 return CONFIG_PARSE_WIN_READ_DOMAIN;
196 if (!ReadDevolutionSetting(policy_reader, &settings->policy_devolution))
197 return CONFIG_PARSE_WIN_READ_POLICY_DEVOLUTION;
199 if (!ReadDevolutionSetting(dnscache_reader, &settings->dnscache_devolution))
200 return CONFIG_PARSE_WIN_READ_DNSCACHE_DEVOLUTION;
202 if (!ReadDevolutionSetting(tcpip_reader, &settings->tcpip_devolution))
203 return CONFIG_PARSE_WIN_READ_TCPIP_DEVOLUTION;
205 if (!policy_reader.ReadDword(L"AppendToMultiLabelName",
206 &settings->append_to_multi_label_name)) {
207 return CONFIG_PARSE_WIN_READ_APPEND_MULTILABEL;
210 if (!primary_dns_suffix_reader.ReadString(L"PrimaryDnsSuffix",
211 &settings->primary_dns_suffix)) {
212 return CONFIG_PARSE_WIN_READ_PRIMARY_SUFFIX;
215 base::win::RegistryKeyIterator nrpt_rules(HKEY_LOCAL_MACHINE, kNRPTPath);
216 settings->have_name_resolution_policy = (nrpt_rules.SubkeyCount() > 0);
218 return CONFIG_PARSE_WIN_OK;
221 // Default address of "localhost" and local computer name can be overridden
222 // by the HOSTS file, but if it's not there, then we need to fill it in.
223 HostsParseWinResult AddLocalhostEntries(DnsHosts* hosts) {
224 const unsigned char kIPv4Localhost[] = { 127, 0, 0, 1 };
225 const unsigned char kIPv6Localhost[] = { 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 1 };
227 IPAddressNumber loopback_ipv4(kIPv4Localhost,
228 kIPv4Localhost + arraysize(kIPv4Localhost));
229 IPAddressNumber loopback_ipv6(kIPv6Localhost,
230 kIPv6Localhost + arraysize(kIPv6Localhost));
232 // This does not override any pre-existing entries from the HOSTS file.
233 hosts->insert(std::make_pair(DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4),
234 loopback_ipv4));
235 hosts->insert(std::make_pair(DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6),
236 loopback_ipv6));
238 WCHAR buffer[MAX_PATH];
239 DWORD size = MAX_PATH;
240 std::string localname;
241 if (!GetComputerNameExW(ComputerNameDnsHostname, buffer, &size) ||
242 !ParseDomainASCII(buffer, &localname)) {
243 return HOSTS_PARSE_WIN_COMPUTER_NAME_FAILED;
245 base::StringToLowerASCII(&localname);
247 bool have_ipv4 =
248 hosts->count(DnsHostsKey(localname, ADDRESS_FAMILY_IPV4)) > 0;
249 bool have_ipv6 =
250 hosts->count(DnsHostsKey(localname, ADDRESS_FAMILY_IPV6)) > 0;
252 if (have_ipv4 && have_ipv6)
253 return HOSTS_PARSE_WIN_OK;
255 scoped_ptr<IP_ADAPTER_ADDRESSES, base::FreeDeleter> addresses =
256 ReadIpHelper(GAA_FLAG_SKIP_ANYCAST |
257 GAA_FLAG_SKIP_DNS_SERVER |
258 GAA_FLAG_SKIP_MULTICAST |
259 GAA_FLAG_SKIP_FRIENDLY_NAME);
260 if (!addresses.get())
261 return HOSTS_PARSE_WIN_IPHELPER_FAILED;
263 // The order of adapters is the network binding order, so stick to the
264 // first good adapter for each family.
265 for (const IP_ADAPTER_ADDRESSES* adapter = addresses.get();
266 adapter != NULL && (!have_ipv4 || !have_ipv6);
267 adapter = adapter->Next) {
268 if (adapter->OperStatus != IfOperStatusUp)
269 continue;
270 if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
271 continue;
273 for (const IP_ADAPTER_UNICAST_ADDRESS* address =
274 adapter->FirstUnicastAddress;
275 address != NULL;
276 address = address->Next) {
277 IPEndPoint ipe;
278 if (!ipe.FromSockAddr(address->Address.lpSockaddr,
279 address->Address.iSockaddrLength)) {
280 return HOSTS_PARSE_WIN_BAD_ADDRESS;
282 if (!have_ipv4 && (ipe.GetFamily() == ADDRESS_FAMILY_IPV4)) {
283 have_ipv4 = true;
284 (*hosts)[DnsHostsKey(localname, ADDRESS_FAMILY_IPV4)] = ipe.address();
285 } else if (!have_ipv6 && (ipe.GetFamily() == ADDRESS_FAMILY_IPV6)) {
286 have_ipv6 = true;
287 (*hosts)[DnsHostsKey(localname, ADDRESS_FAMILY_IPV6)] = ipe.address();
291 return HOSTS_PARSE_WIN_OK;
294 // Watches a single registry key for changes.
295 class RegistryWatcher : public base::NonThreadSafe {
296 public:
297 typedef base::Callback<void(bool succeeded)> CallbackType;
298 RegistryWatcher() {}
300 bool Watch(const wchar_t* key, const CallbackType& callback) {
301 DCHECK(CalledOnValidThread());
302 DCHECK(!callback.is_null());
303 DCHECK(callback_.is_null());
304 callback_ = callback;
305 if (key_.Open(HKEY_LOCAL_MACHINE, key, KEY_NOTIFY) != ERROR_SUCCESS)
306 return false;
308 return key_.StartWatching(base::Bind(&RegistryWatcher::OnObjectSignaled,
309 base::Unretained(this)));
312 void OnObjectSignaled() {
313 // TODO(vadimt): Remove ScopedTracker below once crbug.com/418183 is fixed.
314 tracked_objects::ScopedTracker tracking_profile(
315 FROM_HERE_WITH_EXPLICIT_FUNCTION("RegistryWatcher_OnObjectSignaled"));
317 DCHECK(CalledOnValidThread());
318 DCHECK(!callback_.is_null());
319 if (key_.StartWatching(base::Bind(&RegistryWatcher::OnObjectSignaled,
320 base::Unretained(this)))) {
321 callback_.Run(true);
322 } else {
323 key_.Close();
324 callback_.Run(false);
328 private:
329 CallbackType callback_;
330 base::win::RegKey key_;
332 DISALLOW_COPY_AND_ASSIGN(RegistryWatcher);
335 // Returns true iff |address| is DNS address from IPv6 stateless discovery,
336 // i.e., matches fec0:0:0:ffff::{1,2,3}.
337 // http://tools.ietf.org/html/draft-ietf-ipngwg-dns-discovery
338 bool IsStatelessDiscoveryAddress(const IPAddressNumber& address) {
339 if (address.size() != kIPv6AddressSize)
340 return false;
341 const uint8 kPrefix[] = {
342 0xfe, 0xc0, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
343 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
345 return std::equal(kPrefix, kPrefix + arraysize(kPrefix),
346 address.begin()) && (address.back() < 4);
349 // Returns the path to the HOSTS file.
350 base::FilePath GetHostsPath() {
351 TCHAR buffer[MAX_PATH];
352 UINT rc = GetSystemDirectory(buffer, MAX_PATH);
353 DCHECK(0 < rc && rc < MAX_PATH);
354 return base::FilePath(buffer).Append(
355 FILE_PATH_LITERAL("drivers\\etc\\hosts"));
358 void ConfigureSuffixSearch(const DnsSystemSettings& settings,
359 DnsConfig* config) {
360 // SearchList takes precedence, so check it first.
361 if (settings.policy_search_list.set) {
362 std::vector<std::string> search;
363 if (ParseSearchList(settings.policy_search_list.value, &search)) {
364 config->search.swap(search);
365 return;
367 // Even if invalid, the policy disables the user-specified setting below.
368 } else if (settings.tcpip_search_list.set) {
369 std::vector<std::string> search;
370 if (ParseSearchList(settings.tcpip_search_list.value, &search)) {
371 config->search.swap(search);
372 return;
376 // In absence of explicit search list, suffix search is:
377 // [primary suffix, connection-specific suffix, devolution of primary suffix].
378 // Primary suffix can be set by policy (primary_dns_suffix) or
379 // user setting (tcpip_domain).
381 // The policy (primary_dns_suffix) can be edited via Group Policy Editor
382 // (gpedit.msc) at Local Computer Policy => Computer Configuration
383 // => Administrative Template => Network => DNS Client => Primary DNS Suffix.
385 // The user setting (tcpip_domain) can be configurred at Computer Name in
386 // System Settings
387 std::string primary_suffix;
388 if ((settings.primary_dns_suffix.set &&
389 ParseDomainASCII(settings.primary_dns_suffix.value, &primary_suffix)) ||
390 (settings.tcpip_domain.set &&
391 ParseDomainASCII(settings.tcpip_domain.value, &primary_suffix))) {
392 // Primary suffix goes in front.
393 config->search.insert(config->search.begin(), primary_suffix);
394 } else {
395 return; // No primary suffix, hence no devolution.
398 // Devolution is determined by precedence: policy > dnscache > tcpip.
399 // |enabled|: UseDomainNameDevolution and |level|: DomainNameDevolutionLevel
400 // are overridden independently.
401 DnsSystemSettings::DevolutionSetting devolution = settings.policy_devolution;
403 if (!devolution.enabled.set)
404 devolution.enabled = settings.dnscache_devolution.enabled;
405 if (!devolution.enabled.set)
406 devolution.enabled = settings.tcpip_devolution.enabled;
407 if (devolution.enabled.set && (devolution.enabled.value == 0))
408 return; // Devolution disabled.
410 // By default devolution is enabled.
412 if (!devolution.level.set)
413 devolution.level = settings.dnscache_devolution.level;
414 if (!devolution.level.set)
415 devolution.level = settings.tcpip_devolution.level;
417 // After the recent update, Windows will try to determine a safe default
418 // value by comparing the forest root domain (FRD) to the primary suffix.
419 // See http://support.microsoft.com/kb/957579 for details.
420 // For now, if the level is not set, we disable devolution, assuming that
421 // we will fallback to the system getaddrinfo anyway. This might cause
422 // performance loss for resolutions which depend on the system default
423 // devolution setting.
425 // If the level is explicitly set below 2, devolution is disabled.
426 if (!devolution.level.set || devolution.level.value < 2)
427 return; // Devolution disabled.
429 // Devolve the primary suffix. This naive logic matches the observed
430 // behavior (see also ParseSearchList). If a suffix is not valid, it will be
431 // discarded when the fully-qualified name is converted to DNS format.
433 unsigned num_dots = std::count(primary_suffix.begin(),
434 primary_suffix.end(), '.');
436 for (size_t offset = 0; num_dots >= devolution.level.value; --num_dots) {
437 offset = primary_suffix.find('.', offset + 1);
438 config->search.push_back(primary_suffix.substr(offset + 1));
442 } // namespace
444 bool ParseSearchList(const base::string16& value,
445 std::vector<std::string>* output) {
446 DCHECK(output);
447 if (value.empty())
448 return false;
450 output->clear();
452 // If the list includes an empty hostname (",," or ", ,"), it is terminated.
453 // Although nslookup and network connection property tab ignore such
454 // fragments ("a,b,,c" becomes ["a", "b", "c"]), our reference is getaddrinfo
455 // (which sees ["a", "b"]). WMI queries also return a matching search list.
456 std::vector<base::string16> woutput;
457 base::SplitString(value, ',', &woutput);
458 for (size_t i = 0; i < woutput.size(); ++i) {
459 // Convert non-ASCII to punycode, although getaddrinfo does not properly
460 // handle such suffixes.
461 const base::string16& t = woutput[i];
462 std::string parsed;
463 if (!ParseDomainASCII(t, &parsed))
464 break;
465 output->push_back(parsed);
467 return !output->empty();
470 ConfigParseWinResult ConvertSettingsToDnsConfig(
471 const DnsSystemSettings& settings,
472 DnsConfig* config) {
473 *config = DnsConfig();
475 // Use GetAdapterAddresses to get effective DNS server order and
476 // connection-specific DNS suffix. Ignore disconnected and loopback adapters.
477 // The order of adapters is the network binding order, so stick to the
478 // first good adapter.
479 for (const IP_ADAPTER_ADDRESSES* adapter = settings.addresses.get();
480 adapter != NULL && config->nameservers.empty();
481 adapter = adapter->Next) {
482 if (adapter->OperStatus != IfOperStatusUp)
483 continue;
484 if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
485 continue;
487 for (const IP_ADAPTER_DNS_SERVER_ADDRESS* address =
488 adapter->FirstDnsServerAddress;
489 address != NULL;
490 address = address->Next) {
491 IPEndPoint ipe;
492 if (ipe.FromSockAddr(address->Address.lpSockaddr,
493 address->Address.iSockaddrLength)) {
494 if (IsStatelessDiscoveryAddress(ipe.address()))
495 continue;
496 // Override unset port.
497 if (!ipe.port())
498 ipe = IPEndPoint(ipe.address(), dns_protocol::kDefaultPort);
499 config->nameservers.push_back(ipe);
500 } else {
501 return CONFIG_PARSE_WIN_BAD_ADDRESS;
505 // IP_ADAPTER_ADDRESSES in Vista+ has a search list at |FirstDnsSuffix|,
506 // but it came up empty in all trials.
507 // |DnsSuffix| stores the effective connection-specific suffix, which is
508 // obtained via DHCP (regkey: Tcpip\Parameters\Interfaces\{XXX}\DhcpDomain)
509 // or specified by the user (regkey: Tcpip\Parameters\Domain).
510 std::string dns_suffix;
511 if (ParseDomainASCII(adapter->DnsSuffix, &dns_suffix))
512 config->search.push_back(dns_suffix);
515 if (config->nameservers.empty())
516 return CONFIG_PARSE_WIN_NO_NAMESERVERS; // No point continuing.
518 // Windows always tries a multi-label name "as is" before using suffixes.
519 config->ndots = 1;
521 if (!settings.append_to_multi_label_name.set) {
522 // The default setting is true for XP, false for Vista+.
523 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
524 config->append_to_multi_label_name = false;
525 } else {
526 config->append_to_multi_label_name = true;
528 } else {
529 config->append_to_multi_label_name =
530 (settings.append_to_multi_label_name.value != 0);
533 ConfigParseWinResult result = CONFIG_PARSE_WIN_OK;
534 if (settings.have_name_resolution_policy) {
535 config->unhandled_options = true;
536 // TODO(szym): only set this to true if NRPT has DirectAccess rules.
537 config->use_local_ipv6 = true;
538 result = CONFIG_PARSE_WIN_UNHANDLED_OPTIONS;
541 ConfigureSuffixSearch(settings, config);
542 return result;
545 // Watches registry and HOSTS file for changes. Must live on a thread which
546 // allows IO.
547 class DnsConfigServiceWin::Watcher
548 : public NetworkChangeNotifier::IPAddressObserver {
549 public:
550 explicit Watcher(DnsConfigServiceWin* service) : service_(service) {}
551 ~Watcher() {
552 NetworkChangeNotifier::RemoveIPAddressObserver(this);
555 bool Watch() {
556 RegistryWatcher::CallbackType callback =
557 base::Bind(&DnsConfigServiceWin::OnConfigChanged,
558 base::Unretained(service_));
560 bool success = true;
562 // The Tcpip key must be present.
563 if (!tcpip_watcher_.Watch(kTcpipPath, callback)) {
564 LOG(ERROR) << "DNS registry watch failed to start.";
565 success = false;
566 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.WatchStatus",
567 DNS_CONFIG_WATCH_FAILED_TO_START_CONFIG,
568 DNS_CONFIG_WATCH_MAX);
571 // Watch for IPv6 nameservers.
572 tcpip6_watcher_.Watch(kTcpip6Path, callback);
574 // DNS suffix search list and devolution can be configured via group
575 // policy which sets this registry key. If the key is missing, the policy
576 // does not apply, and the DNS client uses Tcpip and Dnscache settings.
577 // If a policy is installed, DnsConfigService will need to be restarted.
578 // BUG=99509
580 dnscache_watcher_.Watch(kDnscachePath, callback);
581 policy_watcher_.Watch(kPolicyPath, callback);
583 if (!hosts_watcher_.Watch(GetHostsPath(), false,
584 base::Bind(&Watcher::OnHostsChanged,
585 base::Unretained(this)))) {
586 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.WatchStatus",
587 DNS_CONFIG_WATCH_FAILED_TO_START_HOSTS,
588 DNS_CONFIG_WATCH_MAX);
589 LOG(ERROR) << "DNS hosts watch failed to start.";
590 success = false;
591 } else {
592 // Also need to observe changes to local non-loopback IP for DnsHosts.
593 NetworkChangeNotifier::AddIPAddressObserver(this);
595 return success;
598 private:
599 void OnHostsChanged(const base::FilePath& path, bool error) {
600 if (error)
601 NetworkChangeNotifier::RemoveIPAddressObserver(this);
602 service_->OnHostsChanged(!error);
605 // NetworkChangeNotifier::IPAddressObserver:
606 virtual void OnIPAddressChanged() override {
607 // Need to update non-loopback IP of local host.
608 service_->OnHostsChanged(true);
611 DnsConfigServiceWin* service_;
613 RegistryWatcher tcpip_watcher_;
614 RegistryWatcher tcpip6_watcher_;
615 RegistryWatcher dnscache_watcher_;
616 RegistryWatcher policy_watcher_;
617 base::FilePathWatcher hosts_watcher_;
619 DISALLOW_COPY_AND_ASSIGN(Watcher);
622 // Reads config from registry and IpHelper. All work performed on WorkerPool.
623 class DnsConfigServiceWin::ConfigReader : public SerialWorker {
624 public:
625 explicit ConfigReader(DnsConfigServiceWin* service)
626 : service_(service),
627 success_(false) {}
629 private:
630 virtual ~ConfigReader() {}
632 virtual void DoWork() override {
633 // Should be called on WorkerPool.
634 base::TimeTicks start_time = base::TimeTicks::Now();
635 DnsSystemSettings settings = {};
636 ConfigParseWinResult result = ReadSystemSettings(&settings);
637 if (result == CONFIG_PARSE_WIN_OK)
638 result = ConvertSettingsToDnsConfig(settings, &dns_config_);
639 success_ = (result == CONFIG_PARSE_WIN_OK ||
640 result == CONFIG_PARSE_WIN_UNHANDLED_OPTIONS);
641 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ConfigParseWin",
642 result, CONFIG_PARSE_WIN_MAX);
643 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.ConfigParseResult", success_);
644 UMA_HISTOGRAM_TIMES("AsyncDNS.ConfigParseDuration",
645 base::TimeTicks::Now() - start_time);
648 virtual void OnWorkFinished() override {
649 DCHECK(loop()->BelongsToCurrentThread());
650 DCHECK(!IsCancelled());
651 if (success_) {
652 service_->OnConfigRead(dns_config_);
653 } else {
654 LOG(WARNING) << "Failed to read DnsConfig.";
655 // Try again in a while in case DnsConfigWatcher missed the signal.
656 base::MessageLoop::current()->PostDelayedTask(
657 FROM_HERE,
658 base::Bind(&ConfigReader::WorkNow, this),
659 base::TimeDelta::FromSeconds(kRetryIntervalSeconds));
663 DnsConfigServiceWin* service_;
664 // Written in DoWork(), read in OnWorkFinished(). No locking required.
665 DnsConfig dns_config_;
666 bool success_;
669 // Reads hosts from HOSTS file and fills in localhost and local computer name if
670 // necessary. All work performed on WorkerPool.
671 class DnsConfigServiceWin::HostsReader : public SerialWorker {
672 public:
673 explicit HostsReader(DnsConfigServiceWin* service)
674 : path_(GetHostsPath()),
675 service_(service),
676 success_(false) {
679 private:
680 virtual ~HostsReader() {}
682 virtual void DoWork() override {
683 base::TimeTicks start_time = base::TimeTicks::Now();
684 HostsParseWinResult result = HOSTS_PARSE_WIN_UNREADABLE_HOSTS_FILE;
685 if (ParseHostsFile(path_, &hosts_))
686 result = AddLocalhostEntries(&hosts_);
687 success_ = (result == HOSTS_PARSE_WIN_OK);
688 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.HostsParseWin",
689 result, HOSTS_PARSE_WIN_MAX);
690 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HostParseResult", success_);
691 UMA_HISTOGRAM_TIMES("AsyncDNS.HostsParseDuration",
692 base::TimeTicks::Now() - start_time);
695 virtual void OnWorkFinished() override {
696 DCHECK(loop()->BelongsToCurrentThread());
697 if (success_) {
698 service_->OnHostsRead(hosts_);
699 } else {
700 LOG(WARNING) << "Failed to read DnsHosts.";
704 const base::FilePath path_;
705 DnsConfigServiceWin* service_;
706 // Written in DoWork, read in OnWorkFinished, no locking necessary.
707 DnsHosts hosts_;
708 bool success_;
710 DISALLOW_COPY_AND_ASSIGN(HostsReader);
713 DnsConfigServiceWin::DnsConfigServiceWin()
714 : config_reader_(new ConfigReader(this)),
715 hosts_reader_(new HostsReader(this)) {}
717 DnsConfigServiceWin::~DnsConfigServiceWin() {
718 config_reader_->Cancel();
719 hosts_reader_->Cancel();
722 void DnsConfigServiceWin::ReadNow() {
723 config_reader_->WorkNow();
724 hosts_reader_->WorkNow();
727 bool DnsConfigServiceWin::StartWatching() {
728 // TODO(szym): re-start watcher if that makes sense. http://crbug.com/116139
729 watcher_.reset(new Watcher(this));
730 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.WatchStatus", DNS_CONFIG_WATCH_STARTED,
731 DNS_CONFIG_WATCH_MAX);
732 return watcher_->Watch();
735 void DnsConfigServiceWin::OnConfigChanged(bool succeeded) {
736 InvalidateConfig();
737 config_reader_->WorkNow();
738 if (!succeeded) {
739 LOG(ERROR) << "DNS config watch failed.";
740 set_watch_failed(true);
741 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.WatchStatus",
742 DNS_CONFIG_WATCH_FAILED_CONFIG,
743 DNS_CONFIG_WATCH_MAX);
747 void DnsConfigServiceWin::OnHostsChanged(bool succeeded) {
748 InvalidateHosts();
749 if (succeeded) {
750 hosts_reader_->WorkNow();
751 } else {
752 LOG(ERROR) << "DNS hosts watch failed.";
753 set_watch_failed(true);
754 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.WatchStatus",
755 DNS_CONFIG_WATCH_FAILED_HOSTS,
756 DNS_CONFIG_WATCH_MAX);
760 } // namespace internal
762 // static
763 scoped_ptr<DnsConfigService> DnsConfigService::CreateSystemService() {
764 return scoped_ptr<DnsConfigService>(new internal::DnsConfigServiceWin());
767 } // namespace net