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_number_conversions.h"
29 #include "base/strings/string_tokenizer.h"
30 #include "base/strings/utf_string_conversions.h"
31 #include "base/task_runner_util.h"
32 #include "base/threading/worker_pool.h"
33 #include "base/time/time.h"
34 #include "base/win/registry.h"
35 #include "chrome/browser/browser_process.h"
36 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
37 #include "chrome/browser/profiles/profile.h"
38 #include "chrome/browser/safe_browsing/srt_fetcher_win.h"
39 #include "chrome/browser/safe_browsing/srt_field_trial_win.h"
40 #include "chrome/browser/safe_browsing/srt_global_error_win.h"
41 #include "chrome/browser/ui/browser_finder.h"
42 #include "chrome/browser/ui/global_error/global_error_service.h"
43 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
44 #include "chrome/common/pref_names.h"
45 #include "components/component_updater/component_updater_paths.h"
46 #include "components/component_updater/component_updater_service.h"
47 #include "components/component_updater/default_component_installer.h"
48 #include "components/component_updater/pref_names.h"
49 #include "components/pref_registry/pref_registry_syncable.h"
50 #include "components/rappor/rappor_service.h"
51 #include "components/update_client/update_client.h"
52 #include "components/update_client/utils.h"
53 #include "content/public/browser/browser_thread.h"
55 using content::BrowserThread
;
56 using safe_browsing::IsInSRTPromptFieldTrialGroups
;
58 namespace component_updater
{
62 // These two sets of values are used to send UMA information and are replicated
63 // in the histograms.xml file, so the order MUST NOT CHANGE.
64 enum SwReporterUmaValue
{
65 SW_REPORTER_EXPLICIT_REQUEST
= 0, // Deprecated.
66 SW_REPORTER_STARTUP_RETRY
= 1, // Deprecated.
67 SW_REPORTER_RETRIED_TOO_MANY_TIMES
= 2, // Deprecated.
68 SW_REPORTER_START_EXECUTION
= 3,
69 SW_REPORTER_FAILED_TO_START
= 4,
70 SW_REPORTER_REGISTRY_EXIT_CODE
= 5,
71 SW_REPORTER_RESET_RETRIES
= 6, // Deprecated.
72 SW_REPORTER_DOWNLOAD_START
= 7,
73 SW_REPORTER_NO_BROWSER
= 8,
74 SW_REPORTER_NO_LOCAL_STATE
= 9,
75 SW_REPORTER_NO_PROMPT_NEEDED
= 10,
76 SW_REPORTER_NO_PROMPT_FIELD_TRIAL
= 11,
77 SW_REPORTER_ALREADY_PROMPTED
= 12,
81 SRT_COMPLETED_NOT_YET
= 0,
82 SRT_COMPLETED_YES
= 1,
83 SRT_COMPLETED_LATER
= 2,
87 // The maximum number of times to retry a download on startup.
88 const int kMaxRetry
= 20;
90 // The number of days to wait before triggering another sw reporter run.
91 const int kDaysBetweenSwReporterRuns
= 7;
93 // CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was
94 // generated in Python with something like this:
95 // hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest().
96 const uint8_t kSha256Hash
[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6,
97 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e,
98 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c,
99 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7};
101 const base::FilePath::CharType kSwReporterExeName
[] =
102 FILE_PATH_LITERAL("software_reporter_tool.exe");
104 // Where to fetch the reporter exit code in the registry.
105 const wchar_t kSoftwareRemovalToolRegistryKey
[] =
106 L
"Software\\Google\\Software Removal Tool";
107 const wchar_t kCleanerSuffixRegistryKey
[] = L
"Cleaner";
108 const wchar_t kEndTimeValueName
[] = L
"EndTime";
109 const wchar_t kExitCodeValueName
[] = L
"ExitCode";
110 const wchar_t kFoundUwsValueName
[] = L
"FoundUws";
111 const wchar_t kStartTimeValueName
[] = L
"StartTime";
112 const wchar_t kUploadResultsValueName
[] = L
"UploadResults";
113 const wchar_t kVersionValueName
[] = L
"Version";
115 const char kFoundUwsMetricName
[] = "SoftwareReporter.FoundUwS";
116 const char kFoundUwsReadErrorMetricName
[] =
117 "SoftwareReporter.FoundUwSReadError";
119 // Exit codes that identify that a cleanup is needed.
120 const int kCleanupNeeded
= 0;
121 const int kNothingFound
= 2;
122 const int kPostRebootCleanupNeeded
= 4;
123 const int kDelayedPostRebootCleanupNeeded
= 15;
125 void ReportUmaStep(SwReporterUmaValue value
) {
126 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value
, SW_REPORTER_MAX
);
129 void SRTHasCompleted(SRTCompleted value
) {
130 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Cleaner.HasCompleted", value
,
134 void ReportVersionWithUma(const base::Version
& version
) {
135 DCHECK(!version
.components().empty());
136 // The minor version is the 2nd last component of the version,
137 // or just the first component if there is only 1.
138 uint32_t minor_version
= 0;
139 if (version
.components().size() > 1)
140 minor_version
= version
.components()[version
.components().size() - 2];
142 minor_version
= version
.components()[0];
143 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MinorVersion", minor_version
);
145 // The major version for X.Y.Z is X*256^3+Y*256+Z. If there are additional
146 // components, only the first three count, and if there are less than 3, the
147 // missing values are just replaced by zero. So 1 is equivalent 1.0.0.
148 DCHECK_LT(version
.components()[0], 0x100U
);
149 uint32_t major_version
= 0x1000000 * version
.components()[0];
150 if (version
.components().size() >= 2) {
151 DCHECK_LT(version
.components()[1], 0x10000U
);
152 major_version
+= 0x100 * version
.components()[1];
154 if (version
.components().size() >= 3) {
155 DCHECK_LT(version
.components()[2], 0x100U
);
156 major_version
+= version
.components()[2];
158 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MajorVersion", major_version
);
161 void ReportUploadsWithUma(const base::string16
& upload_results
) {
162 base::WStringTokenizer
tokenizer(upload_results
, L
";");
163 int failure_count
= 0;
164 int success_count
= 0;
165 int longest_failure_run
= 0;
166 int current_failure_run
= 0;
167 bool last_result
= false;
168 while (tokenizer
.GetNext()) {
169 if (tokenizer
.token() == L
"0") {
171 ++current_failure_run
;
175 current_failure_run
= 0;
179 if (current_failure_run
> longest_failure_run
)
180 longest_failure_run
= current_failure_run
;
183 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadFailureCount",
185 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadSuccessCount",
187 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadLongestFailureRun",
188 longest_failure_run
);
189 UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.LastUploadResult", last_result
);
192 // This function is called on the UI thread to report the SwReporter exit code
193 // and then clear it from the registry as well as clear the execution state
194 // from the local state. This could be called from an interruptible worker
195 // thread so should be resilient to unexpected shutdown. |version| is provided
196 // so the kSwReporterPromptVersion prefs can be set.
197 void ReportAndClearExitCode(int exit_code
, const std::string
& version
) {
198 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code
);
200 if (g_browser_process
&& g_browser_process
->local_state()) {
201 g_browser_process
->local_state()->SetInteger(prefs::kSwReporterLastExitCode
,
205 base::win::RegKey
srt_key(HKEY_CURRENT_USER
, kSoftwareRemovalToolRegistryKey
,
207 srt_key
.DeleteValue(kExitCodeValueName
);
209 if (!IsInSRTPromptFieldTrialGroups()) {
210 // Knowing about disabled field trial is more important than reporter not
211 // finding anything to remove.
212 ReportUmaStep(SW_REPORTER_NO_PROMPT_FIELD_TRIAL
);
216 if (exit_code
!= kPostRebootCleanupNeeded
&& exit_code
!= kCleanupNeeded
) {
217 ReportUmaStep(SW_REPORTER_NO_PROMPT_NEEDED
);
221 // Find the last active browser, which may be NULL, in which case we won't
222 // show the prompt this time and will wait until the next run of the
223 // reporter. We can't use other ways of finding a browser because we don't
225 chrome::HostDesktopType desktop_type
= chrome::GetActiveDesktop();
226 Browser
* browser
= chrome::FindLastActiveWithHostDesktopType(desktop_type
);
228 ReportUmaStep(SW_REPORTER_NO_BROWSER
);
232 Profile
* profile
= browser
->profile();
235 PrefService
* prefs
= profile
->GetPrefs();
238 // Don't show the prompt again if it's been shown before for this profile
239 // and for the current Finch seed.
240 std::string incoming_seed
= safe_browsing::GetIncomingSRTSeed();
241 std::string old_seed
= prefs
->GetString(prefs::kSwReporterPromptSeed
);
242 if (!incoming_seed
.empty() && incoming_seed
== old_seed
) {
243 ReportUmaStep(SW_REPORTER_ALREADY_PROMPTED
);
247 if (!incoming_seed
.empty())
248 prefs
->SetString(prefs::kSwReporterPromptSeed
, incoming_seed
);
249 prefs
->SetString(prefs::kSwReporterPromptVersion
, version
);
250 prefs
->SetInteger(prefs::kSwReporterPromptReason
, exit_code
);
253 ReportUmaStep(SW_REPORTER_DOWNLOAD_START
);
254 safe_browsing::FetchSRTAndDisplayBubble();
257 // This function is called from a worker thread to launch the SwReporter and
258 // wait for termination to collect its exit code. This task could be interrupted
259 // by a shutdown at anytime, so it shouldn't depend on anything external that
260 // could be shutdown beforehand.
261 void LaunchAndWaitForExit(const base::FilePath
& exe_path
,
262 const std::string
& version
) {
263 const base::CommandLine
reporter_command_line(exe_path
);
264 base::Process scan_reporter_process
=
265 base::LaunchProcess(reporter_command_line
, base::LaunchOptions());
266 if (!scan_reporter_process
.IsValid()) {
267 ReportUmaStep(SW_REPORTER_FAILED_TO_START
);
270 ReportUmaStep(SW_REPORTER_START_EXECUTION
);
273 bool success
= scan_reporter_process
.WaitForExit(&exit_code
);
275 // It's OK if this doesn't complete, the work will continue on next startup.
276 BrowserThread::PostTask(
279 base::Bind(&ReportAndClearExitCode
, exit_code
, version
));
282 // Reports UwS found by the software reporter tool via UMA and RAPPOR.
283 void ReportFoundUwS() {
284 base::win::RegKey
reporter_key(HKEY_CURRENT_USER
,
285 kSoftwareRemovalToolRegistryKey
,
286 KEY_QUERY_VALUE
| KEY_SET_VALUE
);
287 std::vector
<base::string16
> found_uws_strings
;
288 if (reporter_key
.Valid() &&
289 reporter_key
.ReadValues(kFoundUwsValueName
, &found_uws_strings
) ==
291 rappor::RapporService
* rappor_service
= g_browser_process
->rappor_service();
293 bool parse_error
= false;
294 for (const base::string16
& uws_string
: found_uws_strings
) {
295 // All UwS ids are expected to be integers.
297 if (base::StringToUint(uws_string
, &uws_id
)) {
298 UMA_HISTOGRAM_SPARSE_SLOWLY(kFoundUwsMetricName
, uws_id
);
299 if (rappor_service
) {
300 rappor_service
->RecordSample(kFoundUwsMetricName
,
301 rappor::COARSE_RAPPOR_TYPE
,
302 base::UTF16ToUTF8(uws_string
));
309 // Clean up the old value.
310 reporter_key
.DeleteValue(kFoundUwsValueName
);
312 UMA_HISTOGRAM_BOOLEAN(kFoundUwsReadErrorMetricName
, parse_error
);
316 class SwReporterInstallerTraits
: public ComponentInstallerTraits
{
318 explicit SwReporterInstallerTraits(PrefService
* prefs
) : prefs_(prefs
) {}
320 ~SwReporterInstallerTraits() override
{}
322 bool VerifyInstallation(const base::DictionaryValue
& manifest
,
323 const base::FilePath
& dir
) const override
{
324 return base::PathExists(dir
.Append(kSwReporterExeName
));
327 bool CanAutoUpdate() const override
{ return true; }
329 bool OnCustomInstall(const base::DictionaryValue
& manifest
,
330 const base::FilePath
& install_dir
) override
{
334 void ComponentReady(const base::Version
& version
,
335 const base::FilePath
& install_dir
,
336 scoped_ptr
<base::DictionaryValue
> manifest
) override
{
337 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
338 ReportVersionWithUma(version
);
340 wcsncpy_s(version_dir_
,
342 install_dir
.value().c_str(),
343 install_dir
.value().size());
345 // A previous run may have results in the registry, so check and report
347 std::string
version_string(version
.GetString());
348 base::win::RegKey
srt_key(
349 HKEY_CURRENT_USER
, kSoftwareRemovalToolRegistryKey
, KEY_READ
);
351 if (srt_key
.Valid() &&
352 srt_key
.ReadValueDW(kExitCodeValueName
, &exit_code
) == ERROR_SUCCESS
) {
353 ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE
);
354 ReportAndClearExitCode(exit_code
, version_string
);
357 // If we can't access local state, we can't see when we last ran, so
358 // just exit without running.
359 if (!g_browser_process
|| !g_browser_process
->local_state()) {
360 ReportUmaStep(SW_REPORTER_NO_LOCAL_STATE
);
364 // Run the reporter if it hasn't been triggered in the
365 // kDaysBetweenSwReporterRuns days.
366 const base::Time last_time_triggered
= base::Time::FromInternalValue(
367 g_browser_process
->local_state()->GetInt64(
368 prefs::kSwReporterLastTimeTriggered
));
369 if ((base::Time::Now() - last_time_triggered
).InDays() >=
370 kDaysBetweenSwReporterRuns
) {
371 g_browser_process
->local_state()->SetInt64(
372 prefs::kSwReporterLastTimeTriggered
,
373 base::Time::Now().ToInternalValue());
375 base::WorkerPool::PostTask(
377 base::Bind(&LaunchAndWaitForExit
,
378 install_dir
.Append(kSwReporterExeName
),
384 base::FilePath
GetBaseDirectory() const override
{ return install_dir(); }
386 void GetHash(std::vector
<uint8_t>* hash
) const override
{ GetPkHash(hash
); }
388 std::string
GetName() const override
{ return "Software Reporter Tool"; }
390 static base::FilePath
install_dir() {
391 // The base directory on windows looks like:
392 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\.
393 base::FilePath result
;
394 PathService::Get(DIR_SW_REPORTER
, &result
);
398 static std::string
ID() {
399 update_client::CrxComponent component
;
400 component
.version
= Version("0.0.0.0");
401 GetPkHash(&component
.pk_hash
);
402 return update_client::GetCrxComponentID(component
);
405 static base::FilePath
VersionPath() { return base::FilePath(version_dir_
); }
408 static void GetPkHash(std::vector
<uint8_t>* hash
) {
410 hash
->assign(kSha256Hash
, kSha256Hash
+ sizeof(kSha256Hash
));
414 static wchar_t version_dir_
[_MAX_PATH
];
417 wchar_t SwReporterInstallerTraits::version_dir_
[] = {};
421 void RegisterSwReporterComponent(ComponentUpdateService
* cus
,
422 PrefService
* prefs
) {
423 // The Sw reporter doesn't need to run if the user isn't reporting metrics and
424 // isn't in the SRTPrompt field trial "On" group.
425 if (!ChromeMetricsServiceAccessor::IsMetricsReportingEnabled() &&
426 !IsInSRTPromptFieldTrialGroups()) {
430 // Check if we have information from Cleaner and record UMA statistics.
431 base::string16
cleaner_key_name(kSoftwareRemovalToolRegistryKey
);
432 cleaner_key_name
.append(1, L
'\\').append(kCleanerSuffixRegistryKey
);
433 base::win::RegKey
cleaner_key(
434 HKEY_CURRENT_USER
, cleaner_key_name
.c_str(), KEY_ALL_ACCESS
);
435 // Cleaner is assumed to have run if we have a start time.
436 if (cleaner_key
.Valid()) {
437 if (cleaner_key
.HasValue(kStartTimeValueName
)) {
438 // Get version number.
439 if (cleaner_key
.HasValue(kVersionValueName
)) {
441 cleaner_key
.ReadValueDW(kVersionValueName
, &version
);
442 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.Version",
444 cleaner_key
.DeleteValue(kVersionValueName
);
446 // Get start & end time. If we don't have an end time, we can assume the
447 // cleaner has not completed.
448 int64 start_time_value
;
449 cleaner_key
.ReadInt64(kStartTimeValueName
, &start_time_value
);
451 bool completed
= cleaner_key
.HasValue(kEndTimeValueName
);
452 SRTHasCompleted(completed
? SRT_COMPLETED_YES
: SRT_COMPLETED_NOT_YET
);
454 int64 end_time_value
;
455 cleaner_key
.ReadInt64(kEndTimeValueName
, &end_time_value
);
456 cleaner_key
.DeleteValue(kEndTimeValueName
);
457 base::TimeDelta
run_time(
458 base::Time::FromInternalValue(end_time_value
) -
459 base::Time::FromInternalValue(start_time_value
));
460 UMA_HISTOGRAM_LONG_TIMES("SoftwareReporter.Cleaner.RunningTime",
463 // Get exit code. Assume nothing was found if we can't read the exit code.
464 DWORD exit_code
= kNothingFound
;
465 if (cleaner_key
.HasValue(kExitCodeValueName
)) {
466 cleaner_key
.ReadValueDW(kExitCodeValueName
, &exit_code
);
467 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.ExitCode",
469 cleaner_key
.DeleteValue(kExitCodeValueName
);
471 cleaner_key
.DeleteValue(kStartTimeValueName
);
473 if (exit_code
== kPostRebootCleanupNeeded
||
474 exit_code
== kDelayedPostRebootCleanupNeeded
) {
475 // Check if we are running after the user has rebooted.
476 base::TimeDelta
elapsed(
478 base::Time::FromInternalValue(start_time_value
));
479 DCHECK_GT(elapsed
.InMilliseconds(), 0);
480 UMA_HISTOGRAM_BOOLEAN(
481 "SoftwareReporter.Cleaner.HasRebooted",
482 static_cast<uint64
>(elapsed
.InMilliseconds()) > ::GetTickCount());
485 if (cleaner_key
.HasValue(kUploadResultsValueName
)) {
486 base::string16 upload_results
;
487 cleaner_key
.ReadValue(kUploadResultsValueName
, &upload_results
);
488 ReportUploadsWithUma(upload_results
);
491 if (cleaner_key
.HasValue(kEndTimeValueName
)) {
492 SRTHasCompleted(SRT_COMPLETED_LATER
);
493 cleaner_key
.DeleteValue(kEndTimeValueName
);
499 // Install the component.
500 scoped_ptr
<ComponentInstallerTraits
> traits(
501 new SwReporterInstallerTraits(prefs
));
502 // |cus| will take ownership of |installer| during installer->Register(cus).
503 DefaultComponentInstaller
* installer
=
504 new DefaultComponentInstaller(traits
.Pass());
505 installer
->Register(cus
, base::Closure());
508 void RegisterPrefsForSwReporter(PrefRegistrySimple
* registry
) {
509 registry
->RegisterInt64Pref(prefs::kSwReporterLastTimeTriggered
, 0);
510 registry
->RegisterIntegerPref(prefs::kSwReporterLastExitCode
, -1);
513 void RegisterProfilePrefsForSwReporter(
514 user_prefs::PrefRegistrySyncable
* registry
) {
515 registry
->RegisterIntegerPref(prefs::kSwReporterPromptReason
, -1);
517 registry
->RegisterStringPref(prefs::kSwReporterPromptVersion
, "");
519 registry
->RegisterStringPref(prefs::kSwReporterPromptSeed
, "");
522 } // namespace component_updater