Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / upgrade_detector_impl.cc
1 // Copyright (c) 2012 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/upgrade_detector_impl.h"
6
7 #include <string>
8
9 #include "base/bind.h"
10 #include "base/build_time.h"
11 #include "base/command_line.h"
12 #include "base/cpu.h"
13 #include "base/files/file_path.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/singleton.h"
16 #include "base/path_service.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/process/launch.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/time/time.h"
23 #include "base/version.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/google/google_util.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "chrome/common/chrome_version_info.h"
28 #include "chrome/common/pref_names.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "ui/base/resource/resource_bundle.h"
31
32 #if defined(OS_WIN)
33 #include "base/win/win_util.h"
34 #include "chrome/installer/util/browser_distribution.h"
35 #include "chrome/installer/util/google_update_settings.h"
36 #include "chrome/installer/util/helper.h"
37 #include "chrome/installer/util/install_util.h"
38 #elif defined(OS_MACOSX)
39 #include "chrome/browser/mac/keystone_glue.h"
40 #endif
41
42 using content::BrowserThread;
43
44 namespace {
45
46 // How long (in milliseconds) to wait (each cycle) before checking whether
47 // Chrome's been upgraded behind our back.
48 const int kCheckForUpgradeMs = 2 * 60 * 60 * 1000;  // 2 hours.
49
50 // How long to wait (each cycle) before checking which severity level we should
51 // be at. Once we reach the highest severity, the timer will stop.
52 const int kNotifyCycleTimeMs = 20 * 60 * 1000;  // 20 minutes.
53
54 // Same as kNotifyCycleTimeMs but only used during testing.
55 const int kNotifyCycleTimeForTestingMs = 500;  // Half a second.
56
57 // The number of days after which we identify a build/install as outdated.
58 const uint64 kOutdatedBuildAgeInDays = 12 * 7;
59
60 // Return the string that was passed as a value for the
61 // kCheckForUpdateIntervalSec switch.
62 std::string CmdLineInterval() {
63   const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
64   return cmd_line.GetSwitchValueASCII(switches::kCheckForUpdateIntervalSec);
65 }
66
67 // Check if one of the outdated simulation switches was present on the command
68 // line.
69 bool SimulatingOutdated() {
70   const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
71   return cmd_line.HasSwitch(switches::kSimulateOutdated) ||
72       cmd_line.HasSwitch(switches::kSimulateOutdatedNoAU);
73 }
74
75 // Check if any of the testing switches was present on the command line.
76 bool IsTesting() {
77   const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
78   return cmd_line.HasSwitch(switches::kSimulateUpgrade) ||
79       cmd_line.HasSwitch(switches::kCheckForUpdateIntervalSec) ||
80       cmd_line.HasSwitch(switches::kSimulateCriticalUpdate) ||
81       SimulatingOutdated();
82 }
83
84 // How often to check for an upgrade.
85 int GetCheckForUpgradeEveryMs() {
86   // Check for a value passed via the command line.
87   int interval_ms;
88   std::string interval = CmdLineInterval();
89   if (!interval.empty() && base::StringToInt(interval, &interval_ms))
90     return interval_ms * 1000;  // Command line value is in seconds.
91
92   return kCheckForUpgradeMs;
93 }
94
95 // Return true if the current build is one of the unstable channels.
96 bool IsUnstableChannel() {
97   // TODO(mad): Investigate whether we still need to be on the file thread for
98   // this. On Windows, the file thread used to be required for registry access
99   // but no anymore. But other platform may still need the file thread.
100   // crbug.com/366647.
101   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
102   chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
103   return channel == chrome::VersionInfo::CHANNEL_DEV ||
104          channel == chrome::VersionInfo::CHANNEL_CANARY;
105 }
106
107 // This task identifies whether we are running an unstable version. And then it
108 // unconditionally calls back the provided task.
109 void CheckForUnstableChannel(const base::Closure& callback_task,
110                              bool* is_unstable_channel) {
111   *is_unstable_channel = IsUnstableChannel();
112   BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback_task);
113 }
114
115 #if defined(OS_WIN)
116 // Return true if the currently running Chrome is a system install.
117 bool IsSystemInstall() {
118   // Get the version of the currently *installed* instance of Chrome,
119   // which might be newer than the *running* instance if we have been
120   // upgraded in the background.
121   base::FilePath exe_path;
122   if (!PathService::Get(base::DIR_EXE, &exe_path)) {
123     NOTREACHED() << "Failed to find executable path";
124     return false;
125   }
126
127   return !InstallUtil::IsPerUserInstall(exe_path.value().c_str());
128 }
129
130 // This task checks the update policy and calls back the task only if the
131 // system is not enrolled in a domain (i.e., not in an enterprise environment).
132 // It also identifies if autoupdate is enabled and whether we are running an
133 // unstable channel. |is_auto_update_enabled| can be NULL.
134 void DetectUpdatability(const base::Closure& callback_task,
135                         bool* is_unstable_channel,
136                         bool* is_auto_update_enabled) {
137   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
138
139   base::string16 app_guid = installer::GetAppGuidForUpdates(IsSystemInstall());
140   DCHECK(!app_guid.empty());
141   // Don't try to turn on autoupdate when we failed previously.
142   if (is_auto_update_enabled) {
143     *is_auto_update_enabled =
144         GoogleUpdateSettings::AreAutoupdatesEnabled(app_guid);
145   }
146   *is_unstable_channel = IsUnstableChannel();
147   // Don't show the update bubbles to entreprise users (i.e., on a domain).
148   if (!base::win::IsEnrolledToDomain())
149     BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback_task);
150 }
151 #endif  // defined(OS_WIN)
152
153 }  // namespace
154
155 UpgradeDetectorImpl::UpgradeDetectorImpl()
156     : weak_factory_(this),
157       is_unstable_channel_(false),
158       is_auto_update_enabled_(true),
159       build_date_(base::GetBuildTime()) {
160   CommandLine command_line(*CommandLine::ForCurrentProcess());
161   // The different command line switches that affect testing can't be used
162   // simultaneously, if they do, here's the precedence order, based on the order
163   // of the if statements below:
164   // - kDisableBackgroundNetworking prevents any of the other command line
165   //   switch from being taken into account.
166   // - kSimulateUpgrade supersedes critical or outdated upgrade switches.
167   // - kSimulateCriticalUpdate has precedence over kSimulateOutdated.
168   // - kSimulateOutdatedNoAU has precedence over kSimulateOutdated.
169   // - kSimulateOutdated[NoAu] can work on its own, or with a specified date.
170   if (command_line.HasSwitch(switches::kDisableBackgroundNetworking))
171     return;
172   if (command_line.HasSwitch(switches::kSimulateUpgrade)) {
173     UpgradeDetected(UPGRADE_AVAILABLE_REGULAR);
174     return;
175   }
176   if (command_line.HasSwitch(switches::kSimulateCriticalUpdate)) {
177     UpgradeDetected(UPGRADE_AVAILABLE_CRITICAL);
178     return;
179   }
180   if (SimulatingOutdated()) {
181     // The outdated simulation can work without a value, which means outdated
182     // now, or with a value that must be a well formed date/time string that
183     // overrides the build date.
184     // Also note that to test with a given time/date, until the network time
185     // tracking moves off of the VariationsService, the "variations-server-url"
186     // command line switch must also be specified for the service to be
187     // available on non GOOGLE_CHROME_BUILD.
188     std::string switch_name;
189     if (command_line.HasSwitch(switches::kSimulateOutdatedNoAU)) {
190       is_auto_update_enabled_ = false;
191       switch_name = switches::kSimulateOutdatedNoAU;
192     } else {
193       switch_name = switches::kSimulateOutdated;
194     }
195     std::string build_date = command_line.GetSwitchValueASCII(switch_name);
196     base::Time maybe_build_time;
197     bool result = base::Time::FromString(build_date.c_str(), &maybe_build_time);
198     if (result && !maybe_build_time.is_null()) {
199       // We got a valid build date simulation so use it and check for upgrades.
200       build_date_ = maybe_build_time;
201       StartTimerForUpgradeCheck();
202     } else {
203       // Without a valid date, we simulate that we are already outdated...
204       UpgradeDetected(
205           is_auto_update_enabled_ ? UPGRADE_NEEDED_OUTDATED_INSTALL
206                                   : UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU);
207     }
208     return;
209   }
210
211   base::Closure start_upgrade_check_timer_task =
212       base::Bind(&UpgradeDetectorImpl::StartTimerForUpgradeCheck,
213                  weak_factory_.GetWeakPtr());
214
215 #if defined(OS_WIN)
216   // Only enable upgrade notifications for official builds.  Chromium has no
217   // upgrade channel.
218 #if defined(GOOGLE_CHROME_BUILD)
219   // On Windows, there might be a policy/enterprise environment preventing
220   // updates, so validate updatability, and then call StartTimerForUpgradeCheck
221   // appropriately. And don't check for autoupdate if we already attempted to
222   // enable it in the past.
223   bool attempted_enabling_autoupdate = g_browser_process->local_state() &&
224       g_browser_process->local_state()->GetBoolean(
225           prefs::kAttemptedToEnableAutoupdate);
226   BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
227                           base::Bind(&DetectUpdatability,
228                                      start_upgrade_check_timer_task,
229                                      &is_unstable_channel_,
230                                      attempted_enabling_autoupdate ?
231                                          NULL : &is_auto_update_enabled_));
232 #endif
233 #else
234 #if defined(OS_MACOSX)
235   // Only enable upgrade notifications if the updater (Keystone) is present.
236   if (!keystone_glue::KeystoneEnabled()) {
237     is_auto_update_enabled_ = false;
238     return;
239   }
240 #elif defined(OS_POSIX)
241   // Always enable upgrade notifications regardless of branding.
242 #else
243   return;
244 #endif
245   // Check whether the build is an unstable channel before starting the timer.
246   BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
247                           base::Bind(&CheckForUnstableChannel,
248                                      start_upgrade_check_timer_task,
249                                      &is_unstable_channel_));
250 #endif
251   // Start tracking network time updates.
252   network_time_tracker_.Start();
253 }
254
255 UpgradeDetectorImpl::~UpgradeDetectorImpl() {
256 }
257
258 // Static
259 // This task checks the currently running version of Chrome against the
260 // installed version. If the installed version is newer, it calls back
261 // UpgradeDetectorImpl::UpgradeDetected using a weak pointer so that it can
262 // be interrupted from the UI thread.
263 void UpgradeDetectorImpl::DetectUpgradeTask(
264     base::WeakPtr<UpgradeDetectorImpl> upgrade_detector) {
265   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
266
267   Version installed_version;
268   Version critical_update;
269
270 #if defined(OS_WIN)
271   // Get the version of the currently *installed* instance of Chrome,
272   // which might be newer than the *running* instance if we have been
273   // upgraded in the background.
274   bool system_install = IsSystemInstall();
275
276   // TODO(tommi): Check if using the default distribution is always the right
277   // thing to do.
278   BrowserDistribution* dist = BrowserDistribution::GetDistribution();
279   InstallUtil::GetChromeVersion(dist, system_install, &installed_version);
280
281   if (installed_version.IsValid()) {
282     InstallUtil::GetCriticalUpdateVersion(dist, system_install,
283                                           &critical_update);
284   }
285 #elif defined(OS_MACOSX)
286   installed_version =
287       Version(base::UTF16ToASCII(keystone_glue::CurrentlyInstalledVersion()));
288 #elif defined(OS_POSIX)
289   // POSIX but not Mac OS X: Linux, etc.
290   CommandLine command_line(*CommandLine::ForCurrentProcess());
291   command_line.AppendSwitch(switches::kProductVersion);
292   std::string reply;
293   if (!base::GetAppOutput(command_line, &reply)) {
294     DLOG(ERROR) << "Failed to get current file version";
295     return;
296   }
297
298   installed_version = Version(reply);
299 #endif
300
301   // Get the version of the currently *running* instance of Chrome.
302   chrome::VersionInfo version_info;
303   if (!version_info.is_valid()) {
304     NOTREACHED() << "Failed to get current file version";
305     return;
306   }
307   Version running_version(version_info.Version());
308   if (!running_version.IsValid()) {
309     NOTREACHED();
310     return;
311   }
312
313   // |installed_version| may be NULL when the user downgrades on Linux (by
314   // switching from dev to beta channel, for example). The user needs a
315   // restart in this case as well. See http://crbug.com/46547
316   if (!installed_version.IsValid() ||
317       (installed_version.CompareTo(running_version) > 0)) {
318     // If a more recent version is available, it might be that we are lacking
319     // a critical update, such as a zero-day fix.
320     UpgradeAvailable upgrade_available = UPGRADE_AVAILABLE_REGULAR;
321     if (critical_update.IsValid() &&
322         critical_update.CompareTo(running_version) > 0) {
323       upgrade_available = UPGRADE_AVAILABLE_CRITICAL;
324     }
325
326     // Fire off the upgrade detected task.
327     BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
328                             base::Bind(&UpgradeDetectorImpl::UpgradeDetected,
329                                        upgrade_detector,
330                                        upgrade_available));
331   }
332 }
333
334 void UpgradeDetectorImpl::StartTimerForUpgradeCheck() {
335   detect_upgrade_timer_.Start(FROM_HERE,
336       base::TimeDelta::FromMilliseconds(GetCheckForUpgradeEveryMs()),
337       this, &UpgradeDetectorImpl::CheckForUpgrade);
338 }
339
340 void UpgradeDetectorImpl::CheckForUpgrade() {
341   // Interrupt any (unlikely) unfinished execution of DetectUpgradeTask, or at
342   // least prevent the callback from being executed, because we will potentially
343   // call it from within DetectOutdatedInstall() or will post
344   // DetectUpgradeTask again below anyway.
345   weak_factory_.InvalidateWeakPtrs();
346
347   // No need to look for upgrades if the install is outdated.
348   if (DetectOutdatedInstall())
349     return;
350
351   // We use FILE as the thread to run the upgrade detection code on all
352   // platforms. For Linux, this is because we don't want to block the UI thread
353   // while launching a background process and reading its output; on the Mac and
354   // on Windows checking for an upgrade requires reading a file.
355   BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
356                           base::Bind(&UpgradeDetectorImpl::DetectUpgradeTask,
357                                      weak_factory_.GetWeakPtr()));
358 }
359
360 bool UpgradeDetectorImpl::DetectOutdatedInstall() {
361   // Don't show the bubble if we have a brand code that is NOT organic, unless
362   // an outdated build is being simulated by command line switches.
363   static bool simulate_outdated = SimulatingOutdated();
364   if (!simulate_outdated) {
365     std::string brand;
366     if (google_util::GetBrand(&brand) && !google_util::IsOrganic(brand))
367       return false;
368
369 #if defined(OS_WIN)
370     // On Windows, we don't want to warn about outdated installs when the
371     // machine doesn't support SSE2, it's been deprecated starting with M35.
372     if (!base::CPU().has_sse2())
373       return false;
374 #endif
375   }
376
377   base::Time network_time;
378   base::TimeDelta uncertainty;
379   if (!network_time_tracker_.GetNetworkTime(base::TimeTicks::Now(),
380                                             &network_time,
381                                             &uncertainty)) {
382     // When network time has not been initialized yet, simply rely on the
383     // machine's current time.
384     network_time = base::Time::Now();
385   }
386
387   if (network_time.is_null() || build_date_.is_null() ||
388       build_date_ > network_time) {
389     NOTREACHED();
390     return false;
391   }
392
393   if (network_time - build_date_ >
394       base::TimeDelta::FromDays(kOutdatedBuildAgeInDays)) {
395     UpgradeDetected(is_auto_update_enabled_ ?
396         UPGRADE_NEEDED_OUTDATED_INSTALL :
397         UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU);
398     return true;
399   }
400   // If we simlated an outdated install with a date, we don't want to keep
401   // checking for version upgrades, which happens on non-official builds.
402   return simulate_outdated;
403 }
404
405 void UpgradeDetectorImpl::UpgradeDetected(UpgradeAvailable upgrade_available) {
406   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
407   upgrade_available_ = upgrade_available;
408
409   // Stop the recurring timer (that is checking for changes).
410   detect_upgrade_timer_.Stop();
411
412   NotifyUpgradeDetected();
413
414   // Start the repeating timer for notifying the user after a certain period.
415   // The called function will eventually figure out that enough time has passed
416   // and stop the timer.
417   int cycle_time = IsTesting() ?
418       kNotifyCycleTimeForTestingMs : kNotifyCycleTimeMs;
419   upgrade_notification_timer_.Start(FROM_HERE,
420       base::TimeDelta::FromMilliseconds(cycle_time),
421       this, &UpgradeDetectorImpl::NotifyOnUpgrade);
422 }
423
424 void UpgradeDetectorImpl::NotifyOnUpgrade() {
425   base::TimeDelta delta = base::Time::Now() - upgrade_detected_time();
426
427   // We'll make testing more convenient by switching to seconds of waiting
428   // instead of days between flipping severity.
429   bool is_testing = IsTesting();
430   int64 time_passed = is_testing ? delta.InSeconds() : delta.InHours();
431
432   bool is_critical_or_outdated = upgrade_available_ > UPGRADE_AVAILABLE_REGULAR;
433   if (is_unstable_channel_) {
434     // There's only one threat level for unstable channels like dev and
435     // canary, and it hits after one hour. During testing, it hits after one
436     // second.
437     const int kUnstableThreshold = 1;
438
439     if (is_critical_or_outdated)
440       set_upgrade_notification_stage(UPGRADE_ANNOYANCE_CRITICAL);
441     else if (time_passed >= kUnstableThreshold) {
442       set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW);
443
444       // That's as high as it goes.
445       upgrade_notification_timer_.Stop();
446     } else {
447       return;  // Not ready to recommend upgrade.
448     }
449   } else {
450     const int kMultiplier = is_testing ? 10 : 24;
451     // 14 days when not testing, otherwise 14 seconds.
452     const int kSevereThreshold = 14 * kMultiplier;
453     const int kHighThreshold = 7 * kMultiplier;
454     const int kElevatedThreshold = 4 * kMultiplier;
455     const int kLowThreshold = 2 * kMultiplier;
456
457     // These if statements must be sorted (highest interval first).
458     if (time_passed >= kSevereThreshold || is_critical_or_outdated) {
459       set_upgrade_notification_stage(
460           is_critical_or_outdated ? UPGRADE_ANNOYANCE_CRITICAL :
461                                     UPGRADE_ANNOYANCE_SEVERE);
462
463       // We can't get any higher, baby.
464       upgrade_notification_timer_.Stop();
465     } else if (time_passed >= kHighThreshold) {
466       set_upgrade_notification_stage(UPGRADE_ANNOYANCE_HIGH);
467     } else if (time_passed >= kElevatedThreshold) {
468       set_upgrade_notification_stage(UPGRADE_ANNOYANCE_ELEVATED);
469     } else if (time_passed >= kLowThreshold) {
470       set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW);
471     } else {
472       return;  // Not ready to recommend upgrade.
473     }
474   }
475
476   NotifyUpgradeRecommended();
477 }
478
479 // static
480 UpgradeDetectorImpl* UpgradeDetectorImpl::GetInstance() {
481   return Singleton<UpgradeDetectorImpl>::get();
482 }
483
484 // static
485 UpgradeDetector* UpgradeDetector::GetInstance() {
486   return UpgradeDetectorImpl::GetInstance();
487 }