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/win/registry.h"
27 #include "chrome/browser/browser_process.h"
28 #include "components/component_updater/component_updater_paths.h"
29 #include "components/component_updater/component_updater_service.h"
30 #include "components/component_updater/component_updater_utils.h"
31 #include "components/component_updater/default_component_installer.h"
32 #include "components/component_updater/pref_names.h"
33 #include "content/public/browser/browser_thread.h"
35 using content::BrowserThread
;
37 namespace component_updater
{
41 // These values are used to send UMA information and are replicated in the
42 // histograms.xml file, so the order MUST NOT CHANGE.
43 enum SwReporterUmaValue
{
44 SW_REPORTER_EXPLICIT_REQUEST
= 0,
45 SW_REPORTER_STARTUP_RETRY
= 1,
46 SW_REPORTER_RETRIED_TOO_MANY_TIMES
= 2,
47 SW_REPORTER_START_EXECUTION
= 3,
48 SW_REPORTER_FAILED_TO_START
= 4,
49 SW_REPORTER_REGISTRY_EXIT_CODE
= 5,
50 SW_REPORTER_RESET_RETRIES
= 6,
54 // The maximum number of times to retry a download on startup.
55 const int kMaxRetry
= 20;
57 // CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was
58 // generated in Python with something like this:
59 // hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest().
60 const uint8 kSha256Hash
[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6,
61 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e,
62 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c,
63 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7};
65 const base::FilePath::CharType kSwReporterExeName
[] =
66 FILE_PATH_LITERAL("software_reporter_tool.exe");
68 // Where to fetch the reporter exit code in the registry.
69 const wchar_t kSoftwareRemovalToolRegistryKey
[] =
70 L
"Software\\Google\\Software Removal Tool";
71 const wchar_t kExitCodeRegistryValueName
[] = L
"ExitCode";
73 void ReportUmaStep(SwReporterUmaValue value
) {
74 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value
, SW_REPORTER_MAX
);
77 // This function is called on the UI thread to report the SwReporter exit code
78 // and then clear it from the registry as well as clear the execution state
79 // from the local state. This could be called from an interruptible worker
80 // thread so should be resilient to unexpected shutdown.
81 void ReportAndClearExitCode(int exit_code
) {
82 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code
);
84 base::win::RegKey
srt_key(
85 HKEY_CURRENT_USER
, kSoftwareRemovalToolRegistryKey
, KEY_WRITE
);
86 srt_key
.DeleteValue(kExitCodeRegistryValueName
);
88 // Now that we are done we can reset the try count.
89 g_browser_process
->local_state()->SetInteger(
90 prefs::kSwReporterExecuteTryCount
, 0);
93 // This function is called from a worker thread to launch the SwReporter and
94 // wait for termination to collect its exit code. This task could be interrupted
95 // by a shutdown at anytime, so it shouldn't depend on anything external that
96 // could be shutdown beforehand.
97 void LaunchAndWaitForExit(const base::FilePath
& exe_path
) {
98 const base::CommandLine
reporter_command_line(exe_path
);
99 base::ProcessHandle scan_reporter_process
= base::kNullProcessHandle
;
100 if (!base::LaunchProcess(reporter_command_line
,
101 base::LaunchOptions(),
102 &scan_reporter_process
)) {
103 ReportUmaStep(SW_REPORTER_FAILED_TO_START
);
106 ReportUmaStep(SW_REPORTER_START_EXECUTION
);
109 bool success
= base::WaitForExitCode(scan_reporter_process
, &exit_code
);
111 base::CloseProcessHandle(scan_reporter_process
);
112 scan_reporter_process
= base::kNullProcessHandle
;
113 // It's OK if this doesn't complete, the work will continue on next startup.
114 BrowserThread::PostTask(BrowserThread::UI
,
116 base::Bind(&ReportAndClearExitCode
, exit_code
));
119 void ExecuteReporter(const base::FilePath
& install_dir
) {
120 base::WorkerPool::PostTask(
122 base::Bind(&LaunchAndWaitForExit
, install_dir
.Append(kSwReporterExeName
)),
126 class SwReporterInstallerTraits
: public ComponentInstallerTraits
{
128 explicit SwReporterInstallerTraits(PrefService
* prefs
) : prefs_(prefs
) {}
130 virtual ~SwReporterInstallerTraits() {}
132 virtual bool VerifyInstallation(const base::FilePath
& dir
) const {
133 return base::PathExists(dir
.Append(kSwReporterExeName
));
136 virtual bool CanAutoUpdate() const { return true; }
138 virtual bool OnCustomInstall(const base::DictionaryValue
& manifest
,
139 const base::FilePath
& install_dir
) {
143 virtual void ComponentReady(const base::Version
& version
,
144 const base::FilePath
& install_dir
,
145 scoped_ptr
<base::DictionaryValue
> manifest
) {
146 wcsncpy_s(version_dir_
,
148 install_dir
.value().c_str(),
149 install_dir
.value().size());
150 // Only execute the reporter if there is still a pending request for it.
151 if (prefs_
->GetInteger(prefs::kSwReporterExecuteTryCount
) > 0)
152 ExecuteReporter(install_dir
);
155 virtual base::FilePath
GetBaseDirectory() const { return install_dir(); }
157 virtual void GetHash(std::vector
<uint8
>* hash
) const { GetPkHash(hash
); }
159 virtual std::string
GetName() const { return "Software Reporter Tool"; }
161 static base::FilePath
install_dir() {
162 // The base directory on windows looks like:
163 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\.
164 base::FilePath result
;
165 PathService::Get(DIR_SW_REPORTER
, &result
);
169 static std::string
ID() {
170 CrxComponent component
;
171 component
.version
= Version("0.0.0.0");
172 GetPkHash(&component
.pk_hash
);
173 return component_updater::GetCrxComponentID(component
);
176 static base::FilePath
VersionPath() { return base::FilePath(version_dir_
); }
179 static void GetPkHash(std::vector
<uint8
>* hash
) {
181 hash
->assign(kSha256Hash
, kSha256Hash
+ sizeof(kSha256Hash
));
185 static wchar_t version_dir_
[_MAX_PATH
];
188 wchar_t SwReporterInstallerTraits::version_dir_
[] = {};
190 void RegisterComponent(ComponentUpdateService
* cus
, PrefService
* prefs
) {
191 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
192 scoped_ptr
<ComponentInstallerTraits
> traits(
193 new SwReporterInstallerTraits(prefs
));
194 // |cus| will take ownership of |installer| during installer->Register(cus).
195 DefaultComponentInstaller
* installer
=
196 new DefaultComponentInstaller(traits
.Pass());
197 installer
->Register(cus
);
200 // We need a conditional version of register component so that it can be called
201 // back on the UI thread after validating on the File thread that the component
202 // path exists and we must re-register on startup for example.
203 void MaybeRegisterComponent(ComponentUpdateService
* cus
,
205 bool register_component
) {
206 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
207 if (register_component
)
208 RegisterComponent(cus
, prefs
);
213 void ExecuteSwReporter(ComponentUpdateService
* cus
, PrefService
* prefs
) {
214 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
215 // If we have a pending execution, send metrics about it so we can account for
216 // missing executions.
217 if (prefs
->GetInteger(prefs::kSwReporterExecuteTryCount
) > 0)
218 ReportUmaStep(SW_REPORTER_RESET_RETRIES
);
219 // This is an explicit call, so let's forget about previous incomplete
220 // execution attempts and start from scratch.
221 prefs
->SetInteger(prefs::kSwReporterExecuteTryCount
, kMaxRetry
);
222 ReportUmaStep(SW_REPORTER_EXPLICIT_REQUEST
);
223 const std::vector
<std::string
> registered_components(cus
->GetComponentIDs());
224 if (std::find(registered_components
.begin(),
225 registered_components
.end(),
226 SwReporterInstallerTraits::ID()) ==
227 registered_components
.end()) {
228 RegisterComponent(cus
, prefs
);
229 } else if (!SwReporterInstallerTraits::VersionPath().empty()) {
230 // Here, we already have a fully registered and installed component
231 // available for immediate use. This doesn't handle cases where the version
232 // folder is there but the executable is not within in. This is a corruption
233 // we don't want to handle here.
234 ExecuteReporter(SwReporterInstallerTraits::VersionPath());
236 // If the component is registered but the version path is not available, it
237 // means the component was not fully installed yet, and it should run the
238 // reporter when ComponentReady is called.
241 void ExecutePendingSwReporter(ComponentUpdateService
* cus
, PrefService
* prefs
) {
242 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
244 // Register the existing component for updates.
245 base::PostTaskAndReplyWithResult(
246 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
248 base::Bind(&base::PathExists
, SwReporterInstallerTraits::install_dir()),
249 base::Bind(&MaybeRegisterComponent
, cus
, prefs
));
251 // Run the reporter if there is a pending execution request.
252 int execute_try_count
= prefs
->GetInteger(prefs::kSwReporterExecuteTryCount
);
253 if (execute_try_count
> 0) {
254 // Retrieve the results if the pending request has completed.
255 base::win::RegKey
srt_key(
256 HKEY_CURRENT_USER
, kSoftwareRemovalToolRegistryKey
, KEY_READ
);
258 if (srt_key
.Valid() &&
259 srt_key
.ReadValueDW(kExitCodeRegistryValueName
, &exit_code
) ==
261 ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE
);
262 ReportAndClearExitCode(exit_code
);
266 // The previous request has not completed. The reporter will run again
267 // when ComponentReady is called or the request is abandoned if it has
268 // been tried too many times.
269 prefs
->SetInteger(prefs::kSwReporterExecuteTryCount
, --execute_try_count
);
270 if (execute_try_count
> 0)
271 ReportUmaStep(SW_REPORTER_STARTUP_RETRY
);
273 ReportUmaStep(SW_REPORTER_RETRIED_TOO_MANY_TIMES
);
277 void RegisterPrefsForSwReporter(PrefRegistrySimple
* registry
) {
278 registry
->RegisterIntegerPref(prefs::kSwReporterExecuteTryCount
, 0);
281 } // namespace component_updater