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