Add new certificateProvider extension API.
[chromium-blink-merge.git] / chrome / browser / upgrade_detector_impl.cc
blob9efdb74b18333f8e2f642747458e8cdf19800d51
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/channel_info.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/common/pref_names.h"
27 #include "components/network_time/network_time_tracker.h"
28 #include "components/version_info/version_info.h"
29 #include "content/public/browser/browser_thread.h"
31 #if defined(OS_WIN)
32 #include "base/win/win_util.h"
33 #include "chrome/installer/util/browser_distribution.h"
34 #include "chrome/installer/util/google_update_settings.h"
35 #include "chrome/installer/util/helper.h"
36 #include "chrome/installer/util/install_util.h"
37 #elif defined(OS_MACOSX)
38 #include "chrome/browser/mac/keystone_glue.h"
39 #endif
41 using content::BrowserThread;
43 namespace {
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 // Return the string that was passed as a value for the
60 // kCheckForUpdateIntervalSec switch.
61 std::string CmdLineInterval() {
62 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
63 return cmd_line.GetSwitchValueASCII(switches::kCheckForUpdateIntervalSec);
66 // Check if one of the outdated simulation switches was present on the command
67 // line.
68 bool SimulatingOutdated() {
69 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
70 return cmd_line.HasSwitch(switches::kSimulateOutdated) ||
71 cmd_line.HasSwitch(switches::kSimulateOutdatedNoAU);
74 // Check if any of the testing switches was present on the command line.
75 bool IsTesting() {
76 const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
77 return cmd_line.HasSwitch(switches::kSimulateUpgrade) ||
78 cmd_line.HasSwitch(switches::kCheckForUpdateIntervalSec) ||
79 cmd_line.HasSwitch(switches::kSimulateCriticalUpdate) ||
80 SimulatingOutdated();
83 // How often to check for an upgrade.
84 int GetCheckForUpgradeEveryMs() {
85 // Check for a value passed via the command line.
86 int interval_ms;
87 std::string interval = CmdLineInterval();
88 if (!interval.empty() && base::StringToInt(interval, &interval_ms))
89 return interval_ms * 1000; // Command line value is in seconds.
91 return kCheckForUpgradeMs;
94 #if !defined(OS_WIN) || defined(GOOGLE_CHROME_BUILD)
95 // Return true if the current build is one of the unstable channels.
96 bool IsUnstableChannel() {
97 // TODO(mad): Investigate whether we still need to be on the file thread for
98 // this. On Windows, the file thread used to be required for registry access
99 // but no anymore. But other platform may still need the file thread.
100 // crbug.com/366647.
101 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
102 version_info::Channel channel = chrome::GetChannel();
103 return channel == version_info::Channel::DEV ||
104 channel == version_info::Channel::CANARY;
106 #endif // !defined(OS_WIN) || defined(GOOGLE_CHROME_BUILD)
108 #if !defined(OS_WIN)
109 // This task identifies whether we are running an unstable version. And then it
110 // unconditionally calls back the provided task.
111 void CheckForUnstableChannel(const base::Closure& callback_task,
112 bool* is_unstable_channel) {
113 *is_unstable_channel = IsUnstableChannel();
114 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback_task);
116 #else
117 // Return true if the currently running Chrome is a system install.
118 bool IsSystemInstall() {
119 // Get the version of the currently *installed* instance of Chrome,
120 // which might be newer than the *running* instance if we have been
121 // upgraded in the background.
122 base::FilePath exe_path;
123 if (!PathService::Get(base::DIR_EXE, &exe_path)) {
124 NOTREACHED() << "Failed to find executable path";
125 return false;
128 return !InstallUtil::IsPerUserInstall(exe_path);
131 #if defined(GOOGLE_CHROME_BUILD)
132 // Sets |is_unstable_channel| to true if the current chrome is on the dev or
133 // canary channels. Sets |is_auto_update_enabled| to true if Google Update will
134 // update the current chrome. Unconditionally posts |callback_task| to the UI
135 // thread to continue processing.
136 void DetectUpdatability(const base::Closure& callback_task,
137 bool* is_unstable_channel,
138 bool* is_auto_update_enabled) {
139 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
141 // Don't try to turn on autoupdate when we failed previously.
142 if (is_auto_update_enabled) {
143 *is_auto_update_enabled =
144 GoogleUpdateSettings::AreAutoupdatesEnabled();
146 *is_unstable_channel = IsUnstableChannel();
147 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback_task);
149 #endif // defined(GOOGLE_CHROME_BUILD)
150 #endif // !defined(OS_WIN)
152 // Gets the currently installed version. On Windows, if |critical_update| is not
153 // NULL, also retrieves the critical update version info if available.
154 base::Version GetCurrentlyInstalledVersionImpl(Version* critical_update) {
155 base::ThreadRestrictions::AssertIOAllowed();
157 Version installed_version;
158 #if defined(OS_WIN)
159 // Get the version of the currently *installed* instance of Chrome,
160 // which might be newer than the *running* instance if we have been
161 // upgraded in the background.
162 bool system_install = IsSystemInstall();
164 // TODO(tommi): Check if using the default distribution is always the right
165 // thing to do.
166 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
167 InstallUtil::GetChromeVersion(dist, system_install, &installed_version);
168 if (critical_update && installed_version.IsValid()) {
169 InstallUtil::GetCriticalUpdateVersion(dist, system_install,
170 critical_update);
172 #elif defined(OS_MACOSX)
173 installed_version =
174 Version(base::UTF16ToASCII(keystone_glue::CurrentlyInstalledVersion()));
175 #elif defined(OS_POSIX)
176 // POSIX but not Mac OS X: Linux, etc.
177 base::CommandLine command_line(*base::CommandLine::ForCurrentProcess());
178 command_line.AppendSwitch(switches::kProductVersion);
179 std::string reply;
180 if (!base::GetAppOutput(command_line, &reply)) {
181 DLOG(ERROR) << "Failed to get current file version";
182 return installed_version;
184 base::TrimWhitespaceASCII(reply, base::TRIM_ALL, &reply);
186 installed_version = Version(reply);
187 #endif
188 return installed_version;
191 } // namespace
193 UpgradeDetectorImpl::UpgradeDetectorImpl()
194 : is_unstable_channel_(false),
195 is_auto_update_enabled_(true),
196 build_date_(base::GetBuildTime()),
197 weak_factory_(this) {
198 base::CommandLine command_line(*base::CommandLine::ForCurrentProcess());
199 // The different command line switches that affect testing can't be used
200 // simultaneously, if they do, here's the precedence order, based on the order
201 // of the if statements below:
202 // - kDisableBackgroundNetworking prevents any of the other command line
203 // switch from being taken into account.
204 // - kSimulateUpgrade supersedes critical or outdated upgrade switches.
205 // - kSimulateCriticalUpdate has precedence over kSimulateOutdated.
206 // - kSimulateOutdatedNoAU has precedence over kSimulateOutdated.
207 // - kSimulateOutdated[NoAu] can work on its own, or with a specified date.
208 if (command_line.HasSwitch(switches::kDisableBackgroundNetworking))
209 return;
210 if (command_line.HasSwitch(switches::kSimulateUpgrade)) {
211 UpgradeDetected(UPGRADE_AVAILABLE_REGULAR);
212 return;
214 if (command_line.HasSwitch(switches::kSimulateCriticalUpdate)) {
215 UpgradeDetected(UPGRADE_AVAILABLE_CRITICAL);
216 return;
218 if (SimulatingOutdated()) {
219 // The outdated simulation can work without a value, which means outdated
220 // now, or with a value that must be a well formed date/time string that
221 // overrides the build date.
222 // Also note that to test with a given time/date, until the network time
223 // tracking moves off of the VariationsService, the "variations-server-url"
224 // command line switch must also be specified for the service to be
225 // available on non GOOGLE_CHROME_BUILD.
226 std::string switch_name;
227 if (command_line.HasSwitch(switches::kSimulateOutdatedNoAU)) {
228 is_auto_update_enabled_ = false;
229 switch_name = switches::kSimulateOutdatedNoAU;
230 } else {
231 switch_name = switches::kSimulateOutdated;
233 std::string build_date = command_line.GetSwitchValueASCII(switch_name);
234 base::Time maybe_build_time;
235 bool result = base::Time::FromString(build_date.c_str(), &maybe_build_time);
236 if (result && !maybe_build_time.is_null()) {
237 // We got a valid build date simulation so use it and check for upgrades.
238 build_date_ = maybe_build_time;
239 StartTimerForUpgradeCheck();
240 } else {
241 // Without a valid date, we simulate that we are already outdated...
242 UpgradeDetected(
243 is_auto_update_enabled_ ? UPGRADE_NEEDED_OUTDATED_INSTALL
244 : UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU);
246 return;
249 // Register for experiment notifications. Note that since this class is a
250 // singleton, it does not need to unregister for notifications when destroyed,
251 // since it outlives the VariationsService.
252 variations::VariationsService* variations_service =
253 g_browser_process->variations_service();
254 if (variations_service)
255 variations_service->AddObserver(this);
257 base::Closure start_upgrade_check_timer_task =
258 base::Bind(&UpgradeDetectorImpl::StartTimerForUpgradeCheck,
259 weak_factory_.GetWeakPtr());
261 #if defined(OS_WIN)
262 // Only enable upgrade notifications for official builds. Chromium has no
263 // upgrade channel.
264 #if defined(GOOGLE_CHROME_BUILD)
265 // On Windows, there might be a policy/enterprise environment preventing
266 // updates, so validate updatability, and then call StartTimerForUpgradeCheck
267 // appropriately. And don't check for autoupdate if we already attempted to
268 // enable it in the past.
269 bool attempted_enabling_autoupdate = g_browser_process->local_state() &&
270 g_browser_process->local_state()->GetBoolean(
271 prefs::kAttemptedToEnableAutoupdate);
272 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
273 base::Bind(&DetectUpdatability,
274 start_upgrade_check_timer_task,
275 &is_unstable_channel_,
276 attempted_enabling_autoupdate ?
277 NULL : &is_auto_update_enabled_));
278 #endif
279 #else
280 #if defined(OS_MACOSX)
281 // Only enable upgrade notifications if the updater (Keystone) is present.
282 if (!keystone_glue::KeystoneEnabled()) {
283 is_auto_update_enabled_ = false;
284 return;
286 #elif defined(OS_POSIX)
287 // Always enable upgrade notifications regardless of branding.
288 #else
289 return;
290 #endif
291 // Check whether the build is an unstable channel before starting the timer.
292 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
293 base::Bind(&CheckForUnstableChannel,
294 start_upgrade_check_timer_task,
295 &is_unstable_channel_));
296 #endif
299 UpgradeDetectorImpl::~UpgradeDetectorImpl() {
302 // static
303 base::Version UpgradeDetectorImpl::GetCurrentlyInstalledVersion() {
304 return GetCurrentlyInstalledVersionImpl(NULL);
307 // static
308 // This task checks the currently running version of Chrome against the
309 // installed version. If the installed version is newer, it calls back
310 // UpgradeDetectorImpl::UpgradeDetected using a weak pointer so that it can
311 // be interrupted from the UI thread.
312 void UpgradeDetectorImpl::DetectUpgradeTask(
313 base::WeakPtr<UpgradeDetectorImpl> upgrade_detector) {
314 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
316 Version critical_update;
317 Version installed_version =
318 GetCurrentlyInstalledVersionImpl(&critical_update);
320 // Get the version of the currently *running* instance of Chrome.
321 Version running_version(version_info::GetVersionNumber());
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_CURRENTLY_ON(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();