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