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