Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / component_updater / sw_reporter_installer_win.cc
blob603a2d2b25642df43869196ebd7748d7253116da
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"
7 #include <stdint.h>
9 #include <map>
10 #include <string>
11 #include <vector>
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 {
60 namespace {
62 // These values are used to send UMA information and are replicated in the
63 // 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_MAX,
76 // The maximum number of times to retry a download on startup.
77 const int kMaxRetry = 20;
79 // The number of days to wait before triggering another sw reporter run.
80 const int kDaysBetweenSwReporterRuns = 7;
82 // CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was
83 // generated in Python with something like this:
84 // hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest().
85 const uint8_t kSha256Hash[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6,
86 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e,
87 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c,
88 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7};
90 const base::FilePath::CharType kSwReporterExeName[] =
91 FILE_PATH_LITERAL("software_reporter_tool.exe");
93 // Where to fetch the reporter exit code in the registry.
94 const wchar_t kSoftwareRemovalToolRegistryKey[] =
95 L"Software\\Google\\Software Removal Tool";
96 const wchar_t kCleanerSuffixRegistryKey[] = L"Cleaner";
97 const wchar_t kEndTimeValueName[] = L"EndTime";
98 const wchar_t kExitCodeValueName[] = L"ExitCode";
99 const wchar_t kFoundUwsValueName[] = L"FoundUws";
100 const wchar_t kStartTimeValueName[] = L"StartTime";
101 const wchar_t kUploadResultsValueName[] = L"UploadResults";
102 const wchar_t kVersionValueName[] = L"Version";
104 const char kFoundUwsMetricName[] = "SoftwareReporter.FoundUwS";
105 const char kFoundUwsReadErrorMetricName[] =
106 "SoftwareReporter.FoundUwSReadError";
108 // Exit codes that identify that a cleanup is needed.
109 const int kCleanupNeeded = 0;
110 const int kNothingFound = 2;
111 const int kPostRebootCleanupNeeded = 4;
112 const int kDelayedPostRebootCleanupNeeded = 15;
114 void ReportUmaStep(SwReporterUmaValue value) {
115 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value, SW_REPORTER_MAX);
118 void ReportVersionWithUma(const base::Version& version) {
119 DCHECK(!version.components().empty());
120 // The minor version is the 2nd last component of the version,
121 // or just the first component if there is only 1.
122 uint32_t minor_version = 0;
123 if (version.components().size() > 1)
124 minor_version = version.components()[version.components().size() - 2];
125 else
126 minor_version = version.components()[0];
127 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MinorVersion", minor_version);
129 // The major version for X.Y.Z is X*256^3+Y*256+Z. If there are additional
130 // components, only the first three count, and if there are less than 3, the
131 // missing values are just replaced by zero. So 1 is equivalent 1.0.0.
132 DCHECK_LT(version.components()[0], 0x100U);
133 uint32_t major_version = 0x1000000 * version.components()[0];
134 if (version.components().size() >= 2) {
135 DCHECK_LT(version.components()[1], 0x10000U);
136 major_version += 0x100 * version.components()[1];
138 if (version.components().size() >= 3) {
139 DCHECK_LT(version.components()[2], 0x100U);
140 major_version += version.components()[2];
142 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MajorVersion", major_version);
145 void ReportUploadsWithUma(const base::string16& upload_results) {
146 base::WStringTokenizer tokenizer(upload_results, L";");
147 int failure_count = 0;
148 int success_count = 0;
149 int longest_failure_run = 0;
150 int current_failure_run = 0;
151 bool last_result = false;
152 while (tokenizer.GetNext()) {
153 if (tokenizer.token() == L"0") {
154 ++failure_count;
155 ++current_failure_run;
156 last_result = false;
157 } else {
158 ++success_count;
159 current_failure_run = 0;
160 last_result = true;
163 if (current_failure_run > longest_failure_run)
164 longest_failure_run = current_failure_run;
167 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadFailureCount",
168 failure_count);
169 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadSuccessCount",
170 success_count);
171 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadLongestFailureRun",
172 longest_failure_run);
173 UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.LastUploadResult", last_result);
176 // This function is called on the UI thread to report the SwReporter exit code
177 // and then clear it from the registry as well as clear the execution state
178 // from the local state. This could be called from an interruptible worker
179 // thread so should be resilient to unexpected shutdown. |version| is provided
180 // so the kSwReporterPromptVersion prefs can be set.
181 void ReportAndClearExitCode(int exit_code, const std::string& version) {
182 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code);
184 if (g_browser_process && g_browser_process->local_state()) {
185 g_browser_process->local_state()->SetInteger(prefs::kSwReporterLastExitCode,
186 exit_code);
189 base::win::RegKey srt_key(HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey,
190 KEY_SET_VALUE);
191 srt_key.DeleteValue(kExitCodeValueName);
193 if ((exit_code != kPostRebootCleanupNeeded && exit_code != kCleanupNeeded) ||
194 !IsInSRTPromptFieldTrialGroups()) {
195 return;
198 // Find the last active browser, which may be NULL, in which case we won't
199 // show the prompt this time and will wait until the next run of the
200 // reporter. We can't use other ways of finding a browser because we don't
201 // have a profile.
202 chrome::HostDesktopType desktop_type = chrome::GetActiveDesktop();
203 Browser* browser = chrome::FindLastActiveWithHostDesktopType(desktop_type);
204 if (!browser)
205 return;
207 Profile* profile = browser->profile();
208 DCHECK(profile);
210 PrefService* prefs = profile->GetPrefs();
211 DCHECK(prefs);
213 // Don't show the prompt again if it's been shown before for this profile
214 // and for the current Finch seed.
215 std::string incoming_seed = safe_browsing::GetIncomingSRTSeed();
216 std::string old_seed = prefs->GetString(prefs::kSwReporterPromptSeed);
217 if (!incoming_seed.empty() && incoming_seed == old_seed)
218 return;
220 if (!incoming_seed.empty())
221 prefs->SetString(prefs::kSwReporterPromptSeed, incoming_seed);
222 prefs->SetString(prefs::kSwReporterPromptVersion, version);
223 prefs->SetInteger(prefs::kSwReporterPromptReason, exit_code);
225 // Download the SRT.
226 ReportUmaStep(SW_REPORTER_DOWNLOAD_START);
227 safe_browsing::FetchSRTAndDisplayBubble();
230 // This function is called from a worker thread to launch the SwReporter and
231 // wait for termination to collect its exit code. This task could be interrupted
232 // by a shutdown at anytime, so it shouldn't depend on anything external that
233 // could be shutdown beforehand.
234 void LaunchAndWaitForExit(const base::FilePath& exe_path,
235 const std::string& version) {
236 const base::CommandLine reporter_command_line(exe_path);
237 base::Process scan_reporter_process =
238 base::LaunchProcess(reporter_command_line, base::LaunchOptions());
239 if (!scan_reporter_process.IsValid()) {
240 ReportUmaStep(SW_REPORTER_FAILED_TO_START);
241 return;
243 ReportUmaStep(SW_REPORTER_START_EXECUTION);
245 int exit_code = -1;
246 bool success = scan_reporter_process.WaitForExit(&exit_code);
247 DCHECK(success);
248 // It's OK if this doesn't complete, the work will continue on next startup.
249 BrowserThread::PostTask(
250 BrowserThread::UI,
251 FROM_HERE,
252 base::Bind(&ReportAndClearExitCode, exit_code, version));
255 // Reports UwS found by the software reporter tool via UMA and RAPPOR.
256 void ReportFoundUwS() {
257 base::win::RegKey reporter_key(HKEY_CURRENT_USER,
258 kSoftwareRemovalToolRegistryKey,
259 KEY_QUERY_VALUE | KEY_SET_VALUE);
260 std::vector<base::string16> found_uws_strings;
261 if (reporter_key.Valid() &&
262 reporter_key.ReadValues(kFoundUwsValueName, &found_uws_strings) ==
263 ERROR_SUCCESS) {
264 rappor::RapporService* rappor_service = g_browser_process->rappor_service();
266 bool parse_error = false;
267 for (const base::string16& uws_string : found_uws_strings) {
268 // All UwS ids are expected to be integers.
269 uint32_t uws_id = 0;
270 if (base::StringToUint(uws_string, &uws_id)) {
271 UMA_HISTOGRAM_SPARSE_SLOWLY(kFoundUwsMetricName, uws_id);
272 if (rappor_service) {
273 rappor_service->RecordSample(kFoundUwsMetricName,
274 rappor::COARSE_RAPPOR_TYPE,
275 base::UTF16ToUTF8(uws_string));
277 } else {
278 parse_error = true;
282 // Clean up the old value.
283 reporter_key.DeleteValue(kFoundUwsValueName);
285 UMA_HISTOGRAM_BOOLEAN(kFoundUwsReadErrorMetricName, parse_error);
289 class SwReporterInstallerTraits : public ComponentInstallerTraits {
290 public:
291 explicit SwReporterInstallerTraits(PrefService* prefs) : prefs_(prefs) {}
293 virtual ~SwReporterInstallerTraits() {}
295 virtual bool VerifyInstallation(const base::DictionaryValue& manifest,
296 const base::FilePath& dir) const {
297 return base::PathExists(dir.Append(kSwReporterExeName));
300 virtual bool CanAutoUpdate() const { return true; }
302 virtual bool OnCustomInstall(const base::DictionaryValue& manifest,
303 const base::FilePath& install_dir) {
304 return true;
307 virtual void ComponentReady(const base::Version& version,
308 const base::FilePath& install_dir,
309 scoped_ptr<base::DictionaryValue> manifest) {
310 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
311 ReportVersionWithUma(version);
313 wcsncpy_s(version_dir_,
314 _MAX_PATH,
315 install_dir.value().c_str(),
316 install_dir.value().size());
318 // A previous run may have results in the registry, so check and report
319 // them if present.
320 std::string version_string(version.GetString());
321 base::win::RegKey srt_key(
322 HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_READ);
323 DWORD exit_code;
324 if (srt_key.Valid() &&
325 srt_key.ReadValueDW(kExitCodeValueName, &exit_code) == ERROR_SUCCESS) {
326 ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE);
327 ReportAndClearExitCode(exit_code, version_string);
330 // If we can't access local state, we can't see when we last ran, so
331 // just exit without running.
332 if (!g_browser_process || !g_browser_process->local_state())
333 return;
335 // Run the reporter if it hasn't been triggered in the
336 // kDaysBetweenSwReporterRuns days.
337 const base::Time last_time_triggered = base::Time::FromInternalValue(
338 g_browser_process->local_state()->GetInt64(
339 prefs::kSwReporterLastTimeTriggered));
340 if ((base::Time::Now() - last_time_triggered).InDays() >=
341 kDaysBetweenSwReporterRuns) {
342 g_browser_process->local_state()->SetInt64(
343 prefs::kSwReporterLastTimeTriggered,
344 base::Time::Now().ToInternalValue());
346 base::WorkerPool::PostTask(
347 FROM_HERE,
348 base::Bind(&LaunchAndWaitForExit,
349 install_dir.Append(kSwReporterExeName),
350 version_string),
351 true);
355 virtual base::FilePath GetBaseDirectory() const { return install_dir(); }
357 virtual void GetHash(std::vector<uint8_t>* hash) const { GetPkHash(hash); }
359 virtual std::string GetName() const { return "Software Reporter Tool"; }
361 static base::FilePath install_dir() {
362 // The base directory on windows looks like:
363 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\.
364 base::FilePath result;
365 PathService::Get(DIR_SW_REPORTER, &result);
366 return result;
369 static std::string ID() {
370 update_client::CrxComponent component;
371 component.version = Version("0.0.0.0");
372 GetPkHash(&component.pk_hash);
373 return update_client::GetCrxComponentID(component);
376 static base::FilePath VersionPath() { return base::FilePath(version_dir_); }
378 private:
379 static void GetPkHash(std::vector<uint8_t>* hash) {
380 DCHECK(hash);
381 hash->assign(kSha256Hash, kSha256Hash + sizeof(kSha256Hash));
384 PrefService* prefs_;
385 static wchar_t version_dir_[_MAX_PATH];
388 wchar_t SwReporterInstallerTraits::version_dir_[] = {};
390 } // namespace
392 void RegisterSwReporterComponent(ComponentUpdateService* cus,
393 PrefService* prefs) {
394 // The Sw reporter doesn't need to run if the user isn't reporting metrics and
395 // isn't in the SRTPrompt field trial "On" group.
396 if (!ChromeMetricsServiceAccessor::IsMetricsReportingEnabled() &&
397 !IsInSRTPromptFieldTrialGroups()) {
398 return;
401 // Check if we have information from Cleaner and record UMA statistics.
402 base::string16 cleaner_key_name(kSoftwareRemovalToolRegistryKey);
403 cleaner_key_name.append(1, L'\\').append(kCleanerSuffixRegistryKey);
404 base::win::RegKey cleaner_key(
405 HKEY_CURRENT_USER, cleaner_key_name.c_str(), KEY_ALL_ACCESS);
406 // Cleaner is assumed to have run if we have a start time.
407 if (cleaner_key.Valid() && cleaner_key.HasValue(kStartTimeValueName)) {
408 // Get version number.
409 if (cleaner_key.HasValue(kVersionValueName)) {
410 DWORD version;
411 cleaner_key.ReadValueDW(kVersionValueName, &version);
412 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.Version", version);
413 cleaner_key.DeleteValue(kVersionValueName);
415 // Get start & end time. If we don't have an end time, we can assume the
416 // cleaner has not completed.
417 int64 start_time_value;
418 cleaner_key.ReadInt64(kStartTimeValueName, &start_time_value);
420 bool completed = cleaner_key.HasValue(kEndTimeValueName);
421 UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.Cleaner.HasCompleted", completed);
422 if (completed) {
423 int64 end_time_value;
424 cleaner_key.ReadInt64(kEndTimeValueName, &end_time_value);
425 cleaner_key.DeleteValue(kEndTimeValueName);
426 base::TimeDelta run_time(base::Time::FromInternalValue(end_time_value) -
427 base::Time::FromInternalValue(start_time_value));
428 UMA_HISTOGRAM_LONG_TIMES("SoftwareReporter.Cleaner.RunningTime",
429 run_time);
431 // Get exit code. Assume nothing was found if we can't read the exit code.
432 DWORD exit_code = kNothingFound;
433 if (cleaner_key.HasValue(kExitCodeValueName)) {
434 cleaner_key.ReadValueDW(kExitCodeValueName, &exit_code);
435 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.ExitCode",
436 exit_code);
437 cleaner_key.DeleteValue(kExitCodeValueName);
439 cleaner_key.DeleteValue(kStartTimeValueName);
441 if (exit_code == kPostRebootCleanupNeeded ||
442 exit_code == kDelayedPostRebootCleanupNeeded) {
443 // Check if we are running after the user has rebooted.
444 base::TimeDelta elapsed(base::Time::Now() -
445 base::Time::FromInternalValue(start_time_value));
446 DCHECK_GT(elapsed.InMilliseconds(), 0);
447 UMA_HISTOGRAM_BOOLEAN(
448 "SoftwareReporter.Cleaner.HasRebooted",
449 static_cast<uint64>(elapsed.InMilliseconds()) > ::GetTickCount());
452 if (cleaner_key.HasValue(kUploadResultsValueName)) {
453 base::string16 upload_results;
454 cleaner_key.ReadValue(kUploadResultsValueName, &upload_results);
455 ReportUploadsWithUma(upload_results);
459 ReportFoundUwS();
461 // Install the component.
462 scoped_ptr<ComponentInstallerTraits> traits(
463 new SwReporterInstallerTraits(prefs));
464 // |cus| will take ownership of |installer| during installer->Register(cus).
465 DefaultComponentInstaller* installer =
466 new DefaultComponentInstaller(traits.Pass());
467 installer->Register(cus, base::Closure());
470 void RegisterPrefsForSwReporter(PrefRegistrySimple* registry) {
471 registry->RegisterInt64Pref(prefs::kSwReporterLastTimeTriggered, 0);
472 registry->RegisterIntegerPref(prefs::kSwReporterLastExitCode, -1);
475 void RegisterProfilePrefsForSwReporter(
476 user_prefs::PrefRegistrySyncable* registry) {
477 registry->RegisterIntegerPref(
478 prefs::kSwReporterPromptReason, -1,
479 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
481 registry->RegisterStringPref(
482 prefs::kSwReporterPromptVersion, "",
483 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
485 registry->RegisterStringPref(
486 prefs::kSwReporterPromptSeed, "",
487 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
490 } // namespace component_updater