sw_reporter_installer_win.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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 <string> 8#include <vector> 9 10#include "base/base_paths.h" 11#include "base/bind.h" 12#include "base/bind_helpers.h" 13#include "base/command_line.h" 14#include "base/file_util.h" 15#include "base/files/file_path.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/prefs/pref_service.h" 22#include "base/process/kill.h" 23#include "base/process/launch.h" 24#include "base/task_runner_util.h" 25#include "base/threading/worker_pool.h" 26#include "base/win/registry.h" 27#include "chrome/browser/browser_process.h" 28#include "chrome/browser/component_updater/component_updater_service.h" 29#include "chrome/browser/component_updater/component_updater_utils.h" 30#include "chrome/browser/component_updater/default_component_installer.h" 31#include "components/component_updater/component_updater_paths.h" 32#include "components/component_updater/pref_names.h" 33#include "content/public/browser/browser_thread.h" 34 35using content::BrowserThread; 36 37namespace component_updater { 38 39namespace { 40 41// These values are used to send UMA information and are replicated in the 42// histograms.xml file, so the order MUST NOT CHANGE. 43enum SwReporterUmaValue { 44 SW_REPORTER_EXPLICIT_REQUEST = 0, 45 SW_REPORTER_STARTUP_RETRY = 1, 46 SW_REPORTER_RETRIED_TOO_MANY_TIMES = 2, 47 SW_REPORTER_START_EXECUTION = 3, 48 SW_REPORTER_FAILED_TO_START = 4, 49 SW_REPORTER_REGISTRY_EXIT_CODE = 5, 50 SW_REPORTER_RESET_RETRIES = 6, 51 SW_REPORTER_MAX, 52}; 53 54// The maximum number of times to retry a download on startup. 55const int kMaxRetry = 20; 56 57// CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was 58// generated in Python with something like this: 59// hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest(). 60const uint8 kSha256Hash[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6, 61 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e, 62 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c, 63 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7}; 64 65const base::FilePath::CharType kSwReporterExeName[] = 66 FILE_PATH_LITERAL("software_reporter_tool.exe"); 67 68// Where to fetch the reporter exit code in the registry. 69const wchar_t kSoftwareRemovalToolRegistryKey[] = 70 L"Software\\Google\\Software Removal Tool"; 71const wchar_t kExitCodeRegistryValueName[] = L"ExitCode"; 72 73void ReportUmaStep(SwReporterUmaValue value) { 74 UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value, SW_REPORTER_MAX); 75} 76 77// This function is called on the UI thread to report the SwReporter exit code 78// and then clear it from the registry as well as clear the execution state 79// from the local state. This could be called from an interruptible worker 80// thread so should be resilient to unexpected shutdown. 81void ReportAndClearExitCode(int exit_code) { 82 UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code); 83 84 base::win::RegKey srt_key( 85 HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_WRITE); 86 srt_key.DeleteValue(kExitCodeRegistryValueName); 87 88 // Now that we are done we can reset the try count. 89 g_browser_process->local_state()->SetInteger( 90 prefs::kSwReporterExecuteTryCount, 0); 91} 92 93// This function is called from a worker thread to launch the SwReporter and 94// wait for termination to collect its exit code. This task could be interrupted 95// by a shutdown at anytime, so it shouldn't depend on anything external that 96// could be shutdown beforehand. 97void LaunchAndWaitForExit(const base::FilePath& exe_path) { 98 const base::CommandLine reporter_command_line(exe_path); 99 base::ProcessHandle scan_reporter_process = base::kNullProcessHandle; 100 if (!base::LaunchProcess(reporter_command_line, 101 base::LaunchOptions(), 102 &scan_reporter_process)) { 103 ReportUmaStep(SW_REPORTER_FAILED_TO_START); 104 return; 105 } 106 ReportUmaStep(SW_REPORTER_START_EXECUTION); 107 108 int exit_code = -1; 109 bool success = base::WaitForExitCode(scan_reporter_process, &exit_code); 110 DCHECK(success); 111 base::CloseProcessHandle(scan_reporter_process); 112 scan_reporter_process = base::kNullProcessHandle; 113 // It's OK if this doesn't complete, the work will continue on next startup. 114 BrowserThread::PostTask(BrowserThread::UI, 115 FROM_HERE, 116 base::Bind(&ReportAndClearExitCode, exit_code)); 117} 118 119void ExecuteReporter(const base::FilePath& install_dir) { 120 base::WorkerPool::PostTask( 121 FROM_HERE, 122 base::Bind(&LaunchAndWaitForExit, install_dir.Append(kSwReporterExeName)), 123 true); 124} 125 126class SwReporterInstallerTraits : public ComponentInstallerTraits { 127 public: 128 explicit SwReporterInstallerTraits(PrefService* prefs) : prefs_(prefs) {} 129 130 virtual ~SwReporterInstallerTraits() {} 131 132 virtual bool VerifyInstallation(const base::FilePath& dir) const { 133 return base::PathExists(dir.Append(kSwReporterExeName)); 134 } 135 136 virtual bool CanAutoUpdate() const { return true; } 137 138 virtual bool OnCustomInstall(const base::DictionaryValue& manifest, 139 const base::FilePath& install_dir) { 140 return true; 141 } 142 143 virtual void ComponentReady(const base::Version& version, 144 const base::FilePath& install_dir, 145 scoped_ptr<base::DictionaryValue> manifest) { 146 wcsncpy_s(version_dir_, 147 _MAX_PATH, 148 install_dir.value().c_str(), 149 install_dir.value().size()); 150 // Only execute the reporter if there is still a pending request for it. 151 if (prefs_->GetInteger(prefs::kSwReporterExecuteTryCount) > 0) 152 ExecuteReporter(install_dir); 153 } 154 155 virtual base::FilePath GetBaseDirectory() const { return install_dir(); } 156 157 virtual void GetHash(std::vector<uint8>* hash) const { GetPkHash(hash); } 158 159 virtual std::string GetName() const { return "Software Reporter Tool"; } 160 161 static base::FilePath install_dir() { 162 // The base directory on windows looks like: 163 // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\. 164 base::FilePath result; 165 PathService::Get(DIR_SW_REPORTER, &result); 166 return result; 167 } 168 169 static std::string ID() { 170 CrxComponent component; 171 component.version = Version("0.0.0.0"); 172 GetPkHash(&component.pk_hash); 173 return component_updater::GetCrxComponentID(component); 174 } 175 176 static base::FilePath VersionPath() { return base::FilePath(version_dir_); } 177 178 private: 179 static void GetPkHash(std::vector<uint8>* hash) { 180 DCHECK(hash); 181 hash->assign(kSha256Hash, kSha256Hash + sizeof(kSha256Hash)); 182 } 183 184 PrefService* prefs_; 185 static wchar_t version_dir_[_MAX_PATH]; 186}; 187 188wchar_t SwReporterInstallerTraits::version_dir_[] = {}; 189 190void RegisterComponent(ComponentUpdateService* cus, PrefService* prefs) { 191 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 192 scoped_ptr<ComponentInstallerTraits> traits( 193 new SwReporterInstallerTraits(prefs)); 194 // |cus| will take ownership of |installer| during installer->Register(cus). 195 DefaultComponentInstaller* installer = 196 new DefaultComponentInstaller(traits.Pass()); 197 installer->Register(cus); 198} 199 200// We need a conditional version of register component so that it can be called 201// back on the UI thread after validating on the File thread that the component 202// path exists and we must re-register on startup for example. 203void MaybeRegisterComponent(ComponentUpdateService* cus, 204 PrefService* prefs, 205 bool register_component) { 206 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 207 if (register_component) 208 RegisterComponent(cus, prefs); 209} 210 211} // namespace 212 213void ExecuteSwReporter(ComponentUpdateService* cus, PrefService* prefs) { 214 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 215 // If we have a pending execution, send metrics about it so we can account for 216 // missing executions. 217 if (prefs->GetInteger(prefs::kSwReporterExecuteTryCount) > 0) 218 ReportUmaStep(SW_REPORTER_RESET_RETRIES); 219 // This is an explicit call, so let's forget about previous incomplete 220 // execution attempts and start from scratch. 221 prefs->SetInteger(prefs::kSwReporterExecuteTryCount, kMaxRetry); 222 ReportUmaStep(SW_REPORTER_EXPLICIT_REQUEST); 223 const std::vector<std::string> registered_components(cus->GetComponentIDs()); 224 if (std::find(registered_components.begin(), 225 registered_components.end(), 226 SwReporterInstallerTraits::ID()) == 227 registered_components.end()) { 228 RegisterComponent(cus, prefs); 229 } else if (!SwReporterInstallerTraits::VersionPath().empty()) { 230 // Here, we already have a fully registered and installed component 231 // available for immediate use. This doesn't handle cases where the version 232 // folder is there but the executable is not within in. This is a corruption 233 // we don't want to handle here. 234 ExecuteReporter(SwReporterInstallerTraits::VersionPath()); 235 } 236 // If the component is registered but the version path is not available, it 237 // means the component was not fully installed yet, and it should run the 238 // reporter when ComponentReady is called. 239} 240 241void ExecutePendingSwReporter(ComponentUpdateService* cus, PrefService* prefs) { 242 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 243 244 // Register the existing component for updates. 245 base::PostTaskAndReplyWithResult( 246 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), 247 FROM_HERE, 248 base::Bind(&base::PathExists, SwReporterInstallerTraits::install_dir()), 249 base::Bind(&MaybeRegisterComponent, cus, prefs)); 250 251 // Run the reporter if there is a pending execution request. 252 int execute_try_count = prefs->GetInteger(prefs::kSwReporterExecuteTryCount); 253 if (execute_try_count > 0) { 254 // Retrieve the results if the pending request has completed. 255 base::win::RegKey srt_key( 256 HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_READ); 257 DWORD exit_code; 258 if (srt_key.Valid() && 259 srt_key.ReadValueDW(kExitCodeRegistryValueName, &exit_code) == 260 ERROR_SUCCESS) { 261 ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE); 262 ReportAndClearExitCode(exit_code); 263 return; 264 } 265 266 // The previous request has not completed. The reporter will run again 267 // when ComponentReady is called or the request is abandoned if it has 268 // been tried too many times. 269 prefs->SetInteger(prefs::kSwReporterExecuteTryCount, --execute_try_count); 270 if (execute_try_count > 0) 271 ReportUmaStep(SW_REPORTER_STARTUP_RETRY); 272 else 273 ReportUmaStep(SW_REPORTER_RETRIED_TOO_MANY_TIMES); 274 } 275} 276 277void RegisterPrefsForSwReporter(PrefRegistrySimple* registry) { 278 registry->RegisterIntegerPref(prefs::kSwReporterExecuteTryCount, 0); 279} 280 281} // namespace component_updater 282