VirtualBox

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

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

Main: bugref:9341: Fixed some scm errors

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 42.0 KB
Line 
1/* $Id: VBoxAutostart-win.cpp 80573 2019-09-04 05:54:47Z vboxsync $ */
2/** @file
3 * VirtualBox Autostart Service - Windows Specific Code.
4 */
5
6/*
7 * Copyright (C) 2012-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#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 SC_HANDLE hSvc = CreateServiceW(hSCM, /* hSCManager */
617 com::Bstr(sServiceName).raw(), /* lpServiceName */
618 com::Bstr(sDisplayName).raw(), /* lpDisplayName */
619 SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, /* dwDesiredAccess */
620 SERVICE_WIN32_OWN_PROCESS, /* dwServiceType ( | SERVICE_INTERACTIVE_PROCESS? ) */
621 SERVICE_AUTO_START, /* dwStartType */
622 SERVICE_ERROR_NORMAL, /* dwErrorControl */
623 com::Bstr(sCmdLine).raw(), /* lpBinaryPathName */
624 NULL, /* lpLoadOrderGroup */
625 NULL, /* lpdwTagId */
626 NULL, /* lpDependencies */
627 com::Bstr(sUserFullName).raw(), /* lpServiceStartName (NULL => LocalSystem) */
628 com::Bstr(strPwd).raw()); /* lpPassword */
629 if (hSvc)
630 {
631 RTPrintf("Successfully created the %s service.\n", sServiceName.c_str());
632 /** @todo Set the service description or it'll look weird in the vista service manager.
633 * Anything else that should be configured? Start access or something? */
634 rc = RTEXITCODE_SUCCESS;
635 CloseServiceHandle(hSvc);
636 }
637 else
638 {
639 DWORD err = GetLastError();
640 switch (err)
641 {
642 case ERROR_SERVICE_EXISTS:
643 autostartSvcDisplayError("create - The service already exists.\n");
644 break;
645 default:
646 autostartSvcDisplayError("create - CreateService failed, err=%d.\n", GetLastError());
647 break;
648 }
649 }
650 CloseServiceHandle(hSvc);
651 }
652 else
653 autostartSvcDisplayError("create - Failed to obtain the executable path: %d\n", GetLastError());
654 }
655 return rc;
656}
657
658
659/**
660 * Sets the service status, just a SetServiceStatus Wrapper.
661 *
662 * @returns See SetServiceStatus.
663 * @param dwStatus The current status.
664 * @param iWaitHint The wait hint, if < 0 then supply a default.
665 * @param dwExitCode The service exit code.
666 */
667static bool autostartSvcWinSetServiceStatus(DWORD dwStatus, int iWaitHint, DWORD dwExitCode)
668{
669 SERVICE_STATUS SvcStatus;
670 SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
671 SvcStatus.dwWin32ExitCode = dwExitCode;
672 SvcStatus.dwServiceSpecificExitCode = 0;
673 SvcStatus.dwWaitHint = iWaitHint >= 0 ? iWaitHint : 3000;
674 SvcStatus.dwCurrentState = dwStatus;
675 LogFlow(("autostartSvcWinSetServiceStatus: %d -> %d\n", g_u32SupSvcWinStatus, dwStatus));
676 g_u32SupSvcWinStatus = dwStatus;
677 switch (dwStatus)
678 {
679 case SERVICE_START_PENDING:
680 SvcStatus.dwControlsAccepted = 0;
681 break;
682 default:
683 SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
684 break;
685 }
686
687 static DWORD dwCheckPoint = 0;
688 switch (dwStatus)
689 {
690 case SERVICE_RUNNING:
691 case SERVICE_STOPPED:
692 SvcStatus.dwCheckPoint = 0;
693 default:
694 SvcStatus.dwCheckPoint = ++dwCheckPoint;
695 break;
696 }
697 return SetServiceStatus(g_hSupSvcWinCtrlHandler, &SvcStatus) != FALSE;
698}
699
700
701/**
702 * Service control handler (extended).
703 *
704 * @returns Windows status (see HandlerEx).
705 * @retval NO_ERROR if handled.
706 * @retval ERROR_CALL_NOT_IMPLEMENTED if not handled.
707 *
708 * @param dwControl The control code.
709 * @param dwEventType Event type. (specific to the control?)
710 * @param pvEventData Event data, specific to the event.
711 * @param pvContext The context pointer registered with the handler.
712 * Currently not used.
713 */
714static DWORD WINAPI autostartSvcWinServiceCtrlHandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID pvEventData, LPVOID pvContext)
715{
716 LogFlow(("autostartSvcWinServiceCtrlHandlerEx: dwControl=%#x dwEventType=%#x pvEventData=%p\n",
717 dwControl, dwEventType, pvEventData));
718
719 switch (dwControl)
720 {
721 /*
722 * Interrogate the service about it's current status.
723 * MSDN says that this should just return NO_ERROR and does
724 * not need to set the status again.
725 */
726 case SERVICE_CONTROL_INTERROGATE:
727 return NO_ERROR;
728
729 /*
730 * Request to stop the service.
731 */
732 case SERVICE_CONTROL_STOP:
733 {
734 /*
735 * Check if the real services can be stopped and then tell them to stop.
736 */
737 autostartSvcWinSetServiceStatus(SERVICE_STOP_PENDING, 3000, NO_ERROR);
738 /*
739 * Notify the main thread that we're done, it will wait for the
740 * VMs to stop, and set the windows service status to SERVICE_STOPPED
741 * and return.
742 */
743 int rc = RTSemEventMultiSignal(g_hSupSvcWinEvent);
744 if (RT_FAILURE(rc))
745 autostartSvcLogError("SERVICE_CONTROL_STOP: RTSemEventMultiSignal failed, %Rrc\n", rc);
746
747 return NO_ERROR;
748 }
749
750 case SERVICE_CONTROL_PAUSE:
751 case SERVICE_CONTROL_CONTINUE:
752 case SERVICE_CONTROL_SHUTDOWN:
753 case SERVICE_CONTROL_PARAMCHANGE:
754 case SERVICE_CONTROL_NETBINDADD:
755 case SERVICE_CONTROL_NETBINDREMOVE:
756 case SERVICE_CONTROL_NETBINDENABLE:
757 case SERVICE_CONTROL_NETBINDDISABLE:
758 case SERVICE_CONTROL_DEVICEEVENT:
759 case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
760 case SERVICE_CONTROL_POWEREVENT:
761 case SERVICE_CONTROL_SESSIONCHANGE:
762#ifdef SERVICE_CONTROL_PRESHUTDOWN /* vista */
763 case SERVICE_CONTROL_PRESHUTDOWN:
764#endif
765 default:
766 return ERROR_CALL_NOT_IMPLEMENTED;
767 }
768
769 NOREF(dwEventType);
770 NOREF(pvEventData);
771 NOREF(pvContext);
772 /* not reached */
773}
774
775static int autostartStartVMs()
776{
777 int rc = autostartSetup();
778
779 const char *pszConfigFile = RTEnvGet("VBOXAUTOSTART_CONFIG");
780 if (!pszConfigFile)
781 return autostartSvcLogError("Starting VMs failed. VBOXAUTOSTART_CONFIG environment variable is not defined.\n");
782 bool fAllow = false;
783
784 PCFGAST pCfgAst = NULL;
785 rc = autostartParseConfig(pszConfigFile, &pCfgAst);
786 if (RT_FAILURE(rc))
787 return autostartSvcLogError("Starting VMs failed. Failed to parse the config file. Check the access permissions and file structure.\n");
788
789 PCFGAST pCfgAstPolicy = autostartConfigAstGetByName(pCfgAst, "default_policy");
790 /* Check default policy. */
791 if (pCfgAstPolicy)
792 {
793 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
794 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow")
795 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "deny")))
796 {
797 if (!RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow"))
798 fAllow = true;
799 }
800 else
801 {
802 autostartConfigAstDestroy(pCfgAst);
803 return autostartSvcLogError("'default_policy' must be either 'allow' or 'deny'.\n");
804 }
805 }
806
807 com::Utf8Str sUser;
808 rc = autostartGetProcessDomainUser(sUser);
809 if (RT_FAILURE(rc))
810 {
811 autostartConfigAstDestroy(pCfgAst);
812 return autostartSvcLogError("Failed to query username of the process (%Rrc).\n", rc);
813 }
814
815 PCFGAST pCfgAstUser = NULL;
816 for (unsigned i = 0; i < pCfgAst->u.Compound.cAstNodes; i++)
817 {
818 PCFGAST pNode = pCfgAst->u.Compound.apAstNodes[i];
819 com::Utf8Str sDomain;
820 com::Utf8Str sUserTmp;
821 int rc = autostartGetDomainAndUser(pNode->pszKey, sDomain, sUserTmp);
822 if (RT_FAILURE(rc))
823 continue;
824 com::Utf8StrFmt sDomainUser("%s\\%s", sDomain.c_str(), sUserTmp.c_str());
825 if (sDomainUser == sUser)
826 {
827 pCfgAstUser = pNode;
828 break;
829 }
830 }
831
832 if ( pCfgAstUser
833 && pCfgAstUser->enmType == CFGASTNODETYPE_COMPOUND)
834 {
835 pCfgAstPolicy = autostartConfigAstGetByName(pCfgAstUser, "allow");
836 if (pCfgAstPolicy)
837 {
838 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
839 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true")
840 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "false")))
841 fAllow = RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true") == 0;
842 else
843 {
844 autostartConfigAstDestroy(pCfgAst);
845 return autostartSvcLogError("'allow' must be either 'true' or 'false'.\n");
846 }
847 }
848 }
849 else if (pCfgAstUser)
850 {
851 autostartConfigAstDestroy(pCfgAst);
852 return autostartSvcLogError("Invalid config, user is not a compound node.\n");
853 }
854
855 if (!fAllow)
856 {
857 autostartConfigAstDestroy(pCfgAst);
858 return autostartSvcLogError("User is not allowed to autostart VMs.\n");
859 }
860
861 rc = autostartStartMain(pCfgAstUser);
862 autostartConfigAstDestroy(pCfgAst);
863 if (RT_FAILURE(rc))
864 autostartSvcLogError("Starting VMs failed, rc=%Rrc\n", rc);
865
866 return rc;
867}
868
869/**
870 * Windows Service Main.
871 *
872 * This is invoked when the service is started and should not return until
873 * the service has been stopped.
874 *
875 * @param cArgs Argument count.
876 * @param papwszArgs Argument vector.
877 */
878static VOID WINAPI autostartSvcWinServiceMain(DWORD cArgs, LPWSTR *papwszArgs)
879{
880 RT_NOREF(papwszArgs);
881 LogFlowFuncEnter();
882
883 /*
884 * Register the control handler function for the service and report to SCM.
885 */
886 Assert(g_u32SupSvcWinStatus == SERVICE_STOPPED);
887 g_hSupSvcWinCtrlHandler = RegisterServiceCtrlHandlerExW(g_bstrServiceName.raw(), autostartSvcWinServiceCtrlHandlerEx, NULL);
888 if (g_hSupSvcWinCtrlHandler)
889 {
890 DWORD err = ERROR_GEN_FAILURE;
891 if (autostartSvcWinSetServiceStatus(SERVICE_START_PENDING, 3000, NO_ERROR))
892 {
893 if (cArgs == 1)
894 {
895 /*
896 * Create the event semaphore we'll be waiting on and
897 * then instantiate the actual services.
898 */
899 int rc = RTSemEventMultiCreate(&g_hSupSvcWinEvent);
900 if (RT_SUCCESS(rc))
901 {
902 /*
903 * Update the status and enter the work loop.
904 */
905 if (autostartSvcWinSetServiceStatus(SERVICE_RUNNING, 0, 0))
906 {
907 LogFlow(("autostartSvcWinServiceMain: calling autostartStartVMs\n"));
908 rc = autostartStartVMs();
909 if (RT_SUCCESS(rc))
910 {
911 LogFlow(("autostartSvcWinServiceMain: done string VMs\n"));
912 err = NO_ERROR;
913 rc = RTSemEventMultiWait(g_hSupSvcWinEvent, RT_INDEFINITE_WAIT);
914 if (RT_SUCCESS(rc))
915 {
916 LogFlow(("autostartSvcWinServiceMain: woke up\n"));
917 /** @todo Autostop part. */
918 err = NO_ERROR;
919 }
920 else
921 autostartSvcLogError("RTSemEventWait failed, rc=%Rrc", rc);
922 }
923
924 autostartShutdown();
925 }
926 else
927 {
928 err = GetLastError();
929 autostartSvcLogError("SetServiceStatus failed, err=%u", err);
930 }
931
932 RTSemEventMultiDestroy(g_hSupSvcWinEvent);
933 g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
934 }
935 else
936 autostartSvcLogError("RTSemEventMultiCreate failed, rc=%Rrc", rc);
937 }
938 else
939 autostartSvcLogTooManyArgsError("main", cArgs, NULL, 0);
940 }
941 else
942 {
943 err = GetLastError();
944 autostartSvcLogError("SetServiceStatus failed, err=%u", err);
945 }
946 autostartSvcWinSetServiceStatus(SERVICE_STOPPED, 0, err);
947 }
948 else
949 autostartSvcLogError("RegisterServiceCtrlHandlerEx failed, err=%u", GetLastError());
950
951 LogFlowFuncLeave();
952}
953
954
955/**
956 * Handle the 'create' action.
957 *
958 * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
959 * @param argc The action argument count.
960 * @param argv The action argument vector.
961 */
962static int autostartSvcWinRunIt(int argc, char **argv)
963{
964 LogFlowFuncEnter();
965
966 /*
967 * Initialize release logging.
968 */
969 /** @todo release logging of the system-wide service. */
970
971 /*
972 * Parse the arguments.
973 */
974 static const RTGETOPTDEF s_aOptions[] =
975 {
976 { "--service", 's', RTGETOPT_REQ_STRING },
977 };
978
979 const char *pszServiceName = NULL;
980 int ch;
981 RTGETOPTUNION Value;
982 RTGETOPTSTATE GetState;
983 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
984 while ((ch = RTGetOpt(&GetState, &Value)))
985 {
986 switch (ch)
987 {
988 case 's':
989 pszServiceName = Value.psz;
990 try
991 {
992 g_bstrServiceName = com::Bstr(Value.psz);
993 }
994 catch (...)
995 {
996 autostartSvcLogError("runit failed, service name is not valid utf-8 string or out of memory");
997 return RTEXITCODE_FAILURE;
998 }
999 break;
1000 default:
1001 return autostartSvcDisplayGetOptError("runit", ch, &Value);
1002 }
1003 }
1004
1005 if (!pszServiceName)
1006 {
1007 autostartSvcLogError("runit failed, service name is missing");
1008 return RTEXITCODE_FAILURE;
1009 }
1010
1011 /*
1012 * Register the service with the service control manager
1013 * and start dispatching requests from it (all done by the API).
1014 */
1015 SERVICE_TABLE_ENTRYW const s_aServiceStartTable[] =
1016 {
1017 { g_bstrServiceName.raw(), autostartSvcWinServiceMain },
1018 { NULL, NULL}
1019 };
1020 if (StartServiceCtrlDispatcherW(&s_aServiceStartTable[0]))
1021 {
1022 LogFlowFuncLeave();
1023 return RTEXITCODE_SUCCESS; /* told to quit, so quit. */
1024 }
1025
1026 DWORD err = GetLastError();
1027 switch (err)
1028 {
1029 case ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
1030 autostartSvcWinServiceMain(0, NULL);//autostartSvcDisplayError("Cannot run a service from the command line. Use the 'start' action to start it the right way.\n");
1031 break;
1032 default:
1033 autostartSvcLogError("StartServiceCtrlDispatcher failed, err=%u", err);
1034 break;
1035 }
1036 return RTEXITCODE_FAILURE;
1037}
1038
1039
1040/**
1041 * Show the version info.
1042 *
1043 * @returns RTEXITCODE_SUCCESS.
1044 */
1045static RTEXITCODE autostartSvcWinShowVersion(int argc, char **argv)
1046{
1047 /*
1048 * Parse the arguments.
1049 */
1050 bool fBrief = false;
1051 static const RTGETOPTDEF s_aOptions[] =
1052 {
1053 { "--brief", 'b', RTGETOPT_REQ_NOTHING }
1054 };
1055 int ch;
1056 RTGETOPTUNION Value;
1057 RTGETOPTSTATE GetState;
1058 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1059 while ((ch = RTGetOpt(&GetState, &Value)))
1060 switch (ch)
1061 {
1062 case 'b': fBrief = true; break;
1063 default: return autostartSvcDisplayGetOptError("version", ch, &Value);
1064 }
1065
1066 /*
1067 * Do the printing.
1068 */
1069 if (fBrief)
1070 RTPrintf("%s\n", VBOX_VERSION_STRING);
1071 else
1072 RTPrintf("VirtualBox Autostart Service Version %s\n"
1073 "(C) 2012 Oracle Corporation\n"
1074 "All rights reserved.\n",
1075 VBOX_VERSION_STRING);
1076 return RTEXITCODE_SUCCESS;
1077}
1078
1079
1080/**
1081 * Show the usage help screen.
1082 *
1083 * @returns RTEXITCODE_SUCCESS.
1084 */
1085static RTEXITCODE autostartSvcWinShowHelp(void)
1086{
1087 RTPrintf("VirtualBox Autostart Service Version %s\n"
1088 "(C) 2012 Oracle Corporation\n"
1089 "All rights reserved.\n"
1090 "\n",
1091 VBOX_VERSION_STRING);
1092 RTPrintf("Usage:\n"
1093 "\n"
1094 "VBoxAutostartSvc\n"
1095 " Runs the service.\n"
1096 "VBoxAutostartSvc <version|-v|--version> [-brief]\n"
1097 " Displays the version.\n"
1098 "VBoxAutostartSvc <help|-?|-h|--help> [...]\n"
1099 " Displays this help screen.\n"
1100 "\n"
1101 "VBoxAutostartSvc <install|/RegServer|/i>\n"
1102 " Installs the service.\n"
1103 "VBoxAutostartSvc <uninstall|delete|/UnregServer|/u>\n"
1104 " Uninstalls the service.\n"
1105 );
1106 return RTEXITCODE_SUCCESS;
1107}
1108
1109
1110/**
1111 * VBoxAutostart main(), Windows edition.
1112 *
1113 *
1114 * @returns 0 on success.
1115 *
1116 * @param argc Number of arguments in argv.
1117 * @param argv Argument vector.
1118 */
1119int main(int argc, char **argv)
1120{
1121 /*
1122 * Initialize the IPRT first of all.
1123 */
1124 int rc = RTR3InitExe(argc, &argv, 0);
1125 if (RT_FAILURE(rc))
1126 {
1127 autostartSvcLogError("RTR3InitExe failed with rc=%Rrc", rc);
1128 return RTEXITCODE_FAILURE;
1129 }
1130
1131 RTThreadSleep(10 * 1000);
1132
1133 /*
1134 * Parse the initial arguments to determine the desired action.
1135 */
1136 enum
1137 {
1138 kAutoSvcAction_RunIt,
1139
1140 kAutoSvcAction_Create,
1141 kAutoSvcAction_Delete,
1142
1143 kAutoSvcAction_Enable,
1144 kAutoSvcAction_Disable,
1145 kAutoSvcAction_QueryConfig,
1146 kAutoSvcAction_QueryDescription,
1147
1148 kAutoSvcAction_Start,
1149 kAutoSvcAction_Pause,
1150 kAutoSvcAction_Continue,
1151 kAutoSvcAction_Stop,
1152 kAutoSvcAction_Interrogate,
1153
1154 kAutoSvcAction_End
1155 } enmAction = kAutoSvcAction_RunIt;
1156 int iArg = 1;
1157 if (argc > 1)
1158 {
1159 if ( !stricmp(argv[iArg], "/RegServer")
1160 || !stricmp(argv[iArg], "install")
1161 || !stricmp(argv[iArg], "/i"))
1162 enmAction = kAutoSvcAction_Create;
1163 else if ( !stricmp(argv[iArg], "/UnregServer")
1164 || !stricmp(argv[iArg], "/u")
1165 || !stricmp(argv[iArg], "uninstall")
1166 || !stricmp(argv[iArg], "delete"))
1167 enmAction = kAutoSvcAction_Delete;
1168
1169 else if (!stricmp(argv[iArg], "enable"))
1170 enmAction = kAutoSvcAction_Enable;
1171 else if (!stricmp(argv[iArg], "disable"))
1172 enmAction = kAutoSvcAction_Disable;
1173 else if (!stricmp(argv[iArg], "qconfig"))
1174 enmAction = kAutoSvcAction_QueryConfig;
1175 else if (!stricmp(argv[iArg], "qdescription"))
1176 enmAction = kAutoSvcAction_QueryDescription;
1177
1178 else if ( !stricmp(argv[iArg], "start")
1179 || !stricmp(argv[iArg], "/t"))
1180 enmAction = kAutoSvcAction_Start;
1181 else if (!stricmp(argv[iArg], "pause"))
1182 enmAction = kAutoSvcAction_Start;
1183 else if (!stricmp(argv[iArg], "continue"))
1184 enmAction = kAutoSvcAction_Continue;
1185 else if (!stricmp(argv[iArg], "stop"))
1186 enmAction = kAutoSvcAction_Stop;
1187 else if (!stricmp(argv[iArg], "interrogate"))
1188 enmAction = kAutoSvcAction_Interrogate;
1189 else if ( !stricmp(argv[iArg], "help")
1190 || !stricmp(argv[iArg], "?")
1191 || !stricmp(argv[iArg], "/?")
1192 || !stricmp(argv[iArg], "-?")
1193 || !stricmp(argv[iArg], "/h")
1194 || !stricmp(argv[iArg], "-h")
1195 || !stricmp(argv[iArg], "/help")
1196 || !stricmp(argv[iArg], "-help")
1197 || !stricmp(argv[iArg], "--help"))
1198 return autostartSvcWinShowHelp();
1199 else if ( !stricmp(argv[iArg], "version")
1200 || !stricmp(argv[iArg], "/v")
1201 || !stricmp(argv[iArg], "-v")
1202 || !stricmp(argv[iArg], "/version")
1203 || !stricmp(argv[iArg], "-version")
1204 || !stricmp(argv[iArg], "--version"))
1205 return autostartSvcWinShowVersion(argc - iArg - 1, argv + iArg + 1);
1206 else
1207 iArg--;
1208 iArg++;
1209 }
1210
1211 /*
1212 * Dispatch it.
1213 */
1214 switch (enmAction)
1215 {
1216 case kAutoSvcAction_RunIt:
1217 return autostartSvcWinRunIt(argc - iArg, argv + iArg);
1218
1219 case kAutoSvcAction_Create:
1220 return autostartSvcWinCreate(argc - iArg, argv + iArg);
1221 case kAutoSvcAction_Delete:
1222 return autostartSvcWinDelete(argc - iArg, argv + iArg);
1223
1224 case kAutoSvcAction_Enable:
1225 return autostartSvcWinEnable(argc - iArg, argv + iArg);
1226 case kAutoSvcAction_Disable:
1227 return autostartSvcWinDisable(argc - iArg, argv + iArg);
1228 case kAutoSvcAction_QueryConfig:
1229 return autostartSvcWinQueryConfig(argc - iArg, argv + iArg);
1230 case kAutoSvcAction_QueryDescription:
1231 return autostartSvcWinQueryDescription(argc - iArg, argv + iArg);
1232
1233 case kAutoSvcAction_Start:
1234 return autostartSvcWinStart(argc - iArg, argv + iArg);
1235 case kAutoSvcAction_Pause:
1236 return autostartSvcWinPause(argc - iArg, argv + iArg);
1237 case kAutoSvcAction_Continue:
1238 return autostartSvcWinContinue(argc - iArg, argv + iArg);
1239 case kAutoSvcAction_Stop:
1240 return autostartSvcWinStop(argc - iArg, argv + iArg);
1241 case kAutoSvcAction_Interrogate:
1242 return autostartSvcWinInterrogate(argc - iArg, argv + iArg);
1243
1244 default:
1245 AssertMsgFailed(("enmAction=%d\n", enmAction));
1246 return RTEXITCODE_FAILURE;
1247 }
1248}
1249
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