Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / component_updater / sw_reporter_installer_win.cc
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 ReportVersionWithUma(const base::Version& version) {
104   DCHECK(!version.components().empty());
105   // The minor version is the 2nd last component of the version,
106   // or just the first component if there is only 1.
107   uint32_t minor_version = 0;
108   if (version.components().size() > 1)
109     minor_version = version.components()[version.components().size() - 2];
110   else
111     minor_version = version.components()[0];
112   UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MinorVersion", minor_version);
113
114   // The major version for X.Y.Z is X*256^3+Y*256+Z. If there are additional
115   // components, only the first three count, and if there are less than 3, the
116   // missing values are just replaced by zero. So 1 is equivalent 1.0.0.
117   DCHECK(version.components()[0] < 0x100);
118   uint32_t major_version = 0x1000000 * version.components()[0];
119   if (version.components().size() >= 2) {
120     DCHECK(version.components()[1] < 0x10000);
121     major_version += 0x100 * version.components()[1];
122   }
123   if (version.components().size() >= 3) {
124     DCHECK(version.components()[2] < 0x100);
125     major_version += version.components()[2];
126   }
127   UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.MajorVersion", major_version);
128 }
129
130 // This function is called on the UI thread to report the SwReporter exit code
131 // and then clear it from the registry as well as clear the execution state
132 // from the local state. This could be called from an interruptible worker
133 // thread so should be resilient to unexpected shutdown. |version| is provided
134 // so the kSwReporterPromptVersion prefs can be set.
135 void ReportAndClearExitCode(int exit_code, const std::string& version) {
136   UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code);
137   if (g_browser_process && g_browser_process->local_state()) {
138     g_browser_process->local_state()->SetInteger(prefs::kSwReporterLastExitCode,
139                                                  exit_code);
140   }
141
142   if ((exit_code == kPostRebootCleanupNeeded || exit_code == kCleanupNeeded) &&
143       base::FieldTrialList::FindFullName(kSRTPromptTrialName) ==
144           kSRTPromptOnGroup) {
145     // Find the last active browser, which may be NULL, in which case we won't
146     // show the prompt this time and will wait until the next run of the
147     // reporter. We can't use other ways of finding a browser because we don't
148     // have a profile.
149     chrome::HostDesktopType desktop_type = chrome::GetActiveDesktop();
150     Browser* browser = chrome::FindLastActiveWithHostDesktopType(desktop_type);
151     if (browser) {
152       Profile* profile = browser->profile();
153       // Don't show the prompt again if it's been shown before for this profile.
154       DCHECK(profile);
155       const std::string prompt_version =
156           profile->GetPrefs()->GetString(prefs::kSwReporterPromptVersion);
157       if (prompt_version.empty()) {
158         profile->GetPrefs()->SetString(prefs::kSwReporterPromptVersion,
159                                        version);
160         profile->GetPrefs()->SetInteger(prefs::kSwReporterPromptReason,
161                                         exit_code);
162         // Now that we have a profile, make sure we have a tabbed browser since
163         // we need to anchor the bubble to the toolbar's wrench menu. Create one
164         // if none exist already.
165         if (browser->type() != Browser::TYPE_TABBED) {
166           browser = chrome::FindTabbedBrowser(profile, false, desktop_type);
167           if (!browser)
168             browser = new Browser(Browser::CreateParams(profile, desktop_type));
169         }
170         GlobalErrorService* global_error_service =
171             GlobalErrorServiceFactory::GetForProfile(profile);
172         SRTGlobalError* global_error = new SRTGlobalError(global_error_service);
173         // |global_error_service| takes ownership of |global_error| and keeps it
174         // alive until RemoveGlobalError() is called, and even then, the object
175         // is not destroyed, the caller of RemoveGlobalError is responsible to
176         // destroy it, and in the case of the SRTGlobalError, it deletes itself
177         // but only after the bubble has been interacted with.
178         global_error_service->AddGlobalError(global_error);
179
180         // Do not try to show bubble if another GlobalError is already showing
181         // one. The bubble will be shown once the others have been dismissed.
182         const GlobalErrorService::GlobalErrorList& global_errors(
183             global_error_service->errors());
184         GlobalErrorService::GlobalErrorList::const_iterator it;
185         for (it = global_errors.begin(); it != global_errors.end(); ++it) {
186           if ((*it)->GetBubbleView())
187             break;
188         }
189         if (it == global_errors.end())
190           global_error->ShowBubbleView(browser);
191       }
192     }
193   }
194
195   base::win::RegKey srt_key(
196       HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_WRITE);
197   srt_key.DeleteValue(kExitCodeRegistryValueName);
198 }
199
200 // This function is called from a worker thread to launch the SwReporter and
201 // wait for termination to collect its exit code. This task could be interrupted
202 // by a shutdown at anytime, so it shouldn't depend on anything external that
203 // could be shutdown beforehand.
204 void LaunchAndWaitForExit(const base::FilePath& exe_path,
205                           const std::string& version) {
206   const base::CommandLine reporter_command_line(exe_path);
207   base::ProcessHandle scan_reporter_process = base::kNullProcessHandle;
208   if (!base::LaunchProcess(reporter_command_line,
209                            base::LaunchOptions(),
210                            &scan_reporter_process)) {
211     ReportUmaStep(SW_REPORTER_FAILED_TO_START);
212     return;
213   }
214   ReportUmaStep(SW_REPORTER_START_EXECUTION);
215
216   int exit_code = -1;
217   bool success = base::WaitForExitCode(scan_reporter_process, &exit_code);
218   DCHECK(success);
219   scan_reporter_process = base::kNullProcessHandle;
220   // It's OK if this doesn't complete, the work will continue on next startup.
221   BrowserThread::PostTask(
222       BrowserThread::UI,
223       FROM_HERE,
224       base::Bind(&ReportAndClearExitCode, exit_code, version));
225 }
226
227 class SwReporterInstallerTraits : public ComponentInstallerTraits {
228  public:
229   explicit SwReporterInstallerTraits(PrefService* prefs) : prefs_(prefs) {}
230
231   virtual ~SwReporterInstallerTraits() {}
232
233   virtual bool VerifyInstallation(const base::DictionaryValue& manifest,
234                                   const base::FilePath& dir) const {
235     return base::PathExists(dir.Append(kSwReporterExeName));
236   }
237
238   virtual bool CanAutoUpdate() const { return true; }
239
240   virtual bool OnCustomInstall(const base::DictionaryValue& manifest,
241                                const base::FilePath& install_dir) {
242     return true;
243   }
244
245   virtual void ComponentReady(const base::Version& version,
246                               const base::FilePath& install_dir,
247                               scoped_ptr<base::DictionaryValue> manifest) {
248     DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
249     ReportVersionWithUma(version);
250
251     wcsncpy_s(version_dir_,
252               _MAX_PATH,
253               install_dir.value().c_str(),
254               install_dir.value().size());
255
256     // A previous run may have results in the registry, so check and report
257     // them if present.
258     std::string version_string(version.GetString());
259     base::win::RegKey srt_key(
260         HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_READ);
261     DWORD exit_code;
262     if (srt_key.Valid() &&
263         srt_key.ReadValueDW(kExitCodeRegistryValueName, &exit_code) ==
264             ERROR_SUCCESS) {
265       ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE);
266       ReportAndClearExitCode(exit_code, version_string);
267     }
268
269     // If we can't access local state, we can't see when we last ran, so
270     // just exit without running.
271     if (!g_browser_process || !g_browser_process->local_state())
272       return;
273
274     // Run the reporter if it hasn't been triggered in the
275     // kDaysBetweenSwReporterRuns days.
276     const base::Time last_time_triggered = base::Time::FromInternalValue(
277         g_browser_process->local_state()->GetInt64(
278             prefs::kSwReporterLastTimeTriggered));
279     if ((base::Time::Now() - last_time_triggered).InDays() >=
280         kDaysBetweenSwReporterRuns) {
281       g_browser_process->local_state()->SetInt64(
282           prefs::kSwReporterLastTimeTriggered,
283           base::Time::Now().ToInternalValue());
284
285       base::WorkerPool::PostTask(
286           FROM_HERE,
287           base::Bind(&LaunchAndWaitForExit,
288                      install_dir.Append(kSwReporterExeName),
289                      version_string),
290           true);
291     }
292   }
293
294   virtual base::FilePath GetBaseDirectory() const { return install_dir(); }
295
296   virtual void GetHash(std::vector<uint8_t>* hash) const { GetPkHash(hash); }
297
298   virtual std::string GetName() const { return "Software Reporter Tool"; }
299
300   static base::FilePath install_dir() {
301     // The base directory on windows looks like:
302     // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\.
303     base::FilePath result;
304     PathService::Get(DIR_SW_REPORTER, &result);
305     return result;
306   }
307
308   static std::string ID() {
309     CrxComponent component;
310     component.version = Version("0.0.0.0");
311     GetPkHash(&component.pk_hash);
312     return component_updater::GetCrxComponentID(component);
313   }
314
315   static base::FilePath VersionPath() { return base::FilePath(version_dir_); }
316
317  private:
318   static void GetPkHash(std::vector<uint8_t>* hash) {
319     DCHECK(hash);
320     hash->assign(kSha256Hash, kSha256Hash + sizeof(kSha256Hash));
321   }
322
323   PrefService* prefs_;
324   static wchar_t version_dir_[_MAX_PATH];
325 };
326
327 wchar_t SwReporterInstallerTraits::version_dir_[] = {};
328
329 }  // namespace
330
331 void RegisterSwReporterComponent(ComponentUpdateService* cus,
332                                  PrefService* prefs) {
333   // The Sw reporter doesn't need to run if the user isn't reporting metrics and
334   // isn't in the SRTPrompt field trial "On" group.
335   if (!ChromeMetricsServiceAccessor::IsMetricsReportingEnabled() &&
336       base::FieldTrialList::FindFullName(kSRTPromptTrialName) !=
337           kSRTPromptOnGroup) {
338     return;
339   }
340
341   // Check if we have information from Cleaner and record UMA statistics.
342   base::string16 cleaner_key_name(kSoftwareRemovalToolRegistryKey);
343   cleaner_key_name.append(1, L'\\').append(kCleanerSuffixRegistryKey);
344   base::win::RegKey cleaner_key(
345       HKEY_CURRENT_USER, cleaner_key_name.c_str(), KEY_ALL_ACCESS);
346   // Cleaner is assumed to have run if we have a start time.
347   if (cleaner_key.Valid() &&
348       cleaner_key.HasValue(kStartTimeRegistryValueName)) {
349     // Get version number.
350     if (cleaner_key.HasValue(kVersionRegistryValueName)) {
351       DWORD version;
352       cleaner_key.ReadValueDW(kVersionRegistryValueName, &version);
353       UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.Version", version);
354       cleaner_key.DeleteValue(kVersionRegistryValueName);
355     }
356     // Get start & end time. If we don't have an end time, we can assume the
357     // cleaner has crashed.
358     bool completed = cleaner_key.HasValue(kEndTimeRegistryValueName);
359     UMA_HISTOGRAM_BOOLEAN("SoftwareReporter.Cleaner.HasCompleted", completed);
360     if (completed) {
361       int64 start_time_value;
362       cleaner_key.ReadInt64(kStartTimeRegistryValueName, &start_time_value);
363       int64 end_time_value;
364       cleaner_key.ReadInt64(kEndTimeRegistryValueName, &end_time_value);
365       cleaner_key.DeleteValue(kEndTimeRegistryValueName);
366       base::TimeDelta run_time(base::Time::FromInternalValue(end_time_value) -
367           base::Time::FromInternalValue(start_time_value));
368       UMA_HISTOGRAM_LONG_TIMES("SoftwareReporter.Cleaner.RunningTime",
369           run_time);
370     }
371     // Get exit code.
372     if (cleaner_key.HasValue(kExitCodeRegistryValueName)) {
373       DWORD exit_code;
374       cleaner_key.ReadValueDW(kExitCodeRegistryValueName, &exit_code);
375       UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.Cleaner.ExitCode",
376           exit_code);
377       cleaner_key.DeleteValue(kExitCodeRegistryValueName);
378     }
379     cleaner_key.DeleteValue(kStartTimeRegistryValueName);
380   }
381
382   // Install the component.
383   scoped_ptr<ComponentInstallerTraits> traits(
384       new SwReporterInstallerTraits(prefs));
385   // |cus| will take ownership of |installer| during installer->Register(cus).
386   DefaultComponentInstaller* installer =
387       new DefaultComponentInstaller(traits.Pass());
388   installer->Register(cus);
389 }
390
391 void RegisterPrefsForSwReporter(PrefRegistrySimple* registry) {
392   registry->RegisterInt64Pref(prefs::kSwReporterLastTimeTriggered, 0);
393   registry->RegisterIntegerPref(prefs::kSwReporterLastExitCode, -1);
394 }
395
396 void RegisterProfilePrefsForSwReporter(
397     user_prefs::PrefRegistrySyncable* registry) {
398   registry->RegisterIntegerPref(
399       prefs::kSwReporterPromptReason,
400       -1,
401       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
402
403   registry->RegisterStringPref(
404       prefs::kSwReporterPromptVersion,
405       "",
406       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
407 }
408
409 }  // namespace component_updater