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