Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / first_run / upgrade_util_win.cc
blob1fa59aab80555419f6cf1ebce4774fe835def844
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.
5 #include "chrome/browser/first_run/upgrade_util.h"
7 #include <windows.h>
8 #include <psapi.h>
9 #include <shellapi.h>
11 #include <algorithm>
12 #include <string>
14 #include "base/base_paths.h"
15 #include "base/command_line.h"
16 #include "base/environment.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/logging.h"
20 #include "base/path_service.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/process/launch.h"
23 #include "base/process/process_handle.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/win/metro.h"
28 #include "base/win/registry.h"
29 #include "base/win/scoped_comptr.h"
30 #include "base/win/windows_version.h"
31 #include "chrome/browser/browser_process.h"
32 #include "chrome/browser/first_run/upgrade_util_win.h"
33 #include "chrome/browser/shell_integration.h"
34 #include "chrome/common/chrome_constants.h"
35 #include "chrome/common/chrome_switches.h"
36 #include "chrome/common/pref_names.h"
37 #include "chrome/installer/util/browser_distribution.h"
38 #include "chrome/installer/util/google_update_constants.h"
39 #include "chrome/installer/util/install_util.h"
40 #include "chrome/installer/util/shell_util.h"
41 #include "chrome/installer/util/util_constants.h"
42 #include "google_update/google_update_idl.h"
43 #include "ui/base/ui_base_switches.h"
45 namespace {
47 bool GetNewerChromeFile(base::FilePath* path) {
48 if (!PathService::Get(base::DIR_EXE, path))
49 return false;
50 *path = path->Append(installer::kChromeNewExe);
51 return true;
54 bool InvokeGoogleUpdateForRename() {
55 base::win::ScopedComPtr<IProcessLauncher> ipl;
56 if (!FAILED(ipl.CreateInstance(__uuidof(ProcessLauncherClass)))) {
57 ULONG_PTR phandle = NULL;
58 DWORD id = GetCurrentProcessId();
59 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
60 if (!FAILED(ipl->LaunchCmdElevated(dist->GetAppGuid().c_str(),
61 google_update::kRegRenameCmdField,
62 id,
63 &phandle))) {
64 HANDLE handle = HANDLE(phandle);
65 WaitForSingleObject(handle, INFINITE);
66 DWORD exit_code;
67 ::GetExitCodeProcess(handle, &exit_code);
68 ::CloseHandle(handle);
69 if (exit_code == installer::RENAME_SUCCESSFUL)
70 return true;
73 return false;
76 base::FilePath GetMetroRelauncherPath(const base::FilePath& chrome_exe,
77 const std::string& version_str) {
78 base::FilePath path(chrome_exe.DirName());
80 // The relauncher is ordinarily in the version directory. When running in a
81 // build tree however (where CHROME_VERSION is not set in the environment)
82 // look for it in Chrome's directory.
83 if (!version_str.empty())
84 path = path.AppendASCII(version_str);
86 return path.Append(installer::kDelegateExecuteExe);
89 } // namespace
91 namespace upgrade_util {
93 const char kRelaunchModeMetro[] = "relaunch.mode.metro";
94 const char kRelaunchModeDesktop[] = "relaunch.mode.desktop";
95 const char kRelaunchModeDefault[] = "relaunch.mode.default";
97 // TODO(shrikant): Have a map/array to quickly map enum to strings.
98 std::string RelaunchModeEnumToString(const RelaunchMode relaunch_mode) {
99 if (relaunch_mode == RELAUNCH_MODE_METRO)
100 return kRelaunchModeMetro;
102 if (relaunch_mode == RELAUNCH_MODE_DESKTOP)
103 return kRelaunchModeDesktop;
105 // For the purpose of code flow, even in case of wrong value we will
106 // return default re-launch mode.
107 return kRelaunchModeDefault;
110 RelaunchMode RelaunchModeStringToEnum(const std::string& relaunch_mode) {
111 if (relaunch_mode == kRelaunchModeMetro)
112 return RELAUNCH_MODE_METRO;
114 if (relaunch_mode == kRelaunchModeDesktop)
115 return RELAUNCH_MODE_DESKTOP;
117 // On Windows 7 if the current browser is in Chrome OS mode, then restart
118 // into Chrome OS mode.
119 if ((base::win::GetVersion() == base::win::VERSION_WIN7) &&
120 base::CommandLine::ForCurrentProcess()->HasSwitch(
121 switches::kViewerConnect) &&
122 !g_browser_process->local_state()->HasPrefPath(prefs::kRelaunchMode)) {
123 // TODO(ananta)
124 // On Windows 8, the delegate execute process looks up the previously
125 // launched mode from the registry and relaunches into that mode. We need
126 // something similar on Windows 7. For now, set the pref to ensure that
127 // we get relaunched into Chrome OS mode.
128 g_browser_process->local_state()->SetString(
129 prefs::kRelaunchMode, upgrade_util::kRelaunchModeMetro);
130 return RELAUNCH_MODE_METRO;
133 return RELAUNCH_MODE_DEFAULT;
136 bool RelaunchChromeHelper(const base::CommandLine& command_line,
137 const RelaunchMode& relaunch_mode) {
138 scoped_ptr<base::Environment> env(base::Environment::Create());
139 std::string version_str;
141 // Get the version variable and remove it from the environment.
142 if (env->GetVar(chrome::kChromeVersionEnvVar, &version_str))
143 env->UnSetVar(chrome::kChromeVersionEnvVar);
144 else
145 version_str.clear();
147 base::FilePath chrome_exe;
148 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
149 NOTREACHED();
150 return false;
153 // Explicitly make sure to relaunch chrome.exe rather than old_chrome.exe.
154 // This can happen when old_chrome.exe is launched by a user.
155 base::CommandLine chrome_exe_command_line = command_line;
156 chrome_exe_command_line.SetProgram(
157 chrome_exe.DirName().Append(installer::kChromeExe));
159 if (base::win::GetVersion() < base::win::VERSION_WIN8 &&
160 relaunch_mode != RELAUNCH_MODE_METRO &&
161 relaunch_mode != RELAUNCH_MODE_DESKTOP) {
162 return base::LaunchProcess(chrome_exe_command_line,
163 base::LaunchOptions()).IsValid();
166 // On Windows 8 we always use the delegate_execute for re-launching chrome.
167 // On Windows 7 we use delegate_execute for re-launching chrome into Windows
168 // ASH.
170 // Pass this Chrome's Start Menu shortcut path to the relauncher so it can re-
171 // activate chrome via ShellExecute which will wait until we exit. Since
172 // ShellExecute does not support handle passing to the child process we create
173 // a uniquely named mutex that we aquire and never release. So when we exit,
174 // Windows marks our mutex as abandoned and the wait is satisfied. The format
175 // of the named mutex is important. See DelegateExecuteOperation for more
176 // details.
177 base::string16 mutex_name =
178 base::StringPrintf(L"chrome.relaunch.%d", ::GetCurrentProcessId());
179 HANDLE mutex = ::CreateMutexW(NULL, TRUE, mutex_name.c_str());
180 // The |mutex| handle needs to be leaked. See comment above.
181 if (!mutex) {
182 NOTREACHED();
183 return false;
185 if (::GetLastError() == ERROR_ALREADY_EXISTS) {
186 NOTREACHED() << "Relaunch mutex already exists";
187 return false;
190 base::CommandLine relaunch_cmd(base::CommandLine::NO_PROGRAM);
191 relaunch_cmd.AppendSwitchPath(switches::kRelaunchShortcut,
192 ShellIntegration::GetStartMenuShortcut(chrome_exe));
193 relaunch_cmd.AppendSwitchNative(switches::kWaitForMutex, mutex_name);
195 if (relaunch_mode != RELAUNCH_MODE_DEFAULT) {
196 relaunch_cmd.AppendSwitch(relaunch_mode == RELAUNCH_MODE_METRO?
197 switches::kForceImmersive : switches::kForceDesktop);
200 base::string16 params(relaunch_cmd.GetCommandLineString());
201 base::string16 path(GetMetroRelauncherPath(chrome_exe, version_str).value());
203 SHELLEXECUTEINFO sei = { sizeof(sei) };
204 sei.fMask = SEE_MASK_FLAG_LOG_USAGE | SEE_MASK_NOCLOSEPROCESS;
205 sei.nShow = SW_SHOWNORMAL;
206 sei.lpFile = path.c_str();
207 sei.lpParameters = params.c_str();
209 if (!::ShellExecuteExW(&sei)) {
210 NOTREACHED() << "ShellExecute failed with " << GetLastError();
211 return false;
213 DWORD pid = ::GetProcessId(sei.hProcess);
214 CloseHandle(sei.hProcess);
215 if (!pid)
216 return false;
217 // The next call appears to be needed if we are relaunching from desktop into
218 // metro mode. The observed effect if not done is that chrome starts in metro
219 // mode but it is not given focus and it gets killed by windows after a few
220 // seconds.
221 ::AllowSetForegroundWindow(pid);
222 return true;
225 bool RelaunchChromeBrowser(const base::CommandLine& command_line) {
226 return RelaunchChromeHelper(command_line, RELAUNCH_MODE_DEFAULT);
229 bool RelaunchChromeWithMode(const base::CommandLine& command_line,
230 const RelaunchMode& relaunch_mode) {
231 return RelaunchChromeHelper(command_line, relaunch_mode);
234 bool IsUpdatePendingRestart() {
235 base::FilePath new_chrome_exe;
236 if (!GetNewerChromeFile(&new_chrome_exe))
237 return false;
238 return base::PathExists(new_chrome_exe);
241 bool SwapNewChromeExeIfPresent() {
242 base::FilePath new_chrome_exe;
243 if (!GetNewerChromeFile(&new_chrome_exe))
244 return false;
245 if (!base::PathExists(new_chrome_exe))
246 return false;
247 base::FilePath cur_chrome_exe;
248 if (!PathService::Get(base::FILE_EXE, &cur_chrome_exe))
249 return false;
251 // Open up the registry key containing current version and rename information.
252 bool user_install = InstallUtil::IsPerUserInstall(cur_chrome_exe);
253 HKEY reg_root = user_install ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE;
254 BrowserDistribution *dist = BrowserDistribution::GetDistribution();
255 base::win::RegKey key;
256 if (key.Open(reg_root, dist->GetVersionKey().c_str(),
257 KEY_QUERY_VALUE) == ERROR_SUCCESS) {
258 // First try to rename exe by launching rename command ourselves.
259 std::wstring rename_cmd;
260 if (key.ReadValue(google_update::kRegRenameCmdField,
261 &rename_cmd) == ERROR_SUCCESS) {
262 base::LaunchOptions options;
263 options.wait = true;
264 options.start_hidden = true;
265 base::Process process = base::LaunchProcess(rename_cmd, options);
266 if (process.IsValid()) {
267 DWORD exit_code;
268 ::GetExitCodeProcess(process.Handle(), &exit_code);
269 if (exit_code == installer::RENAME_SUCCESSFUL)
270 return true;
275 // Rename didn't work so try to rename by calling Google Update
276 return InvokeGoogleUpdateForRename();
279 bool IsRunningOldChrome() {
280 // This figures out the actual file name that the section containing the
281 // mapped exe refers to. This is used instead of GetModuleFileName because the
282 // .exe may have been renamed out from under us while we've been running which
283 // GetModuleFileName won't notice.
284 wchar_t mapped_file_name[MAX_PATH * 2] = {};
286 if (!::GetMappedFileName(::GetCurrentProcess(),
287 reinterpret_cast<void*>(::GetModuleHandle(NULL)),
288 mapped_file_name,
289 arraysize(mapped_file_name))) {
290 return false;
293 base::FilePath file_name(base::FilePath(mapped_file_name).BaseName());
294 return base::FilePath::CompareEqualIgnoreCase(file_name.value(),
295 installer::kChromeOldExe);
298 bool DoUpgradeTasks(const base::CommandLine& command_line) {
299 // The DelegateExecute verb handler finalizes pending in-use updates for
300 // metro mode launches, as Chrome cannot be gracefully relaunched when
301 // running in this mode.
302 if (base::win::IsMetroProcess())
303 return false;
304 if (!SwapNewChromeExeIfPresent() && !IsRunningOldChrome())
305 return false;
306 // At this point the chrome.exe has been swapped with the new one.
307 if (!RelaunchChromeBrowser(command_line)) {
308 // The re-launch fails. Feel free to panic now.
309 NOTREACHED();
311 return true;
314 } // namespace upgrade_util