VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxAutostart/VBoxAutostart-win.cpp@ 82989

Last change on this file since 82989 was 82968, checked in by vboxsync, 5 years ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 42.2 KB
Line 
1/* $Id: VBoxAutostart-win.cpp 82968 2020-02-04 10:35:17Z vboxsync $ */
2/** @file
3 * VirtualBox Autostart Service - Windows Specific Code.
4 */
5
6/*
7 * Copyright (C) 2012-2020 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#include <iprt/win/windows.h>
23#include <tchar.h>
24
25#define SECURITY_WIN32
26#include <Security.h>
27
28#include <VBox/com/array.h>
29#include <VBox/com/com.h>
30#include <VBox/com/ErrorInfo.h>
31#include <VBox/com/errorprint.h>
32#include <VBox/com/Guid.h>
33#include <VBox/com/listeners.h>
34#include <VBox/com/NativeEventQueue.h>
35#include <VBox/com/string.h>
36#include <VBox/com/VirtualBox.h>
37
38#include <VBox/log.h>
39#include <VBox/version.h>
40
41#include <iprt/env.h>
42#include <iprt/errcore.h>
43#include <iprt/getopt.h>
44#include <iprt/initterm.h>
45#include <iprt/mem.h>
46#include <iprt/process.h>
47#include <iprt/path.h>
48#include <iprt/semaphore.h>
49#include <iprt/stream.h>
50#include <iprt/string.h>
51#include <iprt/thread.h>
52
53#include "VBoxAutostart.h"
54#include "PasswordInput.h"
55
56
57/*********************************************************************************************************************************
58* Defined Constants And Macros *
59*********************************************************************************************************************************/
60/** The service name. */
61#define AUTOSTART_SERVICE_NAME "VBoxAutostartSvc"
62/** The service display name. */
63#define AUTOSTART_SERVICE_DISPLAY_NAME "VirtualBox Autostart Service"
64
65ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
66bool g_fVerbose = false;
67ComPtr<IVirtualBox> g_pVirtualBox = NULL;
68ComPtr<ISession> g_pSession = NULL;
69
70
71/*********************************************************************************************************************************
72* Global Variables *
73*********************************************************************************************************************************/
74/** The service control handler handle. */
75static SERVICE_STATUS_HANDLE g_hSupSvcWinCtrlHandler = NULL;
76/** The service status. */
77static uint32_t volatile g_u32SupSvcWinStatus = SERVICE_STOPPED;
78/** The semaphore the main service thread is waiting on in autostartSvcWinServiceMain. */
79static RTSEMEVENTMULTI g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
80/** The service name is used for send to service main. */
81static com::Bstr g_bstrServiceName;
82
83
84/*********************************************************************************************************************************
85* Internal Functions *
86*********************************************************************************************************************************/
87static SC_HANDLE autostartSvcWinOpenSCManager(const char *pszAction, DWORD dwAccess);
88
89static int autostartGetProcessDomainUser(com::Utf8Str &aUser)
90{
91 int rc = VERR_NOT_SUPPORTED;
92
93 RTUTF16 wszUsername[1024] = { 0 };
94 ULONG cwcUsername = RT_ELEMENTS(wszUsername);
95 char *pszUser = NULL;
96 if (!GetUserNameExW(NameSamCompatible, &wszUsername[0], &cwcUsername))
97 return RTErrConvertFromWin32(GetLastError());
98 rc = RTUtf16ToUtf8(wszUsername, &pszUser);
99 aUser = pszUser;
100 RTStrFree(pszUser);
101 return rc;
102}
103
104static int autostartGetLocalDomain(com::Utf8Str &aDomain)
105{
106 RTUTF16 pwszDomain[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
107 uint32_t cwcDomainSize = MAX_COMPUTERNAME_LENGTH + 1;
108 if (!GetComputerNameW(pwszDomain, (LPDWORD)&cwcDomainSize))
109 return RTErrConvertFromWin32(GetLastError());
110 char *pszDomain = NULL;
111 int rc = RTUtf16ToUtf8(pwszDomain, &pszDomain);
112 aDomain = pszDomain;
113 RTStrFree(pszDomain);
114 return rc;
115}
116
117static int autostartGetDomainAndUser(const com::Utf8Str &aDomainAndUser, com::Utf8Str &aDomain, com::Utf8Str &aUser)
118{
119 size_t offDelim = aDomainAndUser.find("\\");
120 if (offDelim != aDomainAndUser.npos)
121 {
122 // if only domain is specified
123 if (aDomainAndUser.length() - offDelim == 1)
124 return VERR_INVALID_PARAMETER;
125
126 if (offDelim == 1 && aDomainAndUser[0] == '.')
127 {
128 int rc = autostartGetLocalDomain(aDomain);
129 aUser = aDomainAndUser.substr(offDelim + 1);
130 return rc;
131 }
132 aDomain = aDomainAndUser.substr(0, offDelim);
133 aUser = aDomainAndUser.substr(offDelim + 1);
134 return VINF_SUCCESS;
135 }
136
137 offDelim = aDomainAndUser.find("@");
138 if (offDelim != aDomainAndUser.npos)
139 {
140 // if only domain is specified
141 if (offDelim == 0)
142 return VERR_INVALID_PARAMETER;
143
144 // with '@' but without domain
145 if (aDomainAndUser.length() - offDelim == 1)
146 {
147 int rc = autostartGetLocalDomain(aDomain);
148 aUser = aDomainAndUser.substr(0, offDelim);
149 return rc;
150 }
151 aDomain = aDomainAndUser.substr(offDelim + 1);
152 aUser = aDomainAndUser.substr(0, offDelim);
153 return VINF_SUCCESS;
154 }
155
156 // only user is specified
157 int rc = autostartGetLocalDomain(aDomain);
158 aUser = aDomainAndUser;
159 return rc;
160}
161
162/** Common helper for formatting the service name. */
163static void autostartFormatServiceName(const com::Utf8Str &aDomain, const com::Utf8Str &aUser, com::Utf8Str &aServiceName)
164{
165 aServiceName.printf("%s%s%s", AUTOSTART_SERVICE_NAME, aDomain.c_str(), aUser.c_str());
166}
167
168/** Used by the delete service operation. */
169static int autostartGetServiceName(const com::Utf8Str &aDomainAndUser, com::Utf8Str &aServiceName)
170{
171 com::Utf8Str sDomain;
172 com::Utf8Str sUser;
173 int rc = autostartGetDomainAndUser(aDomainAndUser, sDomain, sUser);
174 if (RT_FAILURE(rc))
175 return rc;
176 autostartFormatServiceName(sDomain, sUser, aServiceName);
177 return VINF_SUCCESS;
178}
179
180/**
181 * Print out progress on the console.
182 *
183 * This runs the main event queue every now and then to prevent piling up
184 * unhandled things (which doesn't cause real problems, just makes things
185 * react a little slower than in the ideal case).
186 */
187DECLHIDDEN(HRESULT) showProgress(ComPtr<IProgress> progress)
188{
189 using namespace com;
190
191 BOOL fCompleted = FALSE;
192 ULONG uCurrentPercent = 0;
193 Bstr bstrOperationDescription;
194
195 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
196
197 ULONG cOperations = 1;
198 HRESULT hrc = progress->COMGETTER(OperationCount)(&cOperations);
199 if (FAILED(hrc))
200 return hrc;
201
202 /* setup signal handling if cancelable */
203 bool fCanceledAlready = false;
204 BOOL fCancelable;
205 hrc = progress->COMGETTER(Cancelable)(&fCancelable);
206 if (FAILED(hrc))
207 fCancelable = FALSE;
208
209 hrc = progress->COMGETTER(Completed(&fCompleted));
210 while (SUCCEEDED(hrc))
211 {
212 progress->COMGETTER(Percent(&uCurrentPercent));
213
214 if (fCompleted)
215 break;
216
217 /* process async cancelation */
218 if (!fCanceledAlready)
219 {
220 hrc = progress->Cancel();
221 if (SUCCEEDED(hrc))
222 fCanceledAlready = true;
223 }
224
225 /* make sure the loop is not too tight */
226 progress->WaitForCompletion(100);
227
228 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
229 hrc = progress->COMGETTER(Completed(&fCompleted));
230 }
231
232 /* complete the line. */
233 LONG iRc = E_FAIL;
234 hrc = progress->COMGETTER(ResultCode)(&iRc);
235 if (SUCCEEDED(hrc))
236 {
237 hrc = iRc;
238 }
239
240 return hrc;
241}
242
243DECLHIDDEN(void) autostartSvcOsLogStr(const char *pszMsg, AUTOSTARTLOGTYPE enmLogType)
244{
245 HANDLE hEventLog = RegisterEventSourceA(NULL /* local computer */, "VBoxAutostartSvc");
246 AssertReturnVoid(hEventLog != NULL);
247 WORD wType = 0;
248 const char *apsz[2];
249 apsz[0] = "VBoxAutostartSvc";
250 apsz[1] = pszMsg;
251
252 switch (enmLogType)
253 {
254 case AUTOSTARTLOGTYPE_INFO:
255 wType = 0;
256 break;
257 case AUTOSTARTLOGTYPE_ERROR:
258 wType = EVENTLOG_ERROR_TYPE;
259 break;
260 case AUTOSTARTLOGTYPE_WARNING:
261 wType = EVENTLOG_WARNING_TYPE;
262 break;
263 case AUTOSTARTLOGTYPE_VERBOSE:
264 if (!g_fVerbose)
265 return;
266 wType = EVENTLOG_INFORMATION_TYPE;
267 break;
268 default:
269 AssertMsgFailed(("Invalid log type %d\n", enmLogType));
270 }
271
272 BOOL fRc = ReportEventA(hEventLog, /* hEventLog */
273 wType, /* wType */
274 0, /* wCategory */
275 0 /** @todo mc */, /* dwEventID */
276 NULL, /* lpUserSid */
277 RT_ELEMENTS(apsz), /* wNumStrings */
278 0, /* dwDataSize */
279 apsz, /* lpStrings */
280 NULL); /* lpRawData */
281 AssertMsg(fRc, ("%u\n", GetLastError())); NOREF(fRc);
282 DeregisterEventSource(hEventLog);
283}
284
285/**
286 * Opens the service control manager.
287 *
288 * When this fails, an error message will be displayed.
289 *
290 * @returns Valid handle on success.
291 * NULL on failure, will display an error message.
292 *
293 * @param pszAction The action which is requesting access to SCM.
294 * @param dwAccess The desired access.
295 */
296static SC_HANDLE autostartSvcWinOpenSCManager(const char *pszAction, DWORD dwAccess)
297{
298 SC_HANDLE hSCM = OpenSCManager(NULL /* lpMachineName*/, NULL /* lpDatabaseName */, dwAccess);
299 if (hSCM == NULL)
300 {
301 DWORD err = GetLastError();
302 switch (err)
303 {
304 case ERROR_ACCESS_DENIED:
305 autostartSvcDisplayError("%s - OpenSCManager failure: access denied\n", pszAction);
306 break;
307 default:
308 autostartSvcDisplayError("%s - OpenSCManager failure: %d\n", pszAction, err);
309 break;
310 }
311 }
312 return hSCM;
313}
314
315
316/**
317 * Opens the service.
318 *
319 * Last error is preserved on failure and set to 0 on success.
320 *
321 * @returns Valid service handle on success.
322 * NULL on failure, will display an error message unless it's ignored.
323 *
324 * @param pszAction The action which is requesting access to the service.
325 * @param dwSCMAccess The service control manager access.
326 * @param dwSVCAccess The desired service access.
327 * @param cIgnoredErrors The number of ignored errors.
328 * @param ... Errors codes that should not cause a message to be displayed.
329 */
330static SC_HANDLE autostartSvcWinOpenService(const PRTUTF16 pwszServiceName, const char *pszAction, DWORD dwSCMAccess, DWORD dwSVCAccess,
331 unsigned cIgnoredErrors, ...)
332{
333 SC_HANDLE hSCM = autostartSvcWinOpenSCManager(pszAction, dwSCMAccess);
334 if (!hSCM)
335 return NULL;
336
337 SC_HANDLE hSvc = OpenServiceW(hSCM, pwszServiceName, dwSVCAccess);
338 if (hSvc)
339 {
340 CloseServiceHandle(hSCM);
341 SetLastError(0);
342 }
343 else
344 {
345 DWORD err = GetLastError();
346 bool fIgnored = false;
347 va_list va;
348 va_start(va, cIgnoredErrors);
349 while (!fIgnored && cIgnoredErrors-- > 0)
350 fIgnored = (DWORD)va_arg(va, int) == err;
351 va_end(va);
352 if (!fIgnored)
353 {
354 switch (err)
355 {
356 case ERROR_ACCESS_DENIED:
357 autostartSvcDisplayError("%s - OpenService failure: access denied\n", pszAction);
358 break;
359 case ERROR_SERVICE_DOES_NOT_EXIST:
360 autostartSvcDisplayError("%s - OpenService failure: The service %ls does not exist. Reinstall it.\n",
361 pszAction, pwszServiceName);
362 break;
363 default:
364 autostartSvcDisplayError("%s - OpenService failure: %d\n", pszAction, err);
365 break;
366 }
367 }
368
369 CloseServiceHandle(hSCM);
370 SetLastError(err);
371 }
372 return hSvc;
373}
374
375static RTEXITCODE autostartSvcWinInterrogate(int argc, char **argv)
376{
377 RT_NOREF(argc, argv);
378 RTPrintf("VBoxAutostartSvc: The \"interrogate\" action is not implemented.\n");
379 return RTEXITCODE_FAILURE;
380}
381
382
383static RTEXITCODE autostartSvcWinStop(int argc, char **argv)
384{
385 RT_NOREF(argc, argv);
386 RTPrintf("VBoxAutostartSvc: The \"stop\" action is not implemented.\n");
387 return RTEXITCODE_FAILURE;
388}
389
390
391static RTEXITCODE autostartSvcWinContinue(int argc, char **argv)
392{
393 RT_NOREF(argc, argv);
394 RTPrintf("VBoxAutostartSvc: The \"continue\" action is not implemented.\n");
395 return RTEXITCODE_FAILURE;
396}
397
398
399static RTEXITCODE autostartSvcWinPause(int argc, char **argv)
400{
401 RT_NOREF(argc, argv);
402 RTPrintf("VBoxAutostartSvc: The \"pause\" action is not implemented.\n");
403 return RTEXITCODE_FAILURE;
404}
405
406
407static RTEXITCODE autostartSvcWinStart(int argc, char **argv)
408{
409 RT_NOREF(argc, argv);
410 RTPrintf("VBoxAutostartSvc: The \"start\" action is not implemented.\n");
411 return RTEXITCODE_SUCCESS;
412}
413
414
415static RTEXITCODE autostartSvcWinQueryDescription(int argc, char **argv)
416{
417 RT_NOREF(argc, argv);
418 RTPrintf("VBoxAutostartSvc: The \"qdescription\" action is not implemented.\n");
419 return RTEXITCODE_FAILURE;
420}
421
422
423static RTEXITCODE autostartSvcWinQueryConfig(int argc, char **argv)
424{
425 RT_NOREF(argc, argv);
426 RTPrintf("VBoxAutostartSvc: The \"qconfig\" action is not implemented.\n");
427 return RTEXITCODE_FAILURE;
428}
429
430
431static RTEXITCODE autostartSvcWinDisable(int argc, char **argv)
432{
433 RT_NOREF(argc, argv);
434 RTPrintf("VBoxAutostartSvc: The \"disable\" action is not implemented.\n");
435 return RTEXITCODE_FAILURE;
436}
437
438static RTEXITCODE autostartSvcWinEnable(int argc, char **argv)
439{
440 RT_NOREF(argc, argv);
441 RTPrintf("VBoxAutostartSvc: The \"enable\" action is not implemented.\n");
442 return RTEXITCODE_FAILURE;
443}
444
445
446/**
447 * Handle the 'delete' action.
448 *
449 * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
450 * @param argc The action argument count.
451 * @param argv The action argument vector.
452 */
453static int autostartSvcWinDelete(int argc, char **argv)
454{
455 /*
456 * Parse the arguments.
457 */
458 bool fVerbose = false;
459 const char *pszUser = NULL;
460 static const RTGETOPTDEF s_aOptions[] =
461 {
462 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
463 { "--user", 'u', RTGETOPT_REQ_STRING },
464 };
465 int ch;
466 RTGETOPTUNION Value;
467 RTGETOPTSTATE GetState;
468 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
469 while ((ch = RTGetOpt(&GetState, &Value)))
470 {
471 switch (ch)
472 {
473 case 'v':
474 fVerbose = true;
475 break;
476 case 'u':
477 pszUser = Value.psz;
478 break;
479 default:
480 return autostartSvcDisplayGetOptError("delete", ch, &Value);
481 }
482 }
483
484 if (!pszUser)
485 return autostartSvcDisplayError("delete - DeleteService failed, user name required.\n");
486
487 com::Utf8Str sServiceName;
488 int vrc = autostartGetServiceName(pszUser, sServiceName);
489 if (RT_FAILURE(vrc))
490 return autostartSvcDisplayError("delete - DeleteService failed, service name for user %s can not be constructed.\n",
491 pszUser);
492 /*
493 * Create the service.
494 */
495 RTEXITCODE rc = RTEXITCODE_FAILURE;
496 SC_HANDLE hSvc = autostartSvcWinOpenService(com::Bstr(sServiceName).raw(), "delete", SERVICE_CHANGE_CONFIG, DELETE,
497 1, ERROR_SERVICE_DOES_NOT_EXIST);
498 if (hSvc)
499 {
500 if (DeleteService(hSvc))
501 {
502 RTPrintf("Successfully deleted the %s service.\n", sServiceName.c_str());
503 rc = RTEXITCODE_SUCCESS;
504 }
505 else
506 autostartSvcDisplayError("delete - DeleteService failed, err=%d.\n", GetLastError());
507 CloseServiceHandle(hSvc);
508 }
509 else if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST)
510 {
511
512 if (fVerbose)
513 RTPrintf("The service %s was not installed, nothing to be done.", sServiceName.c_str());
514 else
515 RTPrintf("Successfully deleted the %s service.\n", sServiceName.c_str());
516 rc = RTEXITCODE_SUCCESS;
517 }
518 return rc;
519}
520
521
522/**
523 * Handle the 'create' action.
524 *
525 * @returns 0 or 1.
526 * @param argc The action argument count.
527 * @param argv The action argument vector.
528 */
529static RTEXITCODE autostartSvcWinCreate(int argc, char **argv)
530{
531 /*
532 * Parse the arguments.
533 */
534 bool fVerbose = false;
535 const char *pszUser = NULL;
536 com::Utf8Str strPwd;
537 const char *pszPwdFile = NULL;
538 static const RTGETOPTDEF s_aOptions[] =
539 {
540 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
541 { "--user", 'u', RTGETOPT_REQ_STRING },
542 { "--password-file", 'p', RTGETOPT_REQ_STRING }
543 };
544 int ch;
545 RTGETOPTUNION Value;
546 RTGETOPTSTATE GetState;
547 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
548 while ((ch = RTGetOpt(&GetState, &Value)))
549 {
550 switch (ch)
551 {
552 case 'v':
553 fVerbose = true;
554 break;
555 case 'u':
556 pszUser = Value.psz;
557 break;
558 case 'p':
559 pszPwdFile = Value.psz;
560 break;
561 default:
562 return autostartSvcDisplayGetOptError("create", ch, &Value);
563 }
564 }
565
566 if (!pszUser)
567 return autostartSvcDisplayError("Username is missing");
568
569 if (pszPwdFile)
570 {
571 /* Get password from file. */
572 RTEXITCODE rcExit = readPasswordFile(pszPwdFile, &strPwd);
573 if (rcExit == RTEXITCODE_FAILURE)
574 return rcExit;
575 }
576 else
577 {
578 /* Get password from console. */
579 RTEXITCODE rcExit = readPasswordFromConsole(&strPwd, "Enter password:");
580 if (rcExit == RTEXITCODE_FAILURE)
581 return rcExit;
582 }
583
584 if (strPwd.isEmpty())
585 return autostartSvcDisplayError("Password is missing");
586
587 com::Utf8Str sDomain;
588 com::Utf8Str sUserTmp;
589 int vrc = autostartGetDomainAndUser(pszUser, sDomain, sUserTmp);
590 if (RT_FAILURE(vrc))
591 return autostartSvcDisplayError("create - CreateService failed, failed to get domain and user from string %s (%d).\n",
592 pszUser, vrc);
593 com::Utf8StrFmt sUserFullName("%s\\%s", sDomain.c_str(), sUserTmp.c_str());
594 com::Utf8StrFmt sDisplayName("%s %s@%s", AUTOSTART_SERVICE_DISPLAY_NAME, sUserTmp.c_str(), sDomain.c_str());
595 com::Utf8Str sServiceName;
596 autostartFormatServiceName(sDomain, sUserTmp, sServiceName);
597
598 /*
599 * Create the service.
600 */
601 RTEXITCODE rc = RTEXITCODE_FAILURE;
602 SC_HANDLE hSCM = autostartSvcWinOpenSCManager("create", SC_MANAGER_CREATE_SERVICE); /*SC_MANAGER_ALL_ACCESS*/
603 if (hSCM)
604 {
605 char szExecPath[RTPATH_MAX];
606 if (RTProcGetExecutablePath(szExecPath, sizeof(szExecPath)))
607 {
608 if (fVerbose)
609 RTPrintf("Creating the %s service, binary \"%s\"...\n",
610 sServiceName.c_str(), szExecPath); /* yea, the binary name isn't UTF-8, but wtf. */
611
612 /*
613 * Add service name as command line parameter for the service
614 */
615 com::Utf8StrFmt sCmdLine("\"%s\" --service=%s", szExecPath, sServiceName.c_str());
616 com::Bstr bstrServiceName(sServiceName);
617 com::Bstr bstrDisplayName(sDisplayName);
618 com::Bstr bstrCmdLine(sCmdLine);
619 com::Bstr bstrUserFullName(sUserFullName);
620 com::Bstr bstrPwd(strPwd);
621
622 SC_HANDLE hSvc = CreateServiceW(hSCM, /* hSCManager */
623 bstrServiceName.raw(), /* lpServiceName */
624 bstrDisplayName.raw(), /* lpDisplayName */
625 SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, /* dwDesiredAccess */
626 SERVICE_WIN32_OWN_PROCESS, /* dwServiceType ( | SERVICE_INTERACTIVE_PROCESS? ) */
627 SERVICE_AUTO_START, /* dwStartType */
628 SERVICE_ERROR_NORMAL, /* dwErrorControl */
629 bstrCmdLine.raw(), /* lpBinaryPathName */
630 NULL, /* lpLoadOrderGroup */
631 NULL, /* lpdwTagId */
632 NULL, /* lpDependencies */
633 bstrUserFullName.raw(), /* lpServiceStartName (NULL => LocalSystem) */
634 bstrPwd.raw()); /* lpPassword */
635 if (hSvc)
636 {
637 RTPrintf("Successfully created the %s service.\n", sServiceName.c_str());
638 /** @todo Set the service description or it'll look weird in the vista service manager.
639 * Anything else that should be configured? Start access or something? */
640 rc = RTEXITCODE_SUCCESS;
641 CloseServiceHandle(hSvc);
642 }
643 else
644 {
645 DWORD err = GetLastError();
646 switch (err)
647 {
648 case ERROR_SERVICE_EXISTS:
649 autostartSvcDisplayError("create - The service already exists.\n");
650 break;
651 default:
652 autostartSvcDisplayError("create - CreateService failed, err=%d.\n", GetLastError());
653 break;
654 }
655 }
656 CloseServiceHandle(hSvc);
657 }
658 else
659 autostartSvcDisplayError("create - Failed to obtain the executable path: %d\n", GetLastError());
660 }
661 return rc;
662}
663
664
665/**
666 * Sets the service status, just a SetServiceStatus Wrapper.
667 *
668 * @returns See SetServiceStatus.
669 * @param dwStatus The current status.
670 * @param iWaitHint The wait hint, if < 0 then supply a default.
671 * @param dwExitCode The service exit code.
672 */
673static bool autostartSvcWinSetServiceStatus(DWORD dwStatus, int iWaitHint, DWORD dwExitCode)
674{
675 SERVICE_STATUS SvcStatus;
676 SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
677 SvcStatus.dwWin32ExitCode = dwExitCode;
678 SvcStatus.dwServiceSpecificExitCode = 0;
679 SvcStatus.dwWaitHint = iWaitHint >= 0 ? iWaitHint : 3000;
680 SvcStatus.dwCurrentState = dwStatus;
681 LogFlow(("autostartSvcWinSetServiceStatus: %d -> %d\n", g_u32SupSvcWinStatus, dwStatus));
682 g_u32SupSvcWinStatus = dwStatus;
683 switch (dwStatus)
684 {
685 case SERVICE_START_PENDING:
686 SvcStatus.dwControlsAccepted = 0;
687 break;
688 default:
689 SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
690 break;
691 }
692
693 static DWORD dwCheckPoint = 0;
694 switch (dwStatus)
695 {
696 case SERVICE_RUNNING:
697 case SERVICE_STOPPED:
698 SvcStatus.dwCheckPoint = 0;
699 default:
700 SvcStatus.dwCheckPoint = ++dwCheckPoint;
701 break;
702 }
703 return SetServiceStatus(g_hSupSvcWinCtrlHandler, &SvcStatus) != FALSE;
704}
705
706
707/**
708 * Service control handler (extended).
709 *
710 * @returns Windows status (see HandlerEx).
711 * @retval NO_ERROR if handled.
712 * @retval ERROR_CALL_NOT_IMPLEMENTED if not handled.
713 *
714 * @param dwControl The control code.
715 * @param dwEventType Event type. (specific to the control?)
716 * @param pvEventData Event data, specific to the event.
717 * @param pvContext The context pointer registered with the handler.
718 * Currently not used.
719 */
720static DWORD WINAPI autostartSvcWinServiceCtrlHandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID pvEventData, LPVOID pvContext)
721{
722 LogFlow(("autostartSvcWinServiceCtrlHandlerEx: dwControl=%#x dwEventType=%#x pvEventData=%p\n",
723 dwControl, dwEventType, pvEventData));
724
725 switch (dwControl)
726 {
727 /*
728 * Interrogate the service about it's current status.
729 * MSDN says that this should just return NO_ERROR and does
730 * not need to set the status again.
731 */
732 case SERVICE_CONTROL_INTERROGATE:
733 return NO_ERROR;
734
735 /*
736 * Request to stop the service.
737 */
738 case SERVICE_CONTROL_STOP:
739 {
740 /*
741 * Check if the real services can be stopped and then tell them to stop.
742 */
743 autostartSvcWinSetServiceStatus(SERVICE_STOP_PENDING, 3000, NO_ERROR);
744 /*
745 * Notify the main thread that we're done, it will wait for the
746 * VMs to stop, and set the windows service status to SERVICE_STOPPED
747 * and return.
748 */
749 int rc = RTSemEventMultiSignal(g_hSupSvcWinEvent);
750 if (RT_FAILURE(rc))
751 autostartSvcLogError("SERVICE_CONTROL_STOP: RTSemEventMultiSignal failed, %Rrc\n", rc);
752
753 return NO_ERROR;
754 }
755
756 case SERVICE_CONTROL_PAUSE:
757 case SERVICE_CONTROL_CONTINUE:
758 case SERVICE_CONTROL_SHUTDOWN:
759 case SERVICE_CONTROL_PARAMCHANGE:
760 case SERVICE_CONTROL_NETBINDADD:
761 case SERVICE_CONTROL_NETBINDREMOVE:
762 case SERVICE_CONTROL_NETBINDENABLE:
763 case SERVICE_CONTROL_NETBINDDISABLE:
764 case SERVICE_CONTROL_DEVICEEVENT:
765 case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
766 case SERVICE_CONTROL_POWEREVENT:
767 case SERVICE_CONTROL_SESSIONCHANGE:
768#ifdef SERVICE_CONTROL_PRESHUTDOWN /* vista */
769 case SERVICE_CONTROL_PRESHUTDOWN:
770#endif
771 default:
772 return ERROR_CALL_NOT_IMPLEMENTED;
773 }
774
775 NOREF(dwEventType);
776 NOREF(pvEventData);
777 NOREF(pvContext);
778 /* not reached */
779}
780
781static int autostartStartVMs()
782{
783 int rc = autostartSetup();
784
785 const char *pszConfigFile = RTEnvGet("VBOXAUTOSTART_CONFIG");
786 if (!pszConfigFile)
787 return autostartSvcLogError("Starting VMs failed. VBOXAUTOSTART_CONFIG environment variable is not defined.\n");
788 bool fAllow = false;
789
790 PCFGAST pCfgAst = NULL;
791 rc = autostartParseConfig(pszConfigFile, &pCfgAst);
792 if (RT_FAILURE(rc))
793 return autostartSvcLogError("Starting VMs failed. Failed to parse the config file. Check the access permissions and file structure.\n");
794
795 PCFGAST pCfgAstPolicy = autostartConfigAstGetByName(pCfgAst, "default_policy");
796 /* Check default policy. */
797 if (pCfgAstPolicy)
798 {
799 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
800 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow")
801 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "deny")))
802 {
803 if (!RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow"))
804 fAllow = true;
805 }
806 else
807 {
808 autostartConfigAstDestroy(pCfgAst);
809 return autostartSvcLogError("'default_policy' must be either 'allow' or 'deny'.\n");
810 }
811 }
812
813 com::Utf8Str sUser;
814 rc = autostartGetProcessDomainUser(sUser);
815 if (RT_FAILURE(rc))
816 {
817 autostartConfigAstDestroy(pCfgAst);
818 return autostartSvcLogError("Failed to query username of the process (%Rrc).\n", rc);
819 }
820
821 PCFGAST pCfgAstUser = NULL;
822 for (unsigned i = 0; i < pCfgAst->u.Compound.cAstNodes; i++)
823 {
824 PCFGAST pNode = pCfgAst->u.Compound.apAstNodes[i];
825 com::Utf8Str sDomain;
826 com::Utf8Str sUserTmp;
827 int rc = autostartGetDomainAndUser(pNode->pszKey, sDomain, sUserTmp);
828 if (RT_FAILURE(rc))
829 continue;
830 com::Utf8StrFmt sDomainUser("%s\\%s", sDomain.c_str(), sUserTmp.c_str());
831 if (sDomainUser == sUser)
832 {
833 pCfgAstUser = pNode;
834 break;
835 }
836 }
837
838 if ( pCfgAstUser
839 && pCfgAstUser->enmType == CFGASTNODETYPE_COMPOUND)
840 {
841 pCfgAstPolicy = autostartConfigAstGetByName(pCfgAstUser, "allow");
842 if (pCfgAstPolicy)
843 {
844 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
845 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true")
846 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "false")))
847 fAllow = RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true") == 0;
848 else
849 {
850 autostartConfigAstDestroy(pCfgAst);
851 return autostartSvcLogError("'allow' must be either 'true' or 'false'.\n");
852 }
853 }
854 }
855 else if (pCfgAstUser)
856 {
857 autostartConfigAstDestroy(pCfgAst);
858 return autostartSvcLogError("Invalid config, user is not a compound node.\n");
859 }
860
861 if (!fAllow)
862 {
863 autostartConfigAstDestroy(pCfgAst);
864 return autostartSvcLogError("User is not allowed to autostart VMs.\n");
865 }
866
867 rc = autostartStartMain(pCfgAstUser);
868 autostartConfigAstDestroy(pCfgAst);
869 if (RT_FAILURE(rc))
870 autostartSvcLogError("Starting VMs failed, rc=%Rrc\n", rc);
871
872 return rc;
873}
874
875/**
876 * Windows Service Main.
877 *
878 * This is invoked when the service is started and should not return until
879 * the service has been stopped.
880 *
881 * @param cArgs Argument count.
882 * @param papwszArgs Argument vector.
883 */
884static VOID WINAPI autostartSvcWinServiceMain(DWORD cArgs, LPWSTR *papwszArgs)
885{
886 RT_NOREF(papwszArgs);
887 LogFlowFuncEnter();
888
889 /*
890 * Register the control handler function for the service and report to SCM.
891 */
892 Assert(g_u32SupSvcWinStatus == SERVICE_STOPPED);
893 g_hSupSvcWinCtrlHandler = RegisterServiceCtrlHandlerExW(g_bstrServiceName.raw(), autostartSvcWinServiceCtrlHandlerEx, NULL);
894 if (g_hSupSvcWinCtrlHandler)
895 {
896 DWORD err = ERROR_GEN_FAILURE;
897 if (autostartSvcWinSetServiceStatus(SERVICE_START_PENDING, 3000, NO_ERROR))
898 {
899 if (cArgs == 1)
900 {
901 /*
902 * Create the event semaphore we'll be waiting on and
903 * then instantiate the actual services.
904 */
905 int rc = RTSemEventMultiCreate(&g_hSupSvcWinEvent);
906 if (RT_SUCCESS(rc))
907 {
908 /*
909 * Update the status and enter the work loop.
910 */
911 if (autostartSvcWinSetServiceStatus(SERVICE_RUNNING, 0, 0))
912 {
913 LogFlow(("autostartSvcWinServiceMain: calling autostartStartVMs\n"));
914 rc = autostartStartVMs();
915 if (RT_SUCCESS(rc))
916 {
917 LogFlow(("autostartSvcWinServiceMain: done string VMs\n"));
918 err = NO_ERROR;
919 rc = RTSemEventMultiWait(g_hSupSvcWinEvent, RT_INDEFINITE_WAIT);
920 if (RT_SUCCESS(rc))
921 {
922 LogFlow(("autostartSvcWinServiceMain: woke up\n"));
923 /** @todo Autostop part. */
924 err = NO_ERROR;
925 }
926 else
927 autostartSvcLogError("RTSemEventWait failed, rc=%Rrc", rc);
928 }
929
930 autostartShutdown();
931 }
932 else
933 {
934 err = GetLastError();
935 autostartSvcLogError("SetServiceStatus failed, err=%u", err);
936 }
937
938 RTSemEventMultiDestroy(g_hSupSvcWinEvent);
939 g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
940 }
941 else
942 autostartSvcLogError("RTSemEventMultiCreate failed, rc=%Rrc", rc);
943 }
944 else
945 autostartSvcLogTooManyArgsError("main", cArgs, NULL, 0);
946 }
947 else
948 {
949 err = GetLastError();
950 autostartSvcLogError("SetServiceStatus failed, err=%u", err);
951 }
952 autostartSvcWinSetServiceStatus(SERVICE_STOPPED, 0, err);
953 }
954 else
955 autostartSvcLogError("RegisterServiceCtrlHandlerEx failed, err=%u", GetLastError());
956
957 LogFlowFuncLeave();
958}
959
960
961/**
962 * Handle the 'create' action.
963 *
964 * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
965 * @param argc The action argument count.
966 * @param argv The action argument vector.
967 */
968static int autostartSvcWinRunIt(int argc, char **argv)
969{
970 LogFlowFuncEnter();
971
972 /*
973 * Initialize release logging.
974 */
975 /** @todo release logging of the system-wide service. */
976
977 /*
978 * Parse the arguments.
979 */
980 static const RTGETOPTDEF s_aOptions[] =
981 {
982 { "--service", 's', RTGETOPT_REQ_STRING },
983 };
984
985 const char *pszServiceName = NULL;
986 int ch;
987 RTGETOPTUNION Value;
988 RTGETOPTSTATE GetState;
989 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
990 while ((ch = RTGetOpt(&GetState, &Value)))
991 {
992 switch (ch)
993 {
994 case 's':
995 pszServiceName = Value.psz;
996 try
997 {
998 g_bstrServiceName = com::Bstr(Value.psz);
999 }
1000 catch (...)
1001 {
1002 autostartSvcLogError("runit failed, service name is not valid utf-8 string or out of memory");
1003 return RTEXITCODE_FAILURE;
1004 }
1005 break;
1006 default:
1007 return autostartSvcDisplayGetOptError("runit", ch, &Value);
1008 }
1009 }
1010
1011 if (!pszServiceName)
1012 {
1013 autostartSvcLogError("runit failed, service name is missing");
1014 return RTEXITCODE_FAILURE;
1015 }
1016
1017 /*
1018 * Register the service with the service control manager
1019 * and start dispatching requests from it (all done by the API).
1020 */
1021 SERVICE_TABLE_ENTRYW const s_aServiceStartTable[] =
1022 {
1023 { g_bstrServiceName.raw(), autostartSvcWinServiceMain },
1024 { NULL, NULL}
1025 };
1026 if (StartServiceCtrlDispatcherW(&s_aServiceStartTable[0]))
1027 {
1028 LogFlowFuncLeave();
1029 return RTEXITCODE_SUCCESS; /* told to quit, so quit. */
1030 }
1031
1032 DWORD err = GetLastError();
1033 switch (err)
1034 {
1035 case ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
1036 autostartSvcWinServiceMain(0, NULL);//autostartSvcDisplayError("Cannot run a service from the command line. Use the 'start' action to start it the right way.\n");
1037 break;
1038 default:
1039 autostartSvcLogError("StartServiceCtrlDispatcher failed, err=%u", err);
1040 break;
1041 }
1042 return RTEXITCODE_FAILURE;
1043}
1044
1045
1046/**
1047 * Show the version info.
1048 *
1049 * @returns RTEXITCODE_SUCCESS.
1050 */
1051static RTEXITCODE autostartSvcWinShowVersion(int argc, char **argv)
1052{
1053 /*
1054 * Parse the arguments.
1055 */
1056 bool fBrief = false;
1057 static const RTGETOPTDEF s_aOptions[] =
1058 {
1059 { "--brief", 'b', RTGETOPT_REQ_NOTHING }
1060 };
1061 int ch;
1062 RTGETOPTUNION Value;
1063 RTGETOPTSTATE GetState;
1064 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1065 while ((ch = RTGetOpt(&GetState, &Value)))
1066 switch (ch)
1067 {
1068 case 'b': fBrief = true; break;
1069 default: return autostartSvcDisplayGetOptError("version", ch, &Value);
1070 }
1071
1072 /*
1073 * Do the printing.
1074 */
1075 if (fBrief)
1076 RTPrintf("%s\n", VBOX_VERSION_STRING);
1077 else
1078 RTPrintf("VirtualBox Autostart Service Version %s\n"
1079 "(C) 2012 Oracle Corporation\n"
1080 "All rights reserved.\n",
1081 VBOX_VERSION_STRING);
1082 return RTEXITCODE_SUCCESS;
1083}
1084
1085
1086/**
1087 * Show the usage help screen.
1088 *
1089 * @returns RTEXITCODE_SUCCESS.
1090 */
1091static RTEXITCODE autostartSvcWinShowHelp(void)
1092{
1093 RTPrintf("VirtualBox Autostart Service Version %s\n"
1094 "(C) 2012 Oracle Corporation\n"
1095 "All rights reserved.\n"
1096 "\n",
1097 VBOX_VERSION_STRING);
1098 RTPrintf("Usage:\n"
1099 "\n"
1100 "VBoxAutostartSvc\n"
1101 " Runs the service.\n"
1102 "VBoxAutostartSvc <version|-v|--version> [-brief]\n"
1103 " Displays the version.\n"
1104 "VBoxAutostartSvc <help|-?|-h|--help> [...]\n"
1105 " Displays this help screen.\n"
1106 "\n"
1107 "VBoxAutostartSvc <install|/RegServer|/i>\n"
1108 " Installs the service.\n"
1109 "VBoxAutostartSvc <uninstall|delete|/UnregServer|/u>\n"
1110 " Uninstalls the service.\n"
1111 );
1112 return RTEXITCODE_SUCCESS;
1113}
1114
1115
1116/**
1117 * VBoxAutostart main(), Windows edition.
1118 *
1119 *
1120 * @returns 0 on success.
1121 *
1122 * @param argc Number of arguments in argv.
1123 * @param argv Argument vector.
1124 */
1125int main(int argc, char **argv)
1126{
1127 /*
1128 * Initialize the IPRT first of all.
1129 */
1130 int rc = RTR3InitExe(argc, &argv, 0);
1131 if (RT_FAILURE(rc))
1132 {
1133 autostartSvcLogError("RTR3InitExe failed with rc=%Rrc", rc);
1134 return RTEXITCODE_FAILURE;
1135 }
1136
1137 RTThreadSleep(10 * 1000);
1138
1139 /*
1140 * Parse the initial arguments to determine the desired action.
1141 */
1142 enum
1143 {
1144 kAutoSvcAction_RunIt,
1145
1146 kAutoSvcAction_Create,
1147 kAutoSvcAction_Delete,
1148
1149 kAutoSvcAction_Enable,
1150 kAutoSvcAction_Disable,
1151 kAutoSvcAction_QueryConfig,
1152 kAutoSvcAction_QueryDescription,
1153
1154 kAutoSvcAction_Start,
1155 kAutoSvcAction_Pause,
1156 kAutoSvcAction_Continue,
1157 kAutoSvcAction_Stop,
1158 kAutoSvcAction_Interrogate,
1159
1160 kAutoSvcAction_End
1161 } enmAction = kAutoSvcAction_RunIt;
1162 int iArg = 1;
1163 if (argc > 1)
1164 {
1165 if ( !stricmp(argv[iArg], "/RegServer")
1166 || !stricmp(argv[iArg], "install")
1167 || !stricmp(argv[iArg], "/i"))
1168 enmAction = kAutoSvcAction_Create;
1169 else if ( !stricmp(argv[iArg], "/UnregServer")
1170 || !stricmp(argv[iArg], "/u")
1171 || !stricmp(argv[iArg], "uninstall")
1172 || !stricmp(argv[iArg], "delete"))
1173 enmAction = kAutoSvcAction_Delete;
1174
1175 else if (!stricmp(argv[iArg], "enable"))
1176 enmAction = kAutoSvcAction_Enable;
1177 else if (!stricmp(argv[iArg], "disable"))
1178 enmAction = kAutoSvcAction_Disable;
1179 else if (!stricmp(argv[iArg], "qconfig"))
1180 enmAction = kAutoSvcAction_QueryConfig;
1181 else if (!stricmp(argv[iArg], "qdescription"))
1182 enmAction = kAutoSvcAction_QueryDescription;
1183
1184 else if ( !stricmp(argv[iArg], "start")
1185 || !stricmp(argv[iArg], "/t"))
1186 enmAction = kAutoSvcAction_Start;
1187 else if (!stricmp(argv[iArg], "pause"))
1188 enmAction = kAutoSvcAction_Start;
1189 else if (!stricmp(argv[iArg], "continue"))
1190 enmAction = kAutoSvcAction_Continue;
1191 else if (!stricmp(argv[iArg], "stop"))
1192 enmAction = kAutoSvcAction_Stop;
1193 else if (!stricmp(argv[iArg], "interrogate"))
1194 enmAction = kAutoSvcAction_Interrogate;
1195 else if ( !stricmp(argv[iArg], "help")
1196 || !stricmp(argv[iArg], "?")
1197 || !stricmp(argv[iArg], "/?")
1198 || !stricmp(argv[iArg], "-?")
1199 || !stricmp(argv[iArg], "/h")
1200 || !stricmp(argv[iArg], "-h")
1201 || !stricmp(argv[iArg], "/help")
1202 || !stricmp(argv[iArg], "-help")
1203 || !stricmp(argv[iArg], "--help"))
1204 return autostartSvcWinShowHelp();
1205 else if ( !stricmp(argv[iArg], "version")
1206 || !stricmp(argv[iArg], "/v")
1207 || !stricmp(argv[iArg], "-v")
1208 || !stricmp(argv[iArg], "/version")
1209 || !stricmp(argv[iArg], "-version")
1210 || !stricmp(argv[iArg], "--version"))
1211 return autostartSvcWinShowVersion(argc - iArg - 1, argv + iArg + 1);
1212 else
1213 iArg--;
1214 iArg++;
1215 }
1216
1217 /*
1218 * Dispatch it.
1219 */
1220 switch (enmAction)
1221 {
1222 case kAutoSvcAction_RunIt:
1223 return autostartSvcWinRunIt(argc - iArg, argv + iArg);
1224
1225 case kAutoSvcAction_Create:
1226 return autostartSvcWinCreate(argc - iArg, argv + iArg);
1227 case kAutoSvcAction_Delete:
1228 return autostartSvcWinDelete(argc - iArg, argv + iArg);
1229
1230 case kAutoSvcAction_Enable:
1231 return autostartSvcWinEnable(argc - iArg, argv + iArg);
1232 case kAutoSvcAction_Disable:
1233 return autostartSvcWinDisable(argc - iArg, argv + iArg);
1234 case kAutoSvcAction_QueryConfig:
1235 return autostartSvcWinQueryConfig(argc - iArg, argv + iArg);
1236 case kAutoSvcAction_QueryDescription:
1237 return autostartSvcWinQueryDescription(argc - iArg, argv + iArg);
1238
1239 case kAutoSvcAction_Start:
1240 return autostartSvcWinStart(argc - iArg, argv + iArg);
1241 case kAutoSvcAction_Pause:
1242 return autostartSvcWinPause(argc - iArg, argv + iArg);
1243 case kAutoSvcAction_Continue:
1244 return autostartSvcWinContinue(argc - iArg, argv + iArg);
1245 case kAutoSvcAction_Stop:
1246 return autostartSvcWinStop(argc - iArg, argv + iArg);
1247 case kAutoSvcAction_Interrogate:
1248 return autostartSvcWinInterrogate(argc - iArg, argv + iArg);
1249
1250 default:
1251 AssertMsgFailed(("enmAction=%d\n", enmAction));
1252 return RTEXITCODE_FAILURE;
1253 }
1254}
1255
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