VirtualBox

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

Last change on this file since 103068 was 99828, checked in by vboxsync, 14 months ago

*: A bunch of adjustments that allows using /permissive- with Visual C++ (qt 6.x necessity).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 51.3 KB
Line 
1/* $Id: VBoxAutostart-win.cpp 99828 2023-05-17 13:48:57Z vboxsync $ */
2/** @file
3 * VirtualBox Autostart Service - Windows Specific Code.
4 */
5
6/*
7 * Copyright (C) 2012-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#include <iprt/dir.h>
33#include <iprt/env.h>
34#include <iprt/err.h>
35#include <iprt/getopt.h>
36#include <iprt/initterm.h>
37#include <iprt/mem.h>
38#include <iprt/message.h>
39#include <iprt/process.h>
40#include <iprt/path.h>
41#include <iprt/semaphore.h>
42#include <iprt/stream.h>
43#include <iprt/string.h>
44#include <iprt/thread.h>
45
46#include <iprt/win/windows.h>
47#include <ntsecapi.h>
48
49#define SECURITY_WIN32
50#include <Security.h>
51
52#include <VBox/com/array.h>
53#include <VBox/com/com.h>
54#include <VBox/com/ErrorInfo.h>
55#include <VBox/com/errorprint.h>
56#include <VBox/com/Guid.h>
57#include <VBox/com/listeners.h>
58#include <VBox/com/NativeEventQueue.h>
59#include <VBox/com/string.h>
60#include <VBox/com/VirtualBox.h>
61
62#include <VBox/log.h>
63
64#include "VBoxAutostart.h"
65#include "PasswordInput.h"
66
67
68/*********************************************************************************************************************************
69* Defined Constants And Macros *
70*********************************************************************************************************************************/
71/** The service name. */
72#define AUTOSTART_SERVICE_NAME "VBoxAutostartSvc"
73/** The service display name. */
74#define AUTOSTART_SERVICE_DISPLAY_NAME "VirtualBox Autostart Service"
75
76/* just define it here instead of including
77 * a bunch of nt headers */
78#ifndef STATUS_SUCCESS
79#define STATUS_SUCCESS ((NTSTATUS)0)
80#endif
81
82
83ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
84bool g_fVerbose = false;
85ComPtr<IVirtualBox> g_pVirtualBox = NULL;
86ComPtr<ISession> g_pSession = NULL;
87
88
89/*********************************************************************************************************************************
90* Global Variables *
91*********************************************************************************************************************************/
92/** The service control handler handle. */
93static SERVICE_STATUS_HANDLE g_hSupSvcWinCtrlHandler = NULL;
94/** The service status. */
95static uint32_t volatile g_u32SupSvcWinStatus = SERVICE_STOPPED;
96/** The semaphore the main service thread is waiting on in autostartSvcWinServiceMain. */
97static RTSEMEVENTMULTI g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
98/** The service name is used for send to service main. */
99static com::Bstr g_bstrServiceName;
100
101/** Verbosity level. */
102unsigned g_cVerbosity = 0;
103
104/** Logging parameters. */
105static uint32_t g_cHistory = 10; /* Enable log rotation, 10 files. */
106static uint32_t g_uHistoryFileTime = 0; /* No time limit, it's very low volume. */
107static uint64_t g_uHistoryFileSize = 100 * _1M; /* Max 100MB per file. */
108
109
110/*********************************************************************************************************************************
111* Internal Functions *
112*********************************************************************************************************************************/
113static SC_HANDLE autostartSvcWinOpenSCManager(const char *pszAction, DWORD dwAccess);
114
115static int autostartGetProcessDomainUser(com::Utf8Str &aUser)
116{
117 int rc = VERR_NOT_SUPPORTED;
118
119 RTUTF16 wszUsername[1024] = { 0 };
120 ULONG cwcUsername = RT_ELEMENTS(wszUsername);
121 char *pszUser = NULL;
122 if (!GetUserNameExW(NameSamCompatible, &wszUsername[0], &cwcUsername))
123 return RTErrConvertFromWin32(GetLastError());
124 rc = RTUtf16ToUtf8(wszUsername, &pszUser);
125 aUser = pszUser;
126 aUser.toLower();
127 RTStrFree(pszUser);
128 return rc;
129}
130
131static int autostartGetLocalDomain(com::Utf8Str &aDomain)
132{
133 RTUTF16 pwszDomain[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };
134 uint32_t cwcDomainSize = MAX_COMPUTERNAME_LENGTH + 1;
135 if (!GetComputerNameW(pwszDomain, (LPDWORD)&cwcDomainSize))
136 return RTErrConvertFromWin32(GetLastError());
137 char *pszDomain = NULL;
138 int rc = RTUtf16ToUtf8(pwszDomain, &pszDomain);
139 aDomain = pszDomain;
140 aDomain.toLower();
141 RTStrFree(pszDomain);
142 return rc;
143}
144
145static int autostartGetDomainAndUser(const com::Utf8Str &aDomainAndUser, com::Utf8Str &aDomain, com::Utf8Str &aUser)
146{
147 size_t offDelim = aDomainAndUser.find("\\");
148 if (offDelim != aDomainAndUser.npos)
149 {
150 // if only domain is specified
151 if (aDomainAndUser.length() - offDelim == 1)
152 return VERR_INVALID_PARAMETER;
153
154 if (offDelim == 1 && aDomainAndUser[0] == '.')
155 {
156 int rc = autostartGetLocalDomain(aDomain);
157 aUser = aDomainAndUser.substr(offDelim + 1);
158 return rc;
159 }
160 aDomain = aDomainAndUser.substr(0, offDelim);
161 aUser = aDomainAndUser.substr(offDelim + 1);
162 aDomain.toLower();
163 aUser.toLower();
164 return VINF_SUCCESS;
165 }
166
167 offDelim = aDomainAndUser.find("@");
168 if (offDelim != aDomainAndUser.npos)
169 {
170 // if only domain is specified
171 if (offDelim == 0)
172 return VERR_INVALID_PARAMETER;
173
174 // with '@' but without domain
175 if (aDomainAndUser.length() - offDelim == 1)
176 {
177 int rc = autostartGetLocalDomain(aDomain);
178 aUser = aDomainAndUser.substr(0, offDelim);
179 return rc;
180 }
181 aDomain = aDomainAndUser.substr(offDelim + 1);
182 aUser = aDomainAndUser.substr(0, offDelim);
183 aDomain.toLower();
184 aUser.toLower();
185 return VINF_SUCCESS;
186 }
187
188 // only user is specified
189 int rc = autostartGetLocalDomain(aDomain);
190 aUser = aDomainAndUser;
191 aDomain.toLower();
192 aUser.toLower();
193 return rc;
194}
195
196/** Common helper for formatting the service name. */
197static void autostartFormatServiceName(const com::Utf8Str &aDomain, const com::Utf8Str &aUser, com::Utf8Str &aServiceName)
198{
199 aServiceName.printf("%s%s%s", AUTOSTART_SERVICE_NAME, aDomain.c_str(), aUser.c_str());
200}
201
202/** Used by the delete service operation. */
203static int autostartGetServiceName(const com::Utf8Str &aDomainAndUser, com::Utf8Str &aServiceName)
204{
205 com::Utf8Str sDomain;
206 com::Utf8Str sUser;
207 int rc = autostartGetDomainAndUser(aDomainAndUser, sDomain, sUser);
208 if (RT_FAILURE(rc))
209 return rc;
210 autostartFormatServiceName(sDomain, sUser, aServiceName);
211 return VINF_SUCCESS;
212}
213
214/**
215 * Print out progress on the console.
216 *
217 * This runs the main event queue every now and then to prevent piling up
218 * unhandled things (which doesn't cause real problems, just makes things
219 * react a little slower than in the ideal case).
220 */
221DECLHIDDEN(HRESULT) showProgress(ComPtr<IProgress> progress)
222{
223 using namespace com;
224
225 BOOL fCompleted = FALSE;
226 ULONG uCurrentPercent = 0;
227 Bstr bstrOperationDescription;
228
229 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
230
231 ULONG cOperations = 1;
232 HRESULT hrc = progress->COMGETTER(OperationCount)(&cOperations);
233 if (FAILED(hrc))
234 return hrc;
235
236 /* setup signal handling if cancelable */
237 bool fCanceledAlready = false;
238 BOOL fCancelable;
239 hrc = progress->COMGETTER(Cancelable)(&fCancelable);
240 if (FAILED(hrc))
241 fCancelable = FALSE;
242
243 hrc = progress->COMGETTER(Completed(&fCompleted));
244 while (SUCCEEDED(hrc))
245 {
246 progress->COMGETTER(Percent(&uCurrentPercent));
247
248 if (fCompleted)
249 break;
250
251 /* process async cancelation */
252 if (!fCanceledAlready)
253 {
254 hrc = progress->Cancel();
255 if (SUCCEEDED(hrc))
256 fCanceledAlready = true;
257 }
258
259 /* make sure the loop is not too tight */
260 progress->WaitForCompletion(100);
261
262 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
263 hrc = progress->COMGETTER(Completed(&fCompleted));
264 }
265
266 /* complete the line. */
267 LONG iRc = E_FAIL;
268 hrc = progress->COMGETTER(ResultCode)(&iRc);
269 if (SUCCEEDED(hrc))
270 {
271 hrc = iRc;
272 }
273
274 return hrc;
275}
276
277DECLHIDDEN(void) autostartSvcOsLogStr(const char *pszMsg, AUTOSTARTLOGTYPE enmLogType)
278{
279 /* write it to the console + release log too (if configured). */
280 LogRel(("%s", pszMsg));
281
282 /** @todo r=andy Only (un)register source once? */
283 HANDLE hEventLog = RegisterEventSourceA(NULL /* local computer */, "VBoxAutostartSvc");
284 AssertReturnVoid(hEventLog != NULL);
285 WORD wType = 0;
286 const char *apsz[2];
287 apsz[0] = "VBoxAutostartSvc";
288 apsz[1] = pszMsg;
289
290 switch (enmLogType)
291 {
292 case AUTOSTARTLOGTYPE_INFO:
293 RTStrmPrintf(g_pStdOut, "%s", pszMsg);
294 wType = 0;
295 break;
296 case AUTOSTARTLOGTYPE_ERROR:
297 RTStrmPrintf(g_pStdErr, "Error: %s", pszMsg);
298 wType = EVENTLOG_ERROR_TYPE;
299 break;
300 case AUTOSTARTLOGTYPE_WARNING:
301 RTStrmPrintf(g_pStdOut, "Warning: %s", pszMsg);
302 wType = EVENTLOG_WARNING_TYPE;
303 break;
304 case AUTOSTARTLOGTYPE_VERBOSE:
305 RTStrmPrintf(g_pStdOut, "%s", pszMsg);
306 wType = EVENTLOG_INFORMATION_TYPE;
307 break;
308 default:
309 AssertMsgFailed(("Invalid log type %#x\n", enmLogType));
310 break;
311 }
312
313 /** @todo r=andy Why ANSI and not Unicode (xxxW)? */
314 BOOL fRc = ReportEventA(hEventLog, /* hEventLog */
315 wType, /* wType */
316 0, /* wCategory */
317 0 /** @todo mc */, /* dwEventID */
318 NULL, /* lpUserSid */
319 RT_ELEMENTS(apsz), /* wNumStrings */
320 0, /* dwDataSize */
321 apsz, /* lpStrings */
322 NULL); /* lpRawData */
323 AssertMsg(fRc, ("ReportEventA failed with %ld\n", GetLastError())); RT_NOREF(fRc);
324 DeregisterEventSource(hEventLog);
325}
326
327
328/**
329 * Adds "logon as service" policy to user rights
330 *
331 * When this fails, an error message will be displayed.
332 *
333 * @returns VBox status code.
334 *
335 * @param sUser The name of user whom the policy should be added.
336 */
337static int autostartUpdatePolicy(const com::Utf8Str &sUser)
338{
339 LSA_OBJECT_ATTRIBUTES objectAttributes;
340 /* Object attributes are reserved, so initialize to zeros. */
341 RT_ZERO(objectAttributes);
342
343 int vrc;
344
345 /* Get a handle to the Policy object. */
346 LSA_HANDLE hPolicy;
347 NTSTATUS ntRc = LsaOpenPolicy( NULL, &objectAttributes, POLICY_ALL_ACCESS, &hPolicy);
348 if (ntRc != STATUS_SUCCESS)
349 {
350 DWORD dwErr = LsaNtStatusToWinError(ntRc);
351 vrc = RTErrConvertFromWin32(dwErr);
352 autostartSvcDisplayError("LsaOpenPolicy failed rc=%Rrc (%#x)\n", vrc, dwErr);
353 return vrc;
354 }
355 /* Get user SID */
356 DWORD cbDomain = 0;
357 SID_NAME_USE enmSidUse = SidTypeUser;
358 RTUTF16 *pwszUser = NULL;
359 size_t cwUser = 0;
360 vrc = RTStrToUtf16Ex(sUser.c_str(), sUser.length(), &pwszUser, 0, &cwUser);
361 if (RT_SUCCESS(vrc))
362 {
363 PSID pSid = NULL;
364 DWORD cbSid = 0;
365 if (!LookupAccountNameW( NULL, pwszUser, pSid, &cbSid, NULL, &cbDomain, &enmSidUse))
366 {
367 DWORD dwErr = GetLastError();
368 if (dwErr == ERROR_INSUFFICIENT_BUFFER)
369 {
370 pSid = (PSID)RTMemAllocZ(cbSid);
371 if (pSid != NULL)
372 {
373 PRTUTF16 pwszDomain = (PRTUTF16)RTMemAllocZ(cbDomain * sizeof(RTUTF16));
374 if (pwszDomain != NULL)
375 {
376 if (LookupAccountNameW( NULL, pwszUser, pSid, &cbSid, pwszDomain, &cbDomain, &enmSidUse))
377 {
378 if (enmSidUse != SidTypeUser)
379 {
380 vrc = VERR_INVALID_PARAMETER;
381 autostartSvcDisplayError("The name %s is not the user\n", sUser.c_str());
382 }
383 else
384 {
385 /* Add privilege */
386 LSA_UNICODE_STRING lwsPrivilege;
387 // Create an LSA_UNICODE_STRING for the privilege names.
388 lwsPrivilege.Buffer = (PWSTR)L"SeServiceLogonRight";
389 size_t cwPrivilege = wcslen(lwsPrivilege.Buffer);
390 lwsPrivilege.Length = (USHORT)cwPrivilege * sizeof(WCHAR);
391 lwsPrivilege.MaximumLength = (USHORT)(cwPrivilege + 1) * sizeof(WCHAR);
392 ntRc = LsaAddAccountRights(hPolicy, pSid, &lwsPrivilege, 1);
393 if (ntRc != STATUS_SUCCESS)
394 {
395 dwErr = LsaNtStatusToWinError(ntRc);
396 vrc = RTErrConvertFromWin32(dwErr);
397 autostartSvcDisplayError("LsaAddAccountRights failed rc=%Rrc (%#x)\n", vrc, dwErr);
398 }
399 }
400 }
401 else
402 {
403 dwErr = GetLastError();
404 vrc = RTErrConvertFromWin32(dwErr);
405 autostartSvcDisplayError("LookupAccountName failed rc=%Rrc (%#x)\n", vrc, dwErr);
406 }
407 RTMemFree(pwszDomain);
408 }
409 else
410 {
411 vrc = VERR_NO_MEMORY;
412 autostartSvcDisplayError("autostartUpdatePolicy failed rc=%Rrc\n", vrc);
413 }
414
415 RTMemFree(pSid);
416 }
417 else
418 {
419 vrc = VERR_NO_MEMORY;
420 autostartSvcDisplayError("autostartUpdatePolicy failed rc=%Rrc\n", vrc);
421 }
422 }
423 else
424 {
425 vrc = RTErrConvertFromWin32(dwErr);
426 autostartSvcDisplayError("LookupAccountName failed rc=%Rrc (%#x)\n", vrc, dwErr);
427 }
428 }
429 }
430 else
431 autostartSvcDisplayError("Failed to convert user name rc=%Rrc\n", vrc);
432
433 if (pwszUser != NULL)
434 RTUtf16Free(pwszUser);
435
436 LsaClose(hPolicy);
437 return vrc;
438}
439
440
441/**
442 * Opens the service control manager.
443 *
444 * When this fails, an error message will be displayed.
445 *
446 * @returns Valid handle on success.
447 * NULL on failure, will display an error message.
448 *
449 * @param pszAction The action which is requesting access to SCM.
450 * @param dwAccess The desired access.
451 */
452static SC_HANDLE autostartSvcWinOpenSCManager(const char *pszAction, DWORD dwAccess)
453{
454 SC_HANDLE hSCM = OpenSCManager(NULL /* lpMachineName*/, NULL /* lpDatabaseName */, dwAccess);
455 if (hSCM == NULL)
456 {
457 DWORD err = GetLastError();
458 switch (err)
459 {
460 case ERROR_ACCESS_DENIED:
461 autostartSvcDisplayError("%s - OpenSCManager failure: access denied\n", pszAction);
462 break;
463 default:
464 autostartSvcDisplayError("%s - OpenSCManager failure: %d\n", pszAction, err);
465 break;
466 }
467 }
468 return hSCM;
469}
470
471
472/**
473 * Opens the service.
474 *
475 * Last error is preserved on failure and set to 0 on success.
476 *
477 * @returns Valid service handle on success.
478 * NULL on failure, will display an error message unless it's ignored.
479 * Use GetLastError() to find out what the last Windows error was.
480 *
481 * @param pszAction The action which is requesting access to the service.
482 * @param dwSCMAccess The service control manager access.
483 * @param dwSVCAccess The desired service access.
484 * @param cIgnoredErrors The number of ignored errors.
485 * @param ... Errors codes that should not cause a message to be displayed.
486 */
487static SC_HANDLE autostartSvcWinOpenService(const PRTUTF16 pwszServiceName, const char *pszAction, DWORD dwSCMAccess, DWORD dwSVCAccess,
488 unsigned cIgnoredErrors, ...)
489{
490 SC_HANDLE hSCM = autostartSvcWinOpenSCManager(pszAction, dwSCMAccess);
491 if (!hSCM)
492 return NULL;
493
494 SC_HANDLE hSvc = OpenServiceW(hSCM, pwszServiceName, dwSVCAccess);
495 if (hSvc)
496 {
497 CloseServiceHandle(hSCM);
498 SetLastError(0);
499 }
500 else
501 {
502 DWORD const dwErr = GetLastError();
503 bool fIgnored = false;
504 va_list va;
505 va_start(va, cIgnoredErrors);
506 while (!fIgnored && cIgnoredErrors-- > 0)
507 fIgnored = (DWORD)va_arg(va, int) == dwErr;
508 va_end(va);
509 if (!fIgnored)
510 {
511 switch (dwErr)
512 {
513 case ERROR_ACCESS_DENIED:
514 autostartSvcDisplayError("%s - OpenService failure: access denied\n", pszAction);
515 break;
516 case ERROR_SERVICE_DOES_NOT_EXIST:
517 autostartSvcDisplayError("%s - OpenService failure: The service %ls does not exist. Reinstall it.\n",
518 pszAction, pwszServiceName);
519 break;
520 default:
521 autostartSvcDisplayError("%s - OpenService failure, rc=%Rrc (%#x)\n", RTErrConvertFromWin32(dwErr), dwErr);
522 break;
523 }
524 }
525
526 CloseServiceHandle(hSCM);
527 SetLastError(dwErr);
528 }
529 return hSvc;
530}
531
532static RTEXITCODE autostartSvcWinInterrogate(int argc, char **argv)
533{
534 RT_NOREF(argc, argv);
535 RTPrintf("VBoxAutostartSvc: The \"interrogate\" action is not implemented.\n");
536 return RTEXITCODE_FAILURE;
537}
538
539
540static RTEXITCODE autostartSvcWinStop(int argc, char **argv)
541{
542 RT_NOREF(argc, argv);
543 RTPrintf("VBoxAutostartSvc: The \"stop\" action is not implemented.\n");
544 return RTEXITCODE_FAILURE;
545}
546
547
548static RTEXITCODE autostartSvcWinContinue(int argc, char **argv)
549{
550 RT_NOREF(argc, argv);
551 RTPrintf("VBoxAutostartSvc: The \"continue\" action is not implemented.\n");
552 return RTEXITCODE_FAILURE;
553}
554
555
556static RTEXITCODE autostartSvcWinPause(int argc, char **argv)
557{
558 RT_NOREF(argc, argv);
559 RTPrintf("VBoxAutostartSvc: The \"pause\" action is not implemented.\n");
560 return RTEXITCODE_FAILURE;
561}
562
563
564static RTEXITCODE autostartSvcWinStart(int argc, char **argv)
565{
566 RT_NOREF(argc, argv);
567 RTPrintf("VBoxAutostartSvc: The \"start\" action is not implemented.\n");
568 return RTEXITCODE_SUCCESS;
569}
570
571
572static RTEXITCODE autostartSvcWinQueryDescription(int argc, char **argv)
573{
574 RT_NOREF(argc, argv);
575 RTPrintf("VBoxAutostartSvc: The \"qdescription\" action is not implemented.\n");
576 return RTEXITCODE_FAILURE;
577}
578
579
580static RTEXITCODE autostartSvcWinQueryConfig(int argc, char **argv)
581{
582 RT_NOREF(argc, argv);
583 RTPrintf("VBoxAutostartSvc: The \"qconfig\" action is not implemented.\n");
584 return RTEXITCODE_FAILURE;
585}
586
587
588static RTEXITCODE autostartSvcWinDisable(int argc, char **argv)
589{
590 RT_NOREF(argc, argv);
591 RTPrintf("VBoxAutostartSvc: The \"disable\" action is not implemented.\n");
592 return RTEXITCODE_FAILURE;
593}
594
595static RTEXITCODE autostartSvcWinEnable(int argc, char **argv)
596{
597 RT_NOREF(argc, argv);
598 RTPrintf("VBoxAutostartSvc: The \"enable\" action is not implemented.\n");
599 return RTEXITCODE_FAILURE;
600}
601
602
603/**
604 * Handle the 'delete' action.
605 *
606 * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
607 * @param argc The action argument count.
608 * @param argv The action argument vector.
609 */
610static RTEXITCODE autostartSvcWinDelete(int argc, char **argv)
611{
612 /*
613 * Parse the arguments.
614 */
615 const char *pszUser = NULL;
616 static const RTGETOPTDEF s_aOptions[] =
617 {
618 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
619 { "--user", 'u', RTGETOPT_REQ_STRING },
620 };
621 int ch;
622 RTGETOPTUNION Value;
623 RTGETOPTSTATE GetState;
624 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
625 while ((ch = RTGetOpt(&GetState, &Value)))
626 {
627 switch (ch)
628 {
629 case 'v':
630 g_cVerbosity++;
631 break;
632 case 'u':
633 pszUser = Value.psz;
634 break;
635 default:
636 return autostartSvcDisplayGetOptError("delete", ch, &Value);
637 }
638 }
639
640 if (!pszUser)
641 return autostartSvcDisplayError("delete - DeleteService failed, user name required.\n");
642
643 com::Utf8Str sServiceName;
644 int vrc = autostartGetServiceName(pszUser, sServiceName);
645 if (RT_FAILURE(vrc))
646 return autostartSvcDisplayError("delete - DeleteService failed, service name for user %s cannot be constructed.\n",
647 pszUser);
648 /*
649 * Delete the service.
650 */
651 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
652 SC_HANDLE hSvc = autostartSvcWinOpenService(com::Bstr(sServiceName).raw(), "delete", SERVICE_CHANGE_CONFIG, DELETE, 0);
653 if (hSvc)
654 {
655 if (DeleteService(hSvc))
656 {
657 if (g_cVerbosity)
658 RTPrintf("Successfully deleted the %s service.\n", sServiceName.c_str());
659 rcExit = RTEXITCODE_SUCCESS;
660 }
661 else
662 {
663 DWORD const dwErr = GetLastError();
664 autostartSvcDisplayError("delete - DeleteService failed, rc=%Rrc (%#x)\n", RTErrConvertFromWin32(dwErr), dwErr);
665 }
666 CloseServiceHandle(hSvc);
667 }
668 return rcExit;
669}
670
671
672/**
673 * Handle the 'create' action.
674 *
675 * @returns 0 or 1.
676 * @param argc The action argument count.
677 * @param argv The action argument vector.
678 */
679static RTEXITCODE autostartSvcWinCreate(int argc, char **argv)
680{
681 /*
682 * Parse the arguments.
683 */
684 const char *pszUser = NULL;
685 com::Utf8Str strPwd;
686 const char *pszPwdFile = NULL;
687 static const RTGETOPTDEF s_aOptions[] =
688 {
689 /* Common options first. */
690 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
691 { "--user", 'u', RTGETOPT_REQ_STRING },
692 { "--username", 'u', RTGETOPT_REQ_STRING },
693 { "--password-file", 'p', RTGETOPT_REQ_STRING }
694 };
695 int ch;
696 RTGETOPTUNION Value;
697 RTGETOPTSTATE GetState;
698 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
699 while ((ch = RTGetOpt(&GetState, &Value)))
700 {
701 switch (ch)
702 {
703 /* Common options first. */
704 case 'v':
705 g_cVerbosity++;
706 break;
707 case 'u':
708 pszUser = Value.psz;
709 break;
710 case 'p':
711 pszPwdFile = Value.psz;
712 break;
713 default:
714 return autostartSvcDisplayGetOptError("create", ch, &Value);
715 }
716 }
717
718 if (!pszUser)
719 return autostartSvcDisplayError("Username is missing");
720
721 if (pszPwdFile)
722 {
723 /* Get password from file. */
724 RTEXITCODE rcExit = readPasswordFile(pszPwdFile, &strPwd);
725 if (rcExit == RTEXITCODE_FAILURE)
726 return rcExit;
727 }
728 else
729 {
730 /* Get password from console. */
731 RTEXITCODE rcExit = readPasswordFromConsole(&strPwd, "Enter password:");
732 if (rcExit == RTEXITCODE_FAILURE)
733 return rcExit;
734 }
735
736 if (strPwd.isEmpty())
737 return autostartSvcDisplayError("Password is missing");
738
739 com::Utf8Str sDomain;
740 com::Utf8Str sUserTmp;
741 int vrc = autostartGetDomainAndUser(pszUser, sDomain, sUserTmp);
742 if (RT_FAILURE(vrc))
743 return autostartSvcDisplayError("create - Failed to get domain and user from string '%s' (%Rrc)\n",
744 pszUser, vrc);
745 com::Utf8StrFmt sUserFullName("%s\\%s", sDomain.c_str(), sUserTmp.c_str());
746 com::Utf8StrFmt sDisplayName("%s %s@%s", AUTOSTART_SERVICE_DISPLAY_NAME, sUserTmp.c_str(), sDomain.c_str());
747 com::Utf8Str sServiceName;
748 autostartFormatServiceName(sDomain, sUserTmp, sServiceName);
749
750 vrc = autostartUpdatePolicy(sUserFullName);
751 if (RT_FAILURE(vrc))
752 return autostartSvcDisplayError("Failed to get/update \"logon as service\" policy for user %s (%Rrc)\n",
753 sUserFullName.c_str(), vrc);
754 /*
755 * Create the service.
756 */
757 RTEXITCODE rcExit = RTEXITCODE_FAILURE;
758 SC_HANDLE hSCM = autostartSvcWinOpenSCManager("create", SC_MANAGER_CREATE_SERVICE); /*SC_MANAGER_ALL_ACCESS*/
759 if (hSCM)
760 {
761 char szExecPath[RTPATH_MAX];
762 if (RTProcGetExecutablePath(szExecPath, sizeof(szExecPath)))
763 {
764 if (g_cVerbosity)
765 RTPrintf("Creating the %s service, binary \"%s\"...\n",
766 sServiceName.c_str(), szExecPath); /* yea, the binary name isn't UTF-8, but wtf. */
767
768 /*
769 * Add service name as command line parameter for the service
770 */
771 com::Utf8StrFmt sCmdLine("\"%s\" --service=%s", szExecPath, sServiceName.c_str());
772 com::Bstr bstrServiceName(sServiceName);
773 com::Bstr bstrDisplayName(sDisplayName);
774 com::Bstr bstrCmdLine(sCmdLine);
775 com::Bstr bstrUserFullName(sUserFullName);
776 com::Bstr bstrPwd(strPwd);
777
778 SC_HANDLE hSvc = CreateServiceW(hSCM, /* hSCManager */
779 bstrServiceName.raw(), /* lpServiceName */
780 bstrDisplayName.raw(), /* lpDisplayName */
781 SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, /* dwDesiredAccess */
782 SERVICE_WIN32_OWN_PROCESS, /* dwServiceType ( | SERVICE_INTERACTIVE_PROCESS? ) */
783 SERVICE_AUTO_START, /* dwStartType */
784 SERVICE_ERROR_NORMAL, /* dwErrorControl */
785 bstrCmdLine.raw(), /* lpBinaryPathName */
786 NULL, /* lpLoadOrderGroup */
787 NULL, /* lpdwTagId */
788 L"Winmgmt\0RpcSs\0\0", /* lpDependencies */
789 bstrUserFullName.raw(), /* lpServiceStartName (NULL => LocalSystem) */
790 bstrPwd.raw()); /* lpPassword */
791 if (hSvc)
792 {
793 RTPrintf("Successfully created the %s service.\n", sServiceName.c_str());
794 /** @todo Set the service description or it'll look weird in the vista service manager.
795 * Anything else that should be configured? Start access or something? */
796 rcExit = RTEXITCODE_SUCCESS;
797 CloseServiceHandle(hSvc);
798 }
799 else
800 {
801 DWORD const dwErr = GetLastError();
802 switch (dwErr)
803 {
804 case ERROR_SERVICE_EXISTS:
805 autostartSvcDisplayError("create - The service already exists!\n");
806 break;
807 default:
808 autostartSvcDisplayError("create - CreateService failed, rc=%Rrc (%#x)\n",
809 RTErrConvertFromWin32(dwErr), dwErr);
810 break;
811 }
812 }
813 CloseServiceHandle(hSvc);
814 }
815 else
816 autostartSvcDisplayError("create - Failed to obtain the executable path\n");
817 }
818 return rcExit;
819}
820
821
822/**
823 * Sets the service status, just a SetServiceStatus Wrapper.
824 *
825 * @returns See SetServiceStatus.
826 * @param dwStatus The current status.
827 * @param iWaitHint The wait hint, if < 0 then supply a default.
828 * @param dwExitCode The service exit code.
829 */
830static bool autostartSvcWinSetServiceStatus(DWORD dwStatus, int iWaitHint, DWORD dwExitCode)
831{
832 SERVICE_STATUS SvcStatus;
833 SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
834 SvcStatus.dwWin32ExitCode = dwExitCode;
835 SvcStatus.dwServiceSpecificExitCode = 0;
836 SvcStatus.dwWaitHint = iWaitHint >= 0 ? iWaitHint : 3000;
837 SvcStatus.dwCurrentState = dwStatus;
838 LogFlow(("autostartSvcWinSetServiceStatus: %d -> %d\n", g_u32SupSvcWinStatus, dwStatus));
839 g_u32SupSvcWinStatus = dwStatus;
840 switch (dwStatus)
841 {
842 case SERVICE_START_PENDING:
843 SvcStatus.dwControlsAccepted = 0;
844 break;
845 default:
846 SvcStatus.dwControlsAccepted
847 = SERVICE_ACCEPT_STOP
848 | SERVICE_ACCEPT_SHUTDOWN;
849 break;
850 }
851
852 static DWORD dwCheckPoint = 0;
853 switch (dwStatus)
854 {
855 case SERVICE_RUNNING:
856 case SERVICE_STOPPED:
857 SvcStatus.dwCheckPoint = 0;
858 default:
859 SvcStatus.dwCheckPoint = ++dwCheckPoint;
860 break;
861 }
862 return SetServiceStatus(g_hSupSvcWinCtrlHandler, &SvcStatus) != FALSE;
863}
864
865
866/**
867 * Service control handler (extended).
868 *
869 * @returns Windows status (see HandlerEx).
870 * @retval NO_ERROR if handled.
871 * @retval ERROR_CALL_NOT_IMPLEMENTED if not handled.
872 *
873 * @param dwControl The control code.
874 * @param dwEventType Event type. (specific to the control?)
875 * @param pvEventData Event data, specific to the event.
876 * @param pvContext The context pointer registered with the handler.
877 * Currently not used.
878 */
879static DWORD WINAPI
880autostartSvcWinServiceCtrlHandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID pvEventData, LPVOID pvContext) RT_NOTHROW_DEF
881{
882 RT_NOREF(dwEventType);
883 RT_NOREF(pvEventData);
884 RT_NOREF(pvContext);
885
886 LogFlow(("autostartSvcWinServiceCtrlHandlerEx: dwControl=%#x dwEventType=%#x pvEventData=%p\n",
887 dwControl, dwEventType, pvEventData));
888
889 switch (dwControl)
890 {
891 /*
892 * Interrogate the service about it's current status.
893 * MSDN says that this should just return NO_ERROR and does
894 * not need to set the status again.
895 */
896 case SERVICE_CONTROL_INTERROGATE:
897 return NO_ERROR;
898
899 /*
900 * Request to stop the service.
901 */
902 case SERVICE_CONTROL_SHUTDOWN:
903 case SERVICE_CONTROL_STOP:
904 {
905 if (dwControl == SERVICE_CONTROL_SHUTDOWN)
906 autostartSvcLogVerbose(1, "SERVICE_CONTROL_SHUTDOWN\n");
907 else
908 autostartSvcLogVerbose(1, "SERVICE_CONTROL_STOP\n");
909
910 /*
911 * Check if the real services can be stopped and then tell them to stop.
912 */
913 autostartSvcWinSetServiceStatus(SERVICE_STOP_PENDING, 3000, NO_ERROR);
914
915 /*
916 * Notify the main thread that we're done, it will wait for the
917 * VMs to stop, and set the windows service status to SERVICE_STOPPED
918 * and return.
919 */
920 int rc = RTSemEventMultiSignal(g_hSupSvcWinEvent);
921 if (RT_FAILURE(rc)) /** @todo r=andy Don't we want to report back an error here to SCM? */
922 autostartSvcLogErrorRc(rc, "SERVICE_CONTROL_STOP: RTSemEventMultiSignal failed, %Rrc\n", rc);
923
924 return NO_ERROR;
925 }
926
927 default:
928 /*
929 * We only expect to receive controls we explicitly listed
930 * in SERVICE_STATUS::dwControlsAccepted. Logged in hex
931 * b/c WinSvc.h defines them in hex
932 */
933 autostartSvcLogWarning("Unexpected service control message 0x%RX64\n", (uint64_t)dwControl);
934 break;
935 }
936
937 return ERROR_CALL_NOT_IMPLEMENTED;
938}
939
940static int autostartStartVMs(void)
941{
942 int rc = autostartSetup();
943 if (RT_FAILURE(rc))
944 return rc;
945
946 const char *pszConfigFile = RTEnvGet("VBOXAUTOSTART_CONFIG");
947 if (!pszConfigFile)
948 return autostartSvcLogErrorRc(VERR_ENV_VAR_NOT_FOUND,
949 "Starting VMs failed. VBOXAUTOSTART_CONFIG environment variable is not defined.\n");
950 bool fAllow = false;
951
952 PCFGAST pCfgAst = NULL;
953 rc = autostartParseConfig(pszConfigFile, &pCfgAst);
954 if (RT_FAILURE(rc))
955 return autostartSvcLogErrorRc(rc, "Starting VMs failed. Failed to parse the config file. Check the access permissions and file structure.\n");
956 PCFGAST pCfgAstPolicy = autostartConfigAstGetByName(pCfgAst, "default_policy");
957 /* Check default policy. */
958 if (pCfgAstPolicy)
959 {
960 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
961 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow")
962 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "deny")))
963 {
964 if (!RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow"))
965 fAllow = true;
966 }
967 else
968 {
969 autostartConfigAstDestroy(pCfgAst);
970 return autostartSvcLogErrorRc(VERR_INVALID_PARAMETER, "'default_policy' must be either 'allow' or 'deny'.\n");
971 }
972 }
973
974 com::Utf8Str sUser;
975 rc = autostartGetProcessDomainUser(sUser);
976 if (RT_FAILURE(rc))
977 {
978 autostartConfigAstDestroy(pCfgAst);
979 return autostartSvcLogErrorRc(rc, "Failed to query username of the process (%Rrc).\n", rc);
980 }
981
982 PCFGAST pCfgAstUser = NULL;
983 for (unsigned i = 0; i < pCfgAst->u.Compound.cAstNodes; i++)
984 {
985 PCFGAST pNode = pCfgAst->u.Compound.apAstNodes[i];
986 com::Utf8Str sDomain;
987 com::Utf8Str sUserTmp;
988 rc = autostartGetDomainAndUser(pNode->pszKey, sDomain, sUserTmp);
989 if (RT_FAILURE(rc))
990 continue;
991 com::Utf8StrFmt sDomainUser("%s\\%s", sDomain.c_str(), sUserTmp.c_str());
992 if (sDomainUser == sUser)
993 {
994 pCfgAstUser = pNode;
995 break;
996 }
997 }
998
999 if ( pCfgAstUser
1000 && pCfgAstUser->enmType == CFGASTNODETYPE_COMPOUND)
1001 {
1002 pCfgAstPolicy = autostartConfigAstGetByName(pCfgAstUser, "allow");
1003 if (pCfgAstPolicy)
1004 {
1005 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
1006 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true")
1007 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "false")))
1008 fAllow = RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true") == 0;
1009 else
1010 {
1011 autostartConfigAstDestroy(pCfgAst);
1012 return autostartSvcLogErrorRc(VERR_INVALID_PARAMETER, "'allow' must be either 'true' or 'false'.\n");
1013 }
1014 }
1015 }
1016 else if (pCfgAstUser)
1017 {
1018 autostartConfigAstDestroy(pCfgAst);
1019 return autostartSvcLogErrorRc(VERR_INVALID_PARAMETER, "Invalid config, user is not a compound node.\n");
1020 }
1021
1022 if (!fAllow)
1023 {
1024 autostartConfigAstDestroy(pCfgAst);
1025 return autostartSvcLogErrorRc(VERR_INVALID_PARAMETER, "User is not allowed to autostart VMs.\n");
1026 }
1027
1028 if (RT_SUCCESS(rc))
1029 rc = autostartStartMain(pCfgAstUser);
1030
1031 autostartConfigAstDestroy(pCfgAst);
1032
1033 return rc;
1034}
1035
1036/**
1037 * Windows Service Main.
1038 *
1039 * This is invoked when the service is started and should not return until
1040 * the service has been stopped.
1041 *
1042 * @param cArgs Argument count.
1043 * @param papwszArgs Argument vector.
1044 */
1045static VOID WINAPI autostartSvcWinServiceMain(DWORD cArgs, LPWSTR *papwszArgs)
1046{
1047 RT_NOREF(cArgs, papwszArgs);
1048 LogFlowFuncEnter();
1049
1050 /* Give this thread a name in the logs. */
1051 RTThreadAdopt(RTTHREADTYPE_DEFAULT, 0, "service", NULL);
1052
1053#if 0
1054 for (size_t i = 0; i < cArgs; ++i)
1055 LogRel(("arg[%zu] = %ls\n", i, papwszArgs[i]));
1056#endif
1057
1058 DWORD dwErr = ERROR_GEN_FAILURE;
1059
1060 /*
1061 * Register the control handler function for the service and report to SCM.
1062 */
1063 Assert(g_u32SupSvcWinStatus == SERVICE_STOPPED);
1064 g_hSupSvcWinCtrlHandler = RegisterServiceCtrlHandlerExW(g_bstrServiceName.raw(), autostartSvcWinServiceCtrlHandlerEx, NULL);
1065 if (g_hSupSvcWinCtrlHandler)
1066 {
1067 if (autostartSvcWinSetServiceStatus(SERVICE_START_PENDING, 3000, NO_ERROR))
1068 {
1069 /*
1070 * Create the event semaphore we'll be waiting on and
1071 * then instantiate the actual services.
1072 */
1073 int rc = RTSemEventMultiCreate(&g_hSupSvcWinEvent);
1074 if (RT_SUCCESS(rc))
1075 {
1076 /*
1077 * Update the status and enter the work loop.
1078 */
1079 if (autostartSvcWinSetServiceStatus(SERVICE_RUNNING, 0, 0))
1080 {
1081 LogFlow(("autostartSvcWinServiceMain: calling autostartStartVMs\n"));
1082
1083 /* check if we should stopped already, e.g. windows shutdown */
1084 rc = RTSemEventMultiWait(g_hSupSvcWinEvent, 1);
1085 if (RT_FAILURE(rc))
1086 {
1087 /* No one signaled us to stop */
1088 rc = autostartStartVMs();
1089 }
1090 autostartShutdown();
1091 }
1092 else
1093 {
1094 dwErr = GetLastError();
1095 autostartSvcLogError("SetServiceStatus failed, rc=%Rrc (%#x)\n", RTErrConvertFromWin32(dwErr), dwErr);
1096 }
1097
1098 RTSemEventMultiDestroy(g_hSupSvcWinEvent);
1099 g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
1100 }
1101 else
1102 autostartSvcLogError("RTSemEventMultiCreate failed, rc=%Rrc", rc);
1103 }
1104 else
1105 {
1106 dwErr = GetLastError();
1107 autostartSvcLogError("SetServiceStatus failed, rc=%Rrc (%#x)\n", RTErrConvertFromWin32(dwErr), dwErr);
1108 }
1109 autostartSvcWinSetServiceStatus(SERVICE_STOPPED, 0, dwErr);
1110 }
1111 /* else error will be handled by the caller. */
1112}
1113
1114
1115/**
1116 * Handle the 'runit' action.
1117 *
1118 * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
1119 * @param argc The action argument count.
1120 * @param argv The action argument vector.
1121 */
1122static RTEXITCODE autostartSvcWinRunIt(int argc, char **argv)
1123{
1124 int vrc;
1125
1126 LogFlowFuncEnter();
1127
1128 /*
1129 * Init com here for first main thread initialization.
1130 * Service main function called in another thread
1131 * created by service manager.
1132 */
1133 HRESULT hrc = com::Initialize();
1134# ifdef VBOX_WITH_XPCOM
1135 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
1136 {
1137 char szHome[RTPATH_MAX] = "";
1138 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
1139 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1140 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
1141 }
1142# endif
1143 if (FAILED(hrc))
1144 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM (%Rhrc)!", hrc);
1145 /*
1146 * Initialize release logging, do this early. This means command
1147 * line options (like --logfile &c) can't be introduced to affect
1148 * the log file parameters, but the user can't change them easily
1149 * anyway and is better off using environment variables.
1150 */
1151 do
1152 {
1153 char szLogFile[RTPATH_MAX];
1154 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile),
1155 /* :fCreateDir */ false);
1156 if (RT_FAILURE(vrc))
1157 {
1158 autostartSvcLogError("Failed to get VirtualBox user home directory: %Rrc\n", vrc);
1159 break;
1160 }
1161
1162 if (!RTDirExists(szLogFile)) /* vbox user home dir */
1163 {
1164 autostartSvcLogError("%s doesn't exist\n", szLogFile);
1165 break;
1166 }
1167
1168 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxAutostart.log");
1169 if (RT_FAILURE(vrc))
1170 {
1171 autostartSvcLogError( "Failed to construct release log file name: %Rrc\n", vrc);
1172 break;
1173 }
1174
1175 vrc = com::VBoxLogRelCreate(AUTOSTART_SERVICE_NAME,
1176 szLogFile,
1177 RTLOGFLAGS_PREFIX_THREAD
1178 | RTLOGFLAGS_PREFIX_TIME_PROG,
1179 "all",
1180 "VBOXAUTOSTART_RELEASE_LOG",
1181 RTLOGDEST_FILE,
1182 UINT32_MAX /* cMaxEntriesPerGroup */,
1183 g_cHistory,
1184 g_uHistoryFileTime,
1185 g_uHistoryFileSize,
1186 NULL);
1187 if (RT_FAILURE(vrc))
1188 autostartSvcLogError("Failed to create release log file: %Rrc\n", vrc);
1189 } while (0);
1190
1191 /*
1192 * Parse the arguments.
1193 */
1194 static const RTGETOPTDEF s_aOptions[] =
1195 {
1196 /* Common options first. */
1197 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1198 { "--service", 's', RTGETOPT_REQ_STRING },
1199 };
1200
1201 const char *pszServiceName = NULL;
1202 int ch;
1203 RTGETOPTUNION ValueUnion;
1204 RTGETOPTSTATE GetState;
1205 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1206 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1207 {
1208 switch (ch)
1209 {
1210 /* Common options first. */
1211 case 'v':
1212 g_cVerbosity++;
1213 break;
1214 case 's':
1215 pszServiceName = ValueUnion.psz;
1216 try
1217 {
1218 g_bstrServiceName = com::Bstr(ValueUnion.psz);
1219 }
1220 catch (...)
1221 {
1222 autostartSvcLogError("runit failed, service name is not valid UTF-8 string or out of memory");
1223 return RTEXITCODE_FAILURE;
1224 }
1225 break;
1226
1227 default:
1228 return autostartSvcDisplayGetOptError("runit", ch, &ValueUnion);
1229 }
1230 }
1231
1232 if (!pszServiceName)
1233 {
1234 autostartSvcLogError("runit failed, service name is missing");
1235 return RTEXITCODE_SYNTAX;
1236 }
1237
1238 autostartSvcLogInfo("Starting service %ls\n", g_bstrServiceName.raw());
1239
1240 /*
1241 * Register the service with the service control manager
1242 * and start dispatching requests from it (all done by the API).
1243 */
1244 SERVICE_TABLE_ENTRYW const s_aServiceStartTable[] =
1245 {
1246 { g_bstrServiceName.raw(), autostartSvcWinServiceMain },
1247 { NULL, NULL}
1248 };
1249
1250 if (StartServiceCtrlDispatcherW(&s_aServiceStartTable[0]))
1251 {
1252 LogFlowFuncLeave();
1253 return RTEXITCODE_SUCCESS; /* told to quit, so quit. */
1254 }
1255
1256 DWORD const dwErr = GetLastError();
1257 switch (dwErr)
1258 {
1259 case ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
1260 autostartSvcLogWarning("Cannot run a service from the command line. Use the 'start' action to start it the right way.\n");
1261 autostartSvcWinServiceMain(0 /* cArgs */, NULL /* papwszArgs */);
1262 break;
1263 default:
1264 autostartSvcLogError("StartServiceCtrlDispatcher failed, rc=%Rrc (%#x)\n", RTErrConvertFromWin32(dwErr), dwErr);
1265 break;
1266 }
1267
1268 com::Shutdown();
1269
1270 return RTEXITCODE_FAILURE;
1271}
1272
1273
1274/**
1275 * Show the version info.
1276 *
1277 * @returns RTEXITCODE_SUCCESS.
1278 */
1279static RTEXITCODE autostartSvcWinShowVersion(int argc, char **argv)
1280{
1281 /*
1282 * Parse the arguments.
1283 */
1284 bool fBrief = false;
1285 static const RTGETOPTDEF s_aOptions[] =
1286 {
1287 { "--brief", 'b', RTGETOPT_REQ_NOTHING }
1288 };
1289 int ch;
1290 RTGETOPTUNION Value;
1291 RTGETOPTSTATE GetState;
1292 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1293 while ((ch = RTGetOpt(&GetState, &Value)))
1294 switch (ch)
1295 {
1296 case 'b': fBrief = true; break;
1297 default: return autostartSvcDisplayGetOptError("version", ch, &Value);
1298 }
1299
1300 /*
1301 * Do the printing.
1302 */
1303 autostartSvcShowVersion(fBrief);
1304
1305 return RTEXITCODE_SUCCESS;
1306}
1307
1308
1309/**
1310 * Show the usage help screen.
1311 *
1312 * @returns RTEXITCODE_SUCCESS.
1313 */
1314static RTEXITCODE autostartSvcWinShowHelp(void)
1315{
1316 autostartSvcShowHeader();
1317
1318 const char *pszExe = RTPathFilename(RTProcExecutablePath());
1319
1320 RTPrintf("Usage:\n"
1321 "\n"
1322 "%s [global-options] [command] [command-options]\n"
1323 "\n"
1324 "Global options:\n"
1325 " -v\n"
1326 " Increases the verbosity. Can be specified multiple times."
1327 "\n\n"
1328 "No command given:\n"
1329 " Runs the service.\n"
1330 "Options:\n"
1331 " --service <name>\n"
1332 " Specifies the service name to run.\n"
1333 "\n"
1334 "Command </help|help|-?|-h|--help> [...]\n"
1335 " Displays this help screen.\n"
1336 "\n"
1337 "Command </version|version|-V|--version> [-brief]\n"
1338 " Displays the version.\n"
1339 "\n"
1340 "Command </i|install|/RegServer> --user <username> --password-file <...>\n"
1341 " Installs the service.\n"
1342 "Options:\n"
1343 " --user <username>\n"
1344 " Specifies the user name the service should be installed for.\n"
1345 " --password-file <path/to/file>\n"
1346 " Specifies the file for user password to use for installation.\n"
1347 "\n"
1348 "Command </u|uninstall|delete|/UnregServer>\n"
1349 " Uninstalls the service.\n"
1350 " --user <username>\n"
1351 " Specifies the user name the service should will be deleted for.\n",
1352 pszExe);
1353 return RTEXITCODE_SUCCESS;
1354}
1355
1356
1357/**
1358 * VBoxAutostart main(), Windows edition.
1359 *
1360 *
1361 * @returns 0 on success.
1362 *
1363 * @param argc Number of arguments in argv.
1364 * @param argv Argument vector.
1365 */
1366int main(int argc, char **argv)
1367{
1368 /*
1369 * Initialize the IPRT first of all.
1370 */
1371 int rc = RTR3InitExe(argc, &argv, 0);
1372 if (RT_FAILURE(rc))
1373 {
1374 autostartSvcLogError("RTR3InitExe failed with rc=%Rrc", rc);
1375 return RTEXITCODE_FAILURE;
1376 }
1377
1378 /*
1379 * Parse the initial arguments to determine the desired action.
1380 */
1381 enum
1382 {
1383 kAutoSvcAction_RunIt,
1384
1385 kAutoSvcAction_Create,
1386 kAutoSvcAction_Delete,
1387
1388 kAutoSvcAction_Enable,
1389 kAutoSvcAction_Disable,
1390 kAutoSvcAction_QueryConfig,
1391 kAutoSvcAction_QueryDescription,
1392
1393 kAutoSvcAction_Start,
1394 kAutoSvcAction_Pause,
1395 kAutoSvcAction_Continue,
1396 kAutoSvcAction_Stop,
1397 kAutoSvcAction_Interrogate,
1398
1399 kAutoSvcAction_End
1400 } enmAction = kAutoSvcAction_RunIt;
1401 int iArg = 1;
1402 if (argc > 1)
1403 {
1404 if ( !stricmp(argv[iArg], "/RegServer")
1405 || !stricmp(argv[iArg], "install")
1406 || !stricmp(argv[iArg], "/i"))
1407 enmAction = kAutoSvcAction_Create;
1408 else if ( !stricmp(argv[iArg], "/UnregServer")
1409 || !stricmp(argv[iArg], "/u")
1410 || !stricmp(argv[iArg], "uninstall")
1411 || !stricmp(argv[iArg], "delete"))
1412 enmAction = kAutoSvcAction_Delete;
1413
1414 else if (!stricmp(argv[iArg], "enable"))
1415 enmAction = kAutoSvcAction_Enable;
1416 else if (!stricmp(argv[iArg], "disable"))
1417 enmAction = kAutoSvcAction_Disable;
1418 else if (!stricmp(argv[iArg], "qconfig"))
1419 enmAction = kAutoSvcAction_QueryConfig;
1420 else if (!stricmp(argv[iArg], "qdescription"))
1421 enmAction = kAutoSvcAction_QueryDescription;
1422
1423 else if ( !stricmp(argv[iArg], "start")
1424 || !stricmp(argv[iArg], "/t"))
1425 enmAction = kAutoSvcAction_Start;
1426 else if (!stricmp(argv[iArg], "pause"))
1427 enmAction = kAutoSvcAction_Start;
1428 else if (!stricmp(argv[iArg], "continue"))
1429 enmAction = kAutoSvcAction_Continue;
1430 else if (!stricmp(argv[iArg], "stop"))
1431 enmAction = kAutoSvcAction_Stop;
1432 else if (!stricmp(argv[iArg], "interrogate"))
1433 enmAction = kAutoSvcAction_Interrogate;
1434 else if ( !stricmp(argv[iArg], "help")
1435 || !stricmp(argv[iArg], "?")
1436 || !stricmp(argv[iArg], "/?")
1437 || !stricmp(argv[iArg], "-?")
1438 || !stricmp(argv[iArg], "/h")
1439 || !stricmp(argv[iArg], "-h")
1440 || !stricmp(argv[iArg], "/help")
1441 || !stricmp(argv[iArg], "-help")
1442 || !stricmp(argv[iArg], "--help"))
1443 return autostartSvcWinShowHelp();
1444 else if ( !stricmp(argv[iArg], "version")
1445 || !stricmp(argv[iArg], "/ver")
1446 || !stricmp(argv[iArg], "-V") /* Note: "-v" is used for specifying the verbosity. */
1447 || !stricmp(argv[iArg], "/version")
1448 || !stricmp(argv[iArg], "-version")
1449 || !stricmp(argv[iArg], "--version"))
1450 return autostartSvcWinShowVersion(argc - iArg - 1, argv + iArg + 1);
1451 else
1452 iArg--;
1453 iArg++;
1454 }
1455
1456 /*
1457 * Dispatch it.
1458 */
1459 switch (enmAction)
1460 {
1461 case kAutoSvcAction_RunIt:
1462 return autostartSvcWinRunIt(argc - iArg, argv + iArg);
1463
1464 case kAutoSvcAction_Create:
1465 return autostartSvcWinCreate(argc - iArg, argv + iArg);
1466 case kAutoSvcAction_Delete:
1467 return autostartSvcWinDelete(argc - iArg, argv + iArg);
1468
1469 case kAutoSvcAction_Enable:
1470 return autostartSvcWinEnable(argc - iArg, argv + iArg);
1471 case kAutoSvcAction_Disable:
1472 return autostartSvcWinDisable(argc - iArg, argv + iArg);
1473 case kAutoSvcAction_QueryConfig:
1474 return autostartSvcWinQueryConfig(argc - iArg, argv + iArg);
1475 case kAutoSvcAction_QueryDescription:
1476 return autostartSvcWinQueryDescription(argc - iArg, argv + iArg);
1477
1478 case kAutoSvcAction_Start:
1479 return autostartSvcWinStart(argc - iArg, argv + iArg);
1480 case kAutoSvcAction_Pause:
1481 return autostartSvcWinPause(argc - iArg, argv + iArg);
1482 case kAutoSvcAction_Continue:
1483 return autostartSvcWinContinue(argc - iArg, argv + iArg);
1484 case kAutoSvcAction_Stop:
1485 return autostartSvcWinStop(argc - iArg, argv + iArg);
1486 case kAutoSvcAction_Interrogate:
1487 return autostartSvcWinInterrogate(argc - iArg, argv + iArg);
1488
1489 default:
1490 AssertMsgFailed(("enmAction=%d\n", enmAction));
1491 return RTEXITCODE_FAILURE;
1492 }
1493}
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use