sw_reporter_installer_win.cc revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
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 46using content::BrowserThread; 47 48namespace component_updater { 49 50namespace { 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. 54enum 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. 66const int kMaxRetry = 20; 67 68// The number of days to wait before triggering another sw reporter run. 69const 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(). 74const 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 79const base::FilePath::CharType kSwReporterExeName[] = 80 FILE_PATH_LITERAL("software_reporter_tool.exe"); 81 82// Where to fetch the reporter exit code in the registry. 83const wchar_t kSoftwareRemovalToolRegistryKey[] = 84 L"Software\\Google\\Software Removal Tool"; 85const wchar_t kExitCodeRegistryValueName[] = L"ExitCode"; 86 87// Field trial strings. 88const char kSRTPromptTrialName[] = "SRTPromptFieldTrial"; 89const char kSRTPromptOnGroup[] = "On"; 90 91// Exit codes that identify that a cleanup is needed. 92const int kCleanupNeeded = 0; 93const int kPostRebootCleanupNeeded = 4; 94 95void ReportUmaStep(SwReporterUmaValue value) { 96 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value, SW_REPORTER_MAX); 97} 98 99void ReportUmaVersion(const base::Version& version) { 100 DCHECK(!version.components().empty()); 101 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MinorVersion", 102 version.components().back()); 103 // The major version uses the 1st component value (when there is more than 104 // one, since the last one is always the minor version) as a hi word in a 105 // double word. The low word is either the second component (when there are 106 // only three) or the 3rd one if there are at least 4. E.g., for W.X.Y.Z, we 107 // ignore X, and Z is the minor version. We compute the major version with W 108 // as the hi word, and Y as the low word. For X.Y.Z, we use X and Y as hi and 109 // low words, and if we would have Y.Z we would use Y as the hi word and 0 as 110 // the low word. major version is 0 if the version only has one component. 111 uint32_t major_version = 0; 112 if (version.components().size() > 1) 113 major_version = 0x10000 * version.components()[0]; 114 if (version.components().size() < 4 && version.components().size() > 2) 115 major_version += version.components()[1]; 116 else if (version.components().size() > 3) 117 major_version += version.components()[2]; 118 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MajorVersion", major_version); 119} 120 121// This function is called on the UI thread to report the SwReporter exit code 122// and then clear it from the registry as well as clear the execution state 123// from the local state. This could be called from an interruptible worker 124// thread so should be resilient to unexpected shutdown. |version| is provided 125// so the kSwReporterPromptVersion prefs can be set. 126void ReportAndClearExitCode(int exit_code, const std::string& version) { 127 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code); 128 if (g_browser_process && g_browser_process->local_state()) { 129 g_browser_process->local_state()->SetInteger(prefs::kSwReporterLastExitCode, 130 exit_code); 131 } 132 133 if ((exit_code == kPostRebootCleanupNeeded || exit_code == kCleanupNeeded) && 134 base::FieldTrialList::FindFullName(kSRTPromptTrialName) == 135 kSRTPromptOnGroup) { 136 // Find the last active browser, which may be NULL, in which case we won't 137 // show the prompt this time and will wait until the next run of the 138 // reporter. We can't use other ways of finding a browser because we don't 139 // have a profile. 140 chrome::HostDesktopType desktop_type = chrome::GetActiveDesktop(); 141 Browser* browser = chrome::FindLastActiveWithHostDesktopType(desktop_type); 142 if (browser) { 143 Profile* profile = browser->profile(); 144 // Don't show the prompt again if it's been shown before for this profile. 145 DCHECK(profile); 146 const std::string prompt_version = 147 profile->GetPrefs()->GetString(prefs::kSwReporterPromptVersion); 148 if (prompt_version.empty()) { 149 profile->GetPrefs()->SetString(prefs::kSwReporterPromptVersion, 150 version); 151 profile->GetPrefs()->SetInteger(prefs::kSwReporterPromptReason, 152 exit_code); 153 // Now that we have a profile, make sure we have a tabbed browser since 154 // we need to anchor the bubble to the toolbar's wrench menu. Create one 155 // if none exist already. 156 if (browser->type() != Browser::TYPE_TABBED) { 157 browser = chrome::FindTabbedBrowser(profile, false, desktop_type); 158 if (!browser) 159 browser = new Browser(Browser::CreateParams(profile, desktop_type)); 160 } 161 GlobalErrorService* global_error_service = 162 GlobalErrorServiceFactory::GetForProfile(profile); 163 SRTGlobalError* global_error = new SRTGlobalError(global_error_service); 164 // |global_error_service| takes ownership of |global_error| and keeps it 165 // alive until RemoveGlobalError() is called, and even then, the object 166 // is not destroyed, the caller of RemoveGlobalError is responsible to 167 // destroy it, and in the case of the SRTGlobalError, it deletes itself 168 // but only after the bubble has been interacted with. 169 global_error_service->AddGlobalError(global_error); 170 171 // Do not try to show bubble if another GlobalError is already showing 172 // one. The bubble will be shown once the others have been dismissed. 173 const GlobalErrorService::GlobalErrorList& global_errors( 174 global_error_service->errors()); 175 GlobalErrorService::GlobalErrorList::const_iterator it; 176 for (it = global_errors.begin(); it != global_errors.end(); ++it) { 177 if ((*it)->GetBubbleView()) 178 break; 179 } 180 if (it == global_errors.end()) 181 global_error->ShowBubbleView(browser); 182 } 183 } 184 } 185 186 base::win::RegKey srt_key( 187 HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_WRITE); 188 srt_key.DeleteValue(kExitCodeRegistryValueName); 189} 190 191// This function is called from a worker thread to launch the SwReporter and 192// wait for termination to collect its exit code. This task could be interrupted 193// by a shutdown at anytime, so it shouldn't depend on anything external that 194// could be shutdown beforehand. 195void LaunchAndWaitForExit(const base::FilePath& exe_path, 196 const std::string& version) { 197 const base::CommandLine reporter_command_line(exe_path); 198 base::ProcessHandle scan_reporter_process = base::kNullProcessHandle; 199 if (!base::LaunchProcess(reporter_command_line, 200 base::LaunchOptions(), 201 &scan_reporter_process)) { 202 ReportUmaStep(SW_REPORTER_FAILED_TO_START); 203 return; 204 } 205 ReportUmaStep(SW_REPORTER_START_EXECUTION); 206 207 int exit_code = -1; 208 bool success = base::WaitForExitCode(scan_reporter_process, &exit_code); 209 DCHECK(success); 210 base::CloseProcessHandle(scan_reporter_process); 211 scan_reporter_process = base::kNullProcessHandle; 212 // It's OK if this doesn't complete, the work will continue on next startup. 213 BrowserThread::PostTask( 214 BrowserThread::UI, 215 FROM_HERE, 216 base::Bind(&ReportAndClearExitCode, exit_code, version)); 217} 218 219class SwReporterInstallerTraits : public ComponentInstallerTraits { 220 public: 221 explicit SwReporterInstallerTraits(PrefService* prefs) : prefs_(prefs) {} 222 223 virtual ~SwReporterInstallerTraits() {} 224 225 virtual bool VerifyInstallation(const base::FilePath& dir) const { 226 return base::PathExists(dir.Append(kSwReporterExeName)); 227 } 228 229 virtual bool CanAutoUpdate() const { return true; } 230 231 virtual bool OnCustomInstall(const base::DictionaryValue& manifest, 232 const base::FilePath& install_dir) { 233 return true; 234 } 235 236 virtual void ComponentReady(const base::Version& version, 237 const base::FilePath& install_dir, 238 scoped_ptr<base::DictionaryValue> manifest) { 239 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 240 ReportUmaVersion(version); 241 242 wcsncpy_s(version_dir_, 243 _MAX_PATH, 244 install_dir.value().c_str(), 245 install_dir.value().size()); 246 247 // A previous run may have results in the registry, so check and report 248 // them if present. 249 std::string version_string(version.GetString()); 250 base::win::RegKey srt_key( 251 HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_READ); 252 DWORD exit_code; 253 if (srt_key.Valid() && 254 srt_key.ReadValueDW(kExitCodeRegistryValueName, &exit_code) == 255 ERROR_SUCCESS) { 256 ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE); 257 ReportAndClearExitCode(exit_code, version_string); 258 } 259 260 // If we can't access local state, we can't see when we last ran, so 261 // just exit without running. 262 if (!g_browser_process || !g_browser_process->local_state()) 263 return; 264 265 // Run the reporter if it hasn't been triggered in the 266 // kDaysBetweenSwReporterRuns days. 267 const base::Time last_time_triggered = base::Time::FromInternalValue( 268 g_browser_process->local_state()->GetInt64( 269 prefs::kSwReporterLastTimeTriggered)); 270 if ((base::Time::Now() - last_time_triggered).InDays() >= 271 kDaysBetweenSwReporterRuns) { 272 g_browser_process->local_state()->SetInt64( 273 prefs::kSwReporterLastTimeTriggered, 274 base::Time::Now().ToInternalValue()); 275 276 base::WorkerPool::PostTask( 277 FROM_HERE, 278 base::Bind(&LaunchAndWaitForExit, 279 install_dir.Append(kSwReporterExeName), 280 version_string), 281 true); 282 } 283 } 284 285 virtual base::FilePath GetBaseDirectory() const { return install_dir(); } 286 287 virtual void GetHash(std::vector<uint8_t>* hash) const { GetPkHash(hash); } 288 289 virtual std::string GetName() const { return "Software Reporter Tool"; } 290 291 static base::FilePath install_dir() { 292 // The base directory on windows looks like: 293 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\. 294 base::FilePath result; 295 PathService::Get(DIR_SW_REPORTER, &result); 296 return result; 297 } 298 299 static std::string ID() { 300 CrxComponent component; 301 component.version = Version("0.0.0.0"); 302 GetPkHash(&component.pk_hash); 303 return component_updater::GetCrxComponentID(component); 304 } 305 306 static base::FilePath VersionPath() { return base::FilePath(version_dir_); } 307 308 private: 309 static void GetPkHash(std::vector<uint8_t>* hash) { 310 DCHECK(hash); 311 hash->assign(kSha256Hash, kSha256Hash + sizeof(kSha256Hash)); 312 } 313 314 PrefService* prefs_; 315 static wchar_t version_dir_[_MAX_PATH]; 316}; 317 318wchar_t SwReporterInstallerTraits::version_dir_[] = {}; 319 320} // namespace 321 322void RegisterSwReporterComponent(ComponentUpdateService* cus, 323 PrefService* prefs) { 324 // The Sw reporter doesn't need to run if the user isn't reporting metrics and 325 // isn't in the SRTPrompt field trial "On" group. 326 if (!ChromeMetricsServiceAccessor::IsMetricsReportingEnabled() && 327 base::FieldTrialList::FindFullName(kSRTPromptTrialName) != 328 kSRTPromptOnGroup) { 329 return; 330 } 331 332 // Install the component. 333 scoped_ptr<ComponentInstallerTraits> traits( 334 new SwReporterInstallerTraits(prefs)); 335 // |cus| will take ownership of |installer| during installer->Register(cus). 336 DefaultComponentInstaller* installer = 337 new DefaultComponentInstaller(traits.Pass()); 338 installer->Register(cus); 339} 340 341void RegisterPrefsForSwReporter(PrefRegistrySimple* registry) { 342 registry->RegisterInt64Pref(prefs::kSwReporterLastTimeTriggered, 0); 343 registry->RegisterIntegerPref(prefs::kSwReporterLastExitCode, -1); 344} 345 346void RegisterProfilePrefsForSwReporter( 347 user_prefs::PrefRegistrySyncable* registry) { 348 registry->RegisterIntegerPref( 349 prefs::kSwReporterPromptReason, 350 -1, 351 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 352 353 registry->RegisterStringPref( 354 prefs::kSwReporterPromptVersion, 355 "", 356 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); 357} 358 359} // namespace component_updater 360