EME test page application.
[chromium-blink-merge.git] / chrome / browser / upgrade_detector_impl.cc
blob80f9361522f8600160462bae8a57522815f32989
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/cpu.h"
13 #include "base/files/file_path.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/singleton.h"
16 #include "base/path_service.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/process/launch.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/time/time.h"
23 #include "base/version.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/google/google_util.h"
26 #include "chrome/browser/network_time/network_time_tracker.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/chrome_version_info.h"
29 #include "chrome/common/pref_names.h"
30 #include "content/public/browser/browser_thread.h"
31 #include "ui/base/resource/resource_bundle.h"
33 #if defined(OS_WIN)
34 #include "base/win/win_util.h"
35 #include "chrome/installer/util/browser_distribution.h"
36 #include "chrome/installer/util/google_update_settings.h"
37 #include "chrome/installer/util/helper.h"
38 #include "chrome/installer/util/install_util.h"
39 #elif defined(OS_MACOSX)
40 #include "chrome/browser/mac/keystone_glue.h"
41 #endif
43 using content::BrowserThread;
45 namespace {
47 // How long (in milliseconds) to wait (each cycle) before checking whether
48 // Chrome's been upgraded behind our back.
49 const int kCheckForUpgradeMs = 2 * 60 * 60 * 1000; // 2 hours.
51 // How long to wait (each cycle) before checking which severity level we should
52 // be at. Once we reach the highest severity, the timer will stop.
53 const int kNotifyCycleTimeMs = 20 * 60 * 1000; // 20 minutes.
55 // Same as kNotifyCycleTimeMs but only used during testing.
56 const int kNotifyCycleTimeForTestingMs = 500; // Half a second.
58 // The number of days after which we identify a build/install as outdated.
59 const uint64 kOutdatedBuildAgeInDays = 12 * 7;
61 // Return the string that was passed as a value for the
62 // kCheckForUpdateIntervalSec switch.
63 std::string CmdLineInterval() {
64 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
65 return cmd_line.GetSwitchValueASCII(switches::kCheckForUpdateIntervalSec);
68 // Check if one of the outdated simulation switches was present on the command
69 // line.
70 bool SimulatingOutdated() {
71 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
72 return cmd_line.HasSwitch(switches::kSimulateOutdated) ||
73 cmd_line.HasSwitch(switches::kSimulateOutdatedNoAU);
76 // Check if any of the testing switches was present on the command line.
77 bool IsTesting() {
78 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
79 return cmd_line.HasSwitch(switches::kSimulateUpgrade) ||
80 cmd_line.HasSwitch(switches::kCheckForUpdateIntervalSec) ||
81 cmd_line.HasSwitch(switches::kSimulateCriticalUpdate) ||
82 SimulatingOutdated();
85 // How often to check for an upgrade.
86 int GetCheckForUpgradeEveryMs() {
87 // Check for a value passed via the command line.
88 int interval_ms;
89 std::string interval = CmdLineInterval();
90 if (!interval.empty() && base::StringToInt(interval, &interval_ms))
91 return interval_ms * 1000; // Command line value is in seconds.
93 return kCheckForUpgradeMs;
96 // Return true if the current build is one of the unstable channels.
97 bool IsUnstableChannel() {
98 // TODO(mad): Investigate whether we still need to be on the file thread for
99 // this. On Windows, the file thread used to be required for registry access
100 // but no anymore. But other platform may still need the file thread.
101 // crbug.com/366647.
102 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
103 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
104 return channel == chrome::VersionInfo::CHANNEL_DEV ||
105 channel == chrome::VersionInfo::CHANNEL_CANARY;
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);
116 #if defined(OS_WIN)
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.value().c_str());
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 base::string16 app_guid = installer::GetAppGuidForUpdates(IsSystemInstall());
141 DCHECK(!app_guid.empty());
142 // Don't try to turn on autoupdate when we failed previously.
143 if (is_auto_update_enabled) {
144 *is_auto_update_enabled =
145 GoogleUpdateSettings::AreAutoupdatesEnabled(app_guid);
147 *is_unstable_channel = IsUnstableChannel();
148 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback_task);
150 #endif // defined(OS_WIN)
152 } // namespace
154 UpgradeDetectorImpl::UpgradeDetectorImpl()
155 : weak_factory_(this),
156 is_unstable_channel_(false),
157 is_auto_update_enabled_(true),
158 build_date_(base::GetBuildTime()) {
159 CommandLine command_line(*CommandLine::ForCurrentProcess());
160 // The different command line switches that affect testing can't be used
161 // simultaneously, if they do, here's the precedence order, based on the order
162 // of the if statements below:
163 // - kDisableBackgroundNetworking prevents any of the other command line
164 // switch from being taken into account.
165 // - kSimulateUpgrade supersedes critical or outdated upgrade switches.
166 // - kSimulateCriticalUpdate has precedence over kSimulateOutdated.
167 // - kSimulateOutdatedNoAU has precedence over kSimulateOutdated.
168 // - kSimulateOutdated[NoAu] can work on its own, or with a specified date.
169 if (command_line.HasSwitch(switches::kDisableBackgroundNetworking))
170 return;
171 if (command_line.HasSwitch(switches::kSimulateUpgrade)) {
172 UpgradeDetected(UPGRADE_AVAILABLE_REGULAR);
173 return;
175 if (command_line.HasSwitch(switches::kSimulateCriticalUpdate)) {
176 UpgradeDetected(UPGRADE_AVAILABLE_CRITICAL);
177 return;
179 if (SimulatingOutdated()) {
180 // The outdated simulation can work without a value, which means outdated
181 // now, or with a value that must be a well formed date/time string that
182 // overrides the build date.
183 // Also note that to test with a given time/date, until the network time
184 // tracking moves off of the VariationsService, the "variations-server-url"
185 // command line switch must also be specified for the service to be
186 // available on non GOOGLE_CHROME_BUILD.
187 std::string switch_name;
188 if (command_line.HasSwitch(switches::kSimulateOutdatedNoAU)) {
189 is_auto_update_enabled_ = false;
190 switch_name = switches::kSimulateOutdatedNoAU;
191 } else {
192 switch_name = switches::kSimulateOutdated;
194 std::string build_date = command_line.GetSwitchValueASCII(switch_name);
195 base::Time maybe_build_time;
196 bool result = base::Time::FromString(build_date.c_str(), &maybe_build_time);
197 if (result && !maybe_build_time.is_null()) {
198 // We got a valid build date simulation so use it and check for upgrades.
199 build_date_ = maybe_build_time;
200 StartTimerForUpgradeCheck();
201 } else {
202 // Without a valid date, we simulate that we are already outdated...
203 UpgradeDetected(
204 is_auto_update_enabled_ ? UPGRADE_NEEDED_OUTDATED_INSTALL
205 : UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU);
207 return;
210 base::Closure start_upgrade_check_timer_task =
211 base::Bind(&UpgradeDetectorImpl::StartTimerForUpgradeCheck,
212 weak_factory_.GetWeakPtr());
214 #if defined(OS_WIN)
215 // Only enable upgrade notifications for official builds. Chromium has no
216 // upgrade channel.
217 #if defined(GOOGLE_CHROME_BUILD)
218 // On Windows, there might be a policy/enterprise environment preventing
219 // updates, so validate updatability, and then call StartTimerForUpgradeCheck
220 // appropriately. And don't check for autoupdate if we already attempted to
221 // enable it in the past.
222 bool attempted_enabling_autoupdate = g_browser_process->local_state() &&
223 g_browser_process->local_state()->GetBoolean(
224 prefs::kAttemptedToEnableAutoupdate);
225 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
226 base::Bind(&DetectUpdatability,
227 start_upgrade_check_timer_task,
228 &is_unstable_channel_,
229 attempted_enabling_autoupdate ?
230 NULL : &is_auto_update_enabled_));
231 #endif
232 #else
233 #if defined(OS_MACOSX)
234 // Only enable upgrade notifications if the updater (Keystone) is present.
235 if (!keystone_glue::KeystoneEnabled()) {
236 is_auto_update_enabled_ = false;
237 return;
239 #elif defined(OS_POSIX)
240 // Always enable upgrade notifications regardless of branding.
241 #else
242 return;
243 #endif
244 // Check whether the build is an unstable channel before starting the timer.
245 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
246 base::Bind(&CheckForUnstableChannel,
247 start_upgrade_check_timer_task,
248 &is_unstable_channel_));
249 #endif
252 UpgradeDetectorImpl::~UpgradeDetectorImpl() {
255 // Static
256 // This task checks the currently running version of Chrome against the
257 // installed version. If the installed version is newer, it calls back
258 // UpgradeDetectorImpl::UpgradeDetected using a weak pointer so that it can
259 // be interrupted from the UI thread.
260 void UpgradeDetectorImpl::DetectUpgradeTask(
261 base::WeakPtr<UpgradeDetectorImpl> upgrade_detector) {
262 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
264 Version installed_version;
265 Version critical_update;
267 #if defined(OS_WIN)
268 // Get the version of the currently *installed* instance of Chrome,
269 // which might be newer than the *running* instance if we have been
270 // upgraded in the background.
271 bool system_install = IsSystemInstall();
273 // TODO(tommi): Check if using the default distribution is always the right
274 // thing to do.
275 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
276 InstallUtil::GetChromeVersion(dist, system_install, &installed_version);
278 if (installed_version.IsValid()) {
279 InstallUtil::GetCriticalUpdateVersion(dist, system_install,
280 &critical_update);
282 #elif defined(OS_MACOSX)
283 installed_version =
284 Version(base::UTF16ToASCII(keystone_glue::CurrentlyInstalledVersion()));
285 #elif defined(OS_POSIX)
286 // POSIX but not Mac OS X: Linux, etc.
287 CommandLine command_line(*CommandLine::ForCurrentProcess());
288 command_line.AppendSwitch(switches::kProductVersion);
289 std::string reply;
290 if (!base::GetAppOutput(command_line, &reply)) {
291 DLOG(ERROR) << "Failed to get current file version";
292 return;
295 installed_version = Version(reply);
296 #endif
298 // Get the version of the currently *running* instance of Chrome.
299 chrome::VersionInfo version_info;
300 if (!version_info.is_valid()) {
301 NOTREACHED() << "Failed to get current file version";
302 return;
304 Version running_version(version_info.Version());
305 if (!running_version.IsValid()) {
306 NOTREACHED();
307 return;
310 // |installed_version| may be NULL when the user downgrades on Linux (by
311 // switching from dev to beta channel, for example). The user needs a
312 // restart in this case as well. See http://crbug.com/46547
313 if (!installed_version.IsValid() ||
314 (installed_version.CompareTo(running_version) > 0)) {
315 // If a more recent version is available, it might be that we are lacking
316 // a critical update, such as a zero-day fix.
317 UpgradeAvailable upgrade_available = UPGRADE_AVAILABLE_REGULAR;
318 if (critical_update.IsValid() &&
319 critical_update.CompareTo(running_version) > 0) {
320 upgrade_available = UPGRADE_AVAILABLE_CRITICAL;
323 // Fire off the upgrade detected task.
324 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
325 base::Bind(&UpgradeDetectorImpl::UpgradeDetected,
326 upgrade_detector,
327 upgrade_available));
331 void UpgradeDetectorImpl::StartTimerForUpgradeCheck() {
332 detect_upgrade_timer_.Start(FROM_HERE,
333 base::TimeDelta::FromMilliseconds(GetCheckForUpgradeEveryMs()),
334 this, &UpgradeDetectorImpl::CheckForUpgrade);
337 void UpgradeDetectorImpl::CheckForUpgrade() {
338 // Interrupt any (unlikely) unfinished execution of DetectUpgradeTask, or at
339 // least prevent the callback from being executed, because we will potentially
340 // call it from within DetectOutdatedInstall() or will post
341 // DetectUpgradeTask again below anyway.
342 weak_factory_.InvalidateWeakPtrs();
344 // No need to look for upgrades if the install is outdated.
345 if (DetectOutdatedInstall())
346 return;
348 // We use FILE as the thread to run the upgrade detection code on all
349 // platforms. For Linux, this is because we don't want to block the UI thread
350 // while launching a background process and reading its output; on the Mac and
351 // on Windows checking for an upgrade requires reading a file.
352 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
353 base::Bind(&UpgradeDetectorImpl::DetectUpgradeTask,
354 weak_factory_.GetWeakPtr()));
357 bool UpgradeDetectorImpl::DetectOutdatedInstall() {
358 // Don't show the bubble if we have a brand code that is NOT organic, unless
359 // an outdated build is being simulated by command line switches.
360 static bool simulate_outdated = SimulatingOutdated();
361 if (!simulate_outdated) {
362 std::string brand;
363 if (google_util::GetBrand(&brand) && !google_util::IsOrganic(brand))
364 return false;
366 #if defined(OS_WIN)
367 // Don't show the update bubbles to entreprise users (i.e., on a domain).
368 if (base::win::IsEnrolledToDomain())
369 return false;
371 // On Windows, we don't want to warn about outdated installs when the
372 // machine doesn't support SSE2, it's been deprecated starting with M35.
373 if (!base::CPU().has_sse2())
374 return false;
375 #endif
378 base::Time network_time;
379 base::TimeDelta uncertainty;
380 if (!g_browser_process->network_time_tracker()->GetNetworkTime(
381 base::TimeTicks::Now(), &network_time, &uncertainty)) {
382 // When network time has not been initialized yet, simply rely on the
383 // machine's current time.
384 network_time = base::Time::Now();
387 if (network_time.is_null() || build_date_.is_null() ||
388 build_date_ > network_time) {
389 NOTREACHED();
390 return false;
393 if (network_time - build_date_ >
394 base::TimeDelta::FromDays(kOutdatedBuildAgeInDays)) {
395 UpgradeDetected(is_auto_update_enabled_ ?
396 UPGRADE_NEEDED_OUTDATED_INSTALL :
397 UPGRADE_NEEDED_OUTDATED_INSTALL_NO_AU);
398 return true;
400 // If we simlated an outdated install with a date, we don't want to keep
401 // checking for version upgrades, which happens on non-official builds.
402 return simulate_outdated;
405 void UpgradeDetectorImpl::UpgradeDetected(UpgradeAvailable upgrade_available) {
406 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
407 upgrade_available_ = upgrade_available;
409 // Stop the recurring timer (that is checking for changes).
410 detect_upgrade_timer_.Stop();
412 NotifyUpgradeDetected();
414 // Start the repeating timer for notifying the user after a certain period.
415 // The called function will eventually figure out that enough time has passed
416 // and stop the timer.
417 int cycle_time = IsTesting() ?
418 kNotifyCycleTimeForTestingMs : kNotifyCycleTimeMs;
419 upgrade_notification_timer_.Start(FROM_HERE,
420 base::TimeDelta::FromMilliseconds(cycle_time),
421 this, &UpgradeDetectorImpl::NotifyOnUpgrade);
424 void UpgradeDetectorImpl::NotifyOnUpgrade() {
425 base::TimeDelta delta = base::Time::Now() - upgrade_detected_time();
427 // We'll make testing more convenient by switching to seconds of waiting
428 // instead of days between flipping severity.
429 bool is_testing = IsTesting();
430 int64 time_passed = is_testing ? delta.InSeconds() : delta.InHours();
432 bool is_critical_or_outdated = upgrade_available_ > UPGRADE_AVAILABLE_REGULAR;
433 if (is_unstable_channel_) {
434 // There's only one threat level for unstable channels like dev and
435 // canary, and it hits after one hour. During testing, it hits after one
436 // second.
437 const int kUnstableThreshold = 1;
439 if (is_critical_or_outdated)
440 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_CRITICAL);
441 else if (time_passed >= kUnstableThreshold) {
442 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW);
444 // That's as high as it goes.
445 upgrade_notification_timer_.Stop();
446 } else {
447 return; // Not ready to recommend upgrade.
449 } else {
450 const int kMultiplier = is_testing ? 10 : 24;
451 // 14 days when not testing, otherwise 14 seconds.
452 const int kSevereThreshold = 14 * kMultiplier;
453 const int kHighThreshold = 7 * kMultiplier;
454 const int kElevatedThreshold = 4 * kMultiplier;
455 const int kLowThreshold = 2 * kMultiplier;
457 // These if statements must be sorted (highest interval first).
458 if (time_passed >= kSevereThreshold || is_critical_or_outdated) {
459 set_upgrade_notification_stage(
460 is_critical_or_outdated ? UPGRADE_ANNOYANCE_CRITICAL :
461 UPGRADE_ANNOYANCE_SEVERE);
463 // We can't get any higher, baby.
464 upgrade_notification_timer_.Stop();
465 } else if (time_passed >= kHighThreshold) {
466 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_HIGH);
467 } else if (time_passed >= kElevatedThreshold) {
468 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_ELEVATED);
469 } else if (time_passed >= kLowThreshold) {
470 set_upgrade_notification_stage(UPGRADE_ANNOYANCE_LOW);
471 } else {
472 return; // Not ready to recommend upgrade.
476 NotifyUpgradeRecommended();
479 // static
480 UpgradeDetectorImpl* UpgradeDetectorImpl::GetInstance() {
481 return Singleton<UpgradeDetectorImpl>::get();
484 // static
485 UpgradeDetector* UpgradeDetector::GetInstance() {
486 return UpgradeDetectorImpl::GetInstance();