blob: dd01149287300e6b1e709d4d8b768866f87ea298 [file] [log] [blame]
Avi Drissman4a8573c2022-09-09 19:35:541// Copyright 2020 The Chromium Authors
Greg Thompson30225432020-10-15 11:20:292// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/upgrade_detector/registry_monitor.h"
6
7#include <memory>
8#include <utility>
9
Avi Drissman9269d4ed2023-01-07 01:38:0610#include "base/functional/bind.h"
11#include "base/functional/callback.h"
Greg Thompson30225432020-10-15 11:20:2912#include "base/location.h"
Patrick Monette643cdf62021-10-15 19:13:4213#include "base/task/sequenced_task_runner.h"
Greg Thompson30225432020-10-15 11:20:2914#include "base/win/registry.h"
15#include "chrome/browser/upgrade_detector/installed_version_monitor.h"
16#include "chrome/install_static/install_util.h"
17
18namespace {
19
20base::win::RegKey GetDefaultMonitorLocation() {
21 return base::win::RegKey(install_static::IsSystemInstall()
22 ? HKEY_LOCAL_MACHINE
23 : HKEY_CURRENT_USER,
24 install_static::GetClientsKeyPath().c_str(),
25 KEY_NOTIFY | KEY_WOW64_32KEY);
26}
27
28} // namespace
29
30RegistryMonitor::RegistryMonitor(base::win::RegKey key)
31 : clients_key_(std::move(key)) {}
32
33RegistryMonitor::~RegistryMonitor() = default;
34
35void RegistryMonitor::Start(Callback on_change_callback) {
36 DCHECK(on_change_callback);
37 DCHECK(!on_change_callback_);
38 on_change_callback_ = std::move(on_change_callback);
39 StartWatching();
40}
41
42void RegistryMonitor::StartWatching() {
43 // base::Unretained is safe because RegistryMonitor owns the RegKey.
44 // Destruction of this instance will cancel the watch and disable any
45 // outstanding notifications.
46 if (!clients_key_.Valid() ||
47 !clients_key_.StartWatching(base::BindOnce(
48 &RegistryMonitor::OnClientsKeyChanged, base::Unretained(this)))) {
49 // Starting the watch failed. Report this back to the poller via a delayed
50 // task.
Sean Maher5e3ca352022-11-07 20:08:4951 base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
Greg Thompson30225432020-10-15 11:20:2952 FROM_HERE, base::BindOnce(on_change_callback_, /*error=*/true));
53 }
54}
55
56void RegistryMonitor::OnClientsKeyChanged() {
57 on_change_callback_.Run(/*error=*/false);
58 StartWatching();
59}
60
61// static
62std::unique_ptr<InstalledVersionMonitor> InstalledVersionMonitor::Create() {
63 return std::make_unique<RegistryMonitor>(GetDefaultMonitorLocation());
64}