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