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