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. 4 5 #include "chrome/browser/component_updater/sw_reporter_installer_win.h" 6 7 #include <stdint.h> 8 #include <string> 9 #include <vector> 10 11 #include "base/base_paths.h" 12 #include "base/bind.h" 13 #include "base/bind_helpers.h" 14 #include "base/command_line.h" 15 #include "base/files/file_path.h" 16 #include "base/files/file_util.h" 17 #include "base/logging.h" 18 #include "base/metrics/field_trial.h" 19 #include "base/metrics/histogram.h" 20 #include "base/metrics/sparse_histogram.h" 21 #include "base/path_service.h" 22 #include "base/prefs/pref_registry_simple.h" 23 #include "base/prefs/pref_service.h" 24 #include "base/process/kill.h" 25 #include "base/process/launch.h" 26 #include "base/task_runner_util.h" 27 #include "base/threading/worker_pool.h" 28 #include "base/time/time.h" 29 #include "base/win/registry.h" 30 #include "chrome/browser/browser_process.h" 31 #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" 32 #include "chrome/browser/profiles/profile.h" 33 #include "chrome/browser/safe_browsing/srt_global_error_win.h" 34 #include "chrome/browser/ui/browser_finder.h" 35 #include "chrome/browser/ui/global_error/global_error_service.h" 36 #include "chrome/browser/ui/global_error/global_error_service_factory.h" 37 #include "chrome/common/pref_names.h" 38 #include "components/component_updater/component_updater_paths.h" 39 #include "components/component_updater/component_updater_service.h" 40 #include "components/component_updater/component_updater_utils.h" 41 #include "components/component_updater/default_component_installer.h" 42 #include "components/component_updater/pref_names.h" 43 #include "components/pref_registry/pref_registry_syncable.h" 44 #include "content/public/browser/browser_thread.h" 45 46 using content::BrowserThread; 47 48 namespace component_updater { 49 50 namespace { 51 52 // These values are used to send UMA information and are replicated in the 53 // histograms.xml file, so the order MUST NOT CHANGE. 54 enum SwReporterUmaValue { 55 SW_REPORTER_EXPLICIT_REQUEST = 0, // Deprecated. 56 SW_REPORTER_STARTUP_RETRY = 1, // Deprecated. 57 SW_REPORTER_RETRIED_TOO_MANY_TIMES = 2, // Deprecated. 58 SW_REPORTER_START_EXECUTION = 3, 59 SW_REPORTER_FAILED_TO_START = 4, 60 SW_REPORTER_REGISTRY_EXIT_CODE = 5, 61 SW_REPORTER_RESET_RETRIES = 6, // Deprecated. 62 SW_REPORTER_MAX, 63 }; 64 65 // The maximum number of times to retry a download on startup. 66 const int kMaxRetry = 20; 67 68 // The number of days to wait before triggering another sw reporter run. 69 const int kDaysBetweenSwReporterRuns = 7; 70 71 // CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was 72 // generated in Python with something like this: 73 // hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest(). 74 const uint8_t kSha256Hash[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6, 75 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e, 76 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c, 77 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7}; 78 79 const base::FilePath::CharType kSwReporterExeName[] = 80 FILE_PATH_LITERAL("software_reporter_tool.exe"); 81 82 // Where to fetch the reporter exit code in the registry. 83 const wchar_t kSoftwareRemovalToolRegistryKey[] = 84 L"Software\\Google\\Software Removal Tool"; 85 const wchar_t kCleanerSuffixRegistryKey[] = L"Cleaner"; 86 const wchar_t kExitCodeRegistryValueName[] = L"ExitCode"; 87 const wchar_t kVersionRegistryValueName[] = L"Version"; 88 const wchar_t kStartTimeRegistryValueName[] = L"StartTime"; 89 const wchar_t kEndTimeRegistryValueName[] = L"EndTime"; 90 91 // Field trial strings. 92 const char kSRTPromptTrialName[] = "SRTPromptFieldTrial"; 93 const char kSRTPromptOnGroup[] = "On"; 94 95 // Exit codes that identify that a cleanup is needed. 96 const int kCleanupNeeded = 0; 97 const int kPostRebootCleanupNeeded = 4; 98 99 void ReportUmaStep(SwReporterUmaValue value) { 100 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value, SW_REPORTER_MAX); 101 } 102 103 void ReportUmaVersion(const base::Version& version) { 104 DCHECK(!version.components().empty()); 105 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MinorVersion", 106 version.components().back()); 107 // The major version uses the 1st component value (when there is more than 108 // one, since the last one is always the minor version) as a hi word in a 109 // double word. The low word is either the second component (when there are 110 // only three) or the 3rd one if there are at least 4. E.g., for W.X.Y.Z, we 111 // ignore X, and Z is the minor version. We compute the major version with W 112 // as the hi word, and Y as the low word. For X.Y.Z, we use X and Y as hi and 113 // low words, and if we would have Y.Z we would use Y as the hi word and 0 as 114 // the low word. major version is 0 if the version only has one component. 115 uint32_t major_version = 0; 116 if (version.components().size() > 1) 117 major_version = 0x10000 * version.components()[0]; 118 if (version.components().size() < 4 && version.components().size() > 2) 119 major_version += version.components()[1]; 120 else if (version.components().size() > 3) 121 major_version += version.components()[2]; 122 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MajorVersion", major_version); 123 } 124 125 // This function is called on the UI thread to report the SwReporter exit code 126 // and then clear it from the registry as well as clear the execution state 127 // from the local state. This could be called from an interruptible worker 128 // thread so should be resilient to unexpected shutdown. |version| is provided 129 // so the kSwReporterPromptVersion prefs can be set. 130 void ReportAndClearExitCode(int exit_code, const std::string& version) { 131 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code); 132 if (g_browser_process && g_browser_process->local_state()) { 133 g_browser_process->local_state()->SetInteger(prefs::kSwReporterLastExitCode, 134 exit_code); 135 } 136 137 if ((exit_code == kPostRebootCleanupNeeded || exit_code == kCleanupNeeded) && 138 base::FieldTrialList::FindFullName(kSRTPromptTrialName) == 139 kSRTPromptOnGroup) { 140 // Find the last active browser, which may be NULL, in which case we won't 141 // show the prompt this time and will wait until the next run of the 142 // reporter. We can't use other ways of finding a browser because we don't 143 // have a profile. 144 chrome::HostDesktopType desktop_type = chrome::GetActiveDesktop(); 145 Browser* browser = chrome::FindLastActiveWithHostDesktopType(desktop_type); 146 if (browser) { 147 Profile* profile = browser->profile(); 148 // Don't show the prompt again if it's been shown before for this profile. 149 DCHECK(profile); 150 const std::string prompt_version = 151 profile->GetPrefs()->GetString(prefs::kSwReporterPromptVersion); 152 if (prompt_version.empty()) { 153 profile->GetPrefs()->SetString(prefs::kSwReporterPromptVersion, 154 version); 155 profile->GetPrefs()->SetInteger(prefs::kSwReporterPromptReason, 156 exit_code); 157 // Now that we have a profile, make sure we have a tabbed browser since 158 // we need to anchor the bubble to the toolbar's wrench menu. Create one 159 // if none exist already. 160 if (browser->type() != Browser::TYPE_TABBED) { 161 browser = chrome::FindTabbedBrowser(profile, false, desktop_type); 162 if (!browser) 163 browser = new Browser(Browser::CreateParams(profile, desktop_type)); 164 } 165 GlobalErrorService* global_error_service = 166 GlobalErrorServiceFactory::GetForProfile(profile); 167 SRTGlobalError* global_error = new SRTGlobalError(global_error_service); 168 // |global_error_service| takes ownership of |global_error| and keeps it 169 // alive until RemoveGlobalError() is called, and even then, the object 170 // is not destroyed, the caller of RemoveGlobalError is responsible to 171 // destroy it, and in the case of the SRTGlobalError, it deletes itself 172 // but only after the bubble has been interacted with. 173 global_error_service->AddGlobalError(global_error); 174 175 // Do not try to show bubble if another GlobalError is already showing 176 // one. The bubble will be shown once the others have been dismissed. 177 const GlobalErrorService::GlobalErrorList& global_errors( 178 global_error_service->errors()); 179 GlobalErrorService::GlobalErrorList::const_iterator it; 180 for (it = global_errors.begin(); it != global_errors.end(); ++it) { 181 if ((*it)->GetBubbleView()) 182 break; 183 } 184 if (it == global_errors.end()) 185 global_error->ShowBubbleView(browser); 186 } 187 } 188 } 189 190 base::win::RegKey srt_key( 191 HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_WRITE); 192 srt_key.DeleteValue(kExitCodeRegistryValueName); 193 } 194 195 // This function is called from a worker thread to launch the SwReporter and 196 // wait for termination to collect its exit code. This task could be interrupted 197 // by a shutdown at anytime, so it shouldn't depend on anything external that 198 // could be shutdown beforehand. 199 void LaunchAndWaitForExit(const base::FilePath& exe_path, 200 const std::string& version) { 201 const base::CommandLine reporter_command_line(exe_path); 202 base::ProcessHandle scan_reporter_process = base::kNullProcessHandle; 203 if (!base::LaunchProcess(reporter_command_line, 204 base::LaunchOptions(), 205 &scan_reporter_process)) { 206 ReportUmaStep(SW_REPORTER_FAILED_TO_START); 207 return; 208 } 209 ReportUmaStep(SW_REPORTER_START_EXECUTION); 210 211 int exit_code = -1; 212 bool success = base::WaitForExitCode(scan_reporter_process, &exit_code); 213 DCHECK(success); 214 scan_reporter_process = base::kNullProcessHandle; 215 // It's OK if this doesn't complete, the work will continue on next startup. 216 BrowserThread::PostTask( 217 BrowserThread::UI, 218 FROM_HERE, 219 base::Bind(&ReportAndClearExitCode, exit_code, version)); 220 } 221 222 class SwReporterInstallerTraits : public ComponentInstallerTraits { 223 public: 224 explicit SwReporterInstallerTraits(PrefService* prefs) : prefs_(prefs) {} 225 226 virtual ~SwReporterInstallerTraits() {} 227 228 virtual bool VerifyInstallation(const base::FilePath& dir) const { 229 return base::PathExists(dir.Append(kSwReporterExeName)); 230 } 231 232 virtual bool CanAutoUpdate() const { return true; } 233 234 virtual bool OnCustomInstall(const base::DictionaryValue& manifest, 235 const base::FilePath& install_dir) { 236 return true; 237 } 238 239 virtual void ComponentReady(const base::Version& version, 240 const base::FilePath& install_dir, 241 scoped_ptr<base::DictionaryValue> manifest) { 242 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 243 ReportUmaVersion(version); 244 245 wcsncpy_s(version_dir_, 246 _MAX_PATH, 247 install_dir.value().c_str(), 248 install_dir.value().size()); 249 250 // A previous run may have results in the registry, so check and report 251 // them if present. 252 std::string version_string(version.GetString()); 253 base::win::RegKey srt_key( 254 HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_READ); 255 DWORD exit_code; 256 if (srt_key.Valid() && 257 srt_key.ReadValueDW(kExitCodeRegistryValueName, &exit_code) == 258 ERROR_SUCCESS) { 259 ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE); 260 ReportAndClearExitCode(exit_code, version_string); 261 } 262 263 // If we can't access local state, we can't see when we last ran, so 264 // just exit without running. 265 if (!g_browser_process || !g_browser_process->local_state()) 266 return; 267 268 // Run the reporter if it hasn't been triggered in the 269 // kDaysBetweenSwReporterRuns days. 270 const base::Time last_time_triggered = base::Time::FromInternalValue( 271 g_browser_process->local_state()->GetInt64( 272 prefs::kSwReporterLastTimeTriggered)); 273 if ((base::Time::Now() - last_time_triggered).InDays() >= 274 kDaysBetweenSwReporterRuns) { 275 g_browser_process->local_state()->SetInt64( 276 prefs::kSwReporterLastTimeTriggered, 277 base::Time::Now().ToInternalValue()); 278 279 base::WorkerPool::PostTask( 280 FROM_HERE, 281 base::Bind(&LaunchAndWaitForExit, 282 install_dir.Append(kSwReporterExeName), 283 version_string), 284 true); 285 } 286 } 287 288 virtual base::FilePath GetBaseDirectory() const { return install_dir(); } 289 290 virtual void GetHash(std::vector<uint8_t>* hash) const { GetPkHash(hash); } 291 292 virtual std::string GetName() const { return "Software Reporter Tool"; } 293 294 static base::FilePath install_dir() { 295 // The base directory on windows looks like: 296 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\. 297 base::FilePath result; 298 PathService::Get(DIR_SW_REPORTER, &result); 299 return result; 300 } 301 302 static std::string ID() { 303 CrxComponent component; 304 component.version = Version("0.0.0.0"); 305 GetPkHash(&component.pk_hash); 306 return component_updater::GetCrxComponentID(component); 307 } 308 309 static base::FilePath VersionPath() { return base::FilePath(version_dir_); } 310 311 private: 312 static void GetPkHash(std::vector<uint8_t>* hash) { 313 DCHECK(hash); 314 hash->assign(kSha256Hash, kSha256Hash + sizeof(kSha256Hash)); 315 } 316 317 PrefService* prefs_; 318 static wchar_t version_dir_[_MAX_PATH]; 319 }; 320 321 wchar_t SwReporterInstallerTraits::version_dir_[] = {}; 322 323 } // namespace 324 325 void RegisterSwReporterComponent(ComponentUpdateService* cus, 326 PrefService* prefs) { 327 // The Sw reporter doesn't need to run if the user isn't reporting metrics and 328 // isn't in the SRTPrompt field trial "On" group. 329 if (!ChromeMetricsServiceAccessor::IsMetricsReportingEnabled() && 330 base::FieldTrialList::FindFullName(kSRTPromptTrialName) != 331 kSRTPromptOnGroup) { 332 return; 333 } 334 335 // Check if we have information from Cleaner and record UMA statistics. 336 base::string16 cleaner_key_name(kSoftwareRemovalToolRegistryKey); 337 cleaner_key_name.append(1, L'\\').append(kCleanerSuffixRegistryKey); 338 base::win::RegKey cleaner_key( 339 HKEY_CURRENT_USER, cleaner_key_name.c_str(), KEY_ALL_ACCESS); 340 // Cleaner is assumed to have run if we have a start time. 341 if (cleaner_key.Valid() && 342 cleaner_key.HasValue(kStartTimeRegistryValueName)) { 343 // Get version number. 344 if (cleaner_key.HasValue(kVersionRegistryValueName)) { 345 DWORD version; 346 cleaner_key.ReadValueDW(kVersionRegistryValueName, &version); 347 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.Version", version); 348 cleaner_key.DeleteValue(kVersionRegistryValueName); 349 } 350 // Get start & end time. If we don't have an end time, we can assume the 351 // cleaner has crashed. 352 bool completed = cleaner_key.HasValue(kEndTimeRegistryValueName); 353 UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.Cleaner.HasCompleted", completed); 354 if (completed) { 355 int64 start_time_value; 356 cleaner_key.ReadInt64(kStartTimeRegistryValueName, &start_time_value); 357 int64 end_time_value; 358 cleaner_key.ReadInt64(kEndTimeRegistryValueName, &end_time_value); 359 cleaner_key.DeleteValue(kEndTimeRegistryValueName); 360 base::TimeDelta run_time(base::Time::FromInternalValue(end_time_value) - 361 base::Time::FromInternalValue(start_time_value)); 362 UMA_HISTOGRAM_LONG_TIMES("SoftwareReporter.Cleaner.RunningTime", 363 run_time); 364 } 365 // Get exit code. 366 if (cleaner_key.HasValue(kExitCodeRegistryValueName)) { 367 DWORD exit_code; 368 cleaner_key.ReadValueDW(kExitCodeRegistryValueName, &exit_code); 369 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.ExitCode", 370 exit_code); 371 cleaner_key.DeleteValue(kExitCodeRegistryValueName); 372 } 373 cleaner_key.DeleteValue(kStartTimeRegistryValueName); 374 } 375 376 // Install the component. 377 scoped_ptr<ComponentInstallerTraits> traits( 378 new SwReporterInstallerTraits(prefs)); 379 // |cus| will take ownership of |installer| during installer->Register(cus). 380 DefaultComponentInstaller* installer = 381 new DefaultComponentInstaller(traits.Pass()); 382 installer->Register(cus); 383 } 384 385 void RegisterPrefsForSwReporter(PrefRegistrySimple* registry) { 386 registry->RegisterInt64Pref(prefs::kSwReporterLastTimeTriggered, 0); 387 registry->RegisterIntegerPref(prefs::kSwReporterLastExitCode, -1); 388 } 389 390 void RegisterProfilePrefsForSwReporter( 391 user_prefs::PrefRegistrySyncable* registry) { 392 registry->RegisterIntegerPref( 393 prefs::kSwReporterPromptReason, 394 -1, 395 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 396 397 registry->RegisterStringPref( 398 prefs::kSwReporterPromptVersion, 399 "", 400 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 401 } 402 403 } // namespace component_updater 404