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/metrics/field_trial.h"
16 #include "base/path_service.h"
17 #include "base/string_util.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/time.h"
20 #include "base/utf_string_conversions.h"
21 #include "base/version.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/google/google_util.h"
24 #include "chrome/browser/metrics/variations/variations_service.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/common/chrome_version_info.h"
27 #include "content/public/browser/browser_thread.h"
28 #include "ui/base/resource/resource_bundle.h"
31 #include "chrome/installer/util/browser_distribution.h"
32 #include "chrome/installer/util/google_update_settings.h"
33 #include "chrome/installer/util/helper.h"
34 #include "chrome/installer/util/install_util.h"
35 #elif defined(OS_MACOSX)
36 #include "chrome/browser/mac/keystone_glue.h"
37 #elif defined(OS_POSIX)
38 #include "base/process_util.h"
41 using content::BrowserThread
;
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.
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.
53 // Same as kNotifyCycleTimeMs but only used during testing.
54 const int kNotifyCycleTimeForTestingMs
= 500; // Half a second.
56 // The number of days after which we identify a build/install as outdated.
57 const uint64 kOutdatedBuildAgeInDays
= 12 * 7;
59 // Finch Experiment strings to identify if we should check for outdated install.
60 const char kOutdatedInstallCheckTrialName
[] = "OutdatedInstallCheck";
61 const char kOutdatedInstallCheck12WeeksGroupName
[] = "12WeeksOutdatedInstall";
63 std::string
CmdLineInterval() {
64 const CommandLine
& cmd_line
= *CommandLine::ForCurrentProcess();
65 return cmd_line
.GetSwitchValueASCII(switches::kCheckForUpdateIntervalSec
);
69 const CommandLine
& cmd_line
= *CommandLine::ForCurrentProcess();
70 return cmd_line
.HasSwitch(switches::kSimulateUpgrade
) ||
71 cmd_line
.HasSwitch(switches::kCheckForUpdateIntervalSec
) ||
72 cmd_line
.HasSwitch(switches::kSimulateCriticalUpdate
) ||
73 cmd_line
.HasSwitch(switches::kSimulateOutdated
);
76 // How often to check for an upgrade.
77 int GetCheckForUpgradeEveryMs() {
78 // Check for a value passed via the command line.
80 std::string interval
= CmdLineInterval();
81 if (!interval
.empty() && base::StringToInt(interval
, &interval_ms
))
82 return interval_ms
* 1000; // Command line value is in seconds.
84 return kCheckForUpgradeMs
;
87 bool IsUnstableChannel() {
88 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
89 chrome::VersionInfo::Channel channel
= chrome::VersionInfo::GetChannel();
90 return channel
== chrome::VersionInfo::CHANNEL_DEV
||
91 channel
== chrome::VersionInfo::CHANNEL_CANARY
;
94 // This task identifies whether we are running an unstable version. And then
95 // it unconditionally calls back the provided task.
96 void CheckForUnstableChannel(const base::Closure
& callback_task
,
97 bool* is_unstable_channel
) {
98 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
99 *is_unstable_channel
= IsUnstableChannel();
100 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
, callback_task
);
104 bool IsSystemInstall() {
105 // Get the version of the currently *installed* instance of Chrome,
106 // which might be newer than the *running* instance if we have been
107 // upgraded in the background.
108 base::FilePath exe_path
;
109 if (!PathService::Get(base::DIR_EXE
, &exe_path
)) {
110 NOTREACHED() << "Failed to find executable path";
114 return !InstallUtil::IsPerUserInstall(exe_path
.value().c_str());
117 // This task checks the update policy and calls back the task only if automatic
118 // updates are allowed. It also identifies whether we are running an unstable
120 void DetectUpdatability(const base::Closure
& callback_task
,
121 bool* is_unstable_channel
) {
122 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
124 string16 app_guid
= installer::GetAppGuidForUpdates(IsSystemInstall());
125 DCHECK(!app_guid
.empty());
126 if (GoogleUpdateSettings::AUTOMATIC_UPDATES
==
127 GoogleUpdateSettings::GetAppUpdatePolicy(app_guid
, NULL
)) {
128 CheckForUnstableChannel(callback_task
, is_unstable_channel
);
131 #endif // defined(OS_WIN)
135 UpgradeDetectorImpl::UpgradeDetectorImpl()
136 : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
137 is_unstable_channel_(false),
138 build_date_(base::GetBuildTime()) {
139 CommandLine
command_line(*CommandLine::ForCurrentProcess());
140 // The different command line switches that affect testing can't be used
141 // simultaneously, if they do, here's the precedence order, based on the order
142 // of the if statements below:
143 // - kDisableBackgroundNetworking prevents any of the other command line
144 // switch from being taken into account.
145 // - kSimulateUpgrade supersedes critical or outdated upgrade switches.
146 // - kSimulateCriticalUpdate has precedence over kSimulateOutdated.
147 // - kSimulateOutdated can work on its own, or with a specified date.
148 if (command_line
.HasSwitch(switches::kDisableBackgroundNetworking
))
150 if (command_line
.HasSwitch(switches::kSimulateUpgrade
)) {
151 UpgradeDetected(UPGRADE_AVAILABLE_REGULAR
);
154 if (command_line
.HasSwitch(switches::kSimulateCriticalUpdate
)) {
155 UpgradeDetected(UPGRADE_AVAILABLE_CRITICAL
);
158 if (command_line
.HasSwitch(switches::kSimulateOutdated
)) {
159 // The outdated simulation can work without a value, which means outdated
160 // now, or with a value that must be a well formed date/time string that
161 // overrides the build date.
162 // Also note that to test with a given time/date, until the network time
163 // tracking moves off of the VariationsService, the "variations-server-url"
164 // command line switch must also be specified for the service to be
165 // available on non GOOGLE_CHROME_BUILD.
166 std::string build_date
= command_line
.GetSwitchValueASCII(
167 switches::kSimulateOutdated
);
168 base::Time maybe_build_time
;
169 bool result
= base::Time::FromString(build_date
.c_str(), &maybe_build_time
);
170 if (result
&& !maybe_build_time
.is_null()) {
171 // We got a valid build date simulation so use it and check for upgrades.
172 build_date_
= maybe_build_time
;
173 StartTimerForUpgradeCheck();
175 // Without a valid date, we simulate that we are already outdated...
176 UpgradeDetected(UPGRADE_NEEDED_OUTDATED_INSTALL
);
181 // Windows: only enable upgrade notifications for official builds.
182 // Mac: only enable them if the updater (Keystone) is present.
183 // Linux (and other POSIX): always enable regardless of branding.
184 base::Closure start_upgrade_check_timer_task
=
185 base::Bind(&UpgradeDetectorImpl::StartTimerForUpgradeCheck
,
186 weak_factory_
.GetWeakPtr());
187 #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
188 // On Windows, there might be a policy preventing updates, so validate
189 // updatability, and then call StartTimerForUpgradeCheck appropriately.
190 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
191 base::Bind(&DetectUpdatability
,
192 start_upgrade_check_timer_task
,
193 &is_unstable_channel_
));
195 #elif defined(OS_WIN) && !defined(GOOGLE_CHROME_BUILD)
196 return; // Chromium has no upgrade channel.
197 #elif defined(OS_MACOSX)
198 if (!keystone_glue::KeystoneEnabled())
199 return; // Keystone updater not enabled.
200 #elif !defined(OS_POSIX)
204 // Check whether the build is an unstable channel before starting the timer.
205 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
206 base::Bind(&CheckForUnstableChannel
,
207 start_upgrade_check_timer_task
,
208 &is_unstable_channel_
));
211 UpgradeDetectorImpl::~UpgradeDetectorImpl() {
215 // This task checks the currently running version of Chrome against the
216 // installed version. If the installed version is newer, it calls back
217 // UpgradeDetectorImpl::UpgradeDetected using a weak pointer so that it can
218 // be interrupted from the UI thread.
219 void UpgradeDetectorImpl::DetectUpgradeTask(
220 base::WeakPtr
<UpgradeDetectorImpl
> upgrade_detector
) {
221 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
223 Version installed_version
;
224 Version critical_update
;
227 // Get the version of the currently *installed* instance of Chrome,
228 // which might be newer than the *running* instance if we have been
229 // upgraded in the background.
230 bool system_install
= IsSystemInstall();
232 // TODO(tommi): Check if using the default distribution is always the right
234 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
235 InstallUtil::GetChromeVersion(dist
, system_install
, &installed_version
);
237 if (installed_version
.IsValid()) {
238 InstallUtil::GetCriticalUpdateVersion(dist
, system_install
,
241 #elif defined(OS_MACOSX)
243 Version(UTF16ToASCII(keystone_glue::CurrentlyInstalledVersion()));
244 #elif defined(OS_POSIX)
245 // POSIX but not Mac OS X: Linux, etc.
246 CommandLine
command_line(*CommandLine::ForCurrentProcess());
247 command_line
.AppendSwitch(switches::kProductVersion
);
249 if (!base::GetAppOutput(command_line
, &reply
)) {
250 DLOG(ERROR
) << "Failed to get current file version";
254 installed_version
= Version(reply
);
257 // Get the version of the currently *running* instance of Chrome.
258 chrome::VersionInfo version_info
;
259 if (!version_info
.is_valid()) {
260 NOTREACHED() << "Failed to get current file version";
263 Version
running_version(version_info
.Version());
264 if (!running_version
.IsValid()) {
269 // |installed_version| may be NULL when the user downgrades on Linux (by
270 // switching from dev to beta channel, for example). The user needs a
271 // restart in this case as well. See http://crbug.com/46547
272 if (!installed_version
.IsValid() ||
273 (installed_version
.CompareTo(running_version
) > 0)) {
274 // If a more recent version is available, it might be that we are lacking
275 // a critical update, such as a zero-day fix.
276 UpgradeAvailable upgrade_available
= UPGRADE_AVAILABLE_REGULAR
;
277 if (critical_update
.IsValid() &&
278 critical_update
.CompareTo(running_version
) > 0) {
279 upgrade_available
= UPGRADE_AVAILABLE_CRITICAL
;
282 // Fire off the upgrade detected task.
283 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
,
284 base::Bind(&UpgradeDetectorImpl::UpgradeDetected
,
290 void UpgradeDetectorImpl::StartTimerForUpgradeCheck() {
291 detect_upgrade_timer_
.Start(FROM_HERE
,
292 base::TimeDelta::FromMilliseconds(GetCheckForUpgradeEveryMs()),
293 this, &UpgradeDetectorImpl::CheckForUpgrade
);
296 void UpgradeDetectorImpl::CheckForUpgrade() {
297 // Interrupt any (unlikely) unfinished execution of DetectUpgradeTask, or at
298 // least prevent the callback from being executed, because we will potentially
299 // call it from within DetectOutdatedInstall() or will post
300 // DetectUpgradeTask again below anyway.
301 weak_factory_
.InvalidateWeakPtrs();
303 // No need to look for upgrades if the install is outdated.
304 if (DetectOutdatedInstall())
307 // We use FILE as the thread to run the upgrade detection code on all
308 // platforms. For Linux, this is because we don't want to block the UI thread
309 // while launching a background process and reading its output; on the Mac and
310 // on Windows checking for an upgrade requires reading a file.
311 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
312 base::Bind(&UpgradeDetectorImpl::DetectUpgradeTask
,
313 weak_factory_
.GetWeakPtr()));
316 bool UpgradeDetectorImpl::DetectOutdatedInstall() {
317 // Only enable the outdated install check if we are running the trial for it,
318 // unless we are simulating an outdated isntall.
319 static bool simulate_outdated
= CommandLine::ForCurrentProcess()->HasSwitch(
320 switches::kSimulateOutdated
);
321 if (!simulate_outdated
) {
322 if (base::FieldTrialList::FindFullName(kOutdatedInstallCheckTrialName
) !=
323 kOutdatedInstallCheck12WeeksGroupName
) {
327 // Also don't show the bubble if we have a brand code that is NOT organic.
329 if (google_util::GetBrand(&brand
) && !google_util::IsOrganic(brand
))
333 base::Time network_time
;
334 base::TimeDelta uncertainty
;
335 if (!g_browser_process
->variations_service() ||
336 !g_browser_process
->variations_service()->GetNetworkTime(&network_time
,
341 if (network_time
.is_null() || build_date_
.is_null() ||
342 build_date_
> network_time
) {
347 if (network_time
- build_date_
>
348 base::TimeDelta::FromDays(kOutdatedBuildAgeInDays
)) {
349 UpgradeDetected(UPGRADE_NEEDED_OUTDATED_INSTALL
);
352 // If we simlated an outdated install with a date, we don't want to keep
353 // checking for version upgrades, which happens on non-official builds.
354 return simulate_outdated
;
357 void UpgradeDetectorImpl::UpgradeDetected(UpgradeAvailable upgrade_available
) {
358 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
359 upgrade_available_
= upgrade_available
;
361 // Stop the recurring timer (that is checking for changes).
362 detect_upgrade_timer_
.Stop();
364 NotifyUpgradeDetected();
366 // Start the repeating timer for notifying the user after a certain period.
367 // The called function will eventually figure out that enough time has passed
368 // and stop the timer.
369 int cycle_time
= IsTesting() ?
370 kNotifyCycleTimeForTestingMs
: kNotifyCycleTimeMs
;
371 upgrade_notification_timer_
.Start(FROM_HERE
,
372 base::TimeDelta::FromMilliseconds(cycle_time
),
373 this, &UpgradeDetectorImpl::NotifyOnUpgrade
);
376 void UpgradeDetectorImpl::NotifyOnUpgrade() {
377 base::TimeDelta delta
= base::Time::Now() - upgrade_detected_time();
379 // We'll make testing more convenient by switching to seconds of waiting
380 // instead of days between flipping severity.
381 bool is_testing
= IsTesting();
382 int64 time_passed
= is_testing
? delta
.InSeconds() : delta
.InHours();
384 bool is_critical_or_outdated
= upgrade_available_
> UPGRADE_AVAILABLE_REGULAR
;
385 if (is_unstable_channel_
) {
386 // There's only one threat level for unstable channels like dev and
387 // canary, and it hits after one hour. During testing, it hits after one
389 const int kUnstableThreshold
= 1;
391 if (is_critical_or_outdated
)
392 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_CRITICAL
);
393 else if (time_passed
>= kUnstableThreshold
) {
394 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW
);
396 // That's as high as it goes.
397 upgrade_notification_timer_
.Stop();
399 return; // Not ready to recommend upgrade.
402 const int kMultiplier
= is_testing
? 1 : 24;
403 // 14 days when not testing, otherwise 14 seconds.
404 const int kSevereThreshold
= 14 * kMultiplier
;
405 const int kHighThreshold
= 7 * kMultiplier
;
406 const int kElevatedThreshold
= 4 * kMultiplier
;
407 const int kLowThreshold
= 2 * kMultiplier
;
409 // These if statements must be sorted (highest interval first).
410 if (time_passed
>= kSevereThreshold
|| is_critical_or_outdated
) {
411 set_upgrade_notification_stage(
412 is_critical_or_outdated
? UPGRADE_ANNOYANCE_CRITICAL
:
413 UPGRADE_ANNOYANCE_SEVERE
);
415 // We can't get any higher, baby.
416 upgrade_notification_timer_
.Stop();
417 } else if (time_passed
>= kHighThreshold
) {
418 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_HIGH
);
419 } else if (time_passed
>= kElevatedThreshold
) {
420 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_ELEVATED
);
421 } else if (time_passed
>= kLowThreshold
) {
422 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW
);
424 return; // Not ready to recommend upgrade.
428 NotifyUpgradeRecommended();
432 UpgradeDetectorImpl
* UpgradeDetectorImpl::GetInstance() {
433 return Singleton
<UpgradeDetectorImpl
>::get();
437 UpgradeDetector
* UpgradeDetector::GetInstance() {
438 return UpgradeDetectorImpl::GetInstance();