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 // This file declares util functions for setup project.
7 #include "chrome/installer/setup/setup_util.h"
11 #include "base/command_line.h"
13 #include "base/files/file_enumerator.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/logging.h"
17 #include "base/process/kill.h"
18 #include "base/process/launch.h"
19 #include "base/process/process_handle.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/version.h"
23 #include "base/win/registry.h"
24 #include "base/win/windows_version.h"
25 #include "chrome/installer/setup/setup_constants.h"
26 #include "chrome/installer/util/app_registration_data.h"
27 #include "chrome/installer/util/copy_tree_work_item.h"
28 #include "chrome/installer/util/google_update_constants.h"
29 #include "chrome/installer/util/installation_state.h"
30 #include "chrome/installer/util/installer_state.h"
31 #include "chrome/installer/util/master_preferences.h"
32 #include "chrome/installer/util/util_constants.h"
33 #include "chrome/installer/util/work_item.h"
34 #include "courgette/courgette.h"
35 #include "courgette/third_party/bsdiff.h"
36 #include "third_party/bspatch/mbspatch.h"
42 // Launches |setup_exe| with |command_line|, save --install-archive and its
43 // value if present. Returns false if the process failed to launch. Otherwise,
44 // waits indefinitely for it to exit and populates |exit_code| as expected. On
45 // the off chance that waiting itself fails, |exit_code| is set to
46 // WAIT_FOR_EXISTING_FAILED.
47 bool LaunchAndWaitForExistingInstall(const base::FilePath
& setup_exe
,
48 const base::CommandLine
& command_line
,
51 base::CommandLine
new_cl(setup_exe
);
53 // Copy over all switches but --install-archive.
54 base::CommandLine::SwitchMap
switches(command_line
.GetSwitches());
55 switches
.erase(switches::kInstallArchive
);
56 for (base::CommandLine::SwitchMap::const_iterator i
= switches
.begin();
57 i
!= switches
.end(); ++i
) {
58 if (i
->second
.empty())
59 new_cl
.AppendSwitch(i
->first
);
61 new_cl
.AppendSwitchNative(i
->first
, i
->second
);
64 // Copy over all arguments.
65 base::CommandLine::StringVector
args(command_line
.GetArgs());
66 for (base::CommandLine::StringVector::const_iterator i
= args
.begin();
67 i
!= args
.end(); ++i
) {
68 new_cl
.AppendArgNative(*i
);
71 // Launch the process and wait for it to exit.
72 VLOG(1) << "Launching existing installer with command: "
73 << new_cl
.GetCommandLineString();
74 base::Process process
= base::LaunchProcess(new_cl
, base::LaunchOptions());
75 if (!process
.IsValid()) {
76 PLOG(ERROR
) << "Failed to launch existing installer with command: "
77 << new_cl
.GetCommandLineString();
80 if (!process
.WaitForExit(exit_code
)) {
81 PLOG(DFATAL
) << "Failed to get exit code from existing installer";
82 *exit_code
= WAIT_FOR_EXISTING_FAILED
;
84 VLOG(1) << "Existing installer returned exit code " << *exit_code
;
89 // Returns true if product |type| cam be meaningfully installed without the
90 // --multi-install flag.
91 bool SupportsSingleInstall(BrowserDistribution::Type type
) {
92 return (type
== BrowserDistribution::CHROME_BROWSER
||
93 type
== BrowserDistribution::CHROME_FRAME
);
98 int CourgettePatchFiles(const base::FilePath
& src
,
99 const base::FilePath
& patch
,
100 const base::FilePath
& dest
) {
101 VLOG(1) << "Applying Courgette patch " << patch
.value()
102 << " to file " << src
.value()
103 << " and generating file " << dest
.value();
105 if (src
.empty() || patch
.empty() || dest
.empty())
106 return installer::PATCH_INVALID_ARGUMENTS
;
108 const courgette::Status patch_status
=
109 courgette::ApplyEnsemblePatch(src
.value().c_str(),
110 patch
.value().c_str(),
111 dest
.value().c_str());
112 const int exit_code
= (patch_status
!= courgette::C_OK
) ?
113 static_cast<int>(patch_status
) + kCourgetteErrorOffset
: 0;
115 LOG_IF(ERROR
, exit_code
)
116 << "Failed to apply Courgette patch " << patch
.value()
117 << " to file " << src
.value() << " and generating file " << dest
.value()
118 << ". err=" << exit_code
;
123 int BsdiffPatchFiles(const base::FilePath
& src
,
124 const base::FilePath
& patch
,
125 const base::FilePath
& dest
) {
126 VLOG(1) << "Applying bsdiff patch " << patch
.value()
127 << " to file " << src
.value()
128 << " and generating file " << dest
.value();
130 if (src
.empty() || patch
.empty() || dest
.empty())
131 return installer::PATCH_INVALID_ARGUMENTS
;
133 const int patch_status
= courgette::ApplyBinaryPatch(src
, patch
, dest
);
134 const int exit_code
= patch_status
!= OK
?
135 patch_status
+ kBsdiffErrorOffset
: 0;
137 LOG_IF(ERROR
, exit_code
)
138 << "Failed to apply bsdiff patch " << patch
.value()
139 << " to file " << src
.value() << " and generating file " << dest
.value()
140 << ". err=" << exit_code
;
145 Version
* GetMaxVersionFromArchiveDir(const base::FilePath
& chrome_path
) {
146 VLOG(1) << "Looking for Chrome version folder under " << chrome_path
.value();
147 base::FileEnumerator
version_enum(chrome_path
, false,
148 base::FileEnumerator::DIRECTORIES
);
149 // TODO(tommi): The version directory really should match the version of
150 // setup.exe. To begin with, we should at least DCHECK that that's true.
152 scoped_ptr
<Version
> max_version(new Version("0.0.0.0"));
153 bool version_found
= false;
155 while (!version_enum
.Next().empty()) {
156 base::FileEnumerator::FileInfo find_data
= version_enum
.GetInfo();
157 VLOG(1) << "directory found: " << find_data
.GetName().value();
159 scoped_ptr
<Version
> found_version(
160 new Version(base::UTF16ToASCII(find_data
.GetName().value())));
161 if (found_version
->IsValid() &&
162 found_version
->CompareTo(*max_version
.get()) > 0) {
163 max_version
.reset(found_version
.release());
164 version_found
= true;
168 return (version_found
? max_version
.release() : NULL
);
171 base::FilePath
FindArchiveToPatch(const InstallationState
& original_state
,
172 const InstallerState
& installer_state
) {
173 // Check based on the version number advertised to Google Update, since that
174 // is the value used to select a specific differential update. If an archive
175 // can't be found using that, fallback to using the newest version present.
176 base::FilePath patch_source
;
177 const ProductState
* product
=
178 original_state
.GetProductState(installer_state
.system_install(),
179 installer_state
.state_type());
181 patch_source
= installer_state
.GetInstallerDirectory(product
->version())
182 .Append(installer::kChromeArchive
);
183 if (base::PathExists(patch_source
))
186 scoped_ptr
<Version
> version(
187 installer::GetMaxVersionFromArchiveDir(installer_state
.target_path()));
189 patch_source
= installer_state
.GetInstallerDirectory(*version
)
190 .Append(installer::kChromeArchive
);
191 if (base::PathExists(patch_source
))
194 return base::FilePath();
197 bool DeleteFileFromTempProcess(const base::FilePath
& path
,
198 uint32 delay_before_delete_ms
) {
199 static const wchar_t kRunDll32Path
[] =
200 L
"%SystemRoot%\\System32\\rundll32.exe";
201 wchar_t rundll32
[MAX_PATH
];
203 ExpandEnvironmentStrings(kRunDll32Path
, rundll32
, arraysize(rundll32
));
204 if (!size
|| size
>= MAX_PATH
)
207 STARTUPINFO startup
= { sizeof(STARTUPINFO
) };
208 PROCESS_INFORMATION pi
= {0};
209 BOOL ok
= ::CreateProcess(NULL
, rundll32
, NULL
, NULL
, FALSE
, CREATE_SUSPENDED
,
210 NULL
, NULL
, &startup
, &pi
);
212 // We use the main thread of the new process to run:
213 // Sleep(delay_before_delete_ms);
216 // This runs before the main routine of the process runs, so it doesn't
217 // matter much which executable we choose except that we don't want to
218 // use e.g. a console app that causes a window to be created.
219 size
= (path
.value().length() + 1) * sizeof(path
.value()[0]);
220 void* mem
= ::VirtualAllocEx(pi
.hProcess
, NULL
, size
, MEM_COMMIT
,
224 ::WriteProcessMemory(
225 pi
.hProcess
, mem
, path
.value().c_str(),
226 (path
.value().size() + 1) * sizeof(path
.value()[0]), &written
);
227 HMODULE kernel32
= ::GetModuleHandle(L
"kernel32.dll");
228 PAPCFUNC sleep
= reinterpret_cast<PAPCFUNC
>(
229 ::GetProcAddress(kernel32
, "Sleep"));
230 PAPCFUNC delete_file
= reinterpret_cast<PAPCFUNC
>(
231 ::GetProcAddress(kernel32
, "DeleteFileW"));
232 PAPCFUNC exit_process
= reinterpret_cast<PAPCFUNC
>(
233 ::GetProcAddress(kernel32
, "ExitProcess"));
234 if (!sleep
|| !delete_file
|| !exit_process
) {
238 ::QueueUserAPC(sleep
, pi
.hThread
, delay_before_delete_ms
);
239 ::QueueUserAPC(delete_file
, pi
.hThread
,
240 reinterpret_cast<ULONG_PTR
>(mem
));
241 ::QueueUserAPC(exit_process
, pi
.hThread
, 0);
242 ::ResumeThread(pi
.hThread
);
245 PLOG(ERROR
) << "VirtualAllocEx";
246 ::TerminateProcess(pi
.hProcess
, ~static_cast<UINT
>(0));
248 ::CloseHandle(pi
.hThread
);
249 ::CloseHandle(pi
.hProcess
);
255 bool GetExistingHigherInstaller(
256 const InstallationState
& original_state
,
258 const Version
& installer_version
,
259 base::FilePath
* setup_exe
) {
261 bool trying_single_browser
= false;
262 const ProductState
* existing_state
=
263 original_state
.GetProductState(system_install
,
264 BrowserDistribution::CHROME_BINARIES
);
265 if (!existing_state
) {
266 // The binaries aren't installed, but perhaps a single-install Chrome is.
267 trying_single_browser
= true;
269 original_state
.GetProductState(system_install
,
270 BrowserDistribution::CHROME_BROWSER
);
273 if (!existing_state
||
274 existing_state
->version().CompareTo(installer_version
) <= 0) {
278 *setup_exe
= existing_state
->GetSetupPath();
280 VLOG_IF(1, !setup_exe
->empty()) << "Found a higher version of "
281 << (trying_single_browser
? "single-install Chrome."
282 : "multi-install Chrome binaries.");
284 return !setup_exe
->empty();
287 bool DeferToExistingInstall(const base::FilePath
& setup_exe
,
288 const base::CommandLine
& command_line
,
289 const InstallerState
& installer_state
,
290 const base::FilePath
& temp_path
,
291 InstallStatus
* install_status
) {
292 // Copy a master_preferences file if there is one.
293 base::FilePath
prefs_source_path(command_line
.GetSwitchValueNative(
294 switches::kInstallerData
));
295 base::FilePath
prefs_dest_path(installer_state
.target_path().AppendASCII(
296 kDefaultMasterPrefs
));
297 scoped_ptr
<WorkItem
> copy_prefs(WorkItem::CreateCopyTreeWorkItem(
298 prefs_source_path
, prefs_dest_path
, temp_path
, WorkItem::ALWAYS
,
300 // There's nothing to rollback if the copy fails, so punt if so.
301 if (!copy_prefs
->Do())
305 if (!LaunchAndWaitForExistingInstall(setup_exe
, command_line
, &exit_code
)) {
307 copy_prefs
->Rollback();
310 *install_status
= static_cast<InstallStatus
>(exit_code
);
314 // There are 4 disjoint cases => return values {false,true}:
315 // (1) Product is being uninstalled => false.
316 // (2) Product is being installed => true.
317 // (3) Current operation ignores product, product is absent => false.
318 // (4) Current operation ignores product, product is present => true.
319 bool WillProductBePresentAfterSetup(
320 const installer::InstallerState
& installer_state
,
321 const installer::InstallationState
& machine_state
,
322 BrowserDistribution::Type type
) {
323 DCHECK(SupportsSingleInstall(type
) || installer_state
.is_multi_install());
325 const ProductState
* product_state
=
326 machine_state
.GetProductState(installer_state
.system_install(), type
);
328 // Determine if the product is present prior to the current operation.
329 bool is_present
= (product_state
!= NULL
);
330 bool is_uninstall
= installer_state
.operation() == InstallerState::UNINSTALL
;
332 // Determine if current operation affects the product.
333 const Product
* product
= installer_state
.FindProduct(type
);
334 bool is_affected
= (product
!= NULL
);
336 // Decide among {(1),(2),(3),(4)}.
337 return is_affected
? !is_uninstall
: is_present
;
340 bool AdjustProcessPriority() {
341 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
342 DWORD priority_class
= ::GetPriorityClass(::GetCurrentProcess());
343 if (priority_class
== 0) {
344 PLOG(WARNING
) << "Failed to get the process's priority class.";
345 } else if (priority_class
== BELOW_NORMAL_PRIORITY_CLASS
||
346 priority_class
== IDLE_PRIORITY_CLASS
) {
347 BOOL result
= ::SetPriorityClass(::GetCurrentProcess(),
348 PROCESS_MODE_BACKGROUND_BEGIN
);
349 PLOG_IF(WARNING
, !result
) << "Failed to enter background mode.";
356 void MigrateGoogleUpdateStateMultiToSingle(
358 BrowserDistribution::Type to_migrate
,
359 const installer::InstallationState
& machine_state
) {
360 const HKEY root
= system_level
? HKEY_LOCAL_MACHINE
: HKEY_CURRENT_USER
;
361 const ProductState
* product
= NULL
;
362 BrowserDistribution
* dist
= NULL
;
363 LONG result
= ERROR_SUCCESS
;
364 base::win::RegKey state_key
;
366 Product
product_to_migrate(
367 BrowserDistribution::GetSpecificDistribution(to_migrate
));
369 // Copy usagestats from the binaries to the product's ClientState key.
370 product
= machine_state
.GetProductState(system_level
,
371 BrowserDistribution::CHROME_BINARIES
);
372 DWORD usagestats
= 0;
373 if (product
&& product
->GetUsageStats(&usagestats
)) {
374 dist
= product_to_migrate
.distribution();
375 result
= state_key
.Open(root
, dist
->GetStateKey().c_str(),
377 if (result
!= ERROR_SUCCESS
) {
378 LOG(ERROR
) << "Failed opening ClientState key for "
379 << dist
->GetDisplayName() << " to migrate usagestats.";
381 state_key
.WriteValue(google_update::kRegUsageStatsField
, usagestats
);
385 // Remove the migrating product from the "ap" value of other multi-install
387 for (int i
= 0; i
< BrowserDistribution::NUM_TYPES
; ++i
) {
388 BrowserDistribution::Type type
=
389 static_cast<BrowserDistribution::Type
>(i
);
390 if (type
== to_migrate
)
392 product
= machine_state
.GetProductState(system_level
, type
);
393 if (product
&& product
->is_multi_install()) {
394 installer::ChannelInfo channel_info
;
395 dist
= BrowserDistribution::GetSpecificDistribution(type
);
396 result
= state_key
.Open(root
, dist
->GetStateKey().c_str(),
397 KEY_QUERY_VALUE
| KEY_SET_VALUE
);
398 if (result
== ERROR_SUCCESS
&&
399 channel_info
.Initialize(state_key
) &&
400 product_to_migrate
.SetChannelFlags(false, &channel_info
)) {
401 VLOG(1) << "Moving " << dist
->GetDisplayName()
402 << " to channel: " << channel_info
.value();
403 channel_info
.Write(&state_key
);
408 // Remove -multi, all product modifiers, and everything else but the channel
409 // name from the "ap" value of the product to migrate.
410 dist
= product_to_migrate
.distribution();
411 result
= state_key
.Open(root
, dist
->GetStateKey().c_str(),
412 KEY_QUERY_VALUE
| KEY_SET_VALUE
);
413 if (result
== ERROR_SUCCESS
) {
414 installer::ChannelInfo channel_info
;
415 if (!channel_info
.Initialize(state_key
)) {
416 LOG(ERROR
) << "Failed reading " << dist
->GetDisplayName()
418 } else if (channel_info
.RemoveAllModifiersAndSuffixes()) {
419 VLOG(1) << "Moving " << dist
->GetDisplayName()
420 << " to channel: " << channel_info
.value();
421 channel_info
.Write(&state_key
);
426 bool IsUninstallSuccess(InstallStatus install_status
) {
427 // The following status values represent failed uninstalls:
428 // 15: CHROME_NOT_INSTALLED
429 // 20: UNINSTALL_FAILED
430 // 21: UNINSTALL_CANCELLED
431 return (install_status
== UNINSTALL_SUCCESSFUL
||
432 install_status
== UNINSTALL_REQUIRES_REBOOT
);
435 bool ContainsUnsupportedSwitch(const base::CommandLine
& cmd_line
) {
436 static const char* const kLegacySwitches
[] = {
437 // Chrome Frame ready-mode.
440 "ready-mode-temp-opt-out",
441 "ready-mode-end-temp-opt-out",
442 // Chrome Frame quick-enable.
444 // Installation of Chrome Frame.
446 "migrate-chrome-frame",
447 // Stand-alone App Launcher.
451 for (size_t i
= 0; i
< arraysize(kLegacySwitches
); ++i
) {
452 if (cmd_line
.HasSwitch(kLegacySwitches
[i
]))
458 bool IsProcessorSupported() {
459 return base::CPU().has_sse2();
462 base::string16
GetRegistrationDataCommandKey(
463 const AppRegistrationData
& reg_data
,
464 const wchar_t* name
) {
465 base::string16
cmd_key(reg_data
.GetVersionKey());
466 cmd_key
.append(1, base::FilePath::kSeparators
[0])
467 .append(google_update::kRegCommandsKey
)
468 .append(1, base::FilePath::kSeparators
[0])
473 ScopedTokenPrivilege::ScopedTokenPrivilege(const wchar_t* privilege_name
)
474 : is_enabled_(false) {
476 if (!::OpenProcessToken(::GetCurrentProcess(),
477 TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
,
481 token_
.Set(temp_handle
);
484 if (!::LookupPrivilegeValue(NULL
, privilege_name
, &privilege_luid
)) {
489 // Adjust the token's privileges to enable |privilege_name|. If this privilege
490 // was already enabled, |previous_privileges_|.PrivilegeCount will be set to 0
491 // and we then know not to disable this privilege upon destruction.
493 tp
.PrivilegeCount
= 1;
494 tp
.Privileges
[0].Luid
= privilege_luid
;
495 tp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
497 if (!::AdjustTokenPrivileges(token_
.Get(), FALSE
, &tp
,
498 sizeof(TOKEN_PRIVILEGES
),
499 &previous_privileges_
, &return_length
)) {
507 ScopedTokenPrivilege::~ScopedTokenPrivilege() {
508 if (is_enabled_
&& previous_privileges_
.PrivilegeCount
!= 0) {
509 ::AdjustTokenPrivileges(token_
.Get(), FALSE
, &previous_privileges_
,
510 sizeof(TOKEN_PRIVILEGES
), NULL
, NULL
);
514 } // namespace installer