Clean OmniboxEditModel of remaining //content dependencies
[chromium-blink-merge.git] / chrome / browser / upgrade_detector_impl.cc
blob1370b5a9342b232bce540b75dd8877714fccae42
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 base::CommandLine& cmd_line = *base::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 base::CommandLine& cmd_line = *base::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 base::CommandLine& cmd_line = *base::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 #if !defined(OS_WIN) || defined(GOOGLE_CHROME_BUILD)
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 version_info::Channel channel = chrome::VersionInfo::GetChannel();
102 return channel == version_info::Channel::DEV ||
103 channel == version_info::Channel::CANARY;
105 #endif // !defined(OS_WIN) || defined(GOOGLE_CHROME_BUILD)
107 #if !defined(OS_WIN)
108 // This task identifies whether we are running an unstable version. And then it
109 // unconditionally calls back the provided task.
110 void CheckForUnstableChannel(const base::Closure& callback_task,
111 bool* is_unstable_channel) {
112 *is_unstable_channel = IsUnstableChannel();
113 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback_task);
115 #else
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;
127 return !InstallUtil::IsPerUserInstall(exe_path);
130 #if defined(GOOGLE_CHROME_BUILD)
131 // Sets |is_unstable_channel| to true if the current chrome is on the dev or
132 // canary channels. Sets |is_auto_update_enabled| to true if Google Update will
133 // update the current chrome. Unconditionally posts |callback_task| to the UI
134 // thread to continue processing.
135 void DetectUpdatability(const base::Closure& callback_task,
136 bool* is_unstable_channel,
137 bool* is_auto_update_enabled) {
138 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
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();
145 *is_unstable_channel = IsUnstableChannel();
146 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback_task);
148 #endif // defined(GOOGLE_CHROME_BUILD)
149 #endif // !defined(OS_WIN)
151 // Gets the currently installed version. On Windows, if |critical_update| is not
152 // NULL, also retrieves the critical update version info if available.
153 base::Version GetCurrentlyInstalledVersionImpl(Version* critical_update) {
154 base::ThreadRestrictions::AssertIOAllowed();
156 Version installed_version;
157 #if defined(OS_WIN)
158 // Get the version of the currently *installed* instance of Chrome,
159 // which might be newer than the *running* instance if we have been
160 // upgraded in the background.
161 bool system_install = IsSystemInstall();
163 // TODO(tommi): Check if using the default distribution is always the right
164 // thing to do.
165 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
166 InstallUtil::GetChromeVersion(dist, system_install, &installed_version);
167 if (critical_update && installed_version.IsValid()) {
168 InstallUtil::GetCriticalUpdateVersion(dist, system_install,
169 critical_update);
171 #elif defined(OS_MACOSX)
172 installed_version =
173 Version(base::UTF16ToASCII(keystone_glue::CurrentlyInstalledVersion()));
174 #elif defined(OS_POSIX)
175 // POSIX but not Mac OS X: Linux, etc.
176 base::CommandLine command_line(*base::CommandLine::ForCurrentProcess());
177 command_line.AppendSwitch(switches::kProductVersion);
178 std::string reply;
179 if (!base::GetAppOutput(command_line, &reply)) {
180 DLOG(ERROR) << "Failed to get current file version";
181 return installed_version;
183 base::TrimWhitespaceASCII(reply, base::TRIM_ALL, &reply);
185 installed_version = Version(reply);
186 #endif
187 return installed_version;
190 } // namespace
192 UpgradeDetectorImpl::UpgradeDetectorImpl()
193 : is_unstable_channel_(false),
194 is_auto_update_enabled_(true),
195 build_date_(base::GetBuildTime()),
196 weak_factory_(this) {
197 base::CommandLine command_line(*base::CommandLine::ForCurrentProcess());
198 // The different command line switches that affect testing can't be used
199 // simultaneously, if they do, here's the precedence order, based on the order
200 // of the if statements below:
201 // - kDisableBackgroundNetworking prevents any of the other command line
202 // switch from being taken into account.
203 // - kSimulateUpgrade supersedes critical or outdated upgrade switches.
204 // - kSimulateCriticalUpdate has precedence over kSimulateOutdated.
205 // - kSimulateOutdatedNoAU has precedence over kSimulateOutdated.
206 // - kSimulateOutdated[NoAu] can work on its own, or with a specified date.
207 if (command_line.HasSwitch(switches::kDisableBackgroundNetworking))
208 return;
209 if (command_line.HasSwitch(switches::kSimulateUpgrade)) {
210 UpgradeDetected(UPGRADE_AVAILABLE_REGULAR);
211 return;
213 if (command_line.HasSwitch(switches::kSimulateCriticalUpdate)) {
214 UpgradeDetected(UPGRADE_AVAILABLE_CRITICAL);
215 return;
217 if (SimulatingOutdated()) {
218 // The outdated simulation can work without a value, which means outdated
219 // now, or with a value that must be a well formed date/time string that
220 // overrides the build date.
221 // Also note that to test with a given time/date, until the network time
222 // tracking moves off of the VariationsService, the "variations-server-url"
223 // command line switch must also be specified for the service to be
224 // available on non GOOGLE_CHROME_BUILD.
225 std::string switch_name;
226 if (command_line.HasSwitch(switches::kSimulateOutdatedNoAU)) {
227 is_auto_update_enabled_ = false;
228 switch_name = switches::kSimulateOutdatedNoAU;
229 } else {
230 switch_name = switches::kSimulateOutdated;
232 std::string build_date = command_line.GetSwitchValueASCII(switch_name);
233 base::Time maybe_build_time;
234 bool result = base::Time::FromString(build_date.c_str(), &maybe_build_time);
235 if (result && !maybe_build_time.is_null()) {
236 // We got a valid build date simulation so use it and check for upgrades.
237 build_date_ = maybe_build_time;
238 StartTimerForUpgradeCheck();
239 } else {
240 // Without a valid date, we simulate that we are already outdated...
241 UpgradeDetected(
242 is_auto_update_enabled_ ? UPGRADE_NEEDED_OUTDATED_INSTALL
243 : UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU);
245 return;
248 // Register for experiment notifications. Note that since this class is a
249 // singleton, it does not need to unregister for notifications when destroyed,
250 // since it outlives the VariationsService.
251 chrome_variations::VariationsService* variations_service =
252 g_browser_process->variations_service();
253 if (variations_service)
254 variations_service->AddObserver(this);
256 base::Closure start_upgrade_check_timer_task =
257 base::Bind(&UpgradeDetectorImpl::StartTimerForUpgradeCheck,
258 weak_factory_.GetWeakPtr());
260 #if defined(OS_WIN)
261 // Only enable upgrade notifications for official builds. Chromium has no
262 // upgrade channel.
263 #if defined(GOOGLE_CHROME_BUILD)
264 // On Windows, there might be a policy/enterprise environment preventing
265 // updates, so validate updatability, and then call StartTimerForUpgradeCheck
266 // appropriately. And don't check for autoupdate if we already attempted to
267 // enable it in the past.
268 bool attempted_enabling_autoupdate = g_browser_process->local_state() &&
269 g_browser_process->local_state()->GetBoolean(
270 prefs::kAttemptedToEnableAutoupdate);
271 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
272 base::Bind(&DetectUpdatability,
273 start_upgrade_check_timer_task,
274 &is_unstable_channel_,
275 attempted_enabling_autoupdate ?
276 NULL : &is_auto_update_enabled_));
277 #endif
278 #else
279 #if defined(OS_MACOSX)
280 // Only enable upgrade notifications if the updater (Keystone) is present.
281 if (!keystone_glue::KeystoneEnabled()) {
282 is_auto_update_enabled_ = false;
283 return;
285 #elif defined(OS_POSIX)
286 // Always enable upgrade notifications regardless of branding.
287 #else
288 return;
289 #endif
290 // Check whether the build is an unstable channel before starting the timer.
291 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
292 base::Bind(&CheckForUnstableChannel,
293 start_upgrade_check_timer_task,
294 &is_unstable_channel_));
295 #endif
298 UpgradeDetectorImpl::~UpgradeDetectorImpl() {
301 // static
302 base::Version UpgradeDetectorImpl::GetCurrentlyInstalledVersion() {
303 return GetCurrentlyInstalledVersionImpl(NULL);
306 // static
307 // This task checks the currently running version of Chrome against the
308 // installed version. If the installed version is newer, it calls back
309 // UpgradeDetectorImpl::UpgradeDetected using a weak pointer so that it can
310 // be interrupted from the UI thread.
311 void UpgradeDetectorImpl::DetectUpgradeTask(
312 base::WeakPtr<UpgradeDetectorImpl> upgrade_detector) {
313 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
315 Version critical_update;
316 Version installed_version =
317 GetCurrentlyInstalledVersionImpl(&critical_update);
319 // Get the version of the currently *running* instance of Chrome.
320 chrome::VersionInfo version_info;
321 Version running_version(version_info.Version());
322 if (!running_version.IsValid()) {
323 NOTREACHED();
324 return;
327 // |installed_version| may be NULL when the user downgrades on Linux (by
328 // switching from dev to beta channel, for example). The user needs a
329 // restart in this case as well. See http://crbug.com/46547
330 if (!installed_version.IsValid() ||
331 (installed_version.CompareTo(running_version) > 0)) {
332 // If a more recent version is available, it might be that we are lacking
333 // a critical update, such as a zero-day fix.
334 UpgradeAvailable upgrade_available = UPGRADE_AVAILABLE_REGULAR;
335 if (critical_update.IsValid() &&
336 critical_update.CompareTo(running_version) > 0) {
337 upgrade_available = UPGRADE_AVAILABLE_CRITICAL;
340 // Fire off the upgrade detected task.
341 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
342 base::Bind(&UpgradeDetectorImpl::UpgradeDetected,
343 upgrade_detector,
344 upgrade_available));
348 void UpgradeDetectorImpl::StartTimerForUpgradeCheck() {
349 detect_upgrade_timer_.Start(FROM_HERE,
350 base::TimeDelta::FromMilliseconds(GetCheckForUpgradeEveryMs()),
351 this, &UpgradeDetectorImpl::CheckForUpgrade);
354 void UpgradeDetectorImpl::StartUpgradeNotificationTimer() {
355 // The timer may already be running (e.g. due to both a software upgrade and
356 // experiment updates being available).
357 if (upgrade_notification_timer_.IsRunning())
358 return;
360 upgrade_detected_time_ = base::TimeTicks::Now();
362 // Start the repeating timer for notifying the user after a certain period.
363 // The called function will eventually figure out that enough time has passed
364 // and stop the timer.
365 const int cycle_time_ms = IsTesting() ?
366 kNotifyCycleTimeForTestingMs : kNotifyCycleTimeMs;
367 upgrade_notification_timer_.Start(FROM_HERE,
368 base::TimeDelta::FromMilliseconds(cycle_time_ms),
369 this, &UpgradeDetectorImpl::NotifyOnUpgrade);
372 void UpgradeDetectorImpl::CheckForUpgrade() {
373 // Interrupt any (unlikely) unfinished execution of DetectUpgradeTask, or at
374 // least prevent the callback from being executed, because we will potentially
375 // call it from within DetectOutdatedInstall() or will post
376 // DetectUpgradeTask again below anyway.
377 weak_factory_.InvalidateWeakPtrs();
379 // No need to look for upgrades if the install is outdated.
380 if (DetectOutdatedInstall())
381 return;
383 // We use FILE as the thread to run the upgrade detection code on all
384 // platforms. For Linux, this is because we don't want to block the UI thread
385 // while launching a background process and reading its output; on the Mac and
386 // on Windows checking for an upgrade requires reading a file.
387 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
388 base::Bind(&UpgradeDetectorImpl::DetectUpgradeTask,
389 weak_factory_.GetWeakPtr()));
392 bool UpgradeDetectorImpl::DetectOutdatedInstall() {
393 // Don't show the bubble if we have a brand code that is NOT organic, unless
394 // an outdated build is being simulated by command line switches.
395 static bool simulate_outdated = SimulatingOutdated();
396 if (!simulate_outdated) {
397 std::string brand;
398 if (google_brand::GetBrand(&brand) && !google_brand::IsOrganic(brand))
399 return false;
401 #if defined(OS_WIN)
402 // Don't show the update bubbles to enterprise users (i.e., on a domain).
403 if (base::win::IsEnrolledToDomain())
404 return false;
405 #endif
408 base::Time network_time;
409 base::TimeDelta uncertainty;
410 if (!g_browser_process->network_time_tracker()->GetNetworkTime(
411 base::TimeTicks::Now(), &network_time, &uncertainty)) {
412 // When network time has not been initialized yet, simply rely on the
413 // machine's current time.
414 network_time = base::Time::Now();
417 if (network_time.is_null() || build_date_.is_null() ||
418 build_date_ > network_time) {
419 NOTREACHED();
420 return false;
423 if (network_time - build_date_ >
424 base::TimeDelta::FromDays(kOutdatedBuildAgeInDays)) {
425 UpgradeDetected(is_auto_update_enabled_ ?
426 UPGRADE_NEEDED_OUTDATED_INSTALL :
427 UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU);
428 return true;
430 // If we simlated an outdated install with a date, we don't want to keep
431 // checking for version upgrades, which happens on non-official builds.
432 return simulate_outdated;
435 void UpgradeDetectorImpl::OnExperimentChangesDetected(Severity severity) {
436 set_best_effort_experiment_updates_available(severity == BEST_EFFORT);
437 set_critical_experiment_updates_available(severity == CRITICAL);
438 StartUpgradeNotificationTimer();
441 void UpgradeDetectorImpl::UpgradeDetected(UpgradeAvailable upgrade_available) {
442 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
443 set_upgrade_available(upgrade_available);
445 // Stop the recurring timer (that is checking for changes).
446 detect_upgrade_timer_.Stop();
447 set_critical_update_acknowledged(false);
449 StartUpgradeNotificationTimer();
452 void UpgradeDetectorImpl::NotifyOnUpgradeWithTimePassed(
453 base::TimeDelta time_passed) {
454 const bool is_critical_or_outdated =
455 upgrade_available() > UPGRADE_AVAILABLE_REGULAR ||
456 critical_experiment_updates_available();
457 if (is_unstable_channel_) {
458 // There's only one threat level for unstable channels like dev and
459 // canary, and it hits after one hour. During testing, it hits after one
460 // second.
461 const base::TimeDelta unstable_threshold = IsTesting() ?
462 base::TimeDelta::FromSeconds(1) : base::TimeDelta::FromHours(1);
464 if (is_critical_or_outdated) {
465 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_CRITICAL);
466 } else if (time_passed >= unstable_threshold) {
467 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW);
469 // That's as high as it goes.
470 upgrade_notification_timer_.Stop();
471 } else {
472 return; // Not ready to recommend upgrade.
474 } else {
475 const base::TimeDelta multiplier = IsTesting() ?
476 base::TimeDelta::FromSeconds(10) : base::TimeDelta::FromDays(1);
478 // 14 days when not testing, otherwise 140 seconds.
479 const base::TimeDelta severe_threshold = 14 * multiplier;
480 const base::TimeDelta high_threshold = 7 * multiplier;
481 const base::TimeDelta elevated_threshold = 4 * multiplier;
482 const base::TimeDelta low_threshold = 2 * multiplier;
484 // These if statements must be sorted (highest interval first).
485 if (time_passed >= severe_threshold || is_critical_or_outdated) {
486 set_upgrade_notification_stage(
487 is_critical_or_outdated ? UPGRADE_ANNOYANCE_CRITICAL :
488 UPGRADE_ANNOYANCE_SEVERE);
490 // We can't get any higher, baby.
491 upgrade_notification_timer_.Stop();
492 } else if (time_passed >= high_threshold) {
493 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_HIGH);
494 } else if (time_passed >= elevated_threshold) {
495 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_ELEVATED);
496 } else if (time_passed >= low_threshold) {
497 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW);
498 } else {
499 return; // Not ready to recommend upgrade.
503 NotifyUpgradeRecommended();
506 void UpgradeDetectorImpl::NotifyOnUpgrade() {
507 const base::TimeDelta time_passed =
508 base::TimeTicks::Now() - upgrade_detected_time_;
509 NotifyOnUpgradeWithTimePassed(time_passed);
512 // static
513 UpgradeDetectorImpl* UpgradeDetectorImpl::GetInstance() {
514 return Singleton<UpgradeDetectorImpl>::get();
517 // static
518 UpgradeDetector* UpgradeDetector::GetInstance() {
519 return UpgradeDetectorImpl::GetInstance();