install.cc revision cedac228d2dd51db4b79ea1e72c7f249408ee061
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/install.h"
6
7#include <windows.h>
8#include <shlobj.h>
9#include <time.h>
10
11#include <string>
12
13#include "base/command_line.h"
14#include "base/file_util.h"
15#include "base/files/file_path.h"
16#include "base/logging.h"
17#include "base/memory/scoped_ptr.h"
18#include "base/numerics/safe_conversions.h"
19#include "base/path_service.h"
20#include "base/process/launch.h"
21#include "base/strings/string_util.h"
22#include "base/strings/stringprintf.h"
23#include "base/strings/utf_string_conversions.h"
24#include "base/win/shortcut.h"
25#include "base/win/windows_version.h"
26#include "chrome/common/chrome_constants.h"
27#include "chrome/common/chrome_switches.h"
28#include "chrome/installer/launcher_support/chrome_launcher_support.h"
29#include "chrome/installer/setup/install_worker.h"
30#include "chrome/installer/setup/setup_constants.h"
31#include "chrome/installer/util/auto_launch_util.h"
32#include "chrome/installer/util/browser_distribution.h"
33#include "chrome/installer/util/create_reg_key_work_item.h"
34#include "chrome/installer/util/delete_after_reboot_helper.h"
35#include "chrome/installer/util/google_update_constants.h"
36#include "chrome/installer/util/helper.h"
37#include "chrome/installer/util/install_util.h"
38#include "chrome/installer/util/master_preferences.h"
39#include "chrome/installer/util/master_preferences_constants.h"
40#include "chrome/installer/util/set_reg_value_work_item.h"
41#include "chrome/installer/util/shell_util.h"
42#include "chrome/installer/util/util_constants.h"
43#include "chrome/installer/util/work_item_list.h"
44
45
46namespace {
47
48void LogShortcutOperation(ShellUtil::ShortcutLocation location,
49                          BrowserDistribution* dist,
50                          const ShellUtil::ShortcutProperties& properties,
51                          ShellUtil::ShortcutOperation operation,
52                          bool failed) {
53  // ShellUtil::SHELL_SHORTCUT_UPDATE_EXISTING should not be used at install and
54  // thus this method does not handle logging a message for it.
55  DCHECK(operation != ShellUtil::SHELL_SHORTCUT_UPDATE_EXISTING);
56  std::string message;
57  if (failed)
58    message.append("Failed: ");
59  message.append(
60      (operation == ShellUtil::SHELL_SHORTCUT_CREATE_ALWAYS ||
61       operation == ShellUtil::SHELL_SHORTCUT_CREATE_IF_NO_SYSTEM_LEVEL) ?
62      "Creating " : "Overwriting ");
63  if (failed && operation == ShellUtil::SHELL_SHORTCUT_REPLACE_EXISTING)
64    message.append("(maybe the shortcut doesn't exist?) ");
65  message.append((properties.level == ShellUtil::CURRENT_USER) ? "per-user " :
66                                                                 "all-users ");
67  switch (location) {
68    case ShellUtil::SHORTCUT_LOCATION_DESKTOP:
69      message.append("Desktop ");
70      break;
71    case ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH:
72      message.append("Quick Launch ");
73      break;
74    case ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR:
75      message.append("Start menu/" +
76                     base::UTF16ToUTF8(dist->GetStartMenuShortcutSubfolder(
77                                     BrowserDistribution::SUBFOLDER_CHROME)) +
78                      " ");
79      break;
80    case ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR:
81      message.append("Start menu/" +
82                     base::UTF16ToUTF8(dist->GetStartMenuShortcutSubfolder(
83                                     BrowserDistribution::SUBFOLDER_APPS)) +
84                     " ");
85      break;
86    default:
87      NOTREACHED();
88  }
89
90  message.push_back('"');
91  if (properties.has_shortcut_name())
92    message.append(base::UTF16ToUTF8(properties.shortcut_name));
93  else
94    message.append(base::UTF16ToUTF8(dist->GetDisplayName()));
95  message.push_back('"');
96
97  message.append(" shortcut to ");
98  message.append(base::UTF16ToUTF8(properties.target.value()));
99  if (properties.has_arguments())
100    message.append(base::UTF16ToUTF8(properties.arguments));
101
102  if (properties.pin_to_taskbar &&
103      base::win::GetVersion() >= base::win::VERSION_WIN7) {
104    message.append(" and pinning to the taskbar.");
105  } else {
106    message.push_back('.');
107  }
108
109  if (failed)
110    LOG(WARNING) << message;
111  else
112    VLOG(1) << message;
113}
114
115void ExecuteAndLogShortcutOperation(
116    ShellUtil::ShortcutLocation location,
117    BrowserDistribution* dist,
118    const ShellUtil::ShortcutProperties& properties,
119    ShellUtil::ShortcutOperation operation) {
120  LogShortcutOperation(location, dist, properties, operation, false);
121  if (!ShellUtil::CreateOrUpdateShortcut(location, dist, properties,
122                                         operation)) {
123    LogShortcutOperation(location, dist, properties, operation, true);
124  }
125}
126
127void AddChromeToMediaPlayerList() {
128  base::string16 reg_path(installer::kMediaPlayerRegPath);
129  // registry paths can also be appended like file system path
130  reg_path.push_back(base::FilePath::kSeparators[0]);
131  reg_path.append(installer::kChromeExe);
132  VLOG(1) << "Adding Chrome to Media player list at " << reg_path;
133  scoped_ptr<WorkItem> work_item(WorkItem::CreateCreateRegKeyWorkItem(
134      HKEY_LOCAL_MACHINE, reg_path, WorkItem::kWow64Default));
135
136  // if the operation fails we log the error but still continue
137  if (!work_item.get()->Do())
138    LOG(ERROR) << "Could not add Chrome to media player inclusion list.";
139}
140
141// Copy master_preferences file provided to installer, in the same folder
142// as chrome.exe so Chrome first run can find it. This function will be called
143// only on the first install of Chrome.
144void CopyPreferenceFileForFirstRun(
145    const installer::InstallerState& installer_state,
146    const base::FilePath& prefs_source_path) {
147  base::FilePath prefs_dest_path(installer_state.target_path().AppendASCII(
148      installer::kDefaultMasterPrefs));
149  if (!base::CopyFile(prefs_source_path, prefs_dest_path)) {
150    VLOG(1) << "Failed to copy master preferences from:"
151            << prefs_source_path.value() << " gle: " << ::GetLastError();
152  }
153}
154
155// This function installs a new version of Chrome to the specified location.
156//
157// setup_path: Path to the executable (setup.exe) as it will be copied
158//           to Chrome install folder after install is complete
159// archive_path: Path to the archive (chrome.7z) as it will be copied
160//               to Chrome install folder after install is complete
161// src_path: the path that contains a complete and unpacked Chrome package
162//           to be installed.
163// temp_path: the path of working directory used during installation. This path
164//            does not need to exist.
165// new_version: new Chrome version that needs to be installed
166// current_version: returns the current active version (if any)
167//
168// This function makes best effort to do installation in a transactional
169// manner. If failed it tries to rollback all changes on the file system
170// and registry. For example, if package exists before calling the
171// function, it rolls back all new file and directory changes under
172// package. If package does not exist before calling the function
173// (typical new install), the function creates package during install
174// and removes the whole directory during rollback.
175installer::InstallStatus InstallNewVersion(
176    const installer::InstallationState& original_state,
177    const installer::InstallerState& installer_state,
178    const base::FilePath& setup_path,
179    const base::FilePath& archive_path,
180    const base::FilePath& src_path,
181    const base::FilePath& temp_path,
182    const Version& new_version,
183    scoped_ptr<Version>* current_version) {
184  DCHECK(current_version);
185
186  installer_state.UpdateStage(installer::BUILDING);
187
188  current_version->reset(installer_state.GetCurrentVersion(original_state));
189  scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
190
191  AddInstallWorkItems(original_state,
192                      installer_state,
193                      setup_path,
194                      archive_path,
195                      src_path,
196                      temp_path,
197                      current_version->get(),
198                      new_version,
199                      install_list.get());
200
201  base::FilePath new_chrome_exe(
202      installer_state.target_path().Append(installer::kChromeNewExe));
203
204  installer_state.UpdateStage(installer::EXECUTING);
205
206  if (!install_list->Do()) {
207    installer_state.UpdateStage(installer::ROLLINGBACK);
208    installer::InstallStatus result =
209        base::PathExists(new_chrome_exe) && current_version->get() &&
210        new_version.Equals(*current_version->get()) ?
211        installer::SAME_VERSION_REPAIR_FAILED :
212        installer::INSTALL_FAILED;
213    LOG(ERROR) << "Install failed, rolling back... result: " << result;
214    install_list->Rollback();
215    LOG(ERROR) << "Rollback complete. ";
216    return result;
217  }
218
219  installer_state.UpdateStage(installer::REFRESHING_POLICY);
220
221  installer::RefreshElevationPolicy();
222
223  if (!current_version->get()) {
224    VLOG(1) << "First install of version " << new_version.GetString();
225    return installer::FIRST_INSTALL_SUCCESS;
226  }
227
228  if (new_version.Equals(**current_version)) {
229    VLOG(1) << "Install repaired of version " << new_version.GetString();
230    return installer::INSTALL_REPAIRED;
231  }
232
233  if (new_version.CompareTo(**current_version) > 0) {
234    if (base::PathExists(new_chrome_exe)) {
235      VLOG(1) << "Version updated to " << new_version.GetString()
236              << " while running " << (*current_version)->GetString();
237      return installer::IN_USE_UPDATED;
238    }
239    VLOG(1) << "Version updated to " << new_version.GetString();
240    return installer::NEW_VERSION_UPDATED;
241  }
242
243  LOG(ERROR) << "Not sure how we got here while updating"
244             << ", new version: " << new_version.GetString()
245             << ", old version: " << (*current_version)->GetString();
246
247  return installer::INSTALL_FAILED;
248}
249
250// Deletes the old "Uninstall Google Chrome" shortcut in the Start menu and, if
251// this is a system-level install, also deletes the old Default user Quick
252// Launch shortcut. Both of these were created prior to Chrome 24; in Chrome 24,
253// the uninstall shortcut was removed and the Default user Quick Launch shortcut
254// was replaced by per-user shortcuts created via Active Setup.
255void CleanupLegacyShortcuts(const installer::InstallerState& installer_state,
256                            BrowserDistribution* dist,
257                            const base::FilePath& chrome_exe) {
258  ShellUtil::ShellChange shortcut_level = installer_state.system_install() ?
259      ShellUtil::SYSTEM_LEVEL : ShellUtil::CURRENT_USER;
260  base::FilePath uninstall_shortcut_path;
261  ShellUtil::GetShortcutPath(ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR,
262                             dist, shortcut_level, &uninstall_shortcut_path);
263  uninstall_shortcut_path = uninstall_shortcut_path.Append(
264      dist->GetUninstallLinkName() + installer::kLnkExt);
265  base::DeleteFile(uninstall_shortcut_path, false);
266
267  if (installer_state.system_install()) {
268    ShellUtil::RemoveShortcuts(
269        ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH, dist,
270        ShellUtil::SYSTEM_LEVEL, chrome_exe);
271  }
272}
273
274// Returns the appropriate shortcut operations for App Launcher,
275// based on state of installation and master_preferences.
276installer::InstallShortcutOperation GetAppLauncherShortcutOperation(
277    const installer::InstallationState& original_state,
278    const installer::InstallerState& installer_state) {
279  const installer::ProductState* original_app_host_state =
280      original_state.GetProductState(installer_state.system_install(),
281                                     BrowserDistribution::CHROME_APP_HOST);
282  bool app_launcher_exists = original_app_host_state &&
283      original_app_host_state->uninstall_command()
284          .HasSwitch(installer::switches::kChromeAppLauncher);
285  if (!app_launcher_exists)
286    return installer::INSTALL_SHORTCUT_CREATE_ALL;
287
288  return installer::INSTALL_SHORTCUT_REPLACE_EXISTING;
289}
290
291}  // end namespace
292
293namespace installer {
294
295void EscapeXmlAttributeValueInSingleQuotes(base::string16* att_value) {
296  base::ReplaceChars(*att_value, base::ASCIIToUTF16("&"),
297                     base::ASCIIToUTF16("&amp;"), att_value);
298  base::ReplaceChars(*att_value, base::ASCIIToUTF16("'"),
299                     base::ASCIIToUTF16("&apos;"), att_value);
300  base::ReplaceChars(*att_value, base::ASCIIToUTF16("<"),
301                     base::ASCIIToUTF16("&lt;"), att_value);
302}
303
304bool CreateVisualElementsManifest(const base::FilePath& src_path,
305                                  const Version& version) {
306  // Construct the relative path to the versioned VisualElements directory.
307  base::string16 elements_dir(base::ASCIIToUTF16(version.GetString()));
308  elements_dir.push_back(base::FilePath::kSeparators[0]);
309  elements_dir.append(installer::kVisualElements);
310
311  // Some distributions of Chromium may not include visual elements. Only
312  // proceed if this distribution does.
313  if (!base::PathExists(src_path.Append(elements_dir))) {
314    VLOG(1) << "No visual elements found, not writing "
315            << installer::kVisualElementsManifest << " to " << src_path.value();
316    return true;
317  } else {
318    // A printf_p-style format string for generating the visual elements
319    // manifest. Required arguments, in order, are:
320    //   - Localized display name for the product.
321    //   - Relative path to the VisualElements directory.
322    static const char kManifestTemplate[] =
323        "<Application>\r\n"
324        "  <VisualElements\r\n"
325        "      DisplayName='%1$ls'\r\n"
326        "      Logo='%2$ls\\Logo.png'\r\n"
327        "      SmallLogo='%2$ls\\SmallLogo.png'\r\n"
328        "      ForegroundText='light'\r\n"
329        "      BackgroundColor='#323232'>\r\n"
330        "    <DefaultTile ShowName='allLogos'/>\r\n"
331        "    <SplashScreen Image='%2$ls\\splash-620x300.png'/>\r\n"
332        "  </VisualElements>\r\n"
333        "</Application>";
334
335    const base::string16 manifest_template(
336        base::ASCIIToUTF16(kManifestTemplate));
337
338    BrowserDistribution* dist = BrowserDistribution::GetSpecificDistribution(
339        BrowserDistribution::CHROME_BROWSER);
340    // TODO(grt): http://crbug.com/75152 Write a reference to a localized
341    // resource for |display_name|.
342    base::string16 display_name(dist->GetDisplayName());
343    EscapeXmlAttributeValueInSingleQuotes(&display_name);
344
345    // Fill the manifest with the desired values.
346    base::string16 manifest16(base::StringPrintf(
347        manifest_template.c_str(), display_name.c_str(), elements_dir.c_str()));
348
349    // Write the manifest to |src_path|.
350    const std::string manifest(base::UTF16ToUTF8(manifest16));
351    int size = base::checked_cast<int>(manifest.size());
352    if (base::WriteFile(
353        src_path.Append(installer::kVisualElementsManifest),
354            manifest.c_str(), size) == size) {
355      VLOG(1) << "Successfully wrote " << installer::kVisualElementsManifest
356              << " to " << src_path.value();
357      return true;
358    } else {
359      PLOG(ERROR) << "Error writing " << installer::kVisualElementsManifest
360                  << " to " << src_path.value();
361      return false;
362    }
363  }
364}
365
366void CreateOrUpdateShortcuts(
367    const base::FilePath& target,
368    const installer::Product& product,
369    const MasterPreferences& prefs,
370    InstallShortcutLevel install_level,
371    InstallShortcutOperation install_operation) {
372  bool do_not_create_any_shortcuts = false;
373  prefs.GetBool(master_preferences::kDoNotCreateAnyShortcuts,
374                &do_not_create_any_shortcuts);
375  if (do_not_create_any_shortcuts)
376    return;
377
378  // Extract shortcut preferences from |prefs|.
379  bool do_not_create_desktop_shortcut = false;
380  bool do_not_create_quick_launch_shortcut = false;
381  bool do_not_create_taskbar_shortcut = false;
382  bool alternate_desktop_shortcut = false;
383  prefs.GetBool(master_preferences::kDoNotCreateDesktopShortcut,
384                &do_not_create_desktop_shortcut);
385  prefs.GetBool(master_preferences::kDoNotCreateQuickLaunchShortcut,
386                &do_not_create_quick_launch_shortcut);
387  prefs.GetBool(master_preferences::kDoNotCreateTaskbarShortcut,
388                &do_not_create_taskbar_shortcut);
389  prefs.GetBool(master_preferences::kAltShortcutText,
390                &alternate_desktop_shortcut);
391
392  BrowserDistribution* dist = product.distribution();
393
394  // The default operation on update is to overwrite shortcuts with the
395  // currently desired properties, but do so only for shortcuts that still
396  // exist.
397  ShellUtil::ShortcutOperation shortcut_operation;
398  switch (install_operation) {
399    case INSTALL_SHORTCUT_CREATE_ALL:
400      shortcut_operation = ShellUtil::SHELL_SHORTCUT_CREATE_ALWAYS;
401      break;
402    case INSTALL_SHORTCUT_CREATE_EACH_IF_NO_SYSTEM_LEVEL:
403      shortcut_operation = ShellUtil::SHELL_SHORTCUT_CREATE_IF_NO_SYSTEM_LEVEL;
404      break;
405    default:
406      DCHECK(install_operation == INSTALL_SHORTCUT_REPLACE_EXISTING);
407      shortcut_operation = ShellUtil::SHELL_SHORTCUT_REPLACE_EXISTING;
408      break;
409  }
410
411  // Shortcuts are always installed per-user unless specified.
412  ShellUtil::ShellChange shortcut_level = (install_level == ALL_USERS ?
413      ShellUtil::SYSTEM_LEVEL : ShellUtil::CURRENT_USER);
414
415  // |base_properties|: The basic properties to set on every shortcut installed
416  // (to be refined on a per-shortcut basis).
417  ShellUtil::ShortcutProperties base_properties(shortcut_level);
418  product.AddDefaultShortcutProperties(target, &base_properties);
419
420  if (!do_not_create_desktop_shortcut ||
421      shortcut_operation == ShellUtil::SHELL_SHORTCUT_REPLACE_EXISTING) {
422    ShellUtil::ShortcutProperties desktop_properties(base_properties);
423    if (alternate_desktop_shortcut) {
424      desktop_properties.set_shortcut_name(
425          dist->GetShortcutName(
426              BrowserDistribution::SHORTCUT_CHROME_ALTERNATE));
427    }
428    ExecuteAndLogShortcutOperation(
429        ShellUtil::SHORTCUT_LOCATION_DESKTOP, dist, desktop_properties,
430        shortcut_operation);
431
432    // On update there is no harm in always trying to update the alternate
433    // Desktop shortcut.
434    if (!alternate_desktop_shortcut &&
435        shortcut_operation == ShellUtil::SHELL_SHORTCUT_REPLACE_EXISTING) {
436      desktop_properties.set_shortcut_name(
437          dist->GetShortcutName(
438              BrowserDistribution::SHORTCUT_CHROME_ALTERNATE));
439      ExecuteAndLogShortcutOperation(
440          ShellUtil::SHORTCUT_LOCATION_DESKTOP, dist, desktop_properties,
441          shortcut_operation);
442    }
443  }
444
445  if (!do_not_create_quick_launch_shortcut ||
446      shortcut_operation == ShellUtil::SHELL_SHORTCUT_REPLACE_EXISTING) {
447    // There is no such thing as an all-users Quick Launch shortcut, always
448    // install the per-user shortcut.
449    ShellUtil::ShortcutProperties quick_launch_properties(base_properties);
450    quick_launch_properties.level = ShellUtil::CURRENT_USER;
451    ExecuteAndLogShortcutOperation(
452        ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH, dist,
453        quick_launch_properties, shortcut_operation);
454  }
455
456  ShellUtil::ShortcutProperties start_menu_properties(base_properties);
457  // IMPORTANT: Only the default (no arguments and default browserappid) browser
458  // shortcut in the Start menu (Start screen on Win8+) should be made dual
459  // mode.
460  start_menu_properties.set_dual_mode(true);
461  if (!do_not_create_taskbar_shortcut &&
462      (shortcut_operation == ShellUtil::SHELL_SHORTCUT_CREATE_ALWAYS ||
463       shortcut_operation ==
464           ShellUtil::SHELL_SHORTCUT_CREATE_IF_NO_SYSTEM_LEVEL)) {
465    start_menu_properties.set_pin_to_taskbar(true);
466  }
467  ExecuteAndLogShortcutOperation(
468      ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR, dist,
469      start_menu_properties, shortcut_operation);
470}
471
472void RegisterChromeOnMachine(const installer::InstallerState& installer_state,
473                             const installer::Product& product,
474                             bool make_chrome_default) {
475  DCHECK(product.is_chrome());
476
477  // Try to add Chrome to Media Player shim inclusion list. We don't do any
478  // error checking here because this operation will fail if user doesn't
479  // have admin rights and we want to ignore the error.
480  AddChromeToMediaPlayerList();
481
482  // Make Chrome the default browser if desired when possible. Otherwise, only
483  // register it with Windows.
484  BrowserDistribution* dist = product.distribution();
485  const base::string16 chrome_exe(
486      installer_state.target_path().Append(installer::kChromeExe).value());
487  VLOG(1) << "Registering Chrome as browser: " << chrome_exe;
488  if (make_chrome_default && ShellUtil::CanMakeChromeDefaultUnattended()) {
489    int level = ShellUtil::CURRENT_USER;
490    if (installer_state.system_install())
491      level = level | ShellUtil::SYSTEM_LEVEL;
492    ShellUtil::MakeChromeDefault(dist, level, chrome_exe, true);
493  } else {
494    ShellUtil::RegisterChromeBrowser(dist, chrome_exe, base::string16(), false);
495  }
496}
497
498InstallStatus InstallOrUpdateProduct(
499    const installer::InstallationState& original_state,
500    const installer::InstallerState& installer_state,
501    const base::FilePath& setup_path,
502    const base::FilePath& archive_path,
503    const base::FilePath& install_temp_path,
504    const base::FilePath& src_path,
505    const base::FilePath& prefs_path,
506    const MasterPreferences& prefs,
507    const Version& new_version) {
508  DCHECK(!installer_state.products().empty());
509
510  // TODO(robertshield): Removing the pending on-reboot moves should be done
511  // elsewhere.
512  // Remove any scheduled MOVEFILE_DELAY_UNTIL_REBOOT entries in the target of
513  // this installation. These may have been added during a previous uninstall of
514  // the same version.
515  LOG_IF(ERROR, !RemoveFromMovesPendingReboot(installer_state.target_path()))
516      << "Error accessing pending moves value.";
517
518  // Create VisualElementManifest.xml in |src_path| (if required) so that it
519  // looks as if it had been extracted from the archive when calling
520  // InstallNewVersion() below.
521  installer_state.UpdateStage(installer::CREATING_VISUAL_MANIFEST);
522  CreateVisualElementsManifest(src_path, new_version);
523
524  scoped_ptr<Version> existing_version;
525  InstallStatus result = InstallNewVersion(original_state, installer_state,
526      setup_path, archive_path, src_path, install_temp_path, new_version,
527      &existing_version);
528
529  // TODO(robertshield): Everything below this line should instead be captured
530  // by WorkItems.
531  if (!InstallUtil::GetInstallReturnCode(result)) {
532    installer_state.UpdateStage(installer::UPDATING_CHANNELS);
533
534    // Update the modifiers on the channel values for the product(s) being
535    // installed and for the binaries in case of multi-install.
536    installer_state.UpdateChannels();
537
538    installer_state.UpdateStage(installer::COPYING_PREFERENCES_FILE);
539
540    if (result == FIRST_INSTALL_SUCCESS && !prefs_path.empty())
541      CopyPreferenceFileForFirstRun(installer_state, prefs_path);
542
543    installer_state.UpdateStage(installer::CREATING_SHORTCUTS);
544
545    const installer::Product* app_launcher_product =
546        installer_state.FindProduct(BrowserDistribution::CHROME_APP_HOST);
547    // Creates shortcuts for App Launcher.
548    if (app_launcher_product) {
549      // TODO(huangs): Remove this check once we have system-level App Host.
550      DCHECK(!installer_state.system_install());
551      const base::FilePath app_host_exe(
552          installer_state.target_path().Append(kChromeAppHostExe));
553      InstallShortcutOperation app_launcher_shortcut_operation =
554          GetAppLauncherShortcutOperation(original_state, installer_state);
555
556      // Always install per-user shortcuts for App Launcher.
557      CreateOrUpdateShortcuts(app_host_exe, *app_launcher_product, prefs,
558                              CURRENT_USER, app_launcher_shortcut_operation);
559    }
560
561    const installer::Product* chrome_product =
562        installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER);
563    // Creates shortcuts for Chrome.
564    if (chrome_product) {
565      BrowserDistribution* chrome_dist = chrome_product->distribution();
566      const base::FilePath chrome_exe(
567          installer_state.target_path().Append(kChromeExe));
568      CleanupLegacyShortcuts(installer_state, chrome_dist, chrome_exe);
569
570      // Install per-user shortcuts on user-level installs and all-users
571      // shortcuts on system-level installs. Note that Active Setup will take
572      // care of installing missing per-user shortcuts on system-level install
573      // (i.e., quick launch, taskbar pin, and possibly deleted all-users
574      // shortcuts).
575      InstallShortcutLevel install_level = installer_state.system_install() ?
576          ALL_USERS : CURRENT_USER;
577
578      InstallShortcutOperation install_operation =
579          INSTALL_SHORTCUT_REPLACE_EXISTING;
580      if (result == installer::FIRST_INSTALL_SUCCESS ||
581          result == installer::INSTALL_REPAIRED ||
582          !original_state.GetProductState(installer_state.system_install(),
583                                          chrome_dist->GetType())) {
584        // Always create the shortcuts on a new install, a repair install, and
585        // when the Chrome product is being added to the current install.
586        install_operation = INSTALL_SHORTCUT_CREATE_ALL;
587      }
588
589      CreateOrUpdateShortcuts(chrome_exe, *chrome_product, prefs, install_level,
590                              install_operation);
591    }
592
593    if (chrome_product) {
594      // Register Chrome and, if requested, make Chrome the default browser.
595      installer_state.UpdateStage(installer::REGISTERING_CHROME);
596
597      bool make_chrome_default = false;
598      prefs.GetBool(master_preferences::kMakeChromeDefault,
599                    &make_chrome_default);
600
601      // If this is not the user's first Chrome install, but they have chosen
602      // Chrome to become their default browser on the download page, we must
603      // force it here because the master_preferences file will not get copied
604      // into the build.
605      bool force_chrome_default_for_user = false;
606      if (result == NEW_VERSION_UPDATED ||
607          result == INSTALL_REPAIRED) {
608        prefs.GetBool(master_preferences::kMakeChromeDefaultForUser,
609                      &force_chrome_default_for_user);
610      }
611
612      RegisterChromeOnMachine(installer_state, *chrome_product,
613          make_chrome_default || force_chrome_default_for_user);
614
615      // Configure auto-launch.
616      if (result == FIRST_INSTALL_SUCCESS) {
617        installer_state.UpdateStage(installer::CONFIGURE_AUTO_LAUNCH);
618
619        // Add auto-launch key if specified in master_preferences.
620        bool auto_launch_chrome = false;
621        prefs.GetBool(
622            installer::master_preferences::kAutoLaunchChrome,
623            &auto_launch_chrome);
624        if (auto_launch_chrome) {
625          auto_launch_util::EnableForegroundStartAtLogin(
626              base::ASCIIToUTF16(chrome::kInitialProfile),
627              installer_state.target_path());
628        }
629      }
630    }
631
632    installer_state.UpdateStage(installer::REMOVING_OLD_VERSIONS);
633
634    installer_state.RemoveOldVersionDirectories(
635        new_version,
636        existing_version.get(),
637        install_temp_path);
638  }
639
640  return result;
641}
642
643void HandleOsUpgradeForBrowser(const installer::InstallerState& installer_state,
644                               const installer::Product& chrome) {
645  DCHECK(chrome.is_chrome());
646  // Upon upgrading to Windows 8, we need to fix Chrome shortcuts and register
647  // Chrome, so that Metro Chrome would work if Chrome is the default browser.
648  if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
649    VLOG(1) << "Updating and registering shortcuts.";
650    // Read master_preferences copied beside chrome.exe at install.
651    MasterPreferences prefs(
652        installer_state.target_path().AppendASCII(kDefaultMasterPrefs));
653
654    // Unfortunately, if this is a system-level install, we can't update the
655    // shortcuts of each individual user (this only matters if this is an OS
656    // upgrade from XP/Vista to Win7+ as some properties are only set on
657    // shortcuts as of Win7).
658    // At least attempt to update potentially existing all-users shortcuts.
659    InstallShortcutLevel level = installer_state.system_install() ?
660        ALL_USERS : CURRENT_USER;
661    base::FilePath chrome_exe(installer_state.target_path().Append(kChromeExe));
662    CreateOrUpdateShortcuts(
663        chrome_exe, chrome, prefs, level, INSTALL_SHORTCUT_REPLACE_EXISTING);
664    RegisterChromeOnMachine(installer_state, chrome, false);
665  }
666}
667
668// NOTE: Should the work done here, on Active Setup, change: kActiveSetupVersion
669// in install_worker.cc needs to be increased for Active Setup to invoke this
670// again for all users of this install.
671void HandleActiveSetupForBrowser(const base::FilePath& installation_root,
672                                 const installer::Product& chrome,
673                                 bool force) {
674  DCHECK(chrome.is_chrome());
675  // Only create shortcuts on Active Setup if the first run sentinel is not
676  // present for this user (as some shortcuts used to be installed on first
677  // run and this could otherwise re-install shortcuts for users that have
678  // already deleted them in the past).
679  // Decide whether to create the shortcuts or simply replace existing
680  // shortcuts; if the decision is to create them, only shortcuts whose matching
681  // all-users shortcut isn't present on the system will be created.
682  InstallShortcutOperation install_operation =
683      (!force && InstallUtil::IsFirstRunSentinelPresent() ?
684           INSTALL_SHORTCUT_REPLACE_EXISTING :
685           INSTALL_SHORTCUT_CREATE_EACH_IF_NO_SYSTEM_LEVEL);
686
687  // Read master_preferences copied beside chrome.exe at install.
688  MasterPreferences prefs(installation_root.AppendASCII(kDefaultMasterPrefs));
689  base::FilePath chrome_exe(installation_root.Append(kChromeExe));
690  CreateOrUpdateShortcuts(
691      chrome_exe, chrome, prefs, CURRENT_USER, install_operation);
692}
693
694bool InstallFromWebstore(const std::string& app_code) {
695  base::FilePath app_host_path(chrome_launcher_support::GetAnyAppHostPath());
696  if (app_host_path.empty())
697    return false;
698
699  CommandLine cmd(app_host_path);
700  cmd.AppendSwitchASCII(::switches::kInstallFromWebstore, app_code);
701  VLOG(1) << "App install command: " << cmd.GetCommandLineString();
702  return base::LaunchProcess(cmd, base::LaunchOptions(), NULL);
703}
704
705}  // namespace installer
706