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