Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / chrome / installer / setup / setup_main.cc
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 "chrome/installer/setup/setup_main.h"
6
7 #include <windows.h>
8 #include <msi.h>
9 #include <shellapi.h>
10 #include <shlobj.h>
11
12 #include <string>
13
14 #include "base/at_exit.h"
15 #include "base/basictypes.h"
16 #include "base/command_line.h"
17 #include "base/file_util.h"
18 #include "base/file_version_info.h"
19 #include "base/files/file_path.h"
20 #include "base/files/scoped_temp_dir.h"
21 #include "base/path_service.h"
22 #include "base/process/launch.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/values.h"
29 #include "base/win/registry.h"
30 #include "base/win/scoped_com_initializer.h"
31 #include "base/win/scoped_comptr.h"
32 #include "base/win/scoped_handle.h"
33 #include "base/win/win_util.h"
34 #include "base/win/windows_version.h"
35 #include "breakpad/src/client/windows/handler/exception_handler.h"
36 #include "chrome/common/chrome_constants.h"
37 #include "chrome/common/chrome_switches.h"
38 #include "chrome/installer/setup/archive_patch_helper.h"
39 #include "chrome/installer/setup/install.h"
40 #include "chrome/installer/setup/install_worker.h"
41 #include "chrome/installer/setup/setup_constants.h"
42 #include "chrome/installer/setup/setup_util.h"
43 #include "chrome/installer/setup/uninstall.h"
44 #include "chrome/installer/util/browser_distribution.h"
45 #include "chrome/installer/util/channel_info.h"
46 #include "chrome/installer/util/delete_after_reboot_helper.h"
47 #include "chrome/installer/util/delete_tree_work_item.h"
48 #include "chrome/installer/util/eula_util.h"
49 #include "chrome/installer/util/google_update_constants.h"
50 #include "chrome/installer/util/google_update_settings.h"
51 #include "chrome/installer/util/google_update_util.h"
52 #include "chrome/installer/util/helper.h"
53 #include "chrome/installer/util/html_dialog.h"
54 #include "chrome/installer/util/install_util.h"
55 #include "chrome/installer/util/installation_state.h"
56 #include "chrome/installer/util/installation_validator.h"
57 #include "chrome/installer/util/installer_state.h"
58 #include "chrome/installer/util/l10n_string_util.h"
59 #include "chrome/installer/util/logging_installer.h"
60 #include "chrome/installer/util/lzma_util.h"
61 #include "chrome/installer/util/master_preferences.h"
62 #include "chrome/installer/util/master_preferences_constants.h"
63 #include "chrome/installer/util/self_cleaning_temp_dir.h"
64 #include "chrome/installer/util/shell_util.h"
65 #include "chrome/installer/util/user_experiment.h"
66
67 #include "installer_util_strings.h"  // NOLINT
68
69 using installer::InstallerState;
70 using installer::InstallationState;
71 using installer::InstallationValidator;
72 using installer::MasterPreferences;
73 using installer::Product;
74 using installer::ProductState;
75 using installer::Products;
76
77 const wchar_t kChromePipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
78 const wchar_t kGoogleUpdatePipeName[] = L"\\\\.\\pipe\\GoogleCrashServices\\";
79 const wchar_t kSystemPrincipalSid[] = L"S-1-5-18";
80
81 const MINIDUMP_TYPE kLargerDumpType = static_cast<MINIDUMP_TYPE>(
82     MiniDumpWithProcessThreadData |  // Get PEB and TEB.
83     MiniDumpWithUnloadedModules |  // Get unloaded modules when available.
84     MiniDumpWithIndirectlyReferencedMemory);  // Get memory referenced by stack.
85
86 namespace {
87
88 // Returns NULL if no compressed archive is available for processing, otherwise
89 // returns a patch helper configured to uncompress and patch.
90 scoped_ptr<installer::ArchivePatchHelper> CreateChromeArchiveHelper(
91     const CommandLine& command_line,
92     const installer::InstallerState& installer_state,
93     const base::FilePath& working_directory) {
94   // A compressed archive is ordinarily given on the command line by the mini
95   // installer. If one was not given, look for chrome.packed.7z next to the
96   // running program.
97   base::FilePath compressed_archive(
98       command_line.GetSwitchValuePath(installer::switches::kInstallArchive));
99   bool compressed_archive_specified = !compressed_archive.empty();
100   if (!compressed_archive_specified) {
101     compressed_archive =
102         command_line.GetProgram().DirName().Append(
103             installer::kChromeCompressedArchive);
104   }
105
106   // Fail if no compressed archive is found.
107   if (!base::PathExists(compressed_archive)) {
108     if (compressed_archive_specified) {
109       LOG(ERROR) << installer::switches::kInstallArchive << "="
110                  << compressed_archive.value() << " not found.";
111     }
112     return scoped_ptr<installer::ArchivePatchHelper>();
113   }
114
115   // chrome.7z is either extracted directly from the compressed archive into the
116   // working dir or is the target of patching in the working dir.
117   base::FilePath target(working_directory.Append(installer::kChromeArchive));
118   DCHECK(!base::PathExists(target));
119
120   // Specify an empty path for the patch source since it isn't yet known that
121   // one is needed. It will be supplied in UncompressAndPatchChromeArchive if it
122   // is.
123   return scoped_ptr<installer::ArchivePatchHelper>(
124       new installer::ArchivePatchHelper(working_directory,
125                                         compressed_archive,
126                                         base::FilePath(),
127                                         target));
128 }
129
130 // Workhorse for producing an uncompressed archive (chrome.7z) given a
131 // chrome.packed.7z containing either a patch file based on the version of
132 // chrome being updated or the full uncompressed archive. Returns true on
133 // success, in which case |archive_type| is populated based on what was found.
134 // Returns false on failure, in which case |install_status| contains the error
135 // code and the result is written to the registry (via WriteInstallerResult).
136 bool UncompressAndPatchChromeArchive(
137     const installer::InstallationState& original_state,
138     const installer::InstallerState& installer_state,
139     installer::ArchivePatchHelper* archive_helper,
140     installer::ArchiveType* archive_type,
141     installer::InstallStatus* install_status) {
142   installer_state.UpdateStage(installer::UNCOMPRESSING);
143   if (!archive_helper->Uncompress(NULL)) {
144     *install_status = installer::UNCOMPRESSION_FAILED;
145     installer_state.WriteInstallerResult(*install_status,
146                                          IDS_INSTALL_UNCOMPRESSION_FAILED_BASE,
147                                          NULL);
148     return false;
149   }
150
151   // Short-circuit if uncompression produced the uncompressed archive rather
152   // than a patch file.
153   if (base::PathExists(archive_helper->target())) {
154     *archive_type = installer::FULL_ARCHIVE_TYPE;
155     return true;
156   }
157
158   // Find the installed version's archive to serve as the source for patching.
159   base::FilePath patch_source(installer::FindArchiveToPatch(original_state,
160                                                             installer_state));
161   if (patch_source.empty()) {
162     LOG(ERROR) << "Failed to find archive to patch.";
163     *install_status = installer::DIFF_PATCH_SOURCE_MISSING;
164     installer_state.WriteInstallerResult(*install_status,
165                                          IDS_INSTALL_UNCOMPRESSION_FAILED_BASE,
166                                          NULL);
167     return false;
168   }
169   archive_helper->set_patch_source(patch_source);
170
171   // Try courgette first. Failing that, try bspatch.
172   if ((installer_state.UpdateStage(installer::ENSEMBLE_PATCHING),
173        !archive_helper->EnsemblePatch()) &&
174       (installer_state.UpdateStage(installer::BINARY_PATCHING),
175        !archive_helper->BinaryPatch())) {
176     *install_status = installer::APPLY_DIFF_PATCH_FAILED;
177     installer_state.WriteInstallerResult(*install_status,
178                                          IDS_INSTALL_UNCOMPRESSION_FAILED_BASE,
179                                          NULL);
180     return false;
181   }
182
183   *archive_type = installer::INCREMENTAL_ARCHIVE_TYPE;
184   return true;
185 }
186
187 // In multi-install, adds all products to |installer_state| that are
188 // multi-installed and must be updated along with the products already present
189 // in |installer_state|.
190 void AddExistingMultiInstalls(const InstallationState& original_state,
191                               InstallerState* installer_state) {
192   if (installer_state->is_multi_install()) {
193     for (size_t i = 0; i < BrowserDistribution::NUM_TYPES; ++i) {
194       BrowserDistribution::Type type =
195           static_cast<BrowserDistribution::Type>(i);
196
197       if (!installer_state->FindProduct(type)) {
198         const ProductState* state =
199             original_state.GetProductState(installer_state->system_install(),
200                                            type);
201         if ((state != NULL) && state->is_multi_install()) {
202           installer_state->AddProductFromState(type, *state);
203           VLOG(1) << "Product already installed and must be included: "
204                   << BrowserDistribution::GetSpecificDistribution(type)->
205                          GetDisplayName();
206         }
207       }
208     }
209   }
210 }
211
212 // This function is called when --rename-chrome-exe option is specified on
213 // setup.exe command line. This function assumes an in-use update has happened
214 // for Chrome so there should be a file called new_chrome.exe on the file
215 // system and a key called 'opv' in the registry. This function will move
216 // new_chrome.exe to chrome.exe and delete 'opv' key in one atomic operation.
217 // This function also deletes elevation policies associated with the old version
218 // if they exist.
219 installer::InstallStatus RenameChromeExecutables(
220     const InstallationState& original_state,
221     InstallerState* installer_state) {
222   // See what products are already installed in multi mode.  When we do the
223   // rename for multi installs, we must update all installations since they
224   // share the binaries.
225   AddExistingMultiInstalls(original_state, installer_state);
226   const base::FilePath &target_path = installer_state->target_path();
227   base::FilePath chrome_exe(target_path.Append(installer::kChromeExe));
228   base::FilePath chrome_new_exe(target_path.Append(installer::kChromeNewExe));
229   base::FilePath chrome_old_exe(target_path.Append(installer::kChromeOldExe));
230
231   // Create a temporary backup directory on the same volume as chrome.exe so
232   // that moving in-use files doesn't lead to trouble.
233   installer::SelfCleaningTempDir temp_path;
234   if (!temp_path.Initialize(target_path.DirName(),
235                             installer::kInstallTempDir)) {
236     PLOG(ERROR) << "Failed to create Temp directory "
237                 << target_path.DirName()
238                        .Append(installer::kInstallTempDir).value();
239     return installer::RENAME_FAILED;
240   }
241   scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
242   // Move chrome.exe to old_chrome.exe, then move new_chrome.exe to chrome.exe.
243   install_list->AddMoveTreeWorkItem(chrome_exe.value(),
244                                     chrome_old_exe.value(),
245                                     temp_path.path().value(),
246                                     WorkItem::ALWAYS_MOVE);
247   install_list->AddMoveTreeWorkItem(chrome_new_exe.value(),
248                                     chrome_exe.value(),
249                                     temp_path.path().value(),
250                                     WorkItem::ALWAYS_MOVE);
251   install_list->AddDeleteTreeWorkItem(chrome_new_exe, temp_path.path());
252   // old_chrome.exe is still in use in most cases, so ignore failures here.
253   install_list->AddDeleteTreeWorkItem(chrome_old_exe, temp_path.path())->
254       set_ignore_failure(true);
255
256   // Add work items to delete the "opv", "cpv", and "cmd" values from all
257   // products we're operating on (which including the multi-install binaries).
258   const Products& products = installer_state->products();
259   HKEY reg_root = installer_state->root_key();
260   base::string16 version_key;
261   for (Products::const_iterator it = products.begin(); it < products.end();
262        ++it) {
263     version_key = (*it)->distribution()->GetVersionKey();
264     install_list->AddDeleteRegValueWorkItem(
265         reg_root, version_key, google_update::kRegOldVersionField);
266     install_list->AddDeleteRegValueWorkItem(
267         reg_root, version_key, google_update::kRegCriticalVersionField);
268     install_list->AddDeleteRegValueWorkItem(
269         reg_root, version_key, google_update::kRegRenameCmdField);
270   }
271   installer::InstallStatus ret = installer::RENAME_SUCCESSFUL;
272   if (!install_list->Do()) {
273     LOG(ERROR) << "Renaming of executables failed. Rolling back any changes.";
274     install_list->Rollback();
275     ret = installer::RENAME_FAILED;
276   }
277   // temp_path's dtor will take care of deleting or scheduling itself for
278   // deletion at reboot when this scope closes.
279   VLOG(1) << "Deleting temporary directory " << temp_path.path().value();
280
281   return ret;
282 }
283
284 // For each product that is being updated (i.e., already installed at an earlier
285 // version), see if that product has an update policy override that differs from
286 // that for the binaries.  If any are found, fail with an error indicating that
287 // the Group Policy settings are in an inconsistent state.  Do not do this test
288 // for same-version installs, since it would be unkind to block attempts to
289 // repair a corrupt installation.  This function returns false when installation
290 // should be halted, in which case |status| contains the relevant exit code and
291 // the proper installer result has been written to the registry.
292 bool CheckGroupPolicySettings(const InstallationState& original_state,
293                               const InstallerState& installer_state,
294                               const Version& new_version,
295                               installer::InstallStatus* status) {
296 #if !defined(GOOGLE_CHROME_BUILD)
297   // Chromium builds are not updated via Google Update, so there are no
298   // Group Policy settings to consult.
299   return true;
300 #else
301   DCHECK(status);
302
303   // Single installs are always in good shape.
304   if (!installer_state.is_multi_install())
305     return true;
306
307   bool settings_are_valid = true;
308   const bool is_system_install = installer_state.system_install();
309   BrowserDistribution* const binaries_dist =
310       installer_state.multi_package_binaries_distribution();
311
312   // Get the update policy for the binaries.
313   const GoogleUpdateSettings::UpdatePolicy binaries_policy =
314       GoogleUpdateSettings::GetAppUpdatePolicy(binaries_dist->GetAppGuid(),
315                                                NULL);
316
317   // Check for differing update policies for all of the products being updated.
318   const Products& products = installer_state.products();
319   Products::const_iterator scan = products.begin();
320   for (Products::const_iterator end = products.end(); scan != end; ++scan) {
321     BrowserDistribution* dist = (*scan)->distribution();
322     const ProductState* product_state =
323         original_state.GetProductState(is_system_install, dist->GetType());
324     // Is an earlier version of this product already installed?
325     if (product_state != NULL &&
326         product_state->version().CompareTo(new_version) < 0) {
327       bool is_overridden = false;
328       GoogleUpdateSettings::UpdatePolicy app_policy =
329           GoogleUpdateSettings::GetAppUpdatePolicy(dist->GetAppGuid(),
330                                                    &is_overridden);
331       if (is_overridden && app_policy != binaries_policy) {
332         LOG(ERROR) << "Found legacy Group Policy setting for "
333                    << dist->GetDisplayName() << " (value: " << app_policy
334                    << ") that does not match the setting for "
335                    << binaries_dist->GetDisplayName()
336                    << " (value: " << binaries_policy << ").";
337         settings_are_valid = false;
338       }
339     }
340   }
341
342   if (!settings_are_valid) {
343     // TODO(grt): add " See http://goo.gl/+++ for details." to the end of this
344     // log message and to the IDS_INSTALL_INCONSISTENT_UPDATE_POLICY string once
345     // we have a help center article that explains why this error is being
346     // reported and how to resolve it.
347     LOG(ERROR) << "Cannot apply update on account of inconsistent "
348                   "Google Update Group Policy settings. Use the Group Policy "
349                   "Editor to set the update policy override for the "
350                << binaries_dist->GetDisplayName()
351                << " application and try again.";
352     *status = installer::INCONSISTENT_UPDATE_POLICY;
353     installer_state.WriteInstallerResult(
354         *status, IDS_INSTALL_INCONSISTENT_UPDATE_POLICY_BASE, NULL);
355   }
356
357   return settings_are_valid;
358 #endif  // defined(GOOGLE_CHROME_BUILD)
359 }
360
361 // If only the binaries are being updated, fail.
362 // If any product is being installed in single-mode that already exists in
363 // multi-mode, fail.
364 bool CheckMultiInstallConditions(const InstallationState& original_state,
365                                  InstallerState* installer_state,
366                                  installer::InstallStatus* status) {
367   const Products& products = installer_state->products();
368   DCHECK(products.size());
369
370   const bool system_level = installer_state->system_install();
371
372   if (installer_state->is_multi_install()) {
373     const Product* chrome =
374         installer_state->FindProduct(BrowserDistribution::CHROME_BROWSER);
375     const Product* app_host =
376         installer_state->FindProduct(BrowserDistribution::CHROME_APP_HOST);
377     const Product* binaries =
378         installer_state->FindProduct(BrowserDistribution::CHROME_BINARIES);
379     const ProductState* chrome_state =
380         original_state.GetProductState(system_level,
381                                        BrowserDistribution::CHROME_BROWSER);
382
383     if (binaries) {
384       if (products.size() == 1) {
385         // There are no products aside from the binaries, so there is no update
386         // to be applied. This can happen after multi-install Chrome Frame is
387         // migrated to single-install. This is treated as an update failure
388         // unless the binaries are not in-use, in which case they will be
389         // uninstalled and success will be reported (see handling in wWinMain).
390         VLOG(1) << "No products to be updated.";
391         *status = installer::UNUSED_BINARIES;
392         installer_state->WriteInstallerResult(*status, 0, NULL);
393         return false;
394       }
395     } else {
396       // This will only be hit if --multi-install is given with no products, or
397       // if the app host is being installed and doesn't need the binaries at
398       // user-level.
399       // The former case might be due to a request by an orphaned Application
400       // Host to re-install the binaries. Thus we add them to the installation.
401       // The latter case is fine and we let it be.
402       // If this is not an app host install and the binaries are not already
403       // present, the installation will fail later due to a lack of products to
404       // install.
405       if (app_host && !chrome && !chrome_state) {
406         DCHECK(!system_level);
407         // App Host may use Chrome/Chrome binaries at system-level.
408         if (original_state.GetProductState(
409                 true,  // system
410                 BrowserDistribution::CHROME_BROWSER) ||
411             original_state.GetProductState(
412                 true,  // system
413                 BrowserDistribution::CHROME_BINARIES)) {
414           VLOG(1) << "Installing/updating App Launcher without binaries.";
415         } else {
416           // Somehow the binaries were present when the quick-enable app host
417           // command was run, but now they appear to be missing.
418           // Force binaries to be installed/updated.
419           scoped_ptr<Product> binaries_to_add(new Product(
420               BrowserDistribution::GetSpecificDistribution(
421                   BrowserDistribution::CHROME_BINARIES)));
422           binaries_to_add->SetOption(installer::kOptionMultiInstall, true);
423           binaries = installer_state->AddProduct(&binaries_to_add);
424           VLOG(1) <<
425               "Adding binaries for pre-existing App Launcher installation.";
426         }
427       }
428
429       return true;
430     }
431
432     if (!chrome && chrome_state) {
433       // A product other than Chrome is being installed in multi-install mode,
434       // and Chrome is already present. Add Chrome to the set of products
435       // (making it multi-install in the process) so that it is updated, too.
436       scoped_ptr<Product> multi_chrome(new Product(
437           BrowserDistribution::GetSpecificDistribution(
438               BrowserDistribution::CHROME_BROWSER)));
439       multi_chrome->SetOption(installer::kOptionMultiInstall, true);
440       chrome = installer_state->AddProduct(&multi_chrome);
441       VLOG(1) << "Upgrading existing Chrome browser in multi-install mode.";
442     }
443   } else {
444     // This is a non-multi installation.
445
446     // Check for an existing installation of the product.
447     const ProductState* product_state = original_state.GetProductState(
448         system_level, products[0]->distribution()->GetType());
449     if (product_state != NULL) {
450       // Block downgrades from multi-install to single-install.
451       if (product_state->is_multi_install()) {
452         LOG(ERROR) << "Multi-install "
453                    << products[0]->distribution()->GetDisplayName()
454                    << " exists; aborting single install.";
455         *status = installer::MULTI_INSTALLATION_EXISTS;
456         installer_state->WriteInstallerResult(*status,
457             IDS_INSTALL_MULTI_INSTALLATION_EXISTS_BASE, NULL);
458         return false;
459       }
460     }
461   }
462
463   return true;
464 }
465
466 // Checks app host pre-install conditions, specifically that this is a
467 // user-level multi-install.  When the pre-install conditions are not
468 // satisfied, the result is written to the registry (via WriteInstallerResult),
469 // |status| is set appropriately, and false is returned.
470 bool CheckAppHostPreconditions(const InstallationState& original_state,
471                                InstallerState* installer_state,
472                                installer::InstallStatus* status) {
473   if (installer_state->FindProduct(BrowserDistribution::CHROME_APP_HOST)) {
474     if (!installer_state->is_multi_install()) {
475       LOG(DFATAL) << "App Launcher requires multi install";
476       *status = installer::APP_HOST_REQUIRES_MULTI_INSTALL;
477       // No message string since there is nothing a user can do.
478       installer_state->WriteInstallerResult(*status, 0, NULL);
479       return false;
480     }
481
482     if (installer_state->system_install()) {
483       LOG(DFATAL) << "App Launcher may only be installed at user-level.";
484       *status = installer::APP_HOST_REQUIRES_USER_LEVEL;
485       // No message string since there is nothing a user can do.
486       installer_state->WriteInstallerResult(*status, 0, NULL);
487       return false;
488     }
489   }
490
491   return true;
492 }
493
494 // Checks for compatibility between the current state of the system and the
495 // desired operation.  Also applies policy that mutates the desired operation;
496 // specifically, the |installer_state| object.
497 // Also blocks simultaneous user-level and system-level installs.  In the case
498 // of trying to install user-level Chrome when system-level exists, the
499 // existing system-level Chrome is launched.
500 // When the pre-install conditions are not satisfied, the result is written to
501 // the registry (via WriteInstallerResult), |status| is set appropriately, and
502 // false is returned.
503 bool CheckPreInstallConditions(const InstallationState& original_state,
504                                InstallerState* installer_state,
505                                installer::InstallStatus* status) {
506   if (!CheckAppHostPreconditions(original_state, installer_state, status)) {
507     DCHECK_NE(*status, installer::UNKNOWN_STATUS);
508     return false;
509   }
510
511   // See what products are already installed in multi mode.  When we do multi
512   // installs, we must upgrade all installations since they share the binaries.
513   AddExistingMultiInstalls(original_state, installer_state);
514
515   if (!CheckMultiInstallConditions(original_state, installer_state, status)) {
516     DCHECK_NE(*status, installer::UNKNOWN_STATUS);
517     return false;
518   }
519
520   const Products& products = installer_state->products();
521   if (products.empty()) {
522     // We haven't been given any products on which to operate.
523     LOG(ERROR)
524         << "Not given any products to install and no products found to update.";
525     *status = installer::CHROME_NOT_INSTALLED;
526     installer_state->WriteInstallerResult(*status,
527         IDS_INSTALL_NO_PRODUCTS_TO_UPDATE_BASE, NULL);
528     return false;
529   }
530
531   if (!installer_state->system_install()) {
532     // This is a user-level installation. Make sure that we are not installing
533     // on top of an existing system-level installation.
534     for (Products::const_iterator it = products.begin(); it < products.end();
535          ++it) {
536       const Product& product = **it;
537       BrowserDistribution* browser_dist = product.distribution();
538
539       // Skip over the binaries, as it's okay for them to be at both levels
540       // for different products.
541       if (browser_dist->GetType() == BrowserDistribution::CHROME_BINARIES)
542         continue;
543
544       const ProductState* user_level_product_state =
545           original_state.GetProductState(false, browser_dist->GetType());
546       const ProductState* system_level_product_state =
547           original_state.GetProductState(true, browser_dist->GetType());
548
549       // Allow upgrades to proceed so that out-of-date versions are not left
550       // around.
551       if (user_level_product_state)
552         continue;
553
554       // This is a new user-level install...
555
556       if (system_level_product_state) {
557         // ... and the product already exists at system-level.
558         LOG(ERROR) << "Already installed version "
559                    << system_level_product_state->version().GetString()
560                    << " at system-level conflicts with this one at user-level.";
561         if (product.is_chrome()) {
562           // Instruct Google Update to launch the existing system-level Chrome.
563           // There should be no error dialog.
564           base::FilePath install_path(installer::GetChromeInstallPath(
565               true,  // system
566               browser_dist));
567           if (install_path.empty()) {
568             // Give up if we failed to construct the install path.
569             *status = installer::OS_ERROR;
570             installer_state->WriteInstallerResult(*status,
571                                                   IDS_INSTALL_OS_ERROR_BASE,
572                                                   NULL);
573           } else {
574             *status = installer::EXISTING_VERSION_LAUNCHED;
575             base::FilePath chrome_exe =
576                 install_path.Append(installer::kChromeExe);
577             CommandLine cmd(chrome_exe);
578             cmd.AppendSwitch(switches::kForceFirstRun);
579             installer_state->WriteInstallerResult(*status, 0, NULL);
580             VLOG(1) << "Launching existing system-level chrome instead.";
581             base::LaunchProcess(cmd, base::LaunchOptions(), NULL);
582           }
583         } else {
584           // It's no longer possible for |product| to be anything other than
585           // Chrome.
586           NOTREACHED();
587         }
588         return false;
589       }
590     }
591
592   } else {  // System-level install.
593     // --ensure-google-update-present is supported for user-level only.
594     // The flag is generic, but its primary use case involves App Host.
595     if (installer_state->ensure_google_update_present()) {
596       LOG(DFATAL) << "--" << installer::switches::kEnsureGoogleUpdatePresent
597                   << " is supported for user-level only.";
598       *status = installer::APP_HOST_REQUIRES_USER_LEVEL;
599       // No message string since there is nothing a user can do.
600       installer_state->WriteInstallerResult(*status, 0, NULL);
601       return false;
602     }
603   }
604
605   return true;
606 }
607
608 // Initializes |temp_path| to "Temp" within the target directory, and
609 // |unpack_path| to a random directory beginning with "source" within
610 // |temp_path|. Returns false on error.
611 bool CreateTemporaryAndUnpackDirectories(
612     const InstallerState& installer_state,
613     installer::SelfCleaningTempDir* temp_path,
614     base::FilePath* unpack_path) {
615   DCHECK(temp_path && unpack_path);
616
617   if (!temp_path->Initialize(installer_state.target_path().DirName(),
618                              installer::kInstallTempDir)) {
619     PLOG(ERROR) << "Could not create temporary path.";
620     return false;
621   }
622   VLOG(1) << "Created path " << temp_path->path().value();
623
624   if (!base::CreateTemporaryDirInDir(temp_path->path(),
625                                      installer::kInstallSourceDir,
626                                      unpack_path)) {
627     PLOG(ERROR) << "Could not create temporary path for unpacked archive.";
628     return false;
629   }
630
631   return true;
632 }
633
634 installer::InstallStatus UninstallProduct(
635     const InstallationState& original_state,
636     const InstallerState& installer_state,
637     const CommandLine& cmd_line,
638     bool remove_all,
639     bool force_uninstall,
640     const Product& product) {
641   const ProductState* product_state =
642       original_state.GetProductState(installer_state.system_install(),
643                                      product.distribution()->GetType());
644   if (product_state != NULL) {
645     VLOG(1) << "version on the system: "
646             << product_state->version().GetString();
647   } else if (!force_uninstall) {
648     LOG(ERROR) << product.distribution()->GetDisplayName()
649                << " not found for uninstall.";
650     return installer::CHROME_NOT_INSTALLED;
651   }
652
653   return installer::UninstallProduct(
654       original_state, installer_state, cmd_line.GetProgram(), product,
655       remove_all, force_uninstall, cmd_line);
656 }
657
658 installer::InstallStatus UninstallProducts(
659     const InstallationState& original_state,
660     const InstallerState& installer_state,
661     const CommandLine& cmd_line) {
662   const Products& products = installer_state.products();
663
664   // Decide whether Active Setup should be triggered and/or system-level Chrome
665   // should be launched post-uninstall. This needs to be done outside the
666   // UninstallProduct calls as some of them might terminate the processes
667   // launched by a previous one otherwise...
668   bool trigger_active_setup = false;
669   // System-level Chrome will be launched via this command if its program gets
670   // set below.
671   CommandLine system_level_cmd(CommandLine::NO_PROGRAM);
672
673   const Product* chrome =
674       installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER);
675   if (chrome) {
676     // InstallerState::Initialize always puts Chrome first, and we rely on that
677     // here for this reason: if Chrome is in-use, the user will be prompted to
678     // confirm uninstallation.  Upon cancel, we should not continue with the
679     // other products.
680     DCHECK(products[0]->is_chrome());
681
682     if (cmd_line.HasSwitch(installer::switches::kSelfDestruct) &&
683         !installer_state.system_install()) {
684       BrowserDistribution* dist = chrome->distribution();
685       const base::FilePath system_exe_path(
686           installer::GetChromeInstallPath(true, dist)
687               .Append(installer::kChromeExe));
688       system_level_cmd.SetProgram(system_exe_path);
689
690       base::FilePath first_run_sentinel;
691       InstallUtil::GetSentinelFilePath(
692           chrome::kFirstRunSentinel, dist, &first_run_sentinel);
693       if (base::PathExists(first_run_sentinel)) {
694         // If the Chrome being self-destructed has already undergone First Run,
695         // trigger Active Setup and make sure the system-level Chrome doesn't go
696         // through first run.
697         trigger_active_setup = true;
698         system_level_cmd.AppendSwitch(::switches::kCancelFirstRun);
699       }
700     }
701   }
702   if (installer_state.FindProduct(BrowserDistribution::CHROME_BINARIES)) {
703     // Chrome Binaries should be last; if something else is cancelled, they
704     // should stay.
705     DCHECK(products[products.size() - 1]->is_chrome_binaries());
706   }
707
708   installer::InstallStatus install_status = installer::UNINSTALL_SUCCESSFUL;
709   installer::InstallStatus prod_status = installer::UNKNOWN_STATUS;
710   const bool force = cmd_line.HasSwitch(installer::switches::kForceUninstall);
711   const bool remove_all = !cmd_line.HasSwitch(
712       installer::switches::kDoNotRemoveSharedItems);
713
714   for (Products::const_iterator it = products.begin();
715        install_status != installer::UNINSTALL_CANCELLED && it < products.end();
716        ++it) {
717     prod_status = UninstallProduct(original_state, installer_state,
718         cmd_line, remove_all, force, **it);
719     if (prod_status != installer::UNINSTALL_SUCCESSFUL)
720       install_status = prod_status;
721   }
722
723   installer::CleanUpInstallationDirectoryAfterUninstall(
724       original_state, installer_state, cmd_line, &install_status);
725
726   // The app and vendor dirs may now be empty. Make a last-ditch attempt to
727   // delete them.
728   installer::DeleteChromeDirectoriesIfEmpty(installer_state.target_path());
729
730   if (trigger_active_setup)
731     InstallUtil::TriggerActiveSetupCommand();
732
733   if (!system_level_cmd.GetProgram().empty())
734     base::LaunchProcess(system_level_cmd, base::LaunchOptions(), NULL);
735
736   // Tell Google Update that an uninstall has taken place.
737   // Ignore the return value: success or failure of Google Update
738   // has no bearing on the success or failure of Chrome's uninstallation.
739   google_update::UninstallGoogleUpdate(installer_state.system_install());
740
741   return install_status;
742 }
743
744 // Uninstall the binaries if they are the only product present and they're not
745 // in-use.
746 void UninstallBinariesIfUnused(
747     const InstallationState& original_state,
748     const InstallerState& installer_state,
749     installer::InstallStatus* install_status) {
750   // Early exit if the binaries are still in use.
751   if (*install_status != installer::UNUSED_BINARIES ||
752       installer_state.AreBinariesInUse(original_state)) {
753     return;
754   }
755
756   LOG(INFO) << "Uninstalling unused binaries";
757   installer_state.UpdateStage(installer::UNINSTALLING_BINARIES);
758
759   // Simulate the uninstall as coming from the installed version.
760   const ProductState* binaries_state =
761       original_state.GetProductState(installer_state.system_install(),
762                                      BrowserDistribution::CHROME_BINARIES);
763   const CommandLine& uninstall_cmd(binaries_state->uninstall_command());
764   MasterPreferences uninstall_prefs(uninstall_cmd);
765   InstallerState uninstall_state;
766   uninstall_state.Initialize(uninstall_cmd, uninstall_prefs, original_state);
767
768   *install_status =
769       UninstallProducts(original_state, uninstall_state, uninstall_cmd);
770
771   // Report that the binaries were uninstalled if they were. This translates
772   // into a successful install return code.
773   if (IsUninstallSuccess(*install_status)) {
774     *install_status = installer::UNUSED_BINARIES_UNINSTALLED;
775     installer_state.WriteInstallerResult(*install_status, 0, NULL);
776   }
777 }
778
779 installer::InstallStatus InstallProducts(
780     const InstallationState& original_state,
781     const CommandLine& cmd_line,
782     const MasterPreferences& prefs,
783     InstallerState* installer_state,
784     base::FilePath* installer_directory) {
785   DCHECK(installer_state);
786   const bool system_install = installer_state->system_install();
787   installer::InstallStatus install_status = installer::UNKNOWN_STATUS;
788   installer::ArchiveType archive_type = installer::UNKNOWN_ARCHIVE_TYPE;
789   bool delegated_to_existing = false;
790   installer_state->UpdateStage(installer::PRECONDITIONS);
791   // The stage provides more fine-grained information than -multifail, so remove
792   // the -multifail suffix from the Google Update "ap" value.
793   BrowserDistribution::GetSpecificDistribution(installer_state->state_type())->
794       UpdateInstallStatus(system_install, archive_type, install_status);
795   if (CheckPreInstallConditions(original_state, installer_state,
796                                 &install_status)) {
797     VLOG(1) << "Installing to " << installer_state->target_path().value();
798     install_status = InstallProductsHelper(
799         original_state, cmd_line, prefs, *installer_state,
800         installer_directory, &archive_type, &delegated_to_existing);
801   } else {
802     // CheckPreInstallConditions must set the status on failure.
803     DCHECK_NE(install_status, installer::UNKNOWN_STATUS);
804   }
805
806   // Delete the master preferences file if present. Note that we do not care
807   // about rollback here and we schedule for deletion on reboot if the delete
808   // fails. As such, we do not use DeleteTreeWorkItem.
809   if (cmd_line.HasSwitch(installer::switches::kInstallerData)) {
810     base::FilePath prefs_path(cmd_line.GetSwitchValuePath(
811         installer::switches::kInstallerData));
812     if (!base::DeleteFile(prefs_path, false)) {
813       LOG(ERROR) << "Failed deleting master preferences file "
814                  << prefs_path.value()
815                  << ", scheduling for deletion after reboot.";
816       ScheduleFileSystemEntityForDeletion(prefs_path);
817     }
818   }
819
820   // Early exit if this setup.exe delegated to another, since that one would
821   // have taken care of UpdateInstallStatus and UpdateStage.
822   if (delegated_to_existing)
823     return install_status;
824
825   const Products& products = installer_state->products();
826   for (Products::const_iterator it = products.begin(); it < products.end();
827        ++it) {
828     (*it)->distribution()->UpdateInstallStatus(
829         system_install, archive_type, install_status);
830   }
831
832   UninstallBinariesIfUnused(original_state, *installer_state, &install_status);
833
834   installer_state->UpdateStage(installer::NO_STAGE);
835   return install_status;
836 }
837
838 installer::InstallStatus ShowEULADialog(const base::string16& inner_frame) {
839   VLOG(1) << "About to show EULA";
840   base::string16 eula_path = installer::GetLocalizedEulaResource();
841   if (eula_path.empty()) {
842     LOG(ERROR) << "No EULA path available";
843     return installer::EULA_REJECTED;
844   }
845   // Newer versions of the caller pass an inner frame parameter that must
846   // be given to the html page being launched.
847   installer::EulaHTMLDialog dlg(eula_path, inner_frame);
848   installer::EulaHTMLDialog::Outcome outcome = dlg.ShowModal();
849   if (installer::EulaHTMLDialog::REJECTED == outcome) {
850     LOG(ERROR) << "EULA rejected or EULA failure";
851     return installer::EULA_REJECTED;
852   }
853   if (installer::EulaHTMLDialog::ACCEPTED_OPT_IN == outcome) {
854     VLOG(1) << "EULA accepted (opt-in)";
855     return installer::EULA_ACCEPTED_OPT_IN;
856   }
857   VLOG(1) << "EULA accepted (no opt-in)";
858   return installer::EULA_ACCEPTED;
859 }
860
861 // Creates the sentinel indicating that the EULA was required and has been
862 // accepted.
863 bool CreateEULASentinel(BrowserDistribution* dist) {
864   base::FilePath eula_sentinel;
865   if (!InstallUtil::GetSentinelFilePath(installer::kEULASentinelFile,
866                                         dist, &eula_sentinel)) {
867     return false;
868   }
869
870   return (base::CreateDirectory(eula_sentinel.DirName()) &&
871           file_util::WriteFile(eula_sentinel, "", 0) != -1);
872 }
873
874 void ActivateMetroChrome() {
875   // Check to see if we're per-user or not. Need to do this since we may
876   // not have been invoked with --system-level even for a machine install.
877   wchar_t exe_path[MAX_PATH * 2] = {};
878   GetModuleFileName(NULL, exe_path, arraysize(exe_path));
879   bool is_per_user_install = InstallUtil::IsPerUserInstall(exe_path);
880
881   base::string16 app_model_id = ShellUtil::GetBrowserModelId(
882       BrowserDistribution::GetDistribution(), is_per_user_install);
883
884   base::win::ScopedComPtr<IApplicationActivationManager> activator;
885   HRESULT hr = activator.CreateInstance(CLSID_ApplicationActivationManager);
886   if (SUCCEEDED(hr)) {
887     DWORD pid = 0;
888     hr = activator->ActivateApplication(
889         app_model_id.c_str(), L"open", AO_NONE, &pid);
890   }
891
892   LOG_IF(ERROR, FAILED(hr)) << "Tried and failed to launch Metro Chrome. "
893                             << "hr=" << std::hex << hr;
894 }
895
896 installer::InstallStatus RegisterDevChrome(
897     const InstallationState& original_state,
898     const InstallerState& installer_state,
899     const CommandLine& cmd_line) {
900   BrowserDistribution* chrome_dist =
901       BrowserDistribution::GetSpecificDistribution(
902           BrowserDistribution::CHROME_BROWSER);
903
904   // Only proceed with registering a dev chrome if no real Chrome installation
905   // of the same distribution are present on this system.
906   const ProductState* existing_chrome =
907       original_state.GetProductState(false,
908                                      BrowserDistribution::CHROME_BROWSER);
909   if (!existing_chrome) {
910     existing_chrome =
911       original_state.GetProductState(true, BrowserDistribution::CHROME_BROWSER);
912   }
913   if (existing_chrome) {
914     static const wchar_t kPleaseUninstallYourChromeMessage[] =
915         L"You already have a full-installation (non-dev) of %1ls, please "
916         L"uninstall it first using Add/Remove Programs in the control panel.";
917     base::string16 name(chrome_dist->GetDisplayName());
918     base::string16 message(
919         base::StringPrintf(kPleaseUninstallYourChromeMessage, name.c_str()));
920
921     LOG(ERROR) << "Aborting operation: another installation of " << name
922                << " was found, as a last resort (if the product is not present "
923                   "in Add/Remove Programs), try executing: "
924                << existing_chrome->uninstall_command().GetCommandLineString();
925     MessageBox(NULL, message.c_str(), NULL, MB_ICONERROR);
926     return installer::INSTALL_FAILED;
927   }
928
929   base::FilePath chrome_exe(
930       cmd_line.GetSwitchValuePath(installer::switches::kRegisterDevChrome));
931   if (chrome_exe.empty())
932     chrome_exe = cmd_line.GetProgram().DirName().Append(installer::kChromeExe);
933   if (!chrome_exe.IsAbsolute())
934     chrome_exe = base::MakeAbsoluteFilePath(chrome_exe);
935
936   installer::InstallStatus status = installer::FIRST_INSTALL_SUCCESS;
937   if (base::PathExists(chrome_exe)) {
938     Product chrome(chrome_dist);
939
940     // Create the Start menu shortcut and pin it to the taskbar.
941     ShellUtil::ShortcutProperties shortcut_properties(ShellUtil::CURRENT_USER);
942     chrome.AddDefaultShortcutProperties(chrome_exe, &shortcut_properties);
943     shortcut_properties.set_dual_mode(true);
944     shortcut_properties.set_pin_to_taskbar(true);
945     ShellUtil::CreateOrUpdateShortcut(
946         ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR, chrome_dist,
947         shortcut_properties, ShellUtil::SHELL_SHORTCUT_CREATE_ALWAYS);
948
949     // Register Chrome at user-level and make it default.
950     scoped_ptr<WorkItemList> delegate_execute_list(
951         WorkItem::CreateWorkItemList());
952     installer::AddDelegateExecuteWorkItems(
953         installer_state, chrome_exe.DirName(), Version(), chrome,
954         delegate_execute_list.get());
955     delegate_execute_list->Do();
956     if (ShellUtil::CanMakeChromeDefaultUnattended()) {
957       ShellUtil::MakeChromeDefault(
958           chrome_dist, ShellUtil::CURRENT_USER, chrome_exe.value(), true);
959     } else {
960       ShellUtil::ShowMakeChromeDefaultSystemUI(chrome_dist, chrome_exe.value());
961     }
962   } else {
963     LOG(ERROR) << "Path not found: " << chrome_exe.value();
964     status = installer::INSTALL_FAILED;
965   }
966   return status;
967 }
968
969 // This method processes any command line options that make setup.exe do
970 // various tasks other than installation (renaming chrome.exe, showing eula
971 // among others). This function returns true if any such command line option
972 // has been found and processed (so setup.exe should exit at that point).
973 bool HandleNonInstallCmdLineOptions(const InstallationState& original_state,
974                                     const CommandLine& cmd_line,
975                                     InstallerState* installer_state,
976                                     int* exit_code) {
977   // TODO(gab): Add a local |status| variable which each block below sets;
978   // only determine the |exit_code| from |status| at the end (this will allow
979   // this method to validate that
980   // (!handled || status != installer::UNKNOWN_STATUS)).
981   bool handled = true;
982   // TODO(tommi): Split these checks up into functions and use a data driven
983   // map of switch->function.
984   if (cmd_line.HasSwitch(installer::switches::kUpdateSetupExe)) {
985     installer::InstallStatus status = installer::SETUP_PATCH_FAILED;
986     // If --update-setup-exe command line option is given, we apply the given
987     // patch to current exe, and store the resulting binary in the path
988     // specified by --new-setup-exe. But we need to first unpack the file
989     // given in --update-setup-exe.
990     base::ScopedTempDir temp_path;
991     if (!temp_path.CreateUniqueTempDir()) {
992       PLOG(ERROR) << "Could not create temporary path.";
993     } else {
994       base::FilePath compressed_archive(cmd_line.GetSwitchValuePath(
995           installer::switches::kUpdateSetupExe));
996       VLOG(1) << "Opening archive " << compressed_archive.value();
997       if (installer::ArchivePatchHelper::UncompressAndPatch(
998               temp_path.path(),
999               compressed_archive,
1000               cmd_line.GetProgram(),
1001               cmd_line.GetSwitchValuePath(installer::switches::kNewSetupExe))) {
1002         status = installer::NEW_VERSION_UPDATED;
1003       }
1004       if (!temp_path.Delete()) {
1005         // PLOG would be nice, but Delete() doesn't leave a meaningful value in
1006         // the Windows last-error code.
1007         LOG(WARNING) << "Scheduling temporary path " << temp_path.path().value()
1008                      << " for deletion at reboot.";
1009         ScheduleDirectoryForDeletion(temp_path.path());
1010       }
1011     }
1012
1013     *exit_code = InstallUtil::GetInstallReturnCode(status);
1014     if (*exit_code) {
1015       LOG(WARNING) << "setup.exe patching failed.";
1016       installer_state->WriteInstallerResult(
1017           status, IDS_SETUP_PATCH_FAILED_BASE, NULL);
1018     }
1019     // We will be exiting normally, so clear the stage indicator.
1020     installer_state->UpdateStage(installer::NO_STAGE);
1021   } else if (cmd_line.HasSwitch(installer::switches::kShowEula)) {
1022     // Check if we need to show the EULA. If it is passed as a command line
1023     // then the dialog is shown and regardless of the outcome setup exits here.
1024     base::string16 inner_frame =
1025         cmd_line.GetSwitchValueNative(installer::switches::kShowEula);
1026     *exit_code = ShowEULADialog(inner_frame);
1027
1028     if (installer::EULA_REJECTED != *exit_code) {
1029       if (GoogleUpdateSettings::SetEULAConsent(
1030               original_state, BrowserDistribution::GetDistribution(), true)) {
1031         CreateEULASentinel(BrowserDistribution::GetDistribution());
1032       }
1033       // For a metro-originated launch, we now need to launch back into metro.
1034       if (cmd_line.HasSwitch(installer::switches::kShowEulaForMetro))
1035         ActivateMetroChrome();
1036     }
1037   } else if (cmd_line.HasSwitch(installer::switches::kConfigureUserSettings)) {
1038     // NOTE: Should the work done here, on kConfigureUserSettings, change:
1039     // kActiveSetupVersion in install_worker.cc needs to be increased for Active
1040     // Setup to invoke this again for all users of this install.
1041     const Product* chrome_install =
1042         installer_state->FindProduct(BrowserDistribution::CHROME_BROWSER);
1043     installer::InstallStatus status = installer::INVALID_STATE_FOR_OPTION;
1044     if (chrome_install && installer_state->system_install()) {
1045       bool force =
1046           cmd_line.HasSwitch(installer::switches::kForceConfigureUserSettings);
1047       installer::HandleActiveSetupForBrowser(installer_state->target_path(),
1048                                              *chrome_install, force);
1049       status = installer::INSTALL_REPAIRED;
1050     } else {
1051       LOG(DFATAL) << "chrome_install:" << chrome_install
1052                   << ", system_install:" << installer_state->system_install();
1053     }
1054     *exit_code = InstallUtil::GetInstallReturnCode(status);
1055   } else if (cmd_line.HasSwitch(installer::switches::kRegisterDevChrome)) {
1056     installer::InstallStatus status = RegisterDevChrome(
1057         original_state, *installer_state, cmd_line);
1058     *exit_code = InstallUtil::GetInstallReturnCode(status);
1059   } else if (cmd_line.HasSwitch(installer::switches::kRegisterChromeBrowser)) {
1060     installer::InstallStatus status = installer::UNKNOWN_STATUS;
1061     const Product* chrome_install =
1062         installer_state->FindProduct(BrowserDistribution::CHROME_BROWSER);
1063     if (chrome_install) {
1064       // If --register-chrome-browser option is specified, register all
1065       // Chrome protocol/file associations, as well as register it as a valid
1066       // browser for Start Menu->Internet shortcut. This switch will also
1067       // register Chrome as a valid handler for a set of URL protocols that
1068       // Chrome may become the default handler for, either by the user marking
1069       // Chrome as the default browser, through the Windows Default Programs
1070       // control panel settings, or through website use of
1071       // registerProtocolHandler. These protocols are found in
1072       // ShellUtil::kPotentialProtocolAssociations.
1073       // The --register-url-protocol will additionally register Chrome as a
1074       // potential handler for the supplied protocol, and is used if a website
1075       // registers a handler for a protocol not found in
1076       // ShellUtil::kPotentialProtocolAssociations.
1077       // These options should only be used when setup.exe is launched with admin
1078       // rights. We do not make any user specific changes with this option.
1079       DCHECK(IsUserAnAdmin());
1080       base::string16 chrome_exe(cmd_line.GetSwitchValueNative(
1081           installer::switches::kRegisterChromeBrowser));
1082       base::string16 suffix;
1083       if (cmd_line.HasSwitch(
1084           installer::switches::kRegisterChromeBrowserSuffix)) {
1085         suffix = cmd_line.GetSwitchValueNative(
1086             installer::switches::kRegisterChromeBrowserSuffix);
1087       }
1088       if (cmd_line.HasSwitch(installer::switches::kRegisterURLProtocol)) {
1089         base::string16 protocol = cmd_line.GetSwitchValueNative(
1090             installer::switches::kRegisterURLProtocol);
1091         // ShellUtil::RegisterChromeForProtocol performs all registration
1092         // done by ShellUtil::RegisterChromeBrowser, as well as registering
1093         // with Windows as capable of handling the supplied protocol.
1094         if (ShellUtil::RegisterChromeForProtocol(
1095                 chrome_install->distribution(), chrome_exe, suffix, protocol,
1096                 false))
1097           status = installer::IN_USE_UPDATED;
1098       } else {
1099         if (ShellUtil::RegisterChromeBrowser(chrome_install->distribution(),
1100             chrome_exe, suffix, false))
1101           status = installer::IN_USE_UPDATED;
1102       }
1103     } else {
1104       LOG(DFATAL) << "Can't register browser - Chrome distribution not found";
1105     }
1106     *exit_code = InstallUtil::GetInstallReturnCode(status);
1107   } else if (cmd_line.HasSwitch(installer::switches::kRenameChromeExe)) {
1108     // If --rename-chrome-exe is specified, we want to rename the executables
1109     // and exit.
1110     *exit_code = RenameChromeExecutables(original_state, installer_state);
1111   } else if (cmd_line.HasSwitch(
1112                  installer::switches::kRemoveChromeRegistration)) {
1113     // This is almost reverse of --register-chrome-browser option above.
1114     // Here we delete Chrome browser registration. This option should only
1115     // be used when setup.exe is launched with admin rights. We do not
1116     // make any user specific changes in this option.
1117     base::string16 suffix;
1118     if (cmd_line.HasSwitch(
1119             installer::switches::kRegisterChromeBrowserSuffix)) {
1120       suffix = cmd_line.GetSwitchValueNative(
1121           installer::switches::kRegisterChromeBrowserSuffix);
1122     }
1123     installer::InstallStatus tmp = installer::UNKNOWN_STATUS;
1124     const Product* chrome_install =
1125         installer_state->FindProduct(BrowserDistribution::CHROME_BROWSER);
1126     DCHECK(chrome_install);
1127     if (chrome_install) {
1128       installer::DeleteChromeRegistrationKeys(*installer_state,
1129           chrome_install->distribution(), HKEY_LOCAL_MACHINE, suffix, &tmp);
1130     }
1131     *exit_code = tmp;
1132   } else if (cmd_line.HasSwitch(installer::switches::kOnOsUpgrade)) {
1133     const Product* chrome_install =
1134         installer_state->FindProduct(BrowserDistribution::CHROME_BROWSER);
1135     installer::InstallStatus status = installer::INVALID_STATE_FOR_OPTION;
1136     if (chrome_install) {
1137       installer::HandleOsUpgradeForBrowser(*installer_state,
1138                                            *chrome_install);
1139       status = installer::INSTALL_REPAIRED;
1140     } else {
1141       LOG(DFATAL) << "Chrome product not found.";
1142     }
1143     *exit_code = InstallUtil::GetInstallReturnCode(status);
1144   } else if (cmd_line.HasSwitch(installer::switches::kQueryEULAAcceptance)) {
1145     *exit_code = installer::IsEULAAccepted(installer_state->system_install());
1146   } else if (cmd_line.HasSwitch(installer::switches::kInactiveUserToast)) {
1147     // Launch the inactive user toast experiment.
1148     int flavor = -1;
1149     base::StringToInt(cmd_line.GetSwitchValueNative(
1150         installer::switches::kInactiveUserToast), &flavor);
1151     std::string experiment_group =
1152         cmd_line.GetSwitchValueASCII(installer::switches::kExperimentGroup);
1153     DCHECK_NE(-1, flavor);
1154     if (flavor == -1) {
1155       *exit_code = installer::UNKNOWN_STATUS;
1156     } else {
1157       // This code is called (via setup.exe relaunch) only if a product is known
1158       // to run user experiments, so no check is required.
1159       const Products& products = installer_state->products();
1160       for (Products::const_iterator it = products.begin(); it < products.end();
1161            ++it) {
1162         const Product& product = **it;
1163         installer::InactiveUserToastExperiment(
1164             flavor, base::ASCIIToUTF16(experiment_group), product,
1165             installer_state->target_path());
1166       }
1167     }
1168   } else if (cmd_line.HasSwitch(installer::switches::kSystemLevelToast)) {
1169     const Products& products = installer_state->products();
1170     for (Products::const_iterator it = products.begin(); it < products.end();
1171          ++it) {
1172       const Product& product = **it;
1173       BrowserDistribution* browser_dist = product.distribution();
1174       // We started as system-level and have been re-launched as user level
1175       // to continue with the toast experiment.
1176       Version installed_version;
1177       InstallUtil::GetChromeVersion(browser_dist, true, &installed_version);
1178       if (!installed_version.IsValid()) {
1179         LOG(ERROR) << "No installation of "
1180                    << browser_dist->GetDisplayName()
1181                    << " found for system-level toast.";
1182       } else {
1183         product.LaunchUserExperiment(
1184             cmd_line.GetProgram(), installer::REENTRY_SYS_UPDATE, true);
1185       }
1186     }
1187   } else if (cmd_line.HasSwitch(installer::switches::kPatch)) {
1188     const std::string patch_type_str(
1189         cmd_line.GetSwitchValueASCII(installer::switches::kPatch));
1190     const base::FilePath input_file(
1191         cmd_line.GetSwitchValuePath(installer::switches::kInputFile));
1192     const base::FilePath patch_file(
1193         cmd_line.GetSwitchValuePath(installer::switches::kPatchFile));
1194     const base::FilePath output_file(
1195         cmd_line.GetSwitchValuePath(installer::switches::kOutputFile));
1196
1197     if (patch_type_str == installer::kCourgette) {
1198       *exit_code = installer::CourgettePatchFiles(input_file,
1199                                                   patch_file,
1200                                                   output_file);
1201     } else if (patch_type_str == installer::kBsdiff) {
1202       *exit_code = installer::BsdiffPatchFiles(input_file,
1203                                                patch_file,
1204                                                output_file);
1205     } else {
1206       *exit_code = installer::PATCH_INVALID_ARGUMENTS;
1207     }
1208   } else {
1209     handled = false;
1210   }
1211
1212   return handled;
1213 }
1214
1215 bool ShowRebootDialog() {
1216   // Get a token for this process.
1217   HANDLE token;
1218   if (!OpenProcessToken(GetCurrentProcess(),
1219                         TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
1220                         &token)) {
1221     LOG(ERROR) << "Failed to open token.";
1222     return false;
1223   }
1224
1225   // Use a ScopedHandle to keep track of and eventually close our handle.
1226   // TODO(robertshield): Add a Receive() method to base's ScopedHandle.
1227   base::win::ScopedHandle scoped_handle(token);
1228
1229   // Get the LUID for the shutdown privilege.
1230   TOKEN_PRIVILEGES tkp = {0};
1231   LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
1232   tkp.PrivilegeCount = 1;
1233   tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1234
1235   // Get the shutdown privilege for this process.
1236   AdjustTokenPrivileges(token, FALSE, &tkp, 0,
1237                         reinterpret_cast<PTOKEN_PRIVILEGES>(NULL), 0);
1238   if (GetLastError() != ERROR_SUCCESS) {
1239     LOG(ERROR) << "Unable to get shutdown privileges.";
1240     return false;
1241   }
1242
1243   // Popup a dialog that will prompt to reboot using the default system message.
1244   // TODO(robertshield): Add a localized, more specific string to the prompt.
1245   RestartDialog(NULL, NULL, EWX_REBOOT | EWX_FORCEIFHUNG);
1246   return true;
1247 }
1248
1249 // Returns the Custom information for the client identified by the exe path
1250 // passed in. This information is used for crash reporting.
1251 google_breakpad::CustomClientInfo* GetCustomInfo(const wchar_t* exe_path) {
1252   base::string16 product;
1253   base::string16 version;
1254   scoped_ptr<FileVersionInfo> version_info(
1255       FileVersionInfo::CreateFileVersionInfo(base::FilePath(exe_path)));
1256   if (version_info.get()) {
1257     version = version_info->product_version();
1258     product = version_info->product_short_name();
1259   }
1260
1261   if (version.empty())
1262     version = L"0.1.0.0";
1263
1264   if (product.empty())
1265     product = L"Chrome Installer";
1266
1267   static google_breakpad::CustomInfoEntry ver_entry(L"ver", version.c_str());
1268   static google_breakpad::CustomInfoEntry prod_entry(L"prod", product.c_str());
1269   static google_breakpad::CustomInfoEntry plat_entry(L"plat", L"Win32");
1270   static google_breakpad::CustomInfoEntry type_entry(L"ptype",
1271                                                      L"Chrome Installer");
1272   static google_breakpad::CustomInfoEntry entries[] = {
1273       ver_entry, prod_entry, plat_entry, type_entry };
1274   static google_breakpad::CustomClientInfo custom_info = {
1275       entries, arraysize(entries) };
1276   return &custom_info;
1277 }
1278
1279 // Initialize crash reporting for this process. This involves connecting to
1280 // breakpad, etc.
1281 google_breakpad::ExceptionHandler* InitializeCrashReporting(
1282     bool system_install) {
1283   // Only report crashes if the user allows it.
1284   if (!GoogleUpdateSettings::GetCollectStatsConsent())
1285     return NULL;
1286
1287   // Get the alternate dump directory. We use the temp path.
1288   base::FilePath temp_directory;
1289   if (!base::GetTempDir(&temp_directory) || temp_directory.empty())
1290     return NULL;
1291
1292   wchar_t exe_path[MAX_PATH * 2] = {0};
1293   GetModuleFileName(NULL, exe_path, arraysize(exe_path));
1294
1295   // Build the pipe name. It can be either:
1296   // System-wide install: "NamedPipe\GoogleCrashServices\S-1-5-18"
1297   // Per-user install: "NamedPipe\GoogleCrashServices\<user SID>"
1298   base::string16 user_sid = kSystemPrincipalSid;
1299
1300   if (!system_install) {
1301     if (!base::win::GetUserSidString(&user_sid)) {
1302       return NULL;
1303     }
1304   }
1305
1306   base::string16 pipe_name = kGoogleUpdatePipeName;
1307   pipe_name += user_sid;
1308
1309   google_breakpad::ExceptionHandler* breakpad =
1310       new google_breakpad::ExceptionHandler(
1311           temp_directory.value(), NULL, NULL, NULL,
1312           google_breakpad::ExceptionHandler::HANDLER_ALL, kLargerDumpType,
1313           pipe_name.c_str(), GetCustomInfo(exe_path));
1314   return breakpad;
1315 }
1316
1317 // Uninstalls multi-install Chrome Frame if the current operation is a
1318 // multi-install install or update. The operation is performed directly rather
1319 // than delegated to the existing install since there is no facility in older
1320 // versions of setup.exe to uninstall GCF without touching the binaries. The
1321 // binaries will be uninstalled during later processing if they are not in-use
1322 // (see UninstallBinariesIfUnused). |original_state| and |installer_state| are
1323 // updated to reflect the state of the world following the operation.
1324 void UninstallMultiChromeFrameIfPresent(const CommandLine& cmd_line,
1325                                         const MasterPreferences& prefs,
1326                                         InstallationState* original_state,
1327                                         InstallerState* installer_state) {
1328   // Early exit if not installing or updating multi-install product(s).
1329   if (installer_state->operation() != InstallerState::MULTI_INSTALL &&
1330       installer_state->operation() != InstallerState::MULTI_UPDATE) {
1331     return;
1332   }
1333
1334   // Early exit if Chrome Frame is not present as multi-install.
1335   const ProductState* chrome_frame_state =
1336       original_state->GetProductState(installer_state->system_install(),
1337                                       BrowserDistribution::CHROME_FRAME);
1338   if (!chrome_frame_state || !chrome_frame_state->is_multi_install())
1339     return;
1340
1341   LOG(INFO) << "Uninstalling multi-install Chrome Frame.";
1342   installer_state->UpdateStage(installer::UNINSTALLING_CHROME_FRAME);
1343
1344   // Uninstall Chrome Frame without touching the multi-install binaries.
1345   // Simulate the uninstall as coming from the installed version.
1346   const CommandLine& uninstall_cmd(chrome_frame_state->uninstall_command());
1347   MasterPreferences uninstall_prefs(uninstall_cmd);
1348   InstallerState uninstall_state;
1349   uninstall_state.Initialize(uninstall_cmd, uninstall_prefs, *original_state);
1350   const Product* chrome_frame_product = uninstall_state.FindProduct(
1351       BrowserDistribution::CHROME_FRAME);
1352   if (chrome_frame_product) {
1353     // No shared state should be left behind.
1354     const bool remove_all = true;
1355     // Don't accept no for an answer.
1356     const bool force_uninstall = true;
1357     installer::InstallStatus uninstall_status =
1358         installer::UninstallProduct(*original_state, uninstall_state,
1359                                     uninstall_cmd.GetProgram(),
1360                                     *chrome_frame_product, remove_all,
1361                                     force_uninstall, cmd_line);
1362
1363     VLOG(1) << "Uninstallation of Chrome Frame returned status "
1364             << uninstall_status;
1365   } else {
1366     LOG(ERROR) << "Chrome Frame not found for uninstall.";
1367   }
1368
1369   // Refresh state for the continuation of the original install/update.
1370   original_state->Initialize();
1371   installer_state->Initialize(cmd_line, prefs, *original_state);
1372 }
1373
1374 }  // namespace
1375
1376 namespace installer {
1377
1378 InstallStatus InstallProductsHelper(
1379     const InstallationState& original_state,
1380     const CommandLine& cmd_line,
1381     const MasterPreferences& prefs,
1382     const InstallerState& installer_state,
1383     base::FilePath* installer_directory,
1384     ArchiveType* archive_type,
1385     bool* delegated_to_existing) {
1386   DCHECK(archive_type);
1387   DCHECK(delegated_to_existing);
1388   const bool system_install = installer_state.system_install();
1389   InstallStatus install_status = UNKNOWN_STATUS;
1390
1391   // Drop to background processing mode if the process was started below the
1392   // normal process priority class.
1393   bool entered_background_mode = AdjustProcessPriority();
1394   VLOG_IF(1, entered_background_mode) << "Entered background processing mode.";
1395
1396   // Create a temp folder where we will unpack Chrome archive. If it fails,
1397   // then we are doomed, so return immediately and no cleanup is required.
1398   SelfCleaningTempDir temp_path;
1399   base::FilePath unpack_path;
1400   if (!CreateTemporaryAndUnpackDirectories(installer_state, &temp_path,
1401                                            &unpack_path)) {
1402     installer_state.WriteInstallerResult(TEMP_DIR_FAILED,
1403                                          IDS_INSTALL_TEMP_DIR_FAILED_BASE,
1404                                          NULL);
1405     return TEMP_DIR_FAILED;
1406   }
1407
1408   // Uncompress and optionally patch the archive if an uncompressed archive was
1409   // not specified on the command line and a compressed archive is found.
1410   *archive_type = UNKNOWN_ARCHIVE_TYPE;
1411   base::FilePath uncompressed_archive(cmd_line.GetSwitchValuePath(
1412       switches::kUncompressedArchive));
1413   if (uncompressed_archive.empty()) {
1414     scoped_ptr<ArchivePatchHelper> archive_helper(
1415         CreateChromeArchiveHelper(cmd_line, installer_state, unpack_path));
1416     if (archive_helper) {
1417       VLOG(1) << "Installing Chrome from compressed archive "
1418               << archive_helper->compressed_archive().value();
1419       if (!UncompressAndPatchChromeArchive(original_state,
1420                                            installer_state,
1421                                            archive_helper.get(),
1422                                            archive_type,
1423                                            &install_status)) {
1424         DCHECK_NE(install_status, UNKNOWN_STATUS);
1425         return install_status;
1426       }
1427       uncompressed_archive = archive_helper->target();
1428       DCHECK(!uncompressed_archive.empty());
1429     }
1430   }
1431
1432   // Check for an uncompressed archive alongside the current executable if one
1433   // was not given or generated.
1434   if (uncompressed_archive.empty()) {
1435     uncompressed_archive =
1436         cmd_line.GetProgram().DirName().Append(kChromeArchive);
1437   }
1438
1439   if (*archive_type == UNKNOWN_ARCHIVE_TYPE) {
1440     // An archive was not uncompressed or patched above.
1441     if (uncompressed_archive.empty() ||
1442         !base::PathExists(uncompressed_archive)) {
1443       LOG(ERROR) << "Cannot install Chrome without an uncompressed archive.";
1444       installer_state.WriteInstallerResult(
1445           INVALID_ARCHIVE, IDS_INSTALL_INVALID_ARCHIVE_BASE, NULL);
1446       return INVALID_ARCHIVE;
1447     }
1448     *archive_type = FULL_ARCHIVE_TYPE;
1449   }
1450
1451   // Unpack the uncompressed archive.
1452   if (LzmaUtil::UnPackArchive(uncompressed_archive.value(),
1453                               unpack_path.value(),
1454                               NULL)) {
1455     installer_state.WriteInstallerResult(
1456         UNCOMPRESSION_FAILED,
1457         IDS_INSTALL_UNCOMPRESSION_FAILED_BASE,
1458         NULL);
1459     return UNCOMPRESSION_FAILED;
1460   }
1461
1462   VLOG(1) << "unpacked to " << unpack_path.value();
1463   base::FilePath src_path(
1464       unpack_path.Append(kInstallSourceChromeDir));
1465   scoped_ptr<Version>
1466       installer_version(GetMaxVersionFromArchiveDir(src_path));
1467   if (!installer_version.get()) {
1468     LOG(ERROR) << "Did not find any valid version in installer.";
1469     install_status = INVALID_ARCHIVE;
1470     installer_state.WriteInstallerResult(install_status,
1471         IDS_INSTALL_INVALID_ARCHIVE_BASE, NULL);
1472   } else {
1473     VLOG(1) << "version to install: " << installer_version->GetString();
1474     bool proceed_with_installation = true;
1475
1476     if (installer_state.operation() == InstallerState::MULTI_INSTALL) {
1477       // This is a new install of a multi-install product. Rather than give up
1478       // in case a higher version of the binaries (including a single-install
1479       // of Chrome, which can safely be migrated to multi-install by way of
1480       // CheckMultiInstallConditions) is already installed, delegate to the
1481       // installed setup.exe to install the product at hand.
1482       base::FilePath setup_exe;
1483       if (GetExistingHigherInstaller(original_state, system_install,
1484                                      *installer_version, &setup_exe)) {
1485         VLOG(1) << "Deferring to existing installer.";
1486         installer_state.UpdateStage(DEFERRING_TO_HIGHER_VERSION);
1487         if (DeferToExistingInstall(setup_exe, cmd_line, installer_state,
1488                                    temp_path.path(), &install_status)) {
1489           *delegated_to_existing = true;
1490           return install_status;
1491         }
1492       }
1493     }
1494
1495     uint32 higher_products = 0;
1496     COMPILE_ASSERT(
1497         sizeof(higher_products) * 8 > BrowserDistribution::NUM_TYPES,
1498         too_many_distribution_types_);
1499     const Products& products = installer_state.products();
1500     for (Products::const_iterator it = products.begin(); it < products.end();
1501          ++it) {
1502       const Product& product = **it;
1503       const ProductState* product_state =
1504           original_state.GetProductState(system_install,
1505                                          product.distribution()->GetType());
1506       if (product_state != NULL &&
1507           (product_state->version().CompareTo(*installer_version) > 0)) {
1508         LOG(ERROR) << "Higher version of "
1509                    << product.distribution()->GetDisplayName()
1510                    << " is already installed.";
1511         higher_products |= (1 << product.distribution()->GetType());
1512       }
1513     }
1514
1515     if (higher_products != 0) {
1516       COMPILE_ASSERT(BrowserDistribution::NUM_TYPES == 4,
1517                      add_support_for_new_products_here_);
1518       const uint32 kBrowserBit = 1 << BrowserDistribution::CHROME_BROWSER;
1519       const uint32 kAppHostBit = 1 << BrowserDistribution::CHROME_APP_HOST;
1520       int message_id = 0;
1521
1522       proceed_with_installation = false;
1523       install_status = HIGHER_VERSION_EXISTS;
1524       switch (higher_products) {
1525         case kBrowserBit:
1526           message_id = IDS_INSTALL_HIGHER_VERSION_BASE;
1527           break;
1528         default:
1529           message_id = IDS_INSTALL_HIGHER_VERSION_APP_LAUNCHER_BASE;
1530           break;
1531       }
1532
1533       installer_state.WriteInstallerResult(install_status, message_id, NULL);
1534     }
1535
1536     proceed_with_installation =
1537         proceed_with_installation &&
1538         CheckGroupPolicySettings(original_state, installer_state,
1539                                  *installer_version, &install_status);
1540
1541     if (proceed_with_installation) {
1542       // If Google Update is absent at user-level, install it using the
1543       // Google Update installer from an existing system-level installation.
1544       // This is for quick-enable App Host install from a system-level
1545       // Chrome Binaries installation.
1546       if (!system_install && installer_state.ensure_google_update_present()) {
1547         if (!google_update::EnsureUserLevelGoogleUpdatePresent()) {
1548           LOG(ERROR) << "Failed to install Google Update";
1549           proceed_with_installation = false;
1550           install_status = INSTALL_OF_GOOGLE_UPDATE_FAILED;
1551           installer_state.WriteInstallerResult(install_status, 0, NULL);
1552         }
1553       }
1554
1555     }
1556
1557     if (proceed_with_installation) {
1558       base::FilePath prefs_source_path(cmd_line.GetSwitchValueNative(
1559           switches::kInstallerData));
1560       install_status = InstallOrUpdateProduct(
1561           original_state, installer_state, cmd_line.GetProgram(),
1562           uncompressed_archive, temp_path.path(), src_path, prefs_source_path,
1563           prefs, *installer_version);
1564
1565       int install_msg_base = IDS_INSTALL_FAILED_BASE;
1566       base::string16 chrome_exe;
1567       base::string16 quoted_chrome_exe;
1568       if (install_status == SAME_VERSION_REPAIR_FAILED) {
1569         install_msg_base = IDS_SAME_VERSION_REPAIR_FAILED_BASE;
1570       } else if (install_status != INSTALL_FAILED) {
1571         if (installer_state.target_path().empty()) {
1572           // If we failed to construct install path, it means the OS call to
1573           // get %ProgramFiles% or %AppData% failed. Report this as failure.
1574           install_msg_base = IDS_INSTALL_OS_ERROR_BASE;
1575           install_status = OS_ERROR;
1576         } else {
1577           chrome_exe = installer_state.target_path().Append(kChromeExe).value();
1578           quoted_chrome_exe = L"\"" + chrome_exe + L"\"";
1579           install_msg_base = 0;
1580         }
1581       }
1582
1583       installer_state.UpdateStage(FINISHING);
1584
1585       // Only do Chrome-specific stuff (like launching the browser) if
1586       // Chrome was specifically requested (rather than being upgraded as
1587       // part of a multi-install).
1588       const Product* chrome_install = prefs.install_chrome() ?
1589           installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER) :
1590           NULL;
1591
1592       bool do_not_register_for_update_launch = false;
1593       if (chrome_install) {
1594         prefs.GetBool(master_preferences::kDoNotRegisterForUpdateLaunch,
1595                       &do_not_register_for_update_launch);
1596       } else {
1597         do_not_register_for_update_launch = true;  // Never register.
1598       }
1599
1600       bool write_chrome_launch_string =
1601           (!do_not_register_for_update_launch &&
1602            install_status != IN_USE_UPDATED);
1603
1604       installer_state.WriteInstallerResult(install_status, install_msg_base,
1605           write_chrome_launch_string ? &quoted_chrome_exe : NULL);
1606
1607       if (install_status == FIRST_INSTALL_SUCCESS) {
1608         VLOG(1) << "First install successful.";
1609         if (chrome_install) {
1610           // We never want to launch Chrome in system level install mode.
1611           bool do_not_launch_chrome = false;
1612           prefs.GetBool(master_preferences::kDoNotLaunchChrome,
1613                         &do_not_launch_chrome);
1614           if (!system_install && !do_not_launch_chrome)
1615             chrome_install->LaunchChrome(installer_state.target_path());
1616         }
1617       } else if ((install_status == NEW_VERSION_UPDATED) ||
1618                  (install_status == IN_USE_UPDATED)) {
1619         const Product* chrome = installer_state.FindProduct(
1620             BrowserDistribution::CHROME_BROWSER);
1621         if (chrome != NULL) {
1622           DCHECK_NE(chrome_exe, base::string16());
1623           RemoveChromeLegacyRegistryKeys(chrome->distribution(), chrome_exe);
1624         }
1625       }
1626
1627       if (prefs.install_chrome_app_launcher() &&
1628           InstallUtil::GetInstallReturnCode(install_status) == 0) {
1629         std::string webstore_item(google_update::GetUntrustedDataValue(
1630             kInstallFromWebstore));
1631         if (!webstore_item.empty()) {
1632           bool success = InstallFromWebstore(webstore_item);
1633           VLOG_IF(1, !success) << "Failed to launch app installation.";
1634         }
1635       }
1636     }
1637   }
1638
1639   // There might be an experiment (for upgrade usually) that needs to happen.
1640   // An experiment's outcome can include chrome's uninstallation. If that is
1641   // the case we would not do that directly at this point but in another
1642   // instance of setup.exe
1643   //
1644   // There is another way to reach this same function if this is a system
1645   // level install. See HandleNonInstallCmdLineOptions().
1646   {
1647     // If installation failed, use the path to the currently running setup.
1648     // If installation succeeded, use the path to setup in the installer dir.
1649     base::FilePath setup_path(cmd_line.GetProgram());
1650     if (InstallUtil::GetInstallReturnCode(install_status) == 0) {
1651       setup_path = installer_state.GetInstallerDirectory(*installer_version)
1652           .Append(setup_path.BaseName());
1653     }
1654     const Products& products = installer_state.products();
1655     for (Products::const_iterator it = products.begin(); it < products.end();
1656          ++it) {
1657       const Product& product = **it;
1658       product.LaunchUserExperiment(setup_path, install_status,
1659                                    system_install);
1660     }
1661   }
1662
1663   // If installation completed successfully, return the path to the directory
1664   // containing the newly installed setup.exe and uncompressed archive if the
1665   // caller requested it.
1666   if (installer_directory &&
1667       InstallUtil::GetInstallReturnCode(install_status) == 0) {
1668     *installer_directory =
1669         installer_state.GetInstallerDirectory(*installer_version);
1670   }
1671
1672   // temp_path's dtor will take care of deleting or scheduling itself for
1673   // deletion at reboot when this scope closes.
1674   VLOG(1) << "Deleting temporary directory " << temp_path.path().value();
1675
1676   return install_status;
1677 }
1678
1679 }  // namespace installer
1680
1681 int WINAPI wWinMain(HINSTANCE instance, HINSTANCE prev_instance,
1682                     wchar_t* command_line, int show_command) {
1683   // The exit manager is in charge of calling the dtors of singletons.
1684   base::AtExitManager exit_manager;
1685   CommandLine::Init(0, NULL);
1686
1687   const MasterPreferences& prefs = MasterPreferences::ForCurrentProcess();
1688   installer::InitInstallerLogging(prefs);
1689
1690   const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
1691   VLOG(1) << "Command Line: " << cmd_line.GetCommandLineString();
1692
1693   VLOG(1) << "multi install is " << prefs.is_multi_install();
1694   bool system_install = false;
1695   prefs.GetBool(installer::master_preferences::kSystemLevel, &system_install);
1696   VLOG(1) << "system install is " << system_install;
1697
1698   google_breakpad::scoped_ptr<google_breakpad::ExceptionHandler> breakpad(
1699       InitializeCrashReporting(system_install));
1700
1701   InstallationState original_state;
1702   original_state.Initialize();
1703
1704   InstallerState installer_state;
1705   installer_state.Initialize(cmd_line, prefs, original_state);
1706   const bool is_uninstall = cmd_line.HasSwitch(installer::switches::kUninstall);
1707
1708   // Check to make sure current system is WinXP or later. If not, log
1709   // error message and get out.
1710   if (!InstallUtil::IsOSSupported()) {
1711     LOG(ERROR) << "Chrome only supports Windows XP or later.";
1712     installer_state.WriteInstallerResult(
1713         installer::OS_NOT_SUPPORTED, IDS_INSTALL_OS_NOT_SUPPORTED_BASE, NULL);
1714     return installer::OS_NOT_SUPPORTED;
1715   }
1716
1717   // Initialize COM for use later.
1718   base::win::ScopedCOMInitializer com_initializer;
1719   if (!com_initializer.succeeded()) {
1720     installer_state.WriteInstallerResult(
1721         installer::OS_ERROR, IDS_INSTALL_OS_ERROR_BASE, NULL);
1722     return installer::OS_ERROR;
1723   }
1724
1725   // Some command line options don't work with SxS install/uninstall
1726   if (InstallUtil::IsChromeSxSProcess()) {
1727     if (system_install ||
1728         prefs.is_multi_install() ||
1729         cmd_line.HasSwitch(installer::switches::kForceUninstall) ||
1730         cmd_line.HasSwitch(installer::switches::kMakeChromeDefault) ||
1731         cmd_line.HasSwitch(installer::switches::kRegisterChromeBrowser) ||
1732         cmd_line.HasSwitch(installer::switches::kRemoveChromeRegistration) ||
1733         cmd_line.HasSwitch(installer::switches::kInactiveUserToast) ||
1734         cmd_line.HasSwitch(installer::switches::kSystemLevelToast)) {
1735       return installer::SXS_OPTION_NOT_SUPPORTED;
1736     }
1737   }
1738
1739   // Some command line options are no longer supported and must error out.
1740   if (installer::ContainsUnsupportedSwitch(cmd_line))
1741     return installer::UNSUPPORTED_OPTION;
1742
1743   int exit_code = 0;
1744   if (HandleNonInstallCmdLineOptions(
1745           original_state, cmd_line, &installer_state, &exit_code)) {
1746     return exit_code;
1747   }
1748
1749   if (system_install && !IsUserAnAdmin()) {
1750     if (base::win::GetVersion() >= base::win::VERSION_VISTA &&
1751         !cmd_line.HasSwitch(installer::switches::kRunAsAdmin)) {
1752       CommandLine new_cmd(CommandLine::NO_PROGRAM);
1753       new_cmd.AppendArguments(cmd_line, true);
1754       // Append --run-as-admin flag to let the new instance of setup.exe know
1755       // that we already tried to launch ourselves as admin.
1756       new_cmd.AppendSwitch(installer::switches::kRunAsAdmin);
1757       // If system_install became true due to an environment variable, append
1758       // it to the command line here since env vars may not propagate past the
1759       // elevation.
1760       if (!new_cmd.HasSwitch(installer::switches::kSystemLevel))
1761         new_cmd.AppendSwitch(installer::switches::kSystemLevel);
1762
1763       DWORD exit_code = installer::UNKNOWN_STATUS;
1764       InstallUtil::ExecuteExeAsAdmin(new_cmd, &exit_code);
1765       return exit_code;
1766     } else {
1767       LOG(ERROR) << "Non admin user can not install system level Chrome.";
1768       installer_state.WriteInstallerResult(installer::INSUFFICIENT_RIGHTS,
1769           IDS_INSTALL_INSUFFICIENT_RIGHTS_BASE, NULL);
1770       return installer::INSUFFICIENT_RIGHTS;
1771     }
1772   }
1773
1774   UninstallMultiChromeFrameIfPresent(cmd_line, prefs,
1775                                      &original_state, &installer_state);
1776
1777   base::FilePath installer_directory;
1778   installer::InstallStatus install_status = installer::UNKNOWN_STATUS;
1779   // If --uninstall option is given, uninstall the identified product(s)
1780   if (is_uninstall) {
1781     install_status =
1782         UninstallProducts(original_state, installer_state, cmd_line);
1783   } else {
1784     // If --uninstall option is not specified, we assume it is install case.
1785     install_status =
1786         InstallProducts(original_state, cmd_line, prefs, &installer_state,
1787                         &installer_directory);
1788   }
1789
1790   // Validate that the machine is now in a good state following the operation.
1791   // TODO(grt): change this to log at DFATAL once we're convinced that the
1792   // validator handles all cases properly.
1793   InstallationValidator::InstallationType installation_type =
1794       InstallationValidator::NO_PRODUCTS;
1795   LOG_IF(ERROR,
1796          !InstallationValidator::ValidateInstallationType(system_install,
1797                                                           &installation_type));
1798
1799   int return_code = 0;
1800   // MSI demands that custom actions always return 0 (ERROR_SUCCESS) or it will
1801   // rollback the action. If we're uninstalling we want to avoid this, so always
1802   // report success, squashing any more informative return codes.
1803   if (!(installer_state.is_msi() && is_uninstall)) {
1804     // Note that we allow the status installer::UNINSTALL_REQUIRES_REBOOT
1805     // to pass through, since this is only returned on uninstall which is
1806     // never invoked directly by Google Update.
1807     return_code = InstallUtil::GetInstallReturnCode(install_status);
1808   }
1809
1810   VLOG(1) << "Installation complete, returning: " << return_code;
1811
1812   return return_code;
1813 }