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 // See the corresponding header file for description of the functions in this
8 #include "chrome/installer/util/install_util.h"
16 #include "base/command_line.h"
17 #include "base/files/file_util.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/path_service.h"
21 #include "base/process/launch.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/sys_info.h"
25 #include "base/values.h"
26 #include "base/version.h"
27 #include "base/win/metro.h"
28 #include "base/win/registry.h"
29 #include "base/win/windows_version.h"
30 #include "chrome/common/chrome_constants.h"
31 #include "chrome/common/chrome_paths.h"
32 #include "chrome/installer/util/browser_distribution.h"
33 #include "chrome/installer/util/google_update_constants.h"
34 #include "chrome/installer/util/helper.h"
35 #include "chrome/installer/util/installation_state.h"
36 #include "chrome/installer/util/l10n_string_util.h"
37 #include "chrome/installer/util/util_constants.h"
38 #include "chrome/installer/util/work_item_list.h"
40 using base::win::RegKey
;
41 using installer::ProductState
;
45 const wchar_t kStageBinaryPatching
[] = L
"binary_patching";
46 const wchar_t kStageBuilding
[] = L
"building";
47 const wchar_t kStageConfiguringAutoLaunch
[] = L
"configuring_auto_launch";
48 const wchar_t kStageCopyingPreferencesFile
[] = L
"copying_prefs";
49 const wchar_t kStageCreatingShortcuts
[] = L
"creating_shortcuts";
50 const wchar_t kStageEnsemblePatching
[] = L
"ensemble_patching";
51 const wchar_t kStageExecuting
[] = L
"executing";
52 const wchar_t kStageFinishing
[] = L
"finishing";
53 const wchar_t kStagePreconditions
[] = L
"preconditions";
54 const wchar_t kStageRefreshingPolicy
[] = L
"refreshing_policy";
55 const wchar_t kStageRegisteringChrome
[] = L
"registering_chrome";
56 const wchar_t kStageRemovingOldVersions
[] = L
"removing_old_ver";
57 const wchar_t kStageRollingback
[] = L
"rollingback";
58 const wchar_t kStageUncompressing
[] = L
"uncompressing";
59 const wchar_t kStageUnpacking
[] = L
"unpacking";
60 const wchar_t kStageUpdatingChannels
[] = L
"updating_channels";
61 const wchar_t kStageCreatingVisualManifest
[] = L
"creating_visual_manifest";
62 const wchar_t kStageDeferringToHigherVersion
[] = L
"deferring_to_higher_version";
63 const wchar_t kStageUninstallingBinaries
[] = L
"uninstalling_binaries";
64 const wchar_t kStageUninstallingChromeFrame
[] = L
"uninstalling_chrome_frame";
66 const wchar_t* const kStages
[] = {
70 kStageEnsemblePatching
,
76 kStageRefreshingPolicy
,
77 kStageUpdatingChannels
,
78 kStageCopyingPreferencesFile
,
79 kStageCreatingShortcuts
,
80 kStageRegisteringChrome
,
81 kStageRemovingOldVersions
,
83 kStageConfiguringAutoLaunch
,
84 kStageCreatingVisualManifest
,
85 kStageDeferringToHigherVersion
,
86 kStageUninstallingBinaries
,
87 kStageUninstallingChromeFrame
,
90 COMPILE_ASSERT(installer::NUM_STAGES
== arraysize(kStages
),
91 kStages_disagrees_with_Stage_comma_they_must_match_bang
);
93 // Creates a zero-sized non-decorated foreground window that doesn't appear
94 // in the taskbar. This is used as a parent window for calls to ShellExecuteEx
95 // in order for the UAC dialog to appear in the foreground and for focus
96 // to be returned to this process once the UAC task is dismissed. Returns
97 // NULL on failure, a handle to the UAC window on success.
98 HWND
CreateUACForegroundWindow() {
99 HWND foreground_window
= ::CreateWindowEx(WS_EX_TOOLWINDOW
,
102 WS_POPUP
| WS_VISIBLE
,
105 ::GetModuleHandle(NULL
),
107 if (foreground_window
) {
108 HMONITOR monitor
= ::MonitorFromWindow(foreground_window
,
109 MONITOR_DEFAULTTONEAREST
);
111 MONITORINFO mi
= {0};
112 mi
.cbSize
= sizeof(mi
);
113 ::GetMonitorInfo(monitor
, &mi
);
114 RECT screen_rect
= mi
.rcWork
;
115 int x_offset
= (screen_rect
.right
- screen_rect
.left
) / 2;
116 int y_offset
= (screen_rect
.bottom
- screen_rect
.top
) / 2;
117 ::MoveWindow(foreground_window
,
118 screen_rect
.left
+ x_offset
,
119 screen_rect
.top
+ y_offset
,
122 NOTREACHED() << "Unable to get default monitor";
124 ::SetForegroundWindow(foreground_window
);
126 return foreground_window
;
131 base::string16
InstallUtil::GetActiveSetupPath(BrowserDistribution
* dist
) {
132 static const wchar_t kInstalledComponentsPath
[] =
133 L
"Software\\Microsoft\\Active Setup\\Installed Components\\";
134 return kInstalledComponentsPath
+ dist
->GetActiveSetupGuid();
137 void InstallUtil::TriggerActiveSetupCommand() {
138 base::string16
active_setup_reg(
139 GetActiveSetupPath(BrowserDistribution::GetDistribution()));
140 base::win::RegKey
active_setup_key(
141 HKEY_LOCAL_MACHINE
, active_setup_reg
.c_str(), KEY_QUERY_VALUE
);
142 base::string16 cmd_str
;
143 LONG read_status
= active_setup_key
.ReadValue(L
"StubPath", &cmd_str
);
144 if (read_status
!= ERROR_SUCCESS
) {
145 LOG(ERROR
) << active_setup_reg
<< ", " << read_status
;
146 // This should never fail if Chrome is registered at system-level, but if it
147 // does there is not much else to be done.
151 CommandLine
cmd(CommandLine::FromString(cmd_str
));
152 // Force creation of shortcuts as the First Run beacon might land between now
153 // and the time setup.exe checks for it.
154 cmd
.AppendSwitch(installer::switches::kForceConfigureUserSettings
);
156 base::LaunchOptions launch_options
;
157 if (base::win::IsMetroProcess())
158 launch_options
.force_breakaway_from_job_
= true;
159 base::Process process
=
160 base::LaunchProcess(cmd
.GetCommandLineString(), launch_options
);
161 if (!process
.IsValid())
162 PLOG(ERROR
) << cmd
.GetCommandLineString();
165 bool InstallUtil::ExecuteExeAsAdmin(const CommandLine
& cmd
, DWORD
* exit_code
) {
166 base::FilePath::StringType
program(cmd
.GetProgram().value());
167 DCHECK(!program
.empty());
168 DCHECK_NE(program
[0], L
'\"');
170 CommandLine::StringType
params(cmd
.GetCommandLineString());
171 if (params
[0] == '"') {
172 DCHECK_EQ('"', params
[program
.length() + 1]);
173 DCHECK_EQ(program
, params
.substr(1, program
.length()));
174 params
= params
.substr(program
.length() + 2);
176 DCHECK_EQ(program
, params
.substr(0, program
.length()));
177 params
= params
.substr(program
.length());
180 base::TrimWhitespace(params
, base::TRIM_ALL
, ¶ms
);
182 HWND uac_foreground_window
= CreateUACForegroundWindow();
184 SHELLEXECUTEINFO info
= {0};
185 info
.cbSize
= sizeof(SHELLEXECUTEINFO
);
186 info
.fMask
= SEE_MASK_NOCLOSEPROCESS
;
187 info
.hwnd
= uac_foreground_window
;
188 info
.lpVerb
= L
"runas";
189 info
.lpFile
= program
.c_str();
190 info
.lpParameters
= params
.c_str();
191 info
.nShow
= SW_SHOW
;
193 bool success
= false;
194 if (::ShellExecuteEx(&info
) == TRUE
) {
195 ::WaitForSingleObject(info
.hProcess
, INFINITE
);
197 if (::GetExitCodeProcess(info
.hProcess
, &ret_val
)) {
200 *exit_code
= ret_val
;
204 if (uac_foreground_window
) {
205 DestroyWindow(uac_foreground_window
);
211 CommandLine
InstallUtil::GetChromeUninstallCmd(
212 bool system_install
, BrowserDistribution::Type distribution_type
) {
214 if (state
.Initialize(system_install
, distribution_type
)) {
215 return state
.uninstall_command();
217 return CommandLine(CommandLine::NO_PROGRAM
);
220 void InstallUtil::GetChromeVersion(BrowserDistribution
* dist
,
225 HKEY reg_root
= (system_install
) ? HKEY_LOCAL_MACHINE
: HKEY_CURRENT_USER
;
226 LONG result
= key
.Open(reg_root
,
227 dist
->GetVersionKey().c_str(),
228 KEY_QUERY_VALUE
| KEY_WOW64_32KEY
);
230 base::string16 version_str
;
231 if (result
== ERROR_SUCCESS
)
232 result
= key
.ReadValue(google_update::kRegVersionField
, &version_str
);
234 *version
= Version();
235 if (result
== ERROR_SUCCESS
&& !version_str
.empty()) {
236 VLOG(1) << "Existing " << dist
->GetDisplayName() << " version found "
238 *version
= Version(base::UTF16ToASCII(version_str
));
240 DCHECK_EQ(ERROR_FILE_NOT_FOUND
, result
);
241 VLOG(1) << "No existing " << dist
->GetDisplayName()
242 << " install found.";
246 void InstallUtil::GetCriticalUpdateVersion(BrowserDistribution
* dist
,
251 HKEY reg_root
= (system_install
) ? HKEY_LOCAL_MACHINE
: HKEY_CURRENT_USER
;
252 LONG result
= key
.Open(reg_root
,
253 dist
->GetVersionKey().c_str(),
254 KEY_QUERY_VALUE
| KEY_WOW64_32KEY
);
256 base::string16 version_str
;
257 if (result
== ERROR_SUCCESS
)
258 result
= key
.ReadValue(google_update::kRegCriticalVersionField
,
261 *version
= Version();
262 if (result
== ERROR_SUCCESS
&& !version_str
.empty()) {
263 VLOG(1) << "Critical Update version for " << dist
->GetDisplayName()
264 << " found " << version_str
;
265 *version
= Version(base::UTF16ToASCII(version_str
));
267 DCHECK_EQ(ERROR_FILE_NOT_FOUND
, result
);
268 VLOG(1) << "No existing " << dist
->GetDisplayName()
269 << " install found.";
273 bool InstallUtil::IsOSSupported() {
274 // We do not support Win2K or older, or XP without service pack 2.
275 VLOG(1) << base::SysInfo::OperatingSystemName() << ' '
276 << base::SysInfo::OperatingSystemVersion();
277 base::win::Version version
= base::win::GetVersion();
278 return (version
> base::win::VERSION_XP
) ||
279 ((version
== base::win::VERSION_XP
) &&
280 (base::win::OSInfo::GetInstance()->service_pack().major
>= 2));
283 void InstallUtil::AddInstallerResultItems(
285 const base::string16
& state_key
,
286 installer::InstallStatus status
,
287 int string_resource_id
,
288 const base::string16
* const launch_cmd
,
289 WorkItemList
* install_list
) {
290 DCHECK(install_list
);
291 const HKEY root
= system_install
? HKEY_LOCAL_MACHINE
: HKEY_CURRENT_USER
;
292 DWORD installer_result
= (GetInstallReturnCode(status
) == 0) ? 0 : 1;
293 install_list
->AddCreateRegKeyWorkItem(root
, state_key
, KEY_WOW64_32KEY
);
294 install_list
->AddSetRegValueWorkItem(root
,
297 installer::kInstallerResult
,
300 install_list
->AddSetRegValueWorkItem(root
,
303 installer::kInstallerError
,
304 static_cast<DWORD
>(status
),
306 if (string_resource_id
!= 0) {
307 base::string16 msg
= installer::GetLocalizedString(string_resource_id
);
308 install_list
->AddSetRegValueWorkItem(root
,
311 installer::kInstallerResultUIString
,
315 if (launch_cmd
!= NULL
&& !launch_cmd
->empty()) {
316 install_list
->AddSetRegValueWorkItem(
320 installer::kInstallerSuccessLaunchCmdLine
,
326 void InstallUtil::UpdateInstallerStage(bool system_install
,
327 const base::string16
& state_key_path
,
328 installer::InstallerStage stage
) {
329 DCHECK_LE(static_cast<installer::InstallerStage
>(0), stage
);
330 DCHECK_GT(installer::NUM_STAGES
, stage
);
331 const HKEY root
= system_install
? HKEY_LOCAL_MACHINE
: HKEY_CURRENT_USER
;
335 state_key_path
.c_str(),
336 KEY_QUERY_VALUE
| KEY_SET_VALUE
| KEY_WOW64_32KEY
);
337 if (result
== ERROR_SUCCESS
) {
338 if (stage
== installer::NO_STAGE
) {
339 result
= state_key
.DeleteValue(installer::kInstallerExtraCode1
);
340 LOG_IF(ERROR
, result
!= ERROR_SUCCESS
&& result
!= ERROR_FILE_NOT_FOUND
)
341 << "Failed deleting installer stage from " << state_key_path
342 << "; result: " << result
;
344 const DWORD extra_code_1
= static_cast<DWORD
>(stage
);
345 result
= state_key
.WriteValue(installer::kInstallerExtraCode1
,
347 LOG_IF(ERROR
, result
!= ERROR_SUCCESS
)
348 << "Failed writing installer stage to " << state_key_path
349 << "; result: " << result
;
351 // TODO(grt): Remove code below here once we're convinced that our use of
352 // Google Update's new InstallerExtraCode1 value is good.
353 installer::ChannelInfo channel_info
;
354 // This will return false if the "ap" value isn't present, which is fine.
355 channel_info
.Initialize(state_key
);
356 if (channel_info
.SetStage(kStages
[stage
]) &&
357 !channel_info
.Write(&state_key
)) {
358 LOG(ERROR
) << "Failed writing installer stage to " << state_key_path
;
361 LOG(ERROR
) << "Failed opening " << state_key_path
362 << " to update installer stage; result: " << result
;
366 bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path
) {
367 const int kProgramFilesKey
=
369 // TODO(wfh): Revise this when Chrome is/can be installed in the 64-bit
370 // program files directory.
371 base::DIR_PROGRAM_FILESX86
;
373 base::DIR_PROGRAM_FILES
;
375 base::FilePath program_files_path
;
376 if (!PathService::Get(kProgramFilesKey
, &program_files_path
)) {
380 return !StartsWith(exe_path
, program_files_path
.value().c_str(), false);
383 bool InstallUtil::IsMultiInstall(BrowserDistribution
* dist
,
384 bool system_install
) {
387 return state
.Initialize(system_install
, dist
) && state
.is_multi_install();
390 bool CheckIsChromeSxSProcess() {
391 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
394 if (command_line
->HasSwitch(installer::switches::kChromeSxS
))
397 // Also return true if we are running from Chrome SxS installed path.
398 base::FilePath exe_dir
;
399 PathService::Get(base::DIR_EXE
, &exe_dir
);
400 base::string16
chrome_sxs_dir(installer::kGoogleChromeInstallSubDir2
);
401 chrome_sxs_dir
.append(installer::kSxSSuffix
);
403 // This is SxS if current EXE is in or under (possibly multiple levels under)
404 // |chrome_sxs_dir|\|installer::kInstallBinaryDir|
405 std::vector
<base::FilePath::StringType
> components
;
406 exe_dir
.GetComponents(&components
);
407 // We need at least 1 element in the array for the behavior of the following
408 // loop to be defined. This should always be true, since we're splitting the
409 // path to our executable and one of the components will be the drive letter.
410 DCHECK(!components
.empty());
411 typedef std::vector
<base::FilePath::StringType
>::const_reverse_iterator
413 for (ComponentsIterator current
= components
.rbegin(), parent
= current
+ 1;
414 parent
!= components
.rend(); current
= parent
++) {
415 if (base::FilePath::CompareEqualIgnoreCase(
416 *current
, installer::kInstallBinaryDir
) &&
417 base::FilePath::CompareEqualIgnoreCase(*parent
, chrome_sxs_dir
)) {
425 bool InstallUtil::IsChromeSxSProcess() {
426 static bool sxs
= CheckIsChromeSxSProcess();
431 bool InstallUtil::IsFirstRunSentinelPresent() {
432 // TODO(msw): Consolidate with first_run::internal::IsFirstRunSentinelPresent.
433 base::FilePath user_data_dir
;
434 return !PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
) ||
435 base::PathExists(user_data_dir
.Append(chrome::kFirstRunSentinel
));
439 bool InstallUtil::GetEULASentinelFilePath(base::FilePath
* path
) {
440 base::FilePath user_data_dir
;
441 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
443 *path
= user_data_dir
.Append(installer::kEULASentinelFile
);
447 // This method tries to delete a registry key and logs an error message
448 // in case of failure. It returns true if deletion is successful (or the key did
449 // not exist), otherwise false.
450 bool InstallUtil::DeleteRegistryKey(HKEY root_key
,
451 const base::string16
& key_path
,
452 REGSAM wow64_access
) {
453 VLOG(1) << "Deleting registry key " << key_path
;
455 LONG result
= target_key
.Open(root_key
, key_path
.c_str(),
456 KEY_READ
| KEY_WRITE
| wow64_access
);
458 if (result
== ERROR_FILE_NOT_FOUND
)
461 if (result
== ERROR_SUCCESS
)
462 result
= target_key
.DeleteKey(L
"");
464 if (result
!= ERROR_SUCCESS
) {
465 LOG(ERROR
) << "Failed to delete registry key: " << key_path
466 << " error: " << result
;
472 // This method tries to delete a registry value and logs an error message
473 // in case of failure. It returns true if deletion is successful (or the key did
474 // not exist), otherwise false.
475 bool InstallUtil::DeleteRegistryValue(HKEY reg_root
,
476 const base::string16
& key_path
,
478 const base::string16
& value_name
) {
480 LONG result
= key
.Open(reg_root
, key_path
.c_str(),
481 KEY_SET_VALUE
| wow64_access
);
482 if (result
== ERROR_SUCCESS
)
483 result
= key
.DeleteValue(value_name
.c_str());
484 if (result
!= ERROR_SUCCESS
&& result
!= ERROR_FILE_NOT_FOUND
) {
485 LOG(ERROR
) << "Failed to delete registry value: " << value_name
486 << " error: " << result
;
493 InstallUtil::ConditionalDeleteResult
InstallUtil::DeleteRegistryKeyIf(
495 const base::string16
& key_to_delete_path
,
496 const base::string16
& key_to_test_path
,
497 const REGSAM wow64_access
,
498 const wchar_t* value_name
,
499 const RegistryValuePredicate
& predicate
) {
501 ConditionalDeleteResult delete_result
= NOT_FOUND
;
503 base::string16 actual_value
;
504 if (key
.Open(root_key
, key_to_test_path
.c_str(),
505 KEY_QUERY_VALUE
| wow64_access
) == ERROR_SUCCESS
&&
506 key
.ReadValue(value_name
, &actual_value
) == ERROR_SUCCESS
&&
507 predicate
.Evaluate(actual_value
)) {
509 delete_result
= DeleteRegistryKey(root_key
,
512 ? DELETED
: DELETE_FAILED
;
514 return delete_result
;
518 InstallUtil::ConditionalDeleteResult
InstallUtil::DeleteRegistryValueIf(
520 const wchar_t* key_path
,
522 const wchar_t* value_name
,
523 const RegistryValuePredicate
& predicate
) {
526 ConditionalDeleteResult delete_result
= NOT_FOUND
;
528 base::string16 actual_value
;
529 if (key
.Open(root_key
, key_path
,
530 KEY_QUERY_VALUE
| KEY_SET_VALUE
| wow64_access
)
532 key
.ReadValue(value_name
, &actual_value
) == ERROR_SUCCESS
&&
533 predicate
.Evaluate(actual_value
)) {
534 LONG result
= key
.DeleteValue(value_name
);
535 if (result
!= ERROR_SUCCESS
) {
536 LOG(ERROR
) << "Failed to delete registry value: "
537 << (value_name
? value_name
: L
"(Default)")
538 << " error: " << result
;
539 delete_result
= DELETE_FAILED
;
541 delete_result
= DELETED
;
543 return delete_result
;
546 bool InstallUtil::ValueEquals::Evaluate(const base::string16
& value
) const {
547 return value
== value_to_match_
;
551 int InstallUtil::GetInstallReturnCode(installer::InstallStatus status
) {
553 case installer::FIRST_INSTALL_SUCCESS
:
554 case installer::INSTALL_REPAIRED
:
555 case installer::NEW_VERSION_UPDATED
:
556 case installer::IN_USE_UPDATED
:
557 case installer::UNUSED_BINARIES_UNINSTALLED
:
565 void InstallUtil::MakeUninstallCommand(const base::string16
& program
,
566 const base::string16
& arguments
,
567 CommandLine
* command_line
) {
568 *command_line
= CommandLine::FromString(L
"\"" + program
+ L
"\" " + arguments
);
572 base::string16
InstallUtil::GetCurrentDate() {
573 static const wchar_t kDateFormat
[] = L
"yyyyMMdd";
574 wchar_t date_str
[arraysize(kDateFormat
)] = {0};
575 int len
= GetDateFormatW(LOCALE_INVARIANT
, 0, NULL
, kDateFormat
,
576 date_str
, arraysize(date_str
));
578 --len
; // Subtract terminating \0.
580 PLOG(DFATAL
) << "GetDateFormat";
583 return base::string16(date_str
, len
);
586 // Open |path| with minimal access to obtain information about it, returning
587 // true and populating |file| on success.
589 bool InstallUtil::ProgramCompare::OpenForInfo(const base::FilePath
& path
,
592 file
->Initialize(path
, base::File::FLAG_OPEN
);
593 return file
->IsValid();
596 // Populate |info| for |file|, returning true on success.
598 bool InstallUtil::ProgramCompare::GetInfo(const base::File
& file
,
599 BY_HANDLE_FILE_INFORMATION
* info
) {
600 DCHECK(file
.IsValid());
601 return GetFileInformationByHandle(file
.GetPlatformFile(), info
) != 0;
604 InstallUtil::ProgramCompare::ProgramCompare(const base::FilePath
& path_to_match
)
605 : path_to_match_(path_to_match
),
607 DCHECK(!path_to_match_
.empty());
608 if (!OpenForInfo(path_to_match_
, &file_
)) {
609 PLOG(WARNING
) << "Failed opening " << path_to_match_
.value()
610 << "; falling back to path string comparisons.";
611 } else if (!GetInfo(file_
, &file_info_
)) {
612 PLOG(WARNING
) << "Failed getting information for "
613 << path_to_match_
.value()
614 << "; falling back to path string comparisons.";
619 InstallUtil::ProgramCompare::~ProgramCompare() {
622 bool InstallUtil::ProgramCompare::Evaluate(const base::string16
& value
) const {
623 // Suss out the exe portion of the value, which is expected to be a command
624 // line kinda (or exactly) like:
625 // "c:\foo\bar\chrome.exe" -- "%1"
626 base::FilePath
program(CommandLine::FromString(value
).GetProgram());
627 if (program
.empty()) {
628 LOG(WARNING
) << "Failed to parse an executable name from command line: \""
633 return EvaluatePath(program
);
636 bool InstallUtil::ProgramCompare::EvaluatePath(
637 const base::FilePath
& path
) const {
638 // Try the simple thing first: do the paths happen to match?
639 if (base::FilePath::CompareEqualIgnoreCase(path_to_match_
.value(),
643 // If the paths don't match and we couldn't open the expected file, we've done
645 if (!file_
.IsValid())
648 // Open the program and see if it references the expected file.
650 BY_HANDLE_FILE_INFORMATION info
= {};
652 return (OpenForInfo(path
, &file
) &&
653 GetInfo(file
, &info
) &&
654 info
.dwVolumeSerialNumber
== file_info_
.dwVolumeSerialNumber
&&
655 info
.nFileIndexHigh
== file_info_
.nFileIndexHigh
&&
656 info
.nFileIndexLow
== file_info_
.nFileIndexLow
);