Add ICU message format support
[chromium-blink-merge.git] / chrome / browser / google / google_update_win.cc
blob22bd062af84de0de8b53b2849f9b6f96a3c7ba34
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/google/google_update_win.h"
7 #include <atlbase.h>
8 #include <atlcom.h>
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/files/file_path.h"
13 #include "base/location.h"
14 #include "base/metrics/histogram.h"
15 #include "base/metrics/sparse_histogram.h"
16 #include "base/path_service.h"
17 #include "base/sequenced_task_runner_helpers.h"
18 #include "base/single_thread_task_runner.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/thread_task_runner_handle.h"
23 #include "base/time/time.h"
24 #include "base/win/scoped_bstr.h"
25 #include "base/win/windows_version.h"
26 #include "chrome/common/url_constants.h"
27 #include "chrome/grit/generated_resources.h"
28 #include "chrome/installer/util/browser_distribution.h"
29 #include "chrome/installer/util/helper.h"
30 #include "chrome/installer/util/install_util.h"
31 #include "ui/base/l10n/l10n_util.h"
32 #include "ui/base/win/atl_module.h"
33 #include "ui/gfx/geometry/safe_integer_conversions.h"
35 namespace {
37 // The status of the upgrade. These values are used for a histogram. Do not
38 // reorder.
39 enum GoogleUpdateUpgradeStatus {
40 // The upgrade has started. DEPRECATED.
41 // UPGRADE_STARTED = 0,
42 // A check for upgrade has been initiated. DEPRECATED.
43 // UPGRADE_CHECK_STARTED = 1,
44 // An update is available.
45 UPGRADE_IS_AVAILABLE = 2,
46 // The upgrade happened successfully.
47 UPGRADE_SUCCESSFUL = 3,
48 // No need to upgrade, Chrome is up to date.
49 UPGRADE_ALREADY_UP_TO_DATE = 4,
50 // An error occurred.
51 UPGRADE_ERROR = 5,
52 NUM_UPGRADE_STATUS
55 GoogleUpdate3ClassFactory* g_google_update_factory = nullptr;
57 // The time interval, in milliseconds, between polls to Google Update. This
58 // value was chosen unscientificaly during an informal discussion.
59 const int64_t kGoogleUpdatePollIntervalMs = 250;
61 // Constants from Google Update.
62 const HRESULT GOOPDATE_E_APP_UPDATE_DISABLED_BY_POLICY = 0x80040813;
63 const HRESULT GOOPDATEINSTALL_E_INSTALLER_FAILED = 0x80040902;
65 // Check if the currently running instance can be updated by Google Update.
66 // Returns GOOGLE_UPDATE_NO_ERROR only if the instance running is a Google
67 // Chrome distribution installed in a standard location.
68 GoogleUpdateErrorCode CanUpdateCurrentChrome(
69 const base::FilePath& chrome_exe_path,
70 bool system_level_install) {
71 DCHECK_NE(InstallUtil::IsPerUserInstall(chrome_exe_path),
72 system_level_install);
73 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
74 base::FilePath user_exe_path = installer::GetChromeInstallPath(false, dist);
75 base::FilePath machine_exe_path = installer::GetChromeInstallPath(true, dist);
76 if (!base::FilePath::CompareEqualIgnoreCase(chrome_exe_path.value(),
77 user_exe_path.value()) &&
78 !base::FilePath::CompareEqualIgnoreCase(chrome_exe_path.value(),
79 machine_exe_path.value())) {
80 return CANNOT_UPGRADE_CHROME_IN_THIS_DIRECTORY;
83 return GOOGLE_UPDATE_NO_ERROR;
86 // Explicitly allow the Google Update service to impersonate the client since
87 // some COM code elsewhere in the browser process may have previously used
88 // CoInitializeSecurity to set the impersonation level to something other than
89 // the default. Ignore errors since an attempt to use Google Update may succeed
90 // regardless.
91 void ConfigureProxyBlanket(IUnknown* interface_pointer) {
92 ::CoSetProxyBlanket(interface_pointer,
93 RPC_C_AUTHN_DEFAULT,
94 RPC_C_AUTHZ_DEFAULT,
95 COLE_DEFAULT_PRINCIPAL,
96 RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
97 RPC_C_IMP_LEVEL_IMPERSONATE,
98 nullptr,
99 EOAC_DYNAMIC_CLOAKING);
102 // Creates a class factory for a COM Local Server class using either plain
103 // vanilla CoGetClassObject, or using the Elevation moniker if running on
104 // Vista+. |hwnd| must refer to a foregound window in order to get the UAC
105 // prompt to appear in the foreground if running on Vista+. It can also be NULL
106 // if background UAC prompts are desired.
107 HRESULT CoGetClassObjectAsAdmin(REFCLSID class_id,
108 REFIID interface_id,
109 gfx::AcceleratedWidget hwnd,
110 void** interface_ptr) {
111 if (!interface_ptr)
112 return E_POINTER;
114 // For Vista+, need to instantiate the class factory via the elevation
115 // moniker. This ensures that the UAC dialog shows up.
116 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
117 wchar_t class_id_as_string[MAX_PATH] = {};
118 StringFromGUID2(class_id, class_id_as_string,
119 arraysize(class_id_as_string));
121 base::string16 elevation_moniker_name = base::StringPrintf(
122 L"Elevation:Administrator!clsid:%ls", class_id_as_string);
124 BIND_OPTS3 bind_opts;
125 // An explicit memset is needed rather than relying on value initialization
126 // since BIND_OPTS3 is not an aggregate (it is a derived type).
127 memset(&bind_opts, 0, sizeof(bind_opts));
128 bind_opts.cbStruct = sizeof(bind_opts);
129 bind_opts.dwClassContext = CLSCTX_LOCAL_SERVER;
130 bind_opts.hwnd = hwnd;
132 return ::CoGetObject(elevation_moniker_name.c_str(), &bind_opts,
133 interface_id, interface_ptr);
136 return ::CoGetClassObject(class_id, CLSCTX_LOCAL_SERVER, nullptr,
137 interface_id, interface_ptr);
140 HRESULT CreateGoogleUpdate3WebClass(
141 bool system_level_install,
142 bool install_update_if_possible,
143 gfx::AcceleratedWidget elevation_window,
144 base::win::ScopedComPtr<IGoogleUpdate3Web>* google_update) {
145 if (g_google_update_factory)
146 return g_google_update_factory->Run(google_update);
148 const CLSID& google_update_clsid = system_level_install ?
149 CLSID_GoogleUpdate3WebMachineClass :
150 CLSID_GoogleUpdate3WebUserClass;
151 base::win::ScopedComPtr<IClassFactory> class_factory;
152 HRESULT hresult = S_OK;
154 // For a user-level install, update checks and updates can both be done by a
155 // normal user with the UserClass. For a system-level install, update checks
156 // can be done by a normal user with the MachineClass.
157 if (!system_level_install || !install_update_if_possible) {
158 hresult = ::CoGetClassObject(google_update_clsid, CLSCTX_ALL, nullptr,
159 base::win::ScopedComPtr<IClassFactory>::iid(),
160 class_factory.ReceiveVoid());
161 } else {
162 // For a system-level install, an update requires Admin privileges for
163 // writing to %ProgramFiles%. Elevate while instantiating the MachineClass.
164 hresult = CoGetClassObjectAsAdmin(
165 google_update_clsid, base::win::ScopedComPtr<IClassFactory>::iid(),
166 elevation_window, class_factory.ReceiveVoid());
168 if (FAILED(hresult))
169 return hresult;
171 ConfigureProxyBlanket(class_factory.get());
173 return class_factory->CreateInstance(
174 nullptr,
175 base::win::ScopedComPtr<IGoogleUpdate3Web>::iid(),
176 google_update->ReceiveVoid());
179 // UpdateCheckDriver -----------------------------------------------------------
181 // A driver that is created and destroyed on the caller's thread and drives
182 // Google Update on another.
183 class UpdateCheckDriver {
184 public:
185 // Runs an update check on |task_runner|, invoking methods of |delegate| on
186 // the caller's thread to report progress and final results.
187 static void RunUpdateCheck(
188 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
189 const std::string& locale,
190 bool install_update_if_possible,
191 gfx::AcceleratedWidget elevation_window,
192 const base::WeakPtr<UpdateCheckDelegate>& delegate);
194 private:
195 friend class base::DeleteHelper<UpdateCheckDriver>;
197 UpdateCheckDriver(
198 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
199 const std::string& locale,
200 bool install_update_if_possible,
201 gfx::AcceleratedWidget elevation_window,
202 const base::WeakPtr<UpdateCheckDelegate>& delegate);
204 // Invokes a completion or error method on the caller's delegate, as
205 // appropriate.
206 ~UpdateCheckDriver();
208 // Starts an update check.
209 void BeginUpdateCheck();
211 // Returns the result of initiating an update check. Sets |error_code| if the
212 // result is any kind of failure.
213 HRESULT BeginUpdateCheckInternal(GoogleUpdateErrorCode* error_code);
215 // Sets status_ to UPGRADE_ERROR, error_code_ to |error_code|, hresult_ to
216 // |hresult|, installer_exit_code_ to |installer_exit_code|, and
217 // html_error_message_ to a composition of all values suitable for display
218 // to the user. This call should be followed by deletion of the driver,
219 // which will result in the caller being notified via its delegate.
220 void OnUpgradeError(GoogleUpdateErrorCode error_code,
221 HRESULT hresult,
222 int installer_exit_code,
223 const base::string16& error_string);
225 // Returns true if |current_state| and |state_value| can be obtained from the
226 // ongoing update check. Otherwise, populates |hresult| with the reason they
227 // could not be obtained.
228 bool GetCurrentState(base::win::ScopedComPtr<ICurrentState>* current_state,
229 CurrentState* state_value,
230 HRESULT* hresult) const;
232 // Returns true if |current_state| and |state_value| constitute an error state
233 // for the ongoing update check, in which case |error_code| is populated with
234 // one of GOOGLE_UPDATE_ERROR_UPDATING, GOOGLE_UPDATE_DISABLED_BY_POLICY, or
235 // GOOGLE_UPDATE_ONDEMAND_CLASS_REPORTED_ERROR. |hresult| is populated with
236 // the most relevant HRESULT (which may be a value from Google Update; see
237 // https://code.google.com/p/omaha/source/browse/trunk/base/error.h). In case
238 // Chrome's installer failed during execution, |installer_exit_code| may be
239 // populated with its process exit code (see enum installer::InstallStatus in
240 // chrome/installer/util/util_constants.h); otherwise, it will be -1.
241 // |error_string| will be populated with a completion message if one is
242 // provided by Google Update.
243 bool IsErrorState(const base::win::ScopedComPtr<ICurrentState>& current_state,
244 CurrentState state_value,
245 GoogleUpdateErrorCode* error_code,
246 HRESULT* hresult,
247 int* installer_exit_code,
248 base::string16* error_string) const;
250 // Returns true if |current_state| and |state_value| constitute a final state
251 // for the ongoing update check, in which case |upgrade_status| is populated
252 // with one of UPGRADE_ALREADY_UP_TO_DATE or UPGRADE_IS_AVAILABLE (in case a
253 // pure check is being performed rather than an update) or UPGRADE_SUCCESSFUL
254 // (in case an update is being performed). For the UPGRADE_IS_AVAILABLE case,
255 // |new_version| will be populated with the available version, if provided by
256 // Google Update.
257 bool IsFinalState(const base::win::ScopedComPtr<ICurrentState>& current_state,
258 CurrentState state_value,
259 GoogleUpdateUpgradeStatus* upgrade_status,
260 base::string16* new_version) const;
262 // Returns true if |current_state| and |state_value| constitute an
263 // intermediate state for the ongoing update check. |new_version| will be
264 // populated with the version to be installed if it is provided by Google
265 // Update for the current state. |progress| will be populated with a number
266 // between 0 and 100 according to how far Google Update has progressed in the
267 // download and install process.
268 bool IsIntermediateState(
269 const base::win::ScopedComPtr<ICurrentState>& current_state,
270 CurrentState state_value,
271 base::string16* new_version,
272 int* progress) const;
274 // Polls Google Update to determine the state of the ongoing check or
275 // update. If the process has reached a terminal state, this instance will be
276 // deleted and the caller will be notified of the final status. Otherwise, the
277 // caller will be notified of the intermediate state (iff it differs from a
278 // previous notification) and another future poll will be scheduled.
279 void PollGoogleUpdate();
281 // The task runner on which the update checks runs.
282 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
284 // The caller's task runner, on which methods of |delegate_| will be invoked.
285 scoped_refptr<base::SingleThreadTaskRunner> result_runner_;
287 // The UI locale.
288 std::string locale_;
290 // False to only check for an update; true to also install one if available.
291 bool install_update_if_possible_;
293 // A parent window in case any UX is required (e.g., an elevation prompt).
294 gfx::AcceleratedWidget elevation_window_;
296 // The caller's delegate by which feedback is conveyed.
297 base::WeakPtr<UpdateCheckDelegate> delegate_;
299 // True if operating on a per-machine installation rather than a per-user one.
300 bool system_level_install_;
302 // The on-demand updater that is doing the work.
303 base::win::ScopedComPtr<IGoogleUpdate3Web> google_update_;
305 // An app bundle containing the application being updated.
306 base::win::ScopedComPtr<IAppBundleWeb> app_bundle_;
308 // The application being updated (Chrome, Chrome Binaries, or Chrome SxS).
309 base::win::ScopedComPtr<IAppWeb> app_;
311 // The progress value reported most recently to the caller.
312 int last_reported_progress_;
314 // The results of the update check to be logged via UMA and/or reported to the
315 // caller.
316 GoogleUpdateUpgradeStatus status_;
317 GoogleUpdateErrorCode error_code_;
318 base::string16 html_error_message_;
319 base::string16 new_version_;
320 HRESULT hresult_;
321 int installer_exit_code_;
323 DISALLOW_COPY_AND_ASSIGN(UpdateCheckDriver);
326 // static
327 void UpdateCheckDriver::RunUpdateCheck(
328 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
329 const std::string& locale,
330 bool install_update_if_possible,
331 gfx::AcceleratedWidget elevation_window,
332 const base::WeakPtr<UpdateCheckDelegate>& delegate) {
333 // The driver is owned by itself, and will self-destruct when its work is
334 // done.
335 UpdateCheckDriver* driver =
336 new UpdateCheckDriver(task_runner, locale, install_update_if_possible,
337 elevation_window, delegate);
338 task_runner->PostTask(FROM_HERE,
339 base::Bind(&UpdateCheckDriver::BeginUpdateCheck,
340 base::Unretained(driver)));
343 // Runs on the caller's thread.
344 UpdateCheckDriver::UpdateCheckDriver(
345 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
346 const std::string& locale,
347 bool install_update_if_possible,
348 gfx::AcceleratedWidget elevation_window,
349 const base::WeakPtr<UpdateCheckDelegate>& delegate)
350 : task_runner_(task_runner),
351 result_runner_(base::ThreadTaskRunnerHandle::Get()),
352 locale_(locale),
353 install_update_if_possible_(install_update_if_possible),
354 elevation_window_(elevation_window),
355 delegate_(delegate),
356 system_level_install_(false),
357 last_reported_progress_(0),
358 status_(UPGRADE_ERROR),
359 error_code_(GOOGLE_UPDATE_NO_ERROR),
360 hresult_(S_OK),
361 installer_exit_code_(-1) {
364 UpdateCheckDriver::~UpdateCheckDriver() {
365 DCHECK(result_runner_->BelongsToCurrentThread());
366 // If there is an error, then error_code must not be blank, and vice versa.
367 DCHECK_NE(status_ == UPGRADE_ERROR, error_code_ == GOOGLE_UPDATE_NO_ERROR);
368 UMA_HISTOGRAM_ENUMERATION("GoogleUpdate.UpgradeResult", status_,
369 NUM_UPGRADE_STATUS);
370 if (status_ == UPGRADE_ERROR) {
371 UMA_HISTOGRAM_ENUMERATION("GoogleUpdate.UpdateErrorCode", error_code_,
372 NUM_ERROR_CODES);
373 if (FAILED(hresult_))
374 UMA_HISTOGRAM_SPARSE_SLOWLY("GoogleUpdate.ErrorHresult", hresult_);
375 if (installer_exit_code_ != -1) {
376 UMA_HISTOGRAM_SPARSE_SLOWLY("GoogleUpdate.InstallerExitCode",
377 installer_exit_code_);
380 if (delegate_) {
381 if (status_ == UPGRADE_ERROR)
382 delegate_->OnError(error_code_, html_error_message_, new_version_);
383 else if (install_update_if_possible_)
384 delegate_->OnUpgradeComplete(new_version_);
385 else
386 delegate_->OnUpdateCheckComplete(new_version_);
390 void UpdateCheckDriver::BeginUpdateCheck() {
391 GoogleUpdateErrorCode error_code = GOOGLE_UPDATE_NO_ERROR;
392 HRESULT hresult = BeginUpdateCheckInternal(&error_code);
393 if (SUCCEEDED(hresult)) {
394 // Start polling.
395 task_runner_->PostTask(FROM_HERE,
396 base::Bind(&UpdateCheckDriver::PollGoogleUpdate,
397 base::Unretained(this)));
398 } else {
399 // Return results immediately since the driver is not polling Google Update.
400 OnUpgradeError(error_code, hresult, -1, base::string16());
401 result_runner_->DeleteSoon(FROM_HERE, this);
405 HRESULT UpdateCheckDriver::BeginUpdateCheckInternal(
406 GoogleUpdateErrorCode* error_code) {
407 base::FilePath chrome_exe;
408 if (!PathService::Get(base::DIR_EXE, &chrome_exe))
409 NOTREACHED();
411 system_level_install_ = !InstallUtil::IsPerUserInstall(chrome_exe);
413 // Make sure ATL is initialized in this module.
414 ui::win::CreateATLModuleIfNeeded();
416 *error_code = CanUpdateCurrentChrome(chrome_exe, system_level_install_);
417 if (*error_code != GOOGLE_UPDATE_NO_ERROR)
418 return E_FAIL;
420 HRESULT hresult = CreateGoogleUpdate3WebClass(
421 system_level_install_, install_update_if_possible_, elevation_window_,
422 &google_update_);
423 if (FAILED(hresult)) {
424 *error_code = GOOGLE_UPDATE_ONDEMAND_CLASS_NOT_FOUND;
425 return hresult;
428 ConfigureProxyBlanket(google_update_.get());
430 // The class was created, so all subsequent errors are reported as:
431 *error_code = GOOGLE_UPDATE_ONDEMAND_CLASS_REPORTED_ERROR;
432 base::string16 app_guid =
433 installer::GetAppGuidForUpdates(system_level_install_);
434 DCHECK(!app_guid.empty());
437 base::win::ScopedComPtr<IDispatch> dispatch;
438 hresult = google_update_->createAppBundleWeb(dispatch.Receive());
439 if (FAILED(hresult))
440 return hresult;
441 hresult = dispatch.QueryInterface(app_bundle_.Receive());
442 if (FAILED(hresult))
443 return hresult;
445 ConfigureProxyBlanket(app_bundle_.get());
447 if (!locale_.empty()) {
448 // Ignore the result of this since, while setting the display language is
449 // nice to have, a failure to do so does not affect the likelihood that the
450 // update check and/or install will succeed.
451 app_bundle_->put_displayLanguage(
452 base::win::ScopedBstr(base::UTF8ToUTF16(locale_).c_str()));
455 hresult = app_bundle_->initialize();
456 if (FAILED(hresult))
457 return hresult;
458 if (elevation_window_) {
459 // Likewise, a failure to set the parent window need not block an update
460 // check.
461 app_bundle_->put_parentHWND(reinterpret_cast<ULONG_PTR>(elevation_window_));
464 base::win::ScopedComPtr<IDispatch> dispatch;
465 hresult =
466 app_bundle_->createInstalledApp(base::win::ScopedBstr(app_guid.c_str()));
467 if (FAILED(hresult))
468 return hresult;
469 hresult = app_bundle_->get_appWeb(0, dispatch.Receive());
470 if (FAILED(hresult))
471 return hresult;
472 hresult = dispatch.QueryInterface(app_.Receive());
473 if (FAILED(hresult))
474 return hresult;
475 ConfigureProxyBlanket(app_.get());
476 return app_bundle_->checkForUpdate();
479 bool UpdateCheckDriver::GetCurrentState(
480 base::win::ScopedComPtr<ICurrentState>* current_state,
481 CurrentState* state_value,
482 HRESULT* hresult) const {
483 base::win::ScopedComPtr<IDispatch> dispatch;
484 *hresult = app_->get_currentState(dispatch.Receive());
485 if (FAILED(*hresult))
486 return false;
487 *hresult = dispatch.QueryInterface(current_state->Receive());
488 if (FAILED(*hresult))
489 return false;
490 ConfigureProxyBlanket(current_state->get());
491 LONG value = 0;
492 *hresult = (*current_state)->get_stateValue(&value);
493 if (FAILED(*hresult))
494 return false;
495 *state_value = static_cast<CurrentState>(value);
496 return true;
499 bool UpdateCheckDriver::IsErrorState(
500 const base::win::ScopedComPtr<ICurrentState>& current_state,
501 CurrentState state_value,
502 GoogleUpdateErrorCode* error_code,
503 HRESULT* hresult,
504 int* installer_exit_code,
505 base::string16* error_string) const {
506 if (state_value == STATE_ERROR) {
507 // In general, errors reported by Google Update fall under this category
508 // (see special case below).
509 *error_code = GOOGLE_UPDATE_ERROR_UPDATING;
511 // In general, the exit code of Chrome's installer is unknown (see special
512 // case below).
513 *installer_exit_code = -1;
515 // Report the error_code provided by Google Update if possible, or the
516 // reason it wasn't possible otherwise.
517 LONG long_value = 0;
518 *hresult = current_state->get_errorCode(&long_value);
519 if (SUCCEEDED(*hresult))
520 *hresult = long_value;
522 // Special cases:
523 // - Use a custom error code if Google Update repoted that the update was
524 // disabled by a Group Policy setting.
525 // - Extract the exit code of Chrome's installer if Google Update repoted
526 // that the update failed because of a failure in the installer.
527 LONG code = 0;
528 if (*hresult == GOOPDATE_E_APP_UPDATE_DISABLED_BY_POLICY) {
529 *error_code = GOOGLE_UPDATE_DISABLED_BY_POLICY;
530 } else if (*hresult == GOOPDATEINSTALL_E_INSTALLER_FAILED &&
531 SUCCEEDED(current_state->get_installerResultCode(&code))) {
532 *installer_exit_code = code;
535 base::win::ScopedBstr message;
536 if (SUCCEEDED(current_state->get_completionMessage(message.Receive())))
537 error_string->assign(message, message.Length());
539 return true;
541 if (state_value == STATE_UPDATE_AVAILABLE && install_update_if_possible_) {
542 *hresult = app_bundle_->install();
543 if (FAILED(*hresult)) {
544 // Report a failure to start the install as a general error while trying
545 // to interact with Google Update.
546 *error_code = GOOGLE_UPDATE_ONDEMAND_CLASS_REPORTED_ERROR;
547 *installer_exit_code = -1;
548 return true;
550 // Return false for handling in IsIntermediateState.
552 return false;
555 bool UpdateCheckDriver::IsFinalState(
556 const base::win::ScopedComPtr<ICurrentState>& current_state,
557 CurrentState state_value,
558 GoogleUpdateUpgradeStatus* upgrade_status,
559 base::string16* new_version) const {
560 if (state_value == STATE_UPDATE_AVAILABLE && !install_update_if_possible_) {
561 base::win::ScopedBstr version;
562 *upgrade_status = UPGRADE_IS_AVAILABLE;
563 if (SUCCEEDED(current_state->get_availableVersion(version.Receive())))
564 new_version->assign(version, version.Length());
565 return true;
567 if (state_value == STATE_INSTALL_COMPLETE) {
568 DCHECK(install_update_if_possible_);
569 *upgrade_status = UPGRADE_SUCCESSFUL;
570 return true;
572 if (state_value == STATE_NO_UPDATE) {
573 *upgrade_status = UPGRADE_ALREADY_UP_TO_DATE;
574 return true;
576 return false;
579 bool UpdateCheckDriver::IsIntermediateState(
580 const base::win::ScopedComPtr<ICurrentState>& current_state,
581 CurrentState state_value,
582 base::string16* new_version,
583 int* progress) const {
584 // ERROR will have been handled in IsErrorState. UPDATE_AVAILABLE, and
585 // NO_UPDATE will have been handled in IsFinalState if not doing an install,
586 // as will STATE_INSTALL_COMPLETE when doing an install. All other states
587 // following UPDATE_AVAILABLE will only happen when an install is to be done.
588 DCHECK(state_value < STATE_UPDATE_AVAILABLE || install_update_if_possible_);
589 *progress = 0;
591 switch (state_value) {
592 case STATE_INIT:
593 case STATE_WAITING_TO_CHECK_FOR_UPDATE:
594 case STATE_CHECKING_FOR_UPDATE:
595 // There is no news to report yet.
596 break;
598 case STATE_UPDATE_AVAILABLE: {
599 base::win::ScopedBstr version;
600 if (SUCCEEDED(current_state->get_availableVersion(version.Receive())))
601 new_version->assign(version, version.Length());
602 break;
605 case STATE_WAITING_TO_DOWNLOAD:
606 case STATE_RETRYING_DOWNLOAD:
607 break;
609 case STATE_DOWNLOADING: {
610 ULONG bytes_downloaded = 0;
611 ULONG total_bytes = 0;
612 if (SUCCEEDED(current_state->get_bytesDownloaded(&bytes_downloaded)) &&
613 SUCCEEDED(current_state->get_totalBytesToDownload(&total_bytes)) &&
614 total_bytes) {
615 // 0-50 is downloading.
616 *progress = gfx::ToFlooredInt((static_cast<double>(bytes_downloaded) /
617 static_cast<double>(total_bytes)) *
618 50.0);
620 break;
623 case STATE_DOWNLOAD_COMPLETE:
624 case STATE_EXTRACTING:
625 case STATE_APPLYING_DIFFERENTIAL_PATCH:
626 case STATE_READY_TO_INSTALL:
627 case STATE_WAITING_TO_INSTALL:
628 *progress = 50;
629 break;
631 case STATE_INSTALLING: {
632 *progress = 50;
633 LONG install_progress = 0;
634 if (SUCCEEDED(current_state->get_installProgress(&install_progress)) &&
635 install_progress >= 0 && install_progress <= 100) {
636 // 50-100 is installing.
637 *progress = (50 + install_progress / 2);
639 break;
642 case STATE_INSTALL_COMPLETE:
643 case STATE_PAUSED:
644 case STATE_NO_UPDATE:
645 case STATE_ERROR:
646 default:
647 NOTREACHED();
648 UMA_HISTOGRAM_SPARSE_SLOWLY("GoogleUpdate.UnexpectedState", state_value);
649 return false;
651 return true;
654 void UpdateCheckDriver::PollGoogleUpdate() {
655 base::win::ScopedComPtr<ICurrentState> state;
656 CurrentState state_value = STATE_INIT;
657 HRESULT hresult = S_OK;
658 GoogleUpdateErrorCode error_code = GOOGLE_UPDATE_NO_ERROR;
659 int installer_exit_code = -1;
660 base::string16 error_string;
661 GoogleUpdateUpgradeStatus upgrade_status = UPGRADE_ERROR;
662 base::string16 new_version;
663 int progress = 0;
665 if (!GetCurrentState(&state, &state_value, &hresult)) {
666 OnUpgradeError(GOOGLE_UPDATE_ONDEMAND_CLASS_REPORTED_ERROR, hresult, -1,
667 base::string16());
668 } else if (IsErrorState(state, state_value, &error_code, &hresult,
669 &installer_exit_code, &error_string)) {
670 OnUpgradeError(error_code, hresult, installer_exit_code, error_string);
671 } else if (IsFinalState(state, state_value, &upgrade_status, &new_version)) {
672 status_ = upgrade_status;
673 error_code_ = GOOGLE_UPDATE_NO_ERROR;
674 html_error_message_.clear();
675 if (!new_version.empty())
676 new_version_ = new_version;
677 hresult_ = S_OK;
678 installer_exit_code_ = -1;
679 } else if (IsIntermediateState(state, state_value, &new_version, &progress)) {
680 bool got_new_version = new_version_.empty() && !new_version.empty();
681 if (got_new_version)
682 new_version_ = new_version;
683 // Give the caller this status update if it differs from the last one given.
684 if (got_new_version || progress != last_reported_progress_) {
685 last_reported_progress_ = progress;
687 // It is safe to post this task with an unretained pointer since the task
688 // is guaranteed to run before a subsequent DeleteSoon is handled.
689 result_runner_->PostTask(
690 FROM_HERE,
691 base::Bind(&UpdateCheckDelegate::OnUpgradeProgress, delegate_,
692 last_reported_progress_, new_version_));
695 // Schedule the next check.
696 task_runner_->PostDelayedTask(
697 FROM_HERE, base::Bind(&UpdateCheckDriver::PollGoogleUpdate,
698 base::Unretained(this)),
699 base::TimeDelta::FromMilliseconds(kGoogleUpdatePollIntervalMs));
700 // Early return for this non-terminal state.
701 return;
704 // Release the reference on the COM objects before bouncing back to the
705 // caller's thread.
706 state.Release();
707 app_.Release();
708 app_bundle_.Release();
709 google_update_.Release();
711 result_runner_->DeleteSoon(FROM_HERE, this);
714 void UpdateCheckDriver::OnUpgradeError(GoogleUpdateErrorCode error_code,
715 HRESULT hresult,
716 int installer_exit_code,
717 const base::string16& error_string) {
718 status_ = UPGRADE_ERROR;
719 error_code_ = error_code;
720 hresult_ = hresult;
721 installer_exit_code_ = installer_exit_code;
722 base::string16 html_error_msg =
723 base::StringPrintf(L"%d: <a href='%ls0x%X' target=_blank>0x%X</a>",
724 error_code_, base::UTF8ToUTF16(
725 chrome::kUpgradeHelpCenterBaseURL).c_str(),
726 hresult_, hresult_);
727 if (installer_exit_code_ != -1)
728 html_error_msg += base::StringPrintf(L": %d", installer_exit_code_);
729 if (system_level_install_)
730 html_error_msg += L" -- system level";
731 if (error_string.empty()) {
732 html_error_message_ = l10n_util::GetStringFUTF16(
733 IDS_ABOUT_BOX_ERROR_UPDATE_CHECK_FAILED, html_error_msg);
734 } else {
735 html_error_message_ = l10n_util::GetStringFUTF16(
736 IDS_ABOUT_BOX_GOOGLE_UPDATE_ERROR, error_string, html_error_msg);
740 } // namespace
743 // Globals ---------------------------------------------------------------------
745 void BeginUpdateCheck(
746 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
747 const std::string& locale,
748 bool install_update_if_possible,
749 gfx::AcceleratedWidget elevation_window,
750 const base::WeakPtr<UpdateCheckDelegate>& delegate) {
751 UpdateCheckDriver::RunUpdateCheck(task_runner, locale,
752 install_update_if_possible,
753 elevation_window, delegate);
757 // Private API exposed for testing. --------------------------------------------
759 void SetGoogleUpdateFactoryForTesting(
760 const GoogleUpdate3ClassFactory& google_update_factory) {
761 if (g_google_update_factory) {
762 delete g_google_update_factory;
763 g_google_update_factory = nullptr;
765 if (!google_update_factory.is_null()) {
766 g_google_update_factory =
767 new GoogleUpdate3ClassFactory(google_update_factory);