VirtualBox

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

Last change on this file since 103858 was 103858, checked in by vboxsync, 9 months ago

FE/VBoxAutostart: Made it easier to use on Windows by printing out the syntax help if an invalid (or no) command is being specified. Fixed missing newlines for error output.

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