version_updater_win.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
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.
4
5#include "base/memory/ref_counted.h"
6#include "base/memory/scoped_ptr.h"
7#include "base/memory/weak_ptr.h"
8#include "base/string16.h"
9#include "base/version.h"
10#include "base/win/windows_version.h"
11#include "base/win/win_util.h"
12#include "chrome/browser/google/google_update_win.h"
13#include "chrome/browser/lifetime/application_lifetime.h"
14#include "chrome/browser/ui/browser.h"
15#include "chrome/browser/ui/webui/help/version_updater.h"
16#include "chrome/common/chrome_version_info.h"
17#include "chrome/installer/util/browser_distribution.h"
18#include "chrome/installer/util/install_util.h"
19#include "content/public/browser/browser_thread.h"
20#include "content/public/browser/user_metrics.h"
21#include "grit/chromium_strings.h"
22#include "grit/generated_resources.h"
23#include "ui/base/l10n/l10n_util.h"
24#include "ui/views/widget/widget.h"
25
26using content::BrowserThread;
27using content::UserMetricsAction;
28
29namespace {
30
31// Windows implementation of version update functionality, used by the WebUI
32// About/Help page.
33class VersionUpdaterWin : public VersionUpdater,
34                          public GoogleUpdateStatusListener {
35 private:
36  friend class VersionReader;
37  friend class VersionUpdater;
38
39  // Clients must use VersionUpdater::Create().
40  VersionUpdaterWin();
41  virtual ~VersionUpdaterWin();
42
43  // VersionUpdater implementation.
44  virtual void CheckForUpdate(const StatusCallback& callback) OVERRIDE;
45  virtual void RelaunchBrowser() const OVERRIDE;
46
47  // GoogleUpdateStatusListener implementation.
48  virtual void OnReportResults(GoogleUpdateUpgradeResult result,
49                               GoogleUpdateErrorCode error_code,
50                               const string16& error_message,
51                               const string16& version) OVERRIDE;
52
53  // Update the UI to show the status of the upgrade.
54  void UpdateStatus(GoogleUpdateUpgradeResult result,
55                    GoogleUpdateErrorCode error_code,
56                    const string16& error_message);
57
58  // Got the intalled version so the handling of the UPGRADE_ALREADY_UP_TO_DATE
59  // result case can now be completeb on the UI thread.
60  void GotInstalledVersion(const Version& version);
61
62  // Little helper function to reset google_updater_.
63  void SetGoogleUpdater();
64
65  // Returns a window that can be used for elevation.
66  HWND GetElevationParent();
67
68  // The class that communicates with Google Update to find out if an update is
69  // available and asks it to start an upgrade.
70  scoped_refptr<GoogleUpdate> google_updater_;
71
72  // Used for callbacks.
73  base::WeakPtrFactory<VersionUpdaterWin> weak_factory_;
74
75  // Callback used to communicate update status to the client.
76  StatusCallback callback_;
77
78  DISALLOW_COPY_AND_ASSIGN(VersionUpdaterWin);
79};
80
81// This class is used to read the version on the FILE thread and then call back
82// the version updater in the UI thread. Using a class helps better control
83// the lifespan of the Version independently of the lifespan of the version
84// updater, which may die while asynchonicity is happening, thus the usage of
85// the WeakPtr, which can only be used from the thread that created it.
86class VersionReader
87    : public base::RefCountedThreadSafe<VersionReader> {
88 public:
89  explicit VersionReader(
90      const base::WeakPtr<VersionUpdaterWin>& version_updater)
91      : version_updater_(version_updater) {
92  }
93
94  void GetVersionFromFileThread() {
95    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
96    InstallUtil::GetChromeVersion(dist, false, &installed_version_);
97    if (!installed_version_.IsValid()) {
98      // User-level Chrome is not installed, check system-level.
99      InstallUtil::GetChromeVersion(dist, true, &installed_version_);
100    }
101    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
102          &VersionReader::SetVersionInUIThread, this));
103  }
104
105  void SetVersionInUIThread() {
106    if (version_updater_.get() != NULL)
107      version_updater_->GotInstalledVersion(installed_version_);
108  }
109
110 private:
111  friend class base::RefCountedThreadSafe<VersionReader>;
112
113  // The version updater that must be called back when we are done.
114  // We use a weak pointer in case the updater gets destroyed while waiting.
115  base::WeakPtr<VersionUpdaterWin> version_updater_;
116
117  // This is the version that gets read in the FILE thread and set on the
118  // the updater in the UI thread.
119  Version installed_version_;
120};
121
122VersionUpdaterWin::VersionUpdaterWin()
123    : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
124  SetGoogleUpdater();
125}
126
127VersionUpdaterWin::~VersionUpdaterWin() {
128  // The Google Updater will hold a pointer to the listener until it reports
129  // status, so that pointer must be cleared when the listener is destoyed.
130  if (google_updater_)
131    google_updater_->set_status_listener(NULL);
132}
133
134void VersionUpdaterWin::CheckForUpdate(const StatusCallback& callback) {
135  callback_ = callback;
136
137  // On-demand updates for Chrome don't work in Vista RTM when UAC is turned
138  // off. So, in this case, the version updater must not mention
139  // on-demand updates. Silent updates (in the background) should still
140  // work as before - enabling UAC or installing the latest service pack
141  // for Vista is another option.
142  if (!(base::win::GetVersion() == base::win::VERSION_VISTA &&
143        (base::win::OSInfo::GetInstance()->service_pack().major == 0) &&
144        !base::win::UserAccountControlIsEnabled())) {
145    // This could happen if the page got refreshed after results were returned.
146    if (!google_updater_)
147      SetGoogleUpdater();
148    UpdateStatus(UPGRADE_CHECK_STARTED, GOOGLE_UPDATE_NO_ERROR, string16());
149    // Specify false to not upgrade yet.
150    google_updater_->CheckForUpdate(false, GetElevationParent());
151  }
152}
153
154void VersionUpdaterWin::RelaunchBrowser() const {
155  browser::AttemptRestart();
156}
157
158void VersionUpdaterWin::OnReportResults(
159    GoogleUpdateUpgradeResult result, GoogleUpdateErrorCode error_code,
160    const string16& error_message, const string16& version) {
161  // Drop the last reference to the object so that it gets cleaned up here.
162  google_updater_ = NULL;
163  UpdateStatus(result, error_code, error_message);
164}
165
166void VersionUpdaterWin::UpdateStatus(GoogleUpdateUpgradeResult result,
167                                     GoogleUpdateErrorCode error_code,
168                                     const string16& error_message) {
169  // For Chromium builds it would show an error message.
170  // But it looks weird because in fact there is no error,
171  // just the update server is not available for non-official builds.
172#if defined(GOOGLE_CHROME_BUILD)
173  Status status = UPDATED;
174  string16 message;
175
176  switch (result) {
177    case UPGRADE_CHECK_STARTED: {
178      content::RecordAction(UserMetricsAction("UpgradeCheck_Started"));
179      status = CHECKING;
180      break;
181    }
182    case UPGRADE_STARTED: {
183      content::RecordAction(UserMetricsAction("Upgrade_Started"));
184      status = UPDATING;
185      break;
186    }
187    case UPGRADE_IS_AVAILABLE: {
188      content::RecordAction(
189          UserMetricsAction("UpgradeCheck_UpgradeIsAvailable"));
190      DCHECK(!google_updater_);  // Should have been nulled out already.
191      SetGoogleUpdater();
192      UpdateStatus(UPGRADE_STARTED, GOOGLE_UPDATE_NO_ERROR, string16());
193      // Specify true to upgrade now.
194      google_updater_->CheckForUpdate(true, GetElevationParent());
195      return;
196    }
197    case UPGRADE_ALREADY_UP_TO_DATE: {
198      // Google Update reported that Chrome is up-to-date.
199      // To confirm the updated version is running, the reading
200      // must be done on the file thread. The rest of this case
201      // will be handled within GotInstalledVersion.
202      BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(
203            &VersionReader::GetVersionFromFileThread,
204            new VersionReader(weak_factory_.GetWeakPtr())));
205      return;
206    }
207    case UPGRADE_SUCCESSFUL: {
208      content::RecordAction(UserMetricsAction("UpgradeCheck_Upgraded"));
209      status = NEARLY_UPDATED;
210      break;
211    }
212    case UPGRADE_ERROR: {
213      content::RecordAction(UserMetricsAction("UpgradeCheck_Error"));
214      status = FAILED;
215      if (error_code != GOOGLE_UPDATE_DISABLED_BY_POLICY) {
216        message =
217            l10n_util::GetStringFUTF16Int(IDS_UPGRADE_ERROR, error_code);
218      } else {
219        message =
220            l10n_util::GetStringUTF16(IDS_UPGRADE_DISABLED_BY_POLICY);
221      }
222      if (!error_message.empty()) {
223        message +=
224            l10n_util::GetStringFUTF16(IDS_ABOUT_BOX_ERROR_DURING_UPDATE_CHECK,
225                                       error_message);
226      }
227      break;
228    }
229  }
230
231  // TODO(mad): Get proper progress value instead of passing 0.
232  // http://crbug.com/136117
233  callback_.Run(status, 0, message);
234#endif  //  defined(GOOGLE_CHROME_BUILD)
235}
236
237void VersionUpdaterWin::GotInstalledVersion(const Version& version) {
238  // This must be called on the UI thread so that callback_ can be called.
239  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
240
241  // Make sure that the latest version is running and if not,
242  // notify the user by setting the status to NEARLY_UPDATED.
243  //
244  // The extra version check is necessary on Windows because the application
245  // may be already up to date on disk though the running app is still
246  // out of date.
247  chrome::VersionInfo version_info;
248  Version running_version(version_info.Version());
249  if (!version.IsValid() || version.CompareTo(running_version) <= 0) {
250    content::RecordAction(
251        UserMetricsAction("UpgradeCheck_AlreadyUpToDate"));
252    callback_.Run(UPDATED, 0, string16());
253  } else {
254    content::RecordAction(UserMetricsAction("UpgradeCheck_AlreadyUpgraded"));
255    callback_.Run(NEARLY_UPDATED, 0, string16());
256  }
257}
258
259void VersionUpdaterWin::SetGoogleUpdater() {
260  google_updater_ = new GoogleUpdate();
261  google_updater_->set_status_listener(this);
262}
263
264BOOL CALLBACK WindowEnumeration(HWND window, LPARAM param) {
265  if (IsWindowVisible(window)) {
266    HWND* returned_window = reinterpret_cast<HWND*>(param);
267    *returned_window = window;
268    return FALSE;
269  }
270  return TRUE;
271}
272
273HWND VersionUpdaterWin::GetElevationParent() {
274  // Look for a visible window belonging to the UI thread.
275  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
276  HWND window = NULL;
277  EnumThreadWindows(GetCurrentThreadId(),
278                    WindowEnumeration,
279                    reinterpret_cast<LPARAM>(&window));
280  DCHECK(window != NULL) << "Failed to find a valid window handle on thread: "
281                         << GetCurrentThreadId();
282  return window;
283}
284
285}  // namespace
286
287VersionUpdater* VersionUpdater::Create() {
288  return new VersionUpdaterWin;
289}
290