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"
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"
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"
40 using content::BrowserThread
;
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
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.
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
) ||
82 // How often to check for an upgrade.
83 int GetCheckForUpgradeEveryMs() {
84 // Check for a value passed via the command line.
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.
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
);
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";
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
;
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
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
,
169 #elif defined(OS_MACOSX)
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
);
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
);
184 return installed_version
;
189 UpgradeDetectorImpl::UpgradeDetectorImpl()
190 : is_unstable_channel_(false),
191 is_auto_update_enabled_(true),
192 build_date_(base::GetBuildTime()),
193 weak_factory_(this) {
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
))
206 if (command_line
.HasSwitch(switches::kSimulateUpgrade
)) {
207 UpgradeDetected(UPGRADE_AVAILABLE_REGULAR
);
210 if (command_line
.HasSwitch(switches::kSimulateCriticalUpdate
)) {
211 UpgradeDetected(UPGRADE_AVAILABLE_CRITICAL
);
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
;
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();
237 // Without a valid date, we simulate that we are already outdated...
239 is_auto_update_enabled_
? UPGRADE_NEEDED_OUTDATED_INSTALL
240 : UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU
);
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());
258 // Only enable upgrade notifications for official builds. Chromium has no
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_
));
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;
282 #elif defined(OS_POSIX)
283 // Always enable upgrade notifications regardless of branding.
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_
));
295 UpgradeDetectorImpl::~UpgradeDetectorImpl() {
299 base::Version
UpgradeDetectorImpl::GetCurrentlyInstalledVersion() {
300 return GetCurrentlyInstalledVersionImpl(NULL
);
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 Version
running_version(version_info
.Version());
319 if (!running_version
.IsValid()) {
324 // |installed_version| may be NULL when the user downgrades on Linux (by
325 // switching from dev to beta channel, for example). The user needs a
326 // restart in this case as well. See http://crbug.com/46547
327 if (!installed_version
.IsValid() ||
328 (installed_version
.CompareTo(running_version
) > 0)) {
329 // If a more recent version is available, it might be that we are lacking
330 // a critical update, such as a zero-day fix.
331 UpgradeAvailable upgrade_available
= UPGRADE_AVAILABLE_REGULAR
;
332 if (critical_update
.IsValid() &&
333 critical_update
.CompareTo(running_version
) > 0) {
334 upgrade_available
= UPGRADE_AVAILABLE_CRITICAL
;
337 // Fire off the upgrade detected task.
338 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
,
339 base::Bind(&UpgradeDetectorImpl::UpgradeDetected
,
345 void UpgradeDetectorImpl::StartTimerForUpgradeCheck() {
346 detect_upgrade_timer_
.Start(FROM_HERE
,
347 base::TimeDelta::FromMilliseconds(GetCheckForUpgradeEveryMs()),
348 this, &UpgradeDetectorImpl::CheckForUpgrade
);
351 void UpgradeDetectorImpl::StartUpgradeNotificationTimer() {
352 // The timer may already be running (e.g. due to both a software upgrade and
353 // experiment updates being available).
354 if (upgrade_notification_timer_
.IsRunning())
357 upgrade_detected_time_
= base::TimeTicks::Now();
359 // Start the repeating timer for notifying the user after a certain period.
360 // The called function will eventually figure out that enough time has passed
361 // and stop the timer.
362 const int cycle_time_ms
= IsTesting() ?
363 kNotifyCycleTimeForTestingMs
: kNotifyCycleTimeMs
;
364 upgrade_notification_timer_
.Start(FROM_HERE
,
365 base::TimeDelta::FromMilliseconds(cycle_time_ms
),
366 this, &UpgradeDetectorImpl::NotifyOnUpgrade
);
369 void UpgradeDetectorImpl::CheckForUpgrade() {
370 // Interrupt any (unlikely) unfinished execution of DetectUpgradeTask, or at
371 // least prevent the callback from being executed, because we will potentially
372 // call it from within DetectOutdatedInstall() or will post
373 // DetectUpgradeTask again below anyway.
374 weak_factory_
.InvalidateWeakPtrs();
376 // No need to look for upgrades if the install is outdated.
377 if (DetectOutdatedInstall())
380 // We use FILE as the thread to run the upgrade detection code on all
381 // platforms. For Linux, this is because we don't want to block the UI thread
382 // while launching a background process and reading its output; on the Mac and
383 // on Windows checking for an upgrade requires reading a file.
384 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
385 base::Bind(&UpgradeDetectorImpl::DetectUpgradeTask
,
386 weak_factory_
.GetWeakPtr()));
389 bool UpgradeDetectorImpl::DetectOutdatedInstall() {
390 // Don't show the bubble if we have a brand code that is NOT organic, unless
391 // an outdated build is being simulated by command line switches.
392 static bool simulate_outdated
= SimulatingOutdated();
393 if (!simulate_outdated
) {
395 if (google_brand::GetBrand(&brand
) && !google_brand::IsOrganic(brand
))
399 // Don't show the update bubbles to enterprise users (i.e., on a domain).
400 if (base::win::IsEnrolledToDomain())
405 base::Time network_time
;
406 base::TimeDelta uncertainty
;
407 if (!g_browser_process
->network_time_tracker()->GetNetworkTime(
408 base::TimeTicks::Now(), &network_time
, &uncertainty
)) {
409 // When network time has not been initialized yet, simply rely on the
410 // machine's current time.
411 network_time
= base::Time::Now();
414 if (network_time
.is_null() || build_date_
.is_null() ||
415 build_date_
> network_time
) {
420 if (network_time
- build_date_
>
421 base::TimeDelta::FromDays(kOutdatedBuildAgeInDays
)) {
422 UpgradeDetected(is_auto_update_enabled_
?
423 UPGRADE_NEEDED_OUTDATED_INSTALL
:
424 UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU
);
427 // If we simlated an outdated install with a date, we don't want to keep
428 // checking for version upgrades, which happens on non-official builds.
429 return simulate_outdated
;
432 void UpgradeDetectorImpl::OnExperimentChangesDetected(Severity severity
) {
433 set_best_effort_experiment_updates_available(severity
== BEST_EFFORT
);
434 set_critical_experiment_updates_available(severity
== CRITICAL
);
435 StartUpgradeNotificationTimer();
438 void UpgradeDetectorImpl::UpgradeDetected(UpgradeAvailable upgrade_available
) {
439 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
440 set_upgrade_available(upgrade_available
);
442 // Stop the recurring timer (that is checking for changes).
443 detect_upgrade_timer_
.Stop();
444 set_critical_update_acknowledged(false);
446 StartUpgradeNotificationTimer();
449 void UpgradeDetectorImpl::NotifyOnUpgradeWithTimePassed(
450 base::TimeDelta time_passed
) {
451 const bool is_critical_or_outdated
=
452 upgrade_available() > UPGRADE_AVAILABLE_REGULAR
||
453 critical_experiment_updates_available();
454 if (is_unstable_channel_
) {
455 // There's only one threat level for unstable channels like dev and
456 // canary, and it hits after one hour. During testing, it hits after one
458 const base::TimeDelta unstable_threshold
= IsTesting() ?
459 base::TimeDelta::FromSeconds(1) : base::TimeDelta::FromHours(1);
461 if (is_critical_or_outdated
) {
462 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_CRITICAL
);
463 } else if (time_passed
>= unstable_threshold
) {
464 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW
);
466 // That's as high as it goes.
467 upgrade_notification_timer_
.Stop();
469 return; // Not ready to recommend upgrade.
472 const base::TimeDelta multiplier
= IsTesting() ?
473 base::TimeDelta::FromSeconds(10) : base::TimeDelta::FromDays(1);
475 // 14 days when not testing, otherwise 140 seconds.
476 const base::TimeDelta severe_threshold
= 14 * multiplier
;
477 const base::TimeDelta high_threshold
= 7 * multiplier
;
478 const base::TimeDelta elevated_threshold
= 4 * multiplier
;
479 const base::TimeDelta low_threshold
= 2 * multiplier
;
481 // These if statements must be sorted (highest interval first).
482 if (time_passed
>= severe_threshold
|| is_critical_or_outdated
) {
483 set_upgrade_notification_stage(
484 is_critical_or_outdated
? UPGRADE_ANNOYANCE_CRITICAL
:
485 UPGRADE_ANNOYANCE_SEVERE
);
487 // We can't get any higher, baby.
488 upgrade_notification_timer_
.Stop();
489 } else if (time_passed
>= high_threshold
) {
490 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_HIGH
);
491 } else if (time_passed
>= elevated_threshold
) {
492 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_ELEVATED
);
493 } else if (time_passed
>= low_threshold
) {
494 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW
);
496 return; // Not ready to recommend upgrade.
500 NotifyUpgradeRecommended();
503 void UpgradeDetectorImpl::NotifyOnUpgrade() {
504 const base::TimeDelta time_passed
=
505 base::TimeTicks::Now() - upgrade_detected_time_
;
506 NotifyOnUpgradeWithTimePassed(time_passed
);
510 UpgradeDetectorImpl
* UpgradeDetectorImpl::GetInstance() {
511 return Singleton
<UpgradeDetectorImpl
>::get();
515 UpgradeDetector
* UpgradeDetector::GetInstance() {
516 return UpgradeDetectorImpl::GetInstance();