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