1 // Copyright (c) 2014 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 "chrome/browser/component_updater/sw_reporter_installer_win.h"
10 #include "base/base_paths.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/metrics/sparse_histogram.h"
19 #include "base/path_service.h"
20 #include "base/prefs/pref_registry_simple.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/process/kill.h"
23 #include "base/process/launch.h"
24 #include "base/task_runner_util.h"
25 #include "base/threading/worker_pool.h"
26 #include "base/time/time.h"
27 #include "base/win/registry.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
30 #include "chrome/common/pref_names.h"
31 #include "components/component_updater/component_updater_paths.h"
32 #include "components/component_updater/component_updater_service.h"
33 #include "components/component_updater/component_updater_utils.h"
34 #include "components/component_updater/default_component_installer.h"
35 #include "components/component_updater/pref_names.h"
36 #include "content/public/browser/browser_thread.h"
38 using content::BrowserThread
;
40 namespace component_updater
{
44 // These values are used to send UMA information and are replicated in the
45 // histograms.xml file, so the order MUST NOT CHANGE.
46 enum SwReporterUmaValue
{
47 SW_REPORTER_EXPLICIT_REQUEST
= 0, // Deprecated.
48 SW_REPORTER_STARTUP_RETRY
= 1, // Deprecated.
49 SW_REPORTER_RETRIED_TOO_MANY_TIMES
= 2, // Deprecated.
50 SW_REPORTER_START_EXECUTION
= 3,
51 SW_REPORTER_FAILED_TO_START
= 4,
52 SW_REPORTER_REGISTRY_EXIT_CODE
= 5,
53 SW_REPORTER_RESET_RETRIES
= 6, // Deprecated.
57 // The maximum number of times to retry a download on startup.
58 const int kMaxRetry
= 20;
60 // The number of days to wait before triggering another sw reporter run.
61 const int kDaysBetweenSwReporterRuns
= 7;
63 // CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was
64 // generated in Python with something like this:
65 // hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest().
66 const uint8 kSha256Hash
[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6,
67 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e,
68 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c,
69 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7};
71 const base::FilePath::CharType kSwReporterExeName
[] =
72 FILE_PATH_LITERAL("software_reporter_tool.exe");
74 // Where to fetch the reporter exit code in the registry.
75 const wchar_t kSoftwareRemovalToolRegistryKey
[] =
76 L
"Software\\Google\\Software Removal Tool";
77 const wchar_t kExitCodeRegistryValueName
[] = L
"ExitCode";
79 void ReportUmaStep(SwReporterUmaValue value
) {
80 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value
, SW_REPORTER_MAX
);
83 // This function is called on the UI thread to report the SwReporter exit code
84 // and then clear it from the registry as well as clear the execution state
85 // from the local state. This could be called from an interruptible worker
86 // thread so should be resilient to unexpected shutdown.
87 void ReportAndClearExitCode(int exit_code
) {
88 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code
);
90 base::win::RegKey
srt_key(
91 HKEY_CURRENT_USER
, kSoftwareRemovalToolRegistryKey
, KEY_WRITE
);
92 srt_key
.DeleteValue(kExitCodeRegistryValueName
);
95 // This function is called from a worker thread to launch the SwReporter and
96 // wait for termination to collect its exit code. This task could be interrupted
97 // by a shutdown at anytime, so it shouldn't depend on anything external that
98 // could be shutdown beforehand.
99 void LaunchAndWaitForExit(const base::FilePath
& exe_path
) {
100 const base::CommandLine
reporter_command_line(exe_path
);
101 base::ProcessHandle scan_reporter_process
= base::kNullProcessHandle
;
102 if (!base::LaunchProcess(reporter_command_line
,
103 base::LaunchOptions(),
104 &scan_reporter_process
)) {
105 ReportUmaStep(SW_REPORTER_FAILED_TO_START
);
108 ReportUmaStep(SW_REPORTER_START_EXECUTION
);
111 bool success
= base::WaitForExitCode(scan_reporter_process
, &exit_code
);
113 base::CloseProcessHandle(scan_reporter_process
);
114 scan_reporter_process
= base::kNullProcessHandle
;
115 // It's OK if this doesn't complete, the work will continue on next startup.
116 BrowserThread::PostTask(BrowserThread::UI
,
118 base::Bind(&ReportAndClearExitCode
, exit_code
));
121 void ExecuteReporter(const base::FilePath
& install_dir
) {
122 base::WorkerPool::PostTask(
124 base::Bind(&LaunchAndWaitForExit
, install_dir
.Append(kSwReporterExeName
)),
128 class SwReporterInstallerTraits
: public ComponentInstallerTraits
{
130 explicit SwReporterInstallerTraits(PrefService
* prefs
) : prefs_(prefs
) {}
132 virtual ~SwReporterInstallerTraits() {}
134 virtual bool VerifyInstallation(const base::FilePath
& dir
) const {
135 return base::PathExists(dir
.Append(kSwReporterExeName
));
138 virtual bool CanAutoUpdate() const { return true; }
140 virtual bool OnCustomInstall(const base::DictionaryValue
& manifest
,
141 const base::FilePath
& install_dir
) {
145 virtual void ComponentReady(const base::Version
& version
,
146 const base::FilePath
& install_dir
,
147 scoped_ptr
<base::DictionaryValue
> manifest
) {
148 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
150 wcsncpy_s(version_dir_
,
152 install_dir
.value().c_str(),
153 install_dir
.value().size());
155 // A previous run may have results in the registry, so check and report
157 base::win::RegKey
srt_key(
158 HKEY_CURRENT_USER
, kSoftwareRemovalToolRegistryKey
, KEY_READ
);
160 if (srt_key
.Valid() &&
161 srt_key
.ReadValueDW(kExitCodeRegistryValueName
, &exit_code
) ==
163 ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE
);
164 ReportAndClearExitCode(exit_code
);
167 // If we can't access local state, we can't see when we last ran, so
168 // just exit without running.
169 if (!g_browser_process
|| !g_browser_process
->local_state())
172 // Run the reporter if it hasn't been triggered in the
173 // kDaysBetweenSwReporterRuns days.
174 const base::Time last_time_triggered
= base::Time::FromInternalValue(
175 g_browser_process
->local_state()->GetInt64(
176 prefs::kSwReporterLastTimeTriggered
));
177 if ((base::Time::Now() - last_time_triggered
).InDays() >=
178 kDaysBetweenSwReporterRuns
) {
179 g_browser_process
->local_state()->SetInt64(
180 prefs::kSwReporterLastTimeTriggered
,
181 base::Time::Now().ToInternalValue());
183 ExecuteReporter(install_dir
);
187 virtual base::FilePath
GetBaseDirectory() const { return install_dir(); }
189 virtual void GetHash(std::vector
<uint8
>* hash
) const { GetPkHash(hash
); }
191 virtual std::string
GetName() const { return "Software Reporter Tool"; }
193 static base::FilePath
install_dir() {
194 // The base directory on windows looks like:
195 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\.
196 base::FilePath result
;
197 PathService::Get(DIR_SW_REPORTER
, &result
);
201 static std::string
ID() {
202 CrxComponent component
;
203 component
.version
= Version("0.0.0.0");
204 GetPkHash(&component
.pk_hash
);
205 return component_updater::GetCrxComponentID(component
);
208 static base::FilePath
VersionPath() { return base::FilePath(version_dir_
); }
211 static void GetPkHash(std::vector
<uint8
>* hash
) {
213 hash
->assign(kSha256Hash
, kSha256Hash
+ sizeof(kSha256Hash
));
217 static wchar_t version_dir_
[_MAX_PATH
];
220 wchar_t SwReporterInstallerTraits::version_dir_
[] = {};
224 void RegisterSwReporterComponent(ComponentUpdateService
* cus
,
225 PrefService
* prefs
) {
226 // The Sw reporter shouldn't run if the user isn't reporting metrics.
227 if (!ChromeMetricsServiceAccessor::IsMetricsReportingEnabled())
230 // Install the component.
231 scoped_ptr
<ComponentInstallerTraits
> traits(
232 new SwReporterInstallerTraits(prefs
));
233 // |cus| will take ownership of |installer| during installer->Register(cus).
234 DefaultComponentInstaller
* installer
=
235 new DefaultComponentInstaller(traits
.Pass());
236 installer
->Register(cus
);
239 void RegisterPrefsForSwReporter(PrefRegistrySimple
* registry
) {
240 registry
->RegisterInt64Pref(prefs::kSwReporterLastTimeTriggered
, 0);
243 } // namespace component_updater