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"
13 #include "base/base_paths.h"
14 #include "base/bind.h"
15 #include "base/bind_helpers.h"
16 #include "base/command_line.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/logging.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/metrics/histogram.h"
22 #include "base/metrics/sparse_histogram.h"
23 #include "base/path_service.h"
24 #include "base/prefs/pref_registry_simple.h"
25 #include "base/prefs/pref_service.h"
26 #include "base/process/kill.h"
27 #include "base/process/launch.h"
28 #include "base/strings/string_tokenizer.h"
29 #include "base/task_runner_util.h"
30 #include "base/threading/worker_pool.h"
31 #include "base/time/time.h"
32 #include "base/win/registry.h"
33 #include "chrome/browser/browser_process.h"
34 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
35 #include "chrome/browser/profiles/profile.h"
36 #include "chrome/browser/safe_browsing/srt_fetcher_win.h"
37 #include "chrome/browser/safe_browsing/srt_field_trial_win.h"
38 #include "chrome/browser/safe_browsing/srt_global_error_win.h"
39 #include "chrome/browser/ui/browser_finder.h"
40 #include "chrome/browser/ui/global_error/global_error_service.h"
41 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
42 #include "chrome/common/pref_names.h"
43 #include "components/component_updater/component_updater_paths.h"
44 #include "components/component_updater/component_updater_service.h"
45 #include "components/component_updater/default_component_installer.h"
46 #include "components/component_updater/pref_names.h"
47 #include "components/pref_registry/pref_registry_syncable.h"
48 #include "components/update_client/update_client.h"
49 #include "components/update_client/utils.h"
50 #include "content/public/browser/browser_thread.h"
52 using content::BrowserThread
;
53 using safe_browsing::IsInSRTPromptFieldTrialGroups
;
55 namespace component_updater
{
59 // These values are used to send UMA information and are replicated in the
60 // histograms.xml file, so the order MUST NOT CHANGE.
61 enum SwReporterUmaValue
{
62 SW_REPORTER_EXPLICIT_REQUEST
= 0, // Deprecated.
63 SW_REPORTER_STARTUP_RETRY
= 1, // Deprecated.
64 SW_REPORTER_RETRIED_TOO_MANY_TIMES
= 2, // Deprecated.
65 SW_REPORTER_START_EXECUTION
= 3,
66 SW_REPORTER_FAILED_TO_START
= 4,
67 SW_REPORTER_REGISTRY_EXIT_CODE
= 5,
68 SW_REPORTER_RESET_RETRIES
= 6, // Deprecated.
69 SW_REPORTER_DOWNLOAD_START
= 7,
73 // The maximum number of times to retry a download on startup.
74 const int kMaxRetry
= 20;
76 // The number of days to wait before triggering another sw reporter run.
77 const int kDaysBetweenSwReporterRuns
= 7;
79 // CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was
80 // generated in Python with something like this:
81 // hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest().
82 const uint8_t kSha256Hash
[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6,
83 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e,
84 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c,
85 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7};
87 const base::FilePath::CharType kSwReporterExeName
[] =
88 FILE_PATH_LITERAL("software_reporter_tool.exe");
90 // Where to fetch the reporter exit code in the registry.
91 const wchar_t kSoftwareRemovalToolRegistryKey
[] =
92 L
"Software\\Google\\Software Removal Tool";
93 const wchar_t kCleanerSuffixRegistryKey
[] = L
"Cleaner";
94 const wchar_t kEndTimeRegistryValueName
[] = L
"EndTime";
95 const wchar_t kExitCodeRegistryValueName
[] = L
"ExitCode";
96 const wchar_t kStartTimeRegistryValueName
[] = L
"StartTime";
97 const wchar_t kUploadResultsValueName
[] = L
"UploadResults";
98 const wchar_t kVersionRegistryValueName
[] = L
"Version";
100 // Exit codes that identify that a cleanup is needed.
101 const int kCleanupNeeded
= 0;
102 const int kNothingFound
= 2;
103 const int kPostRebootCleanupNeeded
= 4;
104 const int kDelayedPostRebootCleanupNeeded
= 15;
106 void ReportUmaStep(SwReporterUmaValue value
) {
107 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value
, SW_REPORTER_MAX
);
110 void ReportVersionWithUma(const base::Version
& version
) {
111 DCHECK(!version
.components().empty());
112 // The minor version is the 2nd last component of the version,
113 // or just the first component if there is only 1.
114 uint32_t minor_version
= 0;
115 if (version
.components().size() > 1)
116 minor_version
= version
.components()[version
.components().size() - 2];
118 minor_version
= version
.components()[0];
119 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MinorVersion", minor_version
);
121 // The major version for X.Y.Z is X*256^3+Y*256+Z. If there are additional
122 // components, only the first three count, and if there are less than 3, the
123 // missing values are just replaced by zero. So 1 is equivalent 1.0.0.
124 DCHECK_LT(version
.components()[0], 0x100);
125 uint32_t major_version
= 0x1000000 * version
.components()[0];
126 if (version
.components().size() >= 2) {
127 DCHECK_LT(version
.components()[1], 0x10000);
128 major_version
+= 0x100 * version
.components()[1];
130 if (version
.components().size() >= 3) {
131 DCHECK_LT(version
.components()[2], 0x100);
132 major_version
+= version
.components()[2];
134 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MajorVersion", major_version
);
137 void ReportUploadsWithUma(const base::string16
& upload_results
) {
138 base::WStringTokenizer
tokenizer(upload_results
, L
";");
139 int failure_count
= 0;
140 int success_count
= 0;
141 int longest_failure_run
= 0;
142 int current_failure_run
= 0;
143 bool last_result
= false;
144 while (tokenizer
.GetNext()) {
145 if (tokenizer
.token() == L
"0") {
147 ++current_failure_run
;
151 current_failure_run
= 0;
155 if (current_failure_run
> longest_failure_run
)
156 longest_failure_run
= current_failure_run
;
159 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadFailureCount",
161 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadSuccessCount",
163 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadLongestFailureRun",
164 longest_failure_run
);
165 UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.LastUploadResult", last_result
);
168 // This function is called on the UI thread to report the SwReporter exit code
169 // and then clear it from the registry as well as clear the execution state
170 // from the local state. This could be called from an interruptible worker
171 // thread so should be resilient to unexpected shutdown. |version| is provided
172 // so the kSwReporterPromptVersion prefs can be set.
173 void ReportAndClearExitCode(int exit_code
, const std::string
& version
) {
174 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code
);
176 if (g_browser_process
&& g_browser_process
->local_state()) {
177 g_browser_process
->local_state()->SetInteger(prefs::kSwReporterLastExitCode
,
181 base::win::RegKey
srt_key(HKEY_CURRENT_USER
, kSoftwareRemovalToolRegistryKey
,
183 srt_key
.DeleteValue(kExitCodeRegistryValueName
);
185 if ((exit_code
!= kPostRebootCleanupNeeded
&& exit_code
!= kCleanupNeeded
) ||
186 !IsInSRTPromptFieldTrialGroups()) {
190 // Find the last active browser, which may be NULL, in which case we won't
191 // show the prompt this time and will wait until the next run of the
192 // reporter. We can't use other ways of finding a browser because we don't
194 chrome::HostDesktopType desktop_type
= chrome::GetActiveDesktop();
195 Browser
* browser
= chrome::FindLastActiveWithHostDesktopType(desktop_type
);
199 Profile
* profile
= browser
->profile();
202 PrefService
* prefs
= profile
->GetPrefs();
205 // Don't show the prompt again if it's been shown before for this profile
206 // and for the current Finch seed.
207 std::string incoming_seed
= safe_browsing::GetIncomingSRTSeed();
208 std::string old_seed
= prefs
->GetString(prefs::kSwReporterPromptSeed
);
209 if (!incoming_seed
.empty() && incoming_seed
== old_seed
)
212 if (!incoming_seed
.empty())
213 prefs
->SetString(prefs::kSwReporterPromptSeed
, incoming_seed
);
214 prefs
->SetString(prefs::kSwReporterPromptVersion
, version
);
215 prefs
->SetInteger(prefs::kSwReporterPromptReason
, exit_code
);
218 ReportUmaStep(SW_REPORTER_DOWNLOAD_START
);
219 safe_browsing::FetchSRTAndDisplayBubble();
222 // This function is called from a worker thread to launch the SwReporter and
223 // wait for termination to collect its exit code. This task could be interrupted
224 // by a shutdown at anytime, so it shouldn't depend on anything external that
225 // could be shutdown beforehand.
226 void LaunchAndWaitForExit(const base::FilePath
& exe_path
,
227 const std::string
& version
) {
228 const base::CommandLine
reporter_command_line(exe_path
);
229 base::Process scan_reporter_process
=
230 base::LaunchProcess(reporter_command_line
, base::LaunchOptions());
231 if (!scan_reporter_process
.IsValid()) {
232 ReportUmaStep(SW_REPORTER_FAILED_TO_START
);
235 ReportUmaStep(SW_REPORTER_START_EXECUTION
);
238 bool success
= scan_reporter_process
.WaitForExit(&exit_code
);
240 // It's OK if this doesn't complete, the work will continue on next startup.
241 BrowserThread::PostTask(
244 base::Bind(&ReportAndClearExitCode
, exit_code
, version
));
247 class SwReporterInstallerTraits
: public ComponentInstallerTraits
{
249 explicit SwReporterInstallerTraits(PrefService
* prefs
) : prefs_(prefs
) {}
251 virtual ~SwReporterInstallerTraits() {}
253 virtual bool VerifyInstallation(const base::DictionaryValue
& manifest
,
254 const base::FilePath
& dir
) const {
255 return base::PathExists(dir
.Append(kSwReporterExeName
));
258 virtual bool CanAutoUpdate() const { return true; }
260 virtual bool OnCustomInstall(const base::DictionaryValue
& manifest
,
261 const base::FilePath
& install_dir
) {
265 virtual void ComponentReady(const base::Version
& version
,
266 const base::FilePath
& install_dir
,
267 scoped_ptr
<base::DictionaryValue
> manifest
) {
268 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
269 ReportVersionWithUma(version
);
271 wcsncpy_s(version_dir_
,
273 install_dir
.value().c_str(),
274 install_dir
.value().size());
276 // A previous run may have results in the registry, so check and report
278 std::string
version_string(version
.GetString());
279 base::win::RegKey
srt_key(
280 HKEY_CURRENT_USER
, kSoftwareRemovalToolRegistryKey
, KEY_READ
);
282 if (srt_key
.Valid() &&
283 srt_key
.ReadValueDW(kExitCodeRegistryValueName
, &exit_code
) ==
285 ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE
);
286 ReportAndClearExitCode(exit_code
, version_string
);
289 // If we can't access local state, we can't see when we last ran, so
290 // just exit without running.
291 if (!g_browser_process
|| !g_browser_process
->local_state())
294 // Run the reporter if it hasn't been triggered in the
295 // kDaysBetweenSwReporterRuns days.
296 const base::Time last_time_triggered
= base::Time::FromInternalValue(
297 g_browser_process
->local_state()->GetInt64(
298 prefs::kSwReporterLastTimeTriggered
));
299 if ((base::Time::Now() - last_time_triggered
).InDays() >=
300 kDaysBetweenSwReporterRuns
) {
301 g_browser_process
->local_state()->SetInt64(
302 prefs::kSwReporterLastTimeTriggered
,
303 base::Time::Now().ToInternalValue());
305 base::WorkerPool::PostTask(
307 base::Bind(&LaunchAndWaitForExit
,
308 install_dir
.Append(kSwReporterExeName
),
314 virtual base::FilePath
GetBaseDirectory() const { return install_dir(); }
316 virtual void GetHash(std::vector
<uint8_t>* hash
) const { GetPkHash(hash
); }
318 virtual std::string
GetName() const { return "Software Reporter Tool"; }
320 static base::FilePath
install_dir() {
321 // The base directory on windows looks like:
322 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\.
323 base::FilePath result
;
324 PathService::Get(DIR_SW_REPORTER
, &result
);
328 static std::string
ID() {
329 update_client::CrxComponent component
;
330 component
.version
= Version("0.0.0.0");
331 GetPkHash(&component
.pk_hash
);
332 return update_client::GetCrxComponentID(component
);
335 static base::FilePath
VersionPath() { return base::FilePath(version_dir_
); }
338 static void GetPkHash(std::vector
<uint8_t>* hash
) {
340 hash
->assign(kSha256Hash
, kSha256Hash
+ sizeof(kSha256Hash
));
344 static wchar_t version_dir_
[_MAX_PATH
];
347 wchar_t SwReporterInstallerTraits::version_dir_
[] = {};
351 void RegisterSwReporterComponent(ComponentUpdateService
* cus
,
352 PrefService
* prefs
) {
353 // The Sw reporter doesn't need to run if the user isn't reporting metrics and
354 // isn't in the SRTPrompt field trial "On" group.
355 if (!ChromeMetricsServiceAccessor::IsMetricsReportingEnabled() &&
356 !IsInSRTPromptFieldTrialGroups()) {
360 // Check if we have information from Cleaner and record UMA statistics.
361 base::string16
cleaner_key_name(kSoftwareRemovalToolRegistryKey
);
362 cleaner_key_name
.append(1, L
'\\').append(kCleanerSuffixRegistryKey
);
363 base::win::RegKey
cleaner_key(
364 HKEY_CURRENT_USER
, cleaner_key_name
.c_str(), KEY_ALL_ACCESS
);
365 // Cleaner is assumed to have run if we have a start time.
366 if (cleaner_key
.Valid() &&
367 cleaner_key
.HasValue(kStartTimeRegistryValueName
)) {
368 // Get version number.
369 if (cleaner_key
.HasValue(kVersionRegistryValueName
)) {
371 cleaner_key
.ReadValueDW(kVersionRegistryValueName
, &version
);
372 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.Version", version
);
373 cleaner_key
.DeleteValue(kVersionRegistryValueName
);
375 // Get start & end time. If we don't have an end time, we can assume the
376 // cleaner has not completed.
377 int64 start_time_value
;
378 cleaner_key
.ReadInt64(kStartTimeRegistryValueName
, &start_time_value
);
380 bool completed
= cleaner_key
.HasValue(kEndTimeRegistryValueName
);
381 UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.Cleaner.HasCompleted", completed
);
383 int64 end_time_value
;
384 cleaner_key
.ReadInt64(kEndTimeRegistryValueName
, &end_time_value
);
385 cleaner_key
.DeleteValue(kEndTimeRegistryValueName
);
386 base::TimeDelta
run_time(base::Time::FromInternalValue(end_time_value
) -
387 base::Time::FromInternalValue(start_time_value
));
388 UMA_HISTOGRAM_LONG_TIMES("SoftwareReporter.Cleaner.RunningTime",
391 // Get exit code. Assume nothing was found if we can't read the exit code.
392 DWORD exit_code
= kNothingFound
;
393 if (cleaner_key
.HasValue(kExitCodeRegistryValueName
)) {
394 cleaner_key
.ReadValueDW(kExitCodeRegistryValueName
, &exit_code
);
395 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.ExitCode",
397 cleaner_key
.DeleteValue(kExitCodeRegistryValueName
);
399 cleaner_key
.DeleteValue(kStartTimeRegistryValueName
);
401 if (exit_code
== kPostRebootCleanupNeeded
||
402 exit_code
== kDelayedPostRebootCleanupNeeded
) {
403 // Check if we are running after the user has rebooted.
404 base::TimeDelta
elapsed(base::Time::Now() -
405 base::Time::FromInternalValue(start_time_value
));
406 DCHECK_GT(elapsed
.InMilliseconds(), 0);
407 UMA_HISTOGRAM_BOOLEAN(
408 "SoftwareReporter.Cleaner.HasRebooted",
409 static_cast<uint64
>(elapsed
.InMilliseconds()) > ::GetTickCount());
412 if (cleaner_key
.HasValue(kUploadResultsValueName
)) {
413 base::string16 upload_results
;
414 cleaner_key
.ReadValue(kUploadResultsValueName
, &upload_results
);
415 ReportUploadsWithUma(upload_results
);
419 // Install the component.
420 scoped_ptr
<ComponentInstallerTraits
> traits(
421 new SwReporterInstallerTraits(prefs
));
422 // |cus| will take ownership of |installer| during installer->Register(cus).
423 DefaultComponentInstaller
* installer
=
424 new DefaultComponentInstaller(traits
.Pass());
425 installer
->Register(cus
, base::Closure());
428 void RegisterPrefsForSwReporter(PrefRegistrySimple
* registry
) {
429 registry
->RegisterInt64Pref(prefs::kSwReporterLastTimeTriggered
, 0);
430 registry
->RegisterIntegerPref(prefs::kSwReporterLastExitCode
, -1);
433 void RegisterProfilePrefsForSwReporter(
434 user_prefs::PrefRegistrySyncable
* registry
) {
435 registry
->RegisterIntegerPref(
436 prefs::kSwReporterPromptReason
, -1,
437 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF
);
439 registry
->RegisterStringPref(
440 prefs::kSwReporterPromptVersion
, "",
441 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF
);
443 registry
->RegisterStringPref(
444 prefs::kSwReporterPromptSeed
, "",
445 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF
);
448 } // namespace component_updater