Elim cr-checkbox
[chromium-blink-merge.git] / chrome / browser / component_updater / sw_reporter_installer_win.cc
blobe39af666a670ff1467989133143207673abbefbd
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/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/strings/string_number_conversions.h"
22 #include "base/strings/string_tokenizer.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/thread_task_runner_handle.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/browser/safe_browsing/srt_fetcher_win.h"
31 #include "chrome/browser/safe_browsing/srt_field_trial_win.h"
32 #include "components/component_updater/component_updater_paths.h"
33 #include "components/component_updater/component_updater_service.h"
34 #include "components/component_updater/default_component_installer.h"
35 #include "components/component_updater/pref_names.h"
36 #include "components/pref_registry/pref_registry_syncable.h"
37 #include "components/rappor/rappor_service.h"
38 #include "components/update_client/update_client.h"
39 #include "components/update_client/utils.h"
40 #include "content/public/browser/browser_thread.h"
42 namespace component_updater {
44 namespace {
46 // These two sets of values are used to send UMA information and are replicated
47 // in the histograms.xml file, so the order MUST NOT CHANGE.
48 enum SRTCompleted {
49 SRT_COMPLETED_NOT_YET = 0,
50 SRT_COMPLETED_YES = 1,
51 SRT_COMPLETED_LATER = 2,
52 SRT_COMPLETED_MAX,
55 // CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was
56 // generated in Python with something like this:
57 // hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest().
58 const uint8_t kSha256Hash[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6,
59 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e,
60 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c,
61 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7};
63 const base::FilePath::CharType kSwReporterExeName[] =
64 FILE_PATH_LITERAL("software_reporter_tool.exe");
66 // Where to fetch the reporter's list of found uws in the registry.
67 const wchar_t kSoftwareRemovalToolRegistryKey[] =
68 L"Software\\Google\\Software Removal Tool";
69 const wchar_t kCleanerSuffixRegistryKey[] = L"Cleaner";
70 const wchar_t kEndTimeValueName[] = L"EndTime";
71 const wchar_t kExitCodeValueName[] = L"ExitCode";
72 const wchar_t kFoundUwsValueName[] = L"FoundUws";
73 const wchar_t kStartTimeValueName[] = L"StartTime";
74 const wchar_t kUploadResultsValueName[] = L"UploadResults";
75 const wchar_t kVersionValueName[] = L"Version";
77 const char kFoundUwsMetricName[] = "SoftwareReporter.FoundUwS";
78 const char kFoundUwsReadErrorMetricName[] =
79 "SoftwareReporter.FoundUwSReadError";
81 void SRTHasCompleted(SRTCompleted value) {
82 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Cleaner.HasCompleted", value,
83 SRT_COMPLETED_MAX);
86 void ReportVersionWithUma(const base::Version& version) {
87 DCHECK(!version.components().empty());
88 // The minor version is the 2nd last component of the version,
89 // or just the first component if there is only 1.
90 uint32_t minor_version = 0;
91 if (version.components().size() > 1)
92 minor_version = version.components()[version.components().size() - 2];
93 else
94 minor_version = version.components()[0];
95 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MinorVersion", minor_version);
97 // The major version for X.Y.Z is X*256^3+Y*256+Z. If there are additional
98 // components, only the first three count, and if there are less than 3, the
99 // missing values are just replaced by zero. So 1 is equivalent 1.0.0.
100 DCHECK_LT(version.components()[0], 0x100U);
101 uint32_t major_version = 0x1000000 * version.components()[0];
102 if (version.components().size() >= 2) {
103 DCHECK_LT(version.components()[1], 0x10000U);
104 major_version += 0x100 * version.components()[1];
106 if (version.components().size() >= 3) {
107 DCHECK_LT(version.components()[2], 0x100U);
108 major_version += version.components()[2];
110 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MajorVersion", major_version);
113 void ReportUploadsWithUma(const base::string16& upload_results) {
114 base::WStringTokenizer tokenizer(upload_results, L";");
115 int failure_count = 0;
116 int success_count = 0;
117 int longest_failure_run = 0;
118 int current_failure_run = 0;
119 bool last_result = false;
120 while (tokenizer.GetNext()) {
121 if (tokenizer.token() == L"0") {
122 ++failure_count;
123 ++current_failure_run;
124 last_result = false;
125 } else {
126 ++success_count;
127 current_failure_run = 0;
128 last_result = true;
131 if (current_failure_run > longest_failure_run)
132 longest_failure_run = current_failure_run;
135 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadFailureCount",
136 failure_count);
137 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadSuccessCount",
138 success_count);
139 UMA_HISTOGRAM_COUNTS_100("SoftwareReporter.UploadLongestFailureRun",
140 longest_failure_run);
141 UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.LastUploadResult", last_result);
144 // Reports UwS found by the software reporter tool via UMA and RAPPOR.
145 void ReportFoundUwS() {
146 base::win::RegKey reporter_key(HKEY_CURRENT_USER,
147 kSoftwareRemovalToolRegistryKey,
148 KEY_QUERY_VALUE | KEY_SET_VALUE);
149 std::vector<base::string16> found_uws_strings;
150 if (reporter_key.Valid() &&
151 reporter_key.ReadValues(kFoundUwsValueName, &found_uws_strings) ==
152 ERROR_SUCCESS) {
153 rappor::RapporService* rappor_service = g_browser_process->rappor_service();
155 bool parse_error = false;
156 for (const base::string16& uws_string : found_uws_strings) {
157 // All UwS ids are expected to be integers.
158 uint32_t uws_id = 0;
159 if (base::StringToUint(uws_string, &uws_id)) {
160 UMA_HISTOGRAM_SPARSE_SLOWLY(kFoundUwsMetricName, uws_id);
161 if (rappor_service) {
162 rappor_service->RecordSample(kFoundUwsMetricName,
163 rappor::COARSE_RAPPOR_TYPE,
164 base::UTF16ToUTF8(uws_string));
166 } else {
167 parse_error = true;
171 // Clean up the old value.
172 reporter_key.DeleteValue(kFoundUwsValueName);
174 UMA_HISTOGRAM_BOOLEAN(kFoundUwsReadErrorMetricName, parse_error);
178 class SwReporterInstallerTraits : public ComponentInstallerTraits {
179 public:
180 SwReporterInstallerTraits() {}
182 ~SwReporterInstallerTraits() override {}
184 bool VerifyInstallation(const base::DictionaryValue& manifest,
185 const base::FilePath& dir) const override {
186 return base::PathExists(dir.Append(kSwReporterExeName));
189 bool CanAutoUpdate() const override { return true; }
191 bool OnCustomInstall(const base::DictionaryValue& manifest,
192 const base::FilePath& install_dir) override {
193 return true;
196 void ComponentReady(const base::Version& version,
197 const base::FilePath& install_dir,
198 scoped_ptr<base::DictionaryValue> manifest) override {
199 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
200 ReportVersionWithUma(version);
201 safe_browsing::RunSwReporter(install_dir.Append(kSwReporterExeName),
202 version.GetString(),
203 base::ThreadTaskRunnerHandle::Get(),
204 base::WorkerPool::GetTaskRunner(true));
207 base::FilePath GetBaseDirectory() const override { return install_dir(); }
209 void GetHash(std::vector<uint8_t>* hash) const override { GetPkHash(hash); }
211 std::string GetName() const override { return "Software Reporter Tool"; }
213 static base::FilePath install_dir() {
214 // The base directory on windows looks like:
215 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\.
216 base::FilePath result;
217 PathService::Get(DIR_SW_REPORTER, &result);
218 return result;
221 static std::string ID() {
222 update_client::CrxComponent component;
223 component.version = Version("0.0.0.0");
224 GetPkHash(&component.pk_hash);
225 return update_client::GetCrxComponentID(component);
228 private:
229 static void GetPkHash(std::vector<uint8_t>* hash) {
230 DCHECK(hash);
231 hash->assign(kSha256Hash, kSha256Hash + sizeof(kSha256Hash));
235 } // namespace
237 void RegisterSwReporterComponent(ComponentUpdateService* cus) {
238 // The Sw reporter doesn't need to run if the user isn't reporting metrics and
239 // isn't in the SRTPrompt field trial "On" group.
240 // TODO(mad): Reconsider this check to assure equal performance for metrics
241 // enabled and not enabled users crbug.com/533484
242 if (!ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled() &&
243 !safe_browsing::IsInSRTPromptFieldTrialGroups()) {
244 return;
247 // Check if we have information from Cleaner and record UMA statistics.
248 base::string16 cleaner_key_name(kSoftwareRemovalToolRegistryKey);
249 cleaner_key_name.append(1, L'\\').append(kCleanerSuffixRegistryKey);
250 base::win::RegKey cleaner_key(
251 HKEY_CURRENT_USER, cleaner_key_name.c_str(), KEY_ALL_ACCESS);
252 // Cleaner is assumed to have run if we have a start time.
253 if (cleaner_key.Valid()) {
254 if (cleaner_key.HasValue(kStartTimeValueName)) {
255 // Get version number.
256 if (cleaner_key.HasValue(kVersionValueName)) {
257 DWORD version;
258 cleaner_key.ReadValueDW(kVersionValueName, &version);
259 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.Version",
260 version);
261 cleaner_key.DeleteValue(kVersionValueName);
263 // Get start & end time. If we don't have an end time, we can assume the
264 // cleaner has not completed.
265 int64 start_time_value;
266 cleaner_key.ReadInt64(kStartTimeValueName, &start_time_value);
268 bool completed = cleaner_key.HasValue(kEndTimeValueName);
269 SRTHasCompleted(completed ? SRT_COMPLETED_YES : SRT_COMPLETED_NOT_YET);
270 if (completed) {
271 int64 end_time_value;
272 cleaner_key.ReadInt64(kEndTimeValueName, &end_time_value);
273 cleaner_key.DeleteValue(kEndTimeValueName);
274 base::TimeDelta run_time(
275 base::Time::FromInternalValue(end_time_value) -
276 base::Time::FromInternalValue(start_time_value));
277 UMA_HISTOGRAM_LONG_TIMES("SoftwareReporter.Cleaner.RunningTime",
278 run_time);
280 // Get exit code. Assume nothing was found if we can't read the exit code.
281 DWORD exit_code = safe_browsing::kSwReporterNothingFound;
282 if (cleaner_key.HasValue(kExitCodeValueName)) {
283 cleaner_key.ReadValueDW(kExitCodeValueName, &exit_code);
284 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.ExitCode",
285 exit_code);
286 cleaner_key.DeleteValue(kExitCodeValueName);
288 cleaner_key.DeleteValue(kStartTimeValueName);
290 if (exit_code == safe_browsing::kSwReporterPostRebootCleanupNeeded ||
291 exit_code ==
292 safe_browsing::kSwReporterDelayedPostRebootCleanupNeeded) {
293 // Check if we are running after the user has rebooted.
294 base::TimeDelta elapsed(
295 base::Time::Now() -
296 base::Time::FromInternalValue(start_time_value));
297 DCHECK_GT(elapsed.InMilliseconds(), 0);
298 UMA_HISTOGRAM_BOOLEAN(
299 "SoftwareReporter.Cleaner.HasRebooted",
300 static_cast<uint64>(elapsed.InMilliseconds()) > ::GetTickCount());
303 if (cleaner_key.HasValue(kUploadResultsValueName)) {
304 base::string16 upload_results;
305 cleaner_key.ReadValue(kUploadResultsValueName, &upload_results);
306 ReportUploadsWithUma(upload_results);
308 } else {
309 if (cleaner_key.HasValue(kEndTimeValueName)) {
310 SRTHasCompleted(SRT_COMPLETED_LATER);
311 cleaner_key.DeleteValue(kEndTimeValueName);
315 ReportFoundUwS();
317 // Install the component.
318 scoped_ptr<ComponentInstallerTraits> traits(new SwReporterInstallerTraits());
319 // |cus| will take ownership of |installer| during installer->Register(cus).
320 DefaultComponentInstaller* installer =
321 new DefaultComponentInstaller(traits.Pass());
322 installer->Register(cus, base::Closure());
325 void RegisterPrefsForSwReporter(PrefRegistrySimple* registry) {
326 registry->RegisterInt64Pref(prefs::kSwReporterLastTimeTriggered, 0);
327 registry->RegisterIntegerPref(prefs::kSwReporterLastExitCode, -1);
328 registry->RegisterBooleanPref(prefs::kSwReporterPendingPrompt, false);
331 void RegisterProfilePrefsForSwReporter(
332 user_prefs::PrefRegistrySyncable* registry) {
333 registry->RegisterStringPref(prefs::kSwReporterPromptVersion, "");
335 registry->RegisterStringPref(prefs::kSwReporterPromptSeed, "");
338 } // namespace component_updater