VirtualBox

source: vbox/trunk/src/VBox/Installer/win/Stub/VBoxStub.cpp@ 79804

Last change on this file since 79804 was 76553, checked in by vboxsync, 6 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 40.7 KB
Line 
1/* $Id: VBoxStub.cpp 76553 2019-01-01 01:45:53Z vboxsync $ */
2/** @file
3 * VBoxStub - VirtualBox's Windows installer stub.
4 */
5
6/*
7 * Copyright (C) 2010-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0501
23# undef _WIN32_WINNT
24# define _WIN32_WINNT 0x0501 /* AttachConsole() / FreeConsole(). */
25#endif
26
27#include <iprt/win/windows.h>
28#include <commctrl.h>
29#include <fcntl.h>
30#include <io.h>
31#include <lmerr.h>
32#include <msiquery.h>
33#include <iprt/win/objbase.h>
34
35#include <iprt/win/shlobj.h>
36#include <stdlib.h>
37#include <stdio.h>
38#include <string.h>
39#include <strsafe.h>
40
41#include <VBox/version.h>
42
43#include <iprt/assert.h>
44#include <iprt/dir.h>
45#include <iprt/err.h>
46#include <iprt/file.h>
47#include <iprt/getopt.h>
48#include <iprt/initterm.h>
49#include <iprt/list.h>
50#include <iprt/mem.h>
51#include <iprt/message.h>
52#include <iprt/param.h>
53#include <iprt/path.h>
54#include <iprt/stream.h>
55#include <iprt/string.h>
56#include <iprt/thread.h>
57#include <iprt/utf16.h>
58
59#include "VBoxStub.h"
60#include "../StubBld/VBoxStubBld.h"
61#include "resource.h"
62
63#ifdef VBOX_WITH_CODE_SIGNING
64# include "VBoxStubCertUtil.h"
65# include "VBoxStubPublicCert.h"
66#endif
67
68#ifndef TARGET_NT4
69/* Use an own console window if run in verbose mode. */
70# define VBOX_STUB_WITH_OWN_CONSOLE
71#endif
72
73
74/*********************************************************************************************************************************
75* Defined Constants And Macros *
76*********************************************************************************************************************************/
77#define MY_UNICODE_SUB(str) L ##str
78#define MY_UNICODE(str) MY_UNICODE_SUB(str)
79
80
81/*********************************************************************************************************************************
82* Structures and Typedefs *
83*********************************************************************************************************************************/
84/**
85 * Cleanup record.
86 */
87typedef struct STUBCLEANUPREC
88{
89 /** List entry. */
90 RTLISTNODE ListEntry;
91 /** True if file, false if directory. */
92 bool fFile;
93 /** The path to the file or directory to clean up. */
94 char szPath[1];
95} STUBCLEANUPREC;
96/** Pointer to a cleanup record. */
97typedef STUBCLEANUPREC *PSTUBCLEANUPREC;
98
99
100/*********************************************************************************************************************************
101* Global Variables *
102*********************************************************************************************************************************/
103/** Whether it's a silent or interactive GUI driven install. */
104static bool g_fSilent = false;
105/** List of temporary files. */
106static RTLISTANCHOR g_TmpFiles;
107/** Verbosity flag. */
108static int g_iVerbosity = 0;
109
110
111
112/**
113 * Shows an error message box with a printf() style formatted string.
114 *
115 * @returns RTEXITCODE_FAILURE
116 * @param pszFmt Printf-style format string to show in the message box body.
117 *
118 */
119static RTEXITCODE ShowError(const char *pszFmt, ...)
120{
121 char *pszMsg;
122 va_list va;
123
124 va_start(va, pszFmt);
125 if (RTStrAPrintfV(&pszMsg, pszFmt, va))
126 {
127 if (g_fSilent)
128 RTMsgError("%s", pszMsg);
129 else
130 {
131 PRTUTF16 pwszMsg;
132 int rc = RTStrToUtf16(pszMsg, &pwszMsg);
133 if (RT_SUCCESS(rc))
134 {
135 MessageBoxW(GetDesktopWindow(), pwszMsg, MY_UNICODE(VBOX_STUB_TITLE), MB_ICONERROR);
136 RTUtf16Free(pwszMsg);
137 }
138 else
139 MessageBoxA(GetDesktopWindow(), pszMsg, VBOX_STUB_TITLE, MB_ICONERROR);
140 }
141 RTStrFree(pszMsg);
142 }
143 else /* Should never happen! */
144 AssertMsgFailed(("Failed to format error text of format string: %s!\n", pszFmt));
145 va_end(va);
146 return RTEXITCODE_FAILURE;
147}
148
149
150/**
151 * Shows a message box with a printf() style formatted string.
152 *
153 * @param uType Type of the message box (see MSDN).
154 * @param pszFmt Printf-style format string to show in the message box body.
155 *
156 */
157static void ShowInfo(const char *pszFmt, ...)
158{
159 char *pszMsg;
160 va_list va;
161 va_start(va, pszFmt);
162 int rc = RTStrAPrintfV(&pszMsg, pszFmt, va);
163 va_end(va);
164 if (rc >= 0)
165 {
166 if (g_fSilent)
167 RTPrintf("%s\n", pszMsg);
168 else
169 {
170 PRTUTF16 pwszMsg;
171 int rc = RTStrToUtf16(pszMsg, &pwszMsg);
172 if (RT_SUCCESS(rc))
173 {
174 MessageBoxW(GetDesktopWindow(), pwszMsg, MY_UNICODE(VBOX_STUB_TITLE), MB_ICONINFORMATION);
175 RTUtf16Free(pwszMsg);
176 }
177 else
178 MessageBoxA(GetDesktopWindow(), pszMsg, VBOX_STUB_TITLE, MB_ICONINFORMATION);
179 }
180 }
181 else /* Should never happen! */
182 AssertMsgFailed(("Failed to format error text of format string: %s!\n", pszFmt));
183 RTStrFree(pszMsg);
184}
185
186
187/**
188 * Finds the specified in the resource section of the executable.
189 *
190 * @returns IPRT status code.
191 *
192 * @param pszDataName Name of resource to read.
193 * @param ppvResource Where to return the pointer to the data.
194 * @param pdwSize Where to return the size of the data (if found).
195 * Optional.
196 */
197static int FindData(const char *pszDataName, PVOID *ppvResource, DWORD *pdwSize)
198{
199 AssertReturn(pszDataName, VERR_INVALID_PARAMETER);
200 HINSTANCE hInst = NULL; /* indicates the executable image */
201
202 /* Find our resource. */
203 PRTUTF16 pwszDataName;
204 int rc = RTStrToUtf16(pszDataName, &pwszDataName);
205 AssertRCReturn(rc, rc);
206 HRSRC hRsrc = FindResourceExW(hInst,
207 (LPWSTR)RT_RCDATA,
208 pwszDataName,
209 MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
210 RTUtf16Free(pwszDataName);
211 AssertReturn(hRsrc, VERR_IO_GEN_FAILURE);
212
213 /* Get resource size. */
214 DWORD cb = SizeofResource(hInst, hRsrc);
215 AssertReturn(cb > 0, VERR_NO_DATA);
216 if (pdwSize)
217 *pdwSize = cb;
218
219 /* Get pointer to resource. */
220 HGLOBAL hData = LoadResource(hInst, hRsrc);
221 AssertReturn(hData, VERR_IO_GEN_FAILURE);
222
223 /* Lock resource. */
224 *ppvResource = LockResource(hData);
225 AssertReturn(*ppvResource, VERR_IO_GEN_FAILURE);
226 return VINF_SUCCESS;
227}
228
229
230/**
231 * Finds the header for the given package.
232 *
233 * @returns Pointer to the package header on success. On failure NULL is
234 * returned after ShowError has been invoked.
235 * @param iPackage The package number.
236 */
237static PVBOXSTUBPKG FindPackageHeader(unsigned iPackage)
238{
239 char szHeaderName[32];
240 RTStrPrintf(szHeaderName, sizeof(szHeaderName), "HDR_%02d", iPackage);
241
242 PVBOXSTUBPKG pPackage;
243 int rc = FindData(szHeaderName, (PVOID *)&pPackage, NULL);
244 if (RT_FAILURE(rc))
245 {
246 ShowError("Internal error: Could not find package header #%u: %Rrc", iPackage, rc);
247 return NULL;
248 }
249
250 /** @todo validate it. */
251 return pPackage;
252}
253
254
255
256/**
257 * Constructs a full temporary file path from the given parameters.
258 *
259 * @returns iprt status code.
260 *
261 * @param pszTempPath The pure path to use for construction.
262 * @param pszTargetFileName The pure file name to use for construction.
263 * @param ppszTempFile Pointer to the constructed string. Must be freed
264 * using RTStrFree().
265 */
266static int GetTempFileAlloc(const char *pszTempPath,
267 const char *pszTargetFileName,
268 char **ppszTempFile)
269{
270 if (RTStrAPrintf(ppszTempFile, "%s\\%s", pszTempPath, pszTargetFileName) >= 0)
271 return VINF_SUCCESS;
272 return VERR_NO_STR_MEMORY;
273}
274
275
276/**
277 * Extracts a built-in resource to disk.
278 *
279 * @returns iprt status code.
280 *
281 * @param pszResourceName The resource name to extract.
282 * @param pszTempFile The full file path + name to extract the resource to.
283 *
284 */
285static int ExtractFile(const char *pszResourceName,
286 const char *pszTempFile)
287{
288#if 0 /* Another example of how unnecessarily complicated things get with
289 do-break-while-false and you end up with buggy code using uninitialized
290 variables. */
291 int rc;
292 RTFILE fh;
293 BOOL bCreatedFile = FALSE;
294
295 do
296 {
297 AssertMsgBreak(pszResourceName, ("Resource pointer invalid!\n")); /* rc is not initialized here, we'll return garbage. */
298 AssertMsgBreak(pszTempFile, ("Temp file pointer invalid!")); /* Ditto. */
299
300 /* Read the data of the built-in resource. */
301 PVOID pvData = NULL;
302 DWORD dwDataSize = 0;
303 rc = FindData(pszResourceName, &pvData, &dwDataSize);
304 AssertMsgRCBreak(rc, ("Could not read resource data!\n"));
305
306 /* Create new (and replace an old) file. */
307 rc = RTFileOpen(&fh, pszTempFile,
308 RTFILE_O_CREATE_REPLACE
309 | RTFILE_O_WRITE
310 | RTFILE_O_DENY_NOT_DELETE
311 | RTFILE_O_DENY_WRITE);
312 AssertMsgRCBreak(rc, ("Could not open file for writing!\n"));
313 bCreatedFile = TRUE;
314
315 /* Write contents to new file. */
316 size_t cbWritten = 0;
317 rc = RTFileWrite(fh, pvData, dwDataSize, &cbWritten);
318 AssertMsgRCBreak(rc, ("Could not open file for writing!\n"));
319 AssertMsgBreak(dwDataSize == cbWritten, ("File was not extracted completely! Disk full?\n"));
320
321 } while (0);
322
323 if (RTFileIsValid(fh)) /* fh is unused uninitalized (MSC agrees) */
324 RTFileClose(fh);
325
326 if (RT_FAILURE(rc))
327 {
328 if (bCreatedFile)
329 RTFileDelete(pszTempFile);
330 }
331
332#else /* This is exactly the same as above, except no bug and better assertion
333 message. Note only the return-success statment is indented, indicating
334 that the whole do-break-while-false approach was totally unnecessary. */
335
336 AssertPtrReturn(pszResourceName, VERR_INVALID_POINTER);
337 AssertPtrReturn(pszTempFile, VERR_INVALID_POINTER);
338
339 /* Read the data of the built-in resource. */
340 PVOID pvData = NULL;
341 DWORD dwDataSize = 0;
342 int rc = FindData(pszResourceName, &pvData, &dwDataSize);
343 AssertMsgRCReturn(rc, ("Could not read resource data: %Rrc\n", rc), rc);
344
345 /* Create new (and replace an old) file. */
346 RTFILE hFile;
347 rc = RTFileOpen(&hFile, pszTempFile,
348 RTFILE_O_CREATE_REPLACE
349 | RTFILE_O_WRITE
350 | RTFILE_O_DENY_NOT_DELETE
351 | RTFILE_O_DENY_WRITE);
352 AssertMsgRCReturn(rc, ("Could not open '%s' for writing: %Rrc\n", pszTempFile, rc), rc);
353
354 /* Write contents to new file. */
355 size_t cbWritten = 0;
356 rc = RTFileWrite(hFile, pvData, dwDataSize, &cbWritten);
357 AssertMsgStmt(cbWritten == dwDataSize || RT_FAILURE_NP(rc), ("%#zx vs %#x\n", cbWritten, dwDataSize), rc = VERR_WRITE_ERROR);
358
359 int rc2 = RTFileClose(hFile);
360 AssertRC(rc2);
361
362 if (RT_SUCCESS(rc))
363 return VINF_SUCCESS;
364
365 RTFileDelete(pszTempFile);
366
367#endif
368 return rc;
369}
370
371
372/**
373 * Extracts a built-in resource to disk.
374 *
375 * @returns iprt status code.
376 *
377 * @param pPackage Pointer to a VBOXSTUBPKG struct that contains the resource.
378 * @param pszTempFile The full file path + name to extract the resource to.
379 */
380static int Extract(const PVBOXSTUBPKG pPackage,
381 const char *pszTempFile)
382{
383 return ExtractFile(pPackage->szResourceName, pszTempFile);
384}
385
386
387/**
388 * Detects whether we're running on a 32- or 64-bit platform and returns the result.
389 *
390 * @returns TRUE if we're running on a 64-bit OS, FALSE if not.
391 */
392static BOOL IsWow64(void)
393{
394 BOOL fIsWow64 = TRUE;
395 fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
396 if (NULL != fnIsWow64Process)
397 {
398 if (!fnIsWow64Process(GetCurrentProcess(), &fIsWow64))
399 {
400 /* Error in retrieving process type - assume that we're running on 32bit. */
401 return FALSE;
402 }
403 }
404 return fIsWow64;
405}
406
407
408/**
409 * Decides whether we need a specified package to handle or not.
410 *
411 * @returns @c true if we need to handle the specified package, @c false if not.
412 *
413 * @param pPackage Pointer to a VBOXSTUBPKG struct that contains the resource.
414 */
415static bool PackageIsNeeded(PVBOXSTUBPKG pPackage)
416{
417 if (pPackage->byArch == VBOXSTUBPKGARCH_ALL)
418 return true;
419 VBOXSTUBPKGARCH enmArch = IsWow64() ? VBOXSTUBPKGARCH_AMD64 : VBOXSTUBPKGARCH_X86;
420 return pPackage->byArch == enmArch;
421}
422
423
424/**
425 * Adds a cleanup record.
426 *
427 * @returns Fully complained boolean success indicator.
428 * @param pszPath The path to the file or directory to clean up.
429 * @param fFile @c true if file, @c false if directory.
430 */
431static bool AddCleanupRec(const char *pszPath, bool fFile)
432{
433 size_t cchPath = strlen(pszPath); Assert(cchPath > 0);
434 PSTUBCLEANUPREC pRec = (PSTUBCLEANUPREC)RTMemAlloc(RT_UOFFSETOF_DYN(STUBCLEANUPREC, szPath[cchPath + 1]));
435 if (!pRec)
436 {
437 ShowError("Out of memory!");
438 return false;
439 }
440 pRec->fFile = fFile;
441 memcpy(pRec->szPath, pszPath, cchPath + 1);
442
443 RTListPrepend(&g_TmpFiles, &pRec->ListEntry);
444 return true;
445}
446
447
448/**
449 * Cleans up all the extracted files and optionally removes the package
450 * directory.
451 *
452 * @param pszPkgDir The package directory, NULL if it shouldn't be
453 * removed.
454 */
455static void CleanUp(const char *pszPkgDir)
456{
457 for (int i = 0; i < 5; i++)
458 {
459 int rc;
460 bool fFinalTry = i == 4;
461
462 PSTUBCLEANUPREC pCur, pNext;
463 RTListForEachSafe(&g_TmpFiles, pCur, pNext, STUBCLEANUPREC, ListEntry)
464 {
465 if (pCur->fFile)
466 rc = RTFileDelete(pCur->szPath);
467 else
468 {
469 rc = RTDirRemoveRecursive(pCur->szPath, RTDIRRMREC_F_CONTENT_AND_DIR);
470 if (rc == VERR_DIR_NOT_EMPTY && fFinalTry)
471 rc = VINF_SUCCESS;
472 }
473 if (rc == VERR_FILE_NOT_FOUND || rc == VERR_PATH_NOT_FOUND)
474 rc = VINF_SUCCESS;
475 if (RT_SUCCESS(rc))
476 {
477 RTListNodeRemove(&pCur->ListEntry);
478 RTMemFree(pCur);
479 }
480 else if (fFinalTry)
481 {
482 if (pCur->fFile)
483 ShowError("Failed to delete temporary file '%s': %Rrc", pCur->szPath, rc);
484 else
485 ShowError("Failed to delete temporary directory '%s': %Rrc", pCur->szPath, rc);
486 }
487 }
488
489 if (RTListIsEmpty(&g_TmpFiles) || fFinalTry)
490 {
491 if (!pszPkgDir)
492 return;
493 rc = RTDirRemove(pszPkgDir);
494 if (RT_SUCCESS(rc) || rc == VERR_FILE_NOT_FOUND || rc == VERR_PATH_NOT_FOUND || fFinalTry)
495 return;
496 }
497
498 /* Delay a little and try again. */
499 RTThreadSleep(i == 0 ? 100 : 3000);
500 }
501}
502
503
504/**
505 * Processes an MSI package.
506 *
507 * @returns Fully complained exit code.
508 * @param pszMsi The path to the MSI to process.
509 * @param pszMsiArgs Any additional installer (MSI) argument
510 * @param fLogging Whether to enable installer logging.
511 */
512static RTEXITCODE ProcessMsiPackage(const char *pszMsi, const char *pszMsiArgs, bool fLogging)
513{
514 int rc;
515
516 /*
517 * Set UI level.
518 */
519 INSTALLUILEVEL enmDesiredUiLevel = g_fSilent ? INSTALLUILEVEL_NONE : INSTALLUILEVEL_FULL;
520 INSTALLUILEVEL enmRet = MsiSetInternalUI(enmDesiredUiLevel, NULL);
521 if (enmRet == INSTALLUILEVEL_NOCHANGE /* means error */)
522 return ShowError("Internal error: MsiSetInternalUI failed.");
523
524 /*
525 * Enable logging?
526 */
527 if (fLogging)
528 {
529 char szLogFile[RTPATH_MAX];
530 rc = RTStrCopy(szLogFile, sizeof(szLogFile), pszMsi);
531 if (RT_SUCCESS(rc))
532 {
533 RTPathStripFilename(szLogFile);
534 rc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxInstallLog.txt");
535 }
536 if (RT_FAILURE(rc))
537 return ShowError("Internal error: Filename path too long.");
538
539 PRTUTF16 pwszLogFile;
540 rc = RTStrToUtf16(szLogFile, &pwszLogFile);
541 if (RT_FAILURE(rc))
542 return ShowError("RTStrToUtf16 failed on '%s': %Rrc", szLogFile, rc);
543
544 UINT uLogLevel = MsiEnableLogW(INSTALLLOGMODE_VERBOSE,
545 pwszLogFile,
546 INSTALLLOGATTRIBUTES_FLUSHEACHLINE);
547 RTUtf16Free(pwszLogFile);
548 if (uLogLevel != ERROR_SUCCESS)
549 return ShowError("MsiEnableLogW failed");
550 }
551
552 /*
553 * Initialize the common controls (extended version). This is necessary to
554 * run the actual .MSI installers with the new fancy visual control
555 * styles (XP+). Also, an integrated manifest is required.
556 */
557 INITCOMMONCONTROLSEX ccEx;
558 ccEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
559 ccEx.dwICC = ICC_LINK_CLASS | ICC_LISTVIEW_CLASSES | ICC_PAGESCROLLER_CLASS |
560 ICC_PROGRESS_CLASS | ICC_STANDARD_CLASSES | ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES |
561 ICC_UPDOWN_CLASS | ICC_USEREX_CLASSES | ICC_WIN95_CLASSES;
562 InitCommonControlsEx(&ccEx); /* Ignore failure. */
563
564 /*
565 * Convert both strings to UTF-16 and start the installation.
566 */
567 PRTUTF16 pwszMsi;
568 rc = RTStrToUtf16(pszMsi, &pwszMsi);
569 if (RT_FAILURE(rc))
570 return ShowError("RTStrToUtf16 failed on '%s': %Rrc", pszMsi, rc);
571 PRTUTF16 pwszMsiArgs;
572 rc = RTStrToUtf16(pszMsiArgs, &pwszMsiArgs);
573 if (RT_FAILURE(rc))
574 {
575 RTUtf16Free(pwszMsi);
576 return ShowError("RTStrToUtf16 failed on '%s': %Rrc", pszMsi, rc);
577 }
578
579 UINT uStatus = MsiInstallProductW(pwszMsi, pwszMsiArgs);
580 RTUtf16Free(pwszMsi);
581 RTUtf16Free(pwszMsiArgs);
582
583 if (uStatus == ERROR_SUCCESS)
584 return RTEXITCODE_SUCCESS;
585 if (uStatus == ERROR_SUCCESS_REBOOT_REQUIRED)
586 return RTEXITCODE_SUCCESS; /* we currently don't indicate this */
587
588 /*
589 * Installation failed. Figure out what to say.
590 */
591 switch (uStatus)
592 {
593 case ERROR_INSTALL_USEREXIT:
594 /* Don't say anything? */
595 break;
596
597 case ERROR_INSTALL_PACKAGE_VERSION:
598 ShowError("This installation package cannot be installed by the Windows Installer service.\n"
599 "You must install a Windows service pack that contains a newer version of the Windows Installer service.");
600 break;
601
602 case ERROR_INSTALL_PLATFORM_UNSUPPORTED:
603 ShowError("This installation package is not supported on this platform.");
604 break;
605
606 default:
607 {
608 /*
609 * Try get windows to format the message.
610 */
611 DWORD dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER
612 | FORMAT_MESSAGE_IGNORE_INSERTS
613 | FORMAT_MESSAGE_FROM_SYSTEM;
614 HMODULE hModule = NULL;
615 if (uStatus >= NERR_BASE && uStatus <= MAX_NERR)
616 {
617 hModule = LoadLibraryExW(L"netmsg.dll",
618 NULL,
619 LOAD_LIBRARY_AS_DATAFILE);
620 if (hModule != NULL)
621 dwFormatFlags |= FORMAT_MESSAGE_FROM_HMODULE;
622 }
623
624 PWSTR pwszMsg;
625 if (FormatMessageW(dwFormatFlags,
626 hModule, /* If NULL, load system stuff. */
627 uStatus,
628 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
629 (PWSTR)&pwszMsg,
630 0,
631 NULL) > 0)
632 {
633 ShowError("Installation failed! Error: %ls", pwszMsg);
634 LocalFree(pwszMsg);
635 }
636 else /* If text lookup failed, show at least the error number. */
637 ShowError("Installation failed! Error: %u", uStatus);
638
639 if (hModule)
640 FreeLibrary(hModule);
641 break;
642 }
643 }
644
645 return RTEXITCODE_FAILURE;
646}
647
648
649/**
650 * Processes a package.
651 *
652 * @returns Fully complained exit code.
653 * @param iPackage The package number.
654 * @param pszPkgDir The package directory (aka extraction dir).
655 * @param pszMsiArgs Any additional installer (MSI) argument
656 * @param fLogging Whether to enable installer logging.
657 */
658static RTEXITCODE ProcessPackage(unsigned iPackage, const char *pszPkgDir, const char *pszMsiArgs, bool fLogging)
659{
660 /*
661 * Get the package header and check if it's needed.
662 */
663 PVBOXSTUBPKG pPackage = FindPackageHeader(iPackage);
664 if (pPackage == NULL)
665 return RTEXITCODE_FAILURE;
666
667 if (!PackageIsNeeded(pPackage))
668 return RTEXITCODE_SUCCESS;
669
670 /*
671 * Deal with the file based on it's extension.
672 */
673 char szPkgFile[RTPATH_MAX];
674 int rc = RTPathJoin(szPkgFile, sizeof(szPkgFile), pszPkgDir, pPackage->szFileName);
675 if (RT_FAILURE(rc))
676 return ShowError("Internal error: RTPathJoin failed: %Rrc", rc);
677 RTPathChangeToDosSlashes(szPkgFile, true /* Force conversion. */); /* paranoia */
678
679 RTEXITCODE rcExit;
680 const char *pszSuff = RTPathSuffix(szPkgFile);
681 if (RTStrICmp(pszSuff, ".msi") == 0)
682 rcExit = ProcessMsiPackage(szPkgFile, pszMsiArgs, fLogging);
683 else if (RTStrICmp(pszSuff, ".cab") == 0)
684 rcExit = RTEXITCODE_SUCCESS; /* Ignore .cab files, they're generally referenced by other files. */
685 else
686 rcExit = ShowError("Internal error: Do not know how to handle file '%s'.", pPackage->szFileName);
687
688 return rcExit;
689}
690
691
692#ifdef VBOX_WITH_CODE_SIGNING
693/**
694 * Install the public certificate into TrustedPublishers so the installer won't
695 * prompt the user during silent installs.
696 *
697 * @returns Fully complained exit code.
698 */
699static RTEXITCODE InstallCertificates(void)
700{
701 for (uint32_t i = 0; i < RT_ELEMENTS(g_aVBoxStubTrustedCerts); i++)
702 {
703 if (!addCertToStore(CERT_SYSTEM_STORE_LOCAL_MACHINE,
704 "TrustedPublisher",
705 g_aVBoxStubTrustedCerts[i].pab,
706 g_aVBoxStubTrustedCerts[i].cb))
707 return ShowError("Failed to construct install certificate.");
708 }
709 return RTEXITCODE_SUCCESS;
710}
711#endif /* VBOX_WITH_CODE_SIGNING */
712
713
714/**
715 * Copies the "<exepath>.custom" directory to the extraction path if it exists.
716 *
717 * This is used by the MSI packages from the resource section.
718 *
719 * @returns Fully complained exit code.
720 * @param pszDstDir The destination directory.
721 */
722static RTEXITCODE CopyCustomDir(const char *pszDstDir)
723{
724 char szSrcDir[RTPATH_MAX];
725 int rc = RTPathExecDir(szSrcDir, sizeof(szSrcDir));
726 if (RT_SUCCESS(rc))
727 rc = RTPathAppend(szSrcDir, sizeof(szSrcDir), ".custom");
728 if (RT_FAILURE(rc))
729 return ShowError("Failed to construct '.custom' dir path: %Rrc", rc);
730
731 if (RTDirExists(szSrcDir))
732 {
733 /*
734 * Use SHFileOperation w/ FO_COPY to do the job. This API requires an
735 * extra zero at the end of both source and destination paths.
736 */
737 size_t cwc;
738 RTUTF16 wszSrcDir[RTPATH_MAX + 1];
739 PRTUTF16 pwszSrcDir = wszSrcDir;
740 rc = RTStrToUtf16Ex(szSrcDir, RTSTR_MAX, &pwszSrcDir, RTPATH_MAX, &cwc);
741 if (RT_FAILURE(rc))
742 return ShowError("RTStrToUtf16Ex failed on '%s': %Rrc", szSrcDir, rc);
743 wszSrcDir[cwc] = '\0';
744
745 RTUTF16 wszDstDir[RTPATH_MAX + 1];
746 PRTUTF16 pwszDstDir = wszSrcDir;
747 rc = RTStrToUtf16Ex(pszDstDir, RTSTR_MAX, &pwszDstDir, RTPATH_MAX, &cwc);
748 if (RT_FAILURE(rc))
749 return ShowError("RTStrToUtf16Ex failed on '%s': %Rrc", pszDstDir, rc);
750 wszDstDir[cwc] = '\0';
751
752 SHFILEOPSTRUCTW FileOp;
753 RT_ZERO(FileOp); /* paranoia */
754 FileOp.hwnd = NULL;
755 FileOp.wFunc = FO_COPY;
756 FileOp.pFrom = wszSrcDir;
757 FileOp.pTo = wszDstDir;
758 FileOp.fFlags = FOF_SILENT
759 | FOF_NOCONFIRMATION
760 | FOF_NOCONFIRMMKDIR
761 | FOF_NOERRORUI;
762 FileOp.fAnyOperationsAborted = FALSE;
763 FileOp.hNameMappings = NULL;
764 FileOp.lpszProgressTitle = NULL;
765
766 rc = SHFileOperationW(&FileOp);
767 if (rc != 0) /* Not a Win32 status code! */
768 return ShowError("Copying the '.custom' dir failed: %#x", rc);
769
770 /*
771 * Add a cleanup record for recursively deleting the destination
772 * .custom directory. We should actually add this prior to calling
773 * SHFileOperationW since it may partially succeed...
774 */
775 char *pszDstSubDir = RTPathJoinA(pszDstDir, ".custom");
776 if (!pszDstSubDir)
777 return ShowError("Out of memory!");
778 bool fRc = AddCleanupRec(pszDstSubDir, false /*fFile*/);
779 RTStrFree(pszDstSubDir);
780 if (!fRc)
781 return RTEXITCODE_FAILURE;
782 }
783
784 return RTEXITCODE_SUCCESS;
785}
786
787
788static RTEXITCODE ExtractFiles(unsigned cPackages, const char *pszDstDir, bool fExtractOnly, bool *pfCreatedExtractDir)
789{
790 int rc;
791
792 /*
793 * Make sure the directory exists.
794 */
795 *pfCreatedExtractDir = false;
796 if (!RTDirExists(pszDstDir))
797 {
798 rc = RTDirCreate(pszDstDir, 0700, 0);
799 if (RT_FAILURE(rc))
800 return ShowError("Failed to create extraction path '%s': %Rrc", pszDstDir, rc);
801 *pfCreatedExtractDir = true;
802 }
803
804 /*
805 * Extract files.
806 */
807 for (unsigned k = 0; k < cPackages; k++)
808 {
809 PVBOXSTUBPKG pPackage = FindPackageHeader(k);
810 if (!pPackage)
811 return RTEXITCODE_FAILURE; /* Done complaining already. */
812
813 if (fExtractOnly || PackageIsNeeded(pPackage))
814 {
815 char szDstFile[RTPATH_MAX];
816 rc = RTPathJoin(szDstFile, sizeof(szDstFile), pszDstDir, pPackage->szFileName);
817 if (RT_FAILURE(rc))
818 return ShowError("Internal error: RTPathJoin failed: %Rrc", rc);
819
820 rc = Extract(pPackage, szDstFile);
821 if (RT_FAILURE(rc))
822 return ShowError("Error extracting package #%u: %Rrc", k, rc);
823
824 if (!fExtractOnly && !AddCleanupRec(szDstFile, true /*fFile*/))
825 {
826 RTFileDelete(szDstFile);
827 return RTEXITCODE_FAILURE;
828 }
829 }
830 }
831
832 return RTEXITCODE_SUCCESS;
833}
834
835
836int WINAPI WinMain(HINSTANCE hInstance,
837 HINSTANCE hPrevInstance,
838 char *lpCmdLine,
839 int nCmdShow)
840{
841 RT_NOREF(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
842 char **argv = __argv;
843 int argc = __argc;
844
845 /*
846 * Init IPRT. This is _always_ the very first thing we do.
847 */
848 int vrc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_STANDALONE_APP);
849 if (RT_FAILURE(vrc))
850 return RTMsgInitFailure(vrc);
851
852 /*
853 * Check if we're already running and jump out if so.
854 *
855 * Note! Do not use a global namespace ("Global\\") for mutex name here,
856 * will blow up NT4 compatibility!
857 */
858 HANDLE hMutexAppRunning = CreateMutex(NULL, FALSE, "VBoxStubInstaller");
859 if ( hMutexAppRunning != NULL
860 && GetLastError() == ERROR_ALREADY_EXISTS)
861 {
862 /* Close the mutex for this application instance. */
863 CloseHandle(hMutexAppRunning);
864 hMutexAppRunning = NULL;
865 return RTEXITCODE_FAILURE;
866 }
867
868 /*
869 * Parse arguments.
870 */
871
872 /* Parameter variables. */
873 bool fExtractOnly = false;
874 bool fEnableLogging = false;
875#ifdef VBOX_WITH_CODE_SIGNING
876 bool fEnableSilentCert = true;
877#endif
878 char szExtractPath[RTPATH_MAX] = {0};
879 char szMSIArgs[_4K] = {0};
880
881 /* Parameter definitions. */
882 static const RTGETOPTDEF s_aOptions[] =
883 {
884 /** @todo Replace short parameters with enums since they're not
885 * used (and not documented to the public). */
886 { "--extract", 'x', RTGETOPT_REQ_NOTHING },
887 { "-extract", 'x', RTGETOPT_REQ_NOTHING },
888 { "/extract", 'x', RTGETOPT_REQ_NOTHING },
889 { "--silent", 's', RTGETOPT_REQ_NOTHING },
890 { "-silent", 's', RTGETOPT_REQ_NOTHING },
891 { "/silent", 's', RTGETOPT_REQ_NOTHING },
892#ifdef VBOX_WITH_CODE_SIGNING
893 { "--no-silent-cert", 'c', RTGETOPT_REQ_NOTHING },
894 { "-no-silent-cert", 'c', RTGETOPT_REQ_NOTHING },
895 { "/no-silent-cert", 'c', RTGETOPT_REQ_NOTHING },
896#endif
897 { "--logging", 'l', RTGETOPT_REQ_NOTHING },
898 { "-logging", 'l', RTGETOPT_REQ_NOTHING },
899 { "/logging", 'l', RTGETOPT_REQ_NOTHING },
900 { "--path", 'p', RTGETOPT_REQ_STRING },
901 { "-path", 'p', RTGETOPT_REQ_STRING },
902 { "/path", 'p', RTGETOPT_REQ_STRING },
903 { "--msiparams", 'm', RTGETOPT_REQ_STRING },
904 { "-msiparams", 'm', RTGETOPT_REQ_STRING },
905 { "--reinstall", 'f', RTGETOPT_REQ_NOTHING },
906 { "-reinstall", 'f', RTGETOPT_REQ_NOTHING },
907 { "/reinstall", 'f', RTGETOPT_REQ_NOTHING },
908 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
909 { "-verbose", 'v', RTGETOPT_REQ_NOTHING },
910 { "/verbose", 'v', RTGETOPT_REQ_NOTHING },
911 { "--version", 'V', RTGETOPT_REQ_NOTHING },
912 { "-version", 'V', RTGETOPT_REQ_NOTHING },
913 { "/version", 'V', RTGETOPT_REQ_NOTHING },
914 { "-v", 'V', RTGETOPT_REQ_NOTHING },
915 { "--help", 'h', RTGETOPT_REQ_NOTHING },
916 { "-help", 'h', RTGETOPT_REQ_NOTHING },
917 { "/help", 'h', RTGETOPT_REQ_NOTHING },
918 { "/?", 'h', RTGETOPT_REQ_NOTHING },
919 };
920
921 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
922
923 /* Parse the parameters. */
924 int ch;
925 bool fExitEarly = false;
926 RTGETOPTUNION ValueUnion;
927 RTGETOPTSTATE GetState;
928 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
929 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
930 && rcExit == RTEXITCODE_SUCCESS
931 && !fExitEarly)
932 {
933 switch (ch)
934 {
935 case 'f': /* Force re-installation. */
936 if (szMSIArgs[0])
937 vrc = RTStrCat(szMSIArgs, sizeof(szMSIArgs), " ");
938 if (RT_SUCCESS(vrc))
939 vrc = RTStrCat(szMSIArgs, sizeof(szMSIArgs),
940 "REINSTALLMODE=vomus REINSTALL=ALL");
941 if (RT_FAILURE(vrc))
942 rcExit = ShowError("MSI parameters are too long.");
943 break;
944
945 case 'x':
946 fExtractOnly = true;
947 break;
948
949 case 's':
950 g_fSilent = true;
951 break;
952
953#ifdef VBOX_WITH_CODE_SIGNING
954 case 'c':
955 fEnableSilentCert = false;
956 break;
957#endif
958 case 'l':
959 fEnableLogging = true;
960 break;
961
962 case 'p':
963 vrc = RTStrCopy(szExtractPath, sizeof(szExtractPath), ValueUnion.psz);
964 if (RT_FAILURE(vrc))
965 rcExit = ShowError("Extraction path is too long.");
966 break;
967
968 case 'm':
969 if (szMSIArgs[0])
970 vrc = RTStrCat(szMSIArgs, sizeof(szMSIArgs), " ");
971 if (RT_SUCCESS(vrc))
972 vrc = RTStrCat(szMSIArgs, sizeof(szMSIArgs), ValueUnion.psz);
973 if (RT_FAILURE(vrc))
974 rcExit = ShowError("MSI parameters are too long.");
975 break;
976
977 case 'V':
978 ShowInfo("Version: %d.%d.%d.%d",
979 VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD,
980 VBOX_SVN_REV);
981 fExitEarly = true;
982 break;
983
984 case 'v':
985 g_iVerbosity++;
986 break;
987
988 case 'h':
989 ShowInfo("-- %s v%d.%d.%d.%d --\n"
990 "\n"
991 "Command Line Parameters:\n\n"
992 "--extract - Extract file contents to temporary directory\n"
993 "--help - Print this help and exit\n"
994 "--logging - Enables installer logging\n"
995 "--msiparams <parameters> - Specifies extra parameters for the MSI installers\n"
996 "--no-silent-cert - Do not install VirtualBox Certificate automatically when --silent option is specified\n"
997 "--path - Sets the path of the extraction directory\n"
998 "--reinstall - Forces VirtualBox to get re-installed\n"
999 "--silent - Enables silent mode installation\n"
1000 "--version - Print version number and exit\n\n"
1001 "Examples:\n"
1002 "%s --msiparams INSTALLDIR=C:\\VBox\n"
1003 "%s --extract -path C:\\VBox",
1004 VBOX_STUB_TITLE, VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV,
1005 argv[0], argv[0]);
1006 fExitEarly = true;
1007 break;
1008
1009 case VINF_GETOPT_NOT_OPTION:
1010 /* Are (optional) MSI parameters specified and this is the last
1011 * parameter? Append everything to the MSI parameter list then. */
1012 if (szMSIArgs[0])
1013 {
1014 vrc = RTStrCat(szMSIArgs, sizeof(szMSIArgs), " ");
1015 if (RT_SUCCESS(vrc))
1016 vrc = RTStrCat(szMSIArgs, sizeof(szMSIArgs), ValueUnion.psz);
1017 if (RT_FAILURE(vrc))
1018 rcExit = ShowError("MSI parameters are too long.");
1019 continue;
1020 }
1021 /* Fall through is intentional. */
1022
1023 default:
1024 if (g_fSilent)
1025 rcExit = RTGetOptPrintError(ch, &ValueUnion);
1026 if (ch == VERR_GETOPT_UNKNOWN_OPTION)
1027 rcExit = ShowError("Unknown option \"%s\"\n"
1028 "Please refer to the command line help by specifying \"/?\"\n"
1029 "to get more information.", ValueUnion.psz);
1030 else
1031 rcExit = ShowError("Parameter parsing error: %Rrc\n"
1032 "Please refer to the command line help by specifying \"/?\"\n"
1033 "to get more information.", ch);
1034 break;
1035 }
1036 }
1037
1038 /* Check if we can bail out early. */
1039 if (fExitEarly)
1040 return rcExit;
1041
1042 if (rcExit != RTEXITCODE_SUCCESS)
1043 vrc = VERR_PARSE_ERROR;
1044
1045/** @todo
1046 *
1047 * Split the remainder up in functions and simplify the code flow!!
1048 *
1049 * */
1050
1051#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0501
1052# ifdef VBOX_STUB_WITH_OWN_CONSOLE /* Use an own console window if run in debug mode. */
1053 if ( RT_SUCCESS(vrc)
1054 && g_iVerbosity)
1055 {
1056 if (!AllocConsole())
1057 {
1058 DWORD dwErr = GetLastError();
1059 ShowError("Unable to allocate console, error = %ld\n",
1060 dwErr);
1061
1062 /* Close the mutex for this application instance. */
1063 CloseHandle(hMutexAppRunning);
1064 hMutexAppRunning = NULL;
1065 return RTEXITCODE_FAILURE;
1066 }
1067
1068 freopen("CONOUT$", "w", stdout);
1069 setvbuf(stdout, NULL, _IONBF, 0);
1070
1071 freopen("CONOUT$", "w", stderr);
1072 }
1073# endif /* VBOX_STUB_WITH_OWN_CONSOLE */
1074#endif
1075
1076 if ( RT_SUCCESS(vrc)
1077 && g_iVerbosity)
1078 {
1079 RTPrintf("Silent installation : %RTbool\n", g_fSilent);
1080 RTPrintf("Logging enabled : %RTbool\n", fEnableLogging);
1081#ifdef VBOX_WITH_CODE_SIGNING
1082 RTPrintf("Certificate installation : %RTbool\n", fEnableSilentCert);
1083#endif
1084 RTPrintf("Additional MSI parameters: %s\n",
1085 szMSIArgs[0] ? szMSIArgs : "<None>");
1086 }
1087
1088 /*
1089 * 32-bit is not officially supported any more.
1090 */
1091 if ( !fExtractOnly
1092 && !g_fSilent
1093 && !IsWow64())
1094 {
1095 rcExit = ShowError("32-bit Windows hosts are not supported by this VirtualBox release.");
1096 vrc = VERR_NOT_SUPPORTED;
1097 }
1098
1099 if (RT_SUCCESS(vrc))
1100 {
1101 /*
1102 * Determine the extration path if not given by the user, and gather some
1103 * other bits we'll be needing later.
1104 */
1105 if (szExtractPath[0] == '\0')
1106 {
1107 vrc = RTPathTemp(szExtractPath, sizeof(szExtractPath));
1108 if (RT_SUCCESS(vrc))
1109 vrc = RTPathAppend(szExtractPath, sizeof(szExtractPath), "VirtualBox");
1110 if (RT_FAILURE(vrc))
1111 ShowError("Failed to determine extraction path (%Rrc)", vrc);
1112
1113 }
1114 else
1115 {
1116 /** @todo should check if there is a .custom subdirectory there or not. */
1117 }
1118 RTPathChangeToDosSlashes(szExtractPath,
1119 true /* Force conversion. */); /* MSI requirement. */
1120 }
1121
1122 /* Read our manifest. */
1123 if (RT_SUCCESS(vrc))
1124 {
1125 PVBOXSTUBPKGHEADER pHeader;
1126 vrc = FindData("MANIFEST", (PVOID *)&pHeader, NULL);
1127 if (RT_SUCCESS(vrc))
1128 {
1129 /** @todo If we could, we should validate the header. Only the magic isn't
1130 * commonly defined, nor the version number... */
1131
1132 RTListInit(&g_TmpFiles);
1133
1134 /*
1135 * Up to this point, we haven't done anything that requires any cleanup.
1136 * From here on, we do everything in function so we can counter clean up.
1137 */
1138 bool fCreatedExtractDir;
1139 rcExit = ExtractFiles(pHeader->byCntPkgs, szExtractPath,
1140 fExtractOnly, &fCreatedExtractDir);
1141 if (rcExit == RTEXITCODE_SUCCESS)
1142 {
1143 if (fExtractOnly)
1144 ShowInfo("Files were extracted to: %s", szExtractPath);
1145 else
1146 {
1147 rcExit = CopyCustomDir(szExtractPath);
1148#ifdef VBOX_WITH_CODE_SIGNING
1149 if (rcExit == RTEXITCODE_SUCCESS && fEnableSilentCert && g_fSilent)
1150 rcExit = InstallCertificates();
1151#endif
1152 unsigned iPackage = 0;
1153 while ( iPackage < pHeader->byCntPkgs
1154 && rcExit == RTEXITCODE_SUCCESS)
1155 {
1156 rcExit = ProcessPackage(iPackage, szExtractPath,
1157 szMSIArgs, fEnableLogging);
1158 iPackage++;
1159 }
1160
1161 /* Don't fail if cleanup fail. At least for now. */
1162 CleanUp( !fEnableLogging
1163 && fCreatedExtractDir ? szExtractPath : NULL);
1164 }
1165 }
1166
1167 /* Free any left behind cleanup records (not strictly needed). */
1168 PSTUBCLEANUPREC pCur, pNext;
1169 RTListForEachSafe(&g_TmpFiles, pCur, pNext, STUBCLEANUPREC, ListEntry)
1170 {
1171 RTListNodeRemove(&pCur->ListEntry);
1172 RTMemFree(pCur);
1173 }
1174 }
1175 else
1176 rcExit = ShowError("Internal package error: Manifest not found (%Rrc)", vrc);
1177 }
1178
1179#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0501
1180# ifdef VBOX_STUB_WITH_OWN_CONSOLE
1181 if (g_iVerbosity)
1182 FreeConsole();
1183# endif /* VBOX_STUB_WITH_OWN_CONSOLE */
1184#endif
1185
1186 /*
1187 * Release instance mutex.
1188 */
1189 if (hMutexAppRunning != NULL)
1190 {
1191 CloseHandle(hMutexAppRunning);
1192 hMutexAppRunning = NULL;
1193 }
1194
1195 return rcExit;
1196}
1197
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette