VirtualBox

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

Last change on this file since 106814 was 106524, checked in by vboxsync, 6 weeks ago

VBoxAutostart: Missing break. jiraref:VBP-1171

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 51.6 KB
Line 
1/* $Id: VBoxAutostart-win.cpp 106524 2024-10-20 02:34:15Z vboxsync $ */
2/** @file
3 * VirtualBox Autostart Service - Windows Specific Code.
4 */
5
6/*
7 * Copyright (C) 2012-2024 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 = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
849 break;
850 }
851
852 static DWORD s_dwCheckPoint = 0;
853 switch (dwStatus)
854 {
855 case SERVICE_RUNNING:
856 case SERVICE_STOPPED:
857 SvcStatus.dwCheckPoint = 0;
858 break;
859 default:
860 SvcStatus.dwCheckPoint = ++s_dwCheckPoint;
861 break;
862 }
863 return SetServiceStatus(g_hSupSvcWinCtrlHandler, &SvcStatus) != FALSE;
864}
865
866
867/**
868 * Service control handler (extended).
869 *
870 * @returns Windows status (see HandlerEx).
871 * @retval NO_ERROR if handled.
872 * @retval ERROR_CALL_NOT_IMPLEMENTED if not handled.
873 *
874 * @param dwControl The control code.
875 * @param dwEventType Event type. (specific to the control?)
876 * @param pvEventData Event data, specific to the event.
877 * @param pvContext The context pointer registered with the handler.
878 * Currently not used.
879 */
880static DWORD WINAPI
881autostartSvcWinServiceCtrlHandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID pvEventData, LPVOID pvContext) RT_NOTHROW_DEF
882{
883 RT_NOREF(dwEventType);
884 RT_NOREF(pvEventData);
885 RT_NOREF(pvContext);
886
887 LogFlow(("autostartSvcWinServiceCtrlHandlerEx: dwControl=%#x dwEventType=%#x pvEventData=%p\n",
888 dwControl, dwEventType, pvEventData));
889
890 switch (dwControl)
891 {
892 /*
893 * Interrogate the service about it's current status.
894 * MSDN says that this should just return NO_ERROR and does
895 * not need to set the status again.
896 */
897 case SERVICE_CONTROL_INTERROGATE:
898 return NO_ERROR;
899
900 /*
901 * Request to stop the service.
902 */
903 case SERVICE_CONTROL_SHUTDOWN:
904 case SERVICE_CONTROL_STOP:
905 {
906 if (dwControl == SERVICE_CONTROL_SHUTDOWN)
907 autostartSvcLogVerbose(1, "SERVICE_CONTROL_SHUTDOWN\n");
908 else
909 autostartSvcLogVerbose(1, "SERVICE_CONTROL_STOP\n");
910
911 /*
912 * Check if the real services can be stopped and then tell them to stop.
913 */
914 autostartSvcWinSetServiceStatus(SERVICE_STOP_PENDING, 3000, NO_ERROR);
915
916 /*
917 * Notify the main thread that we're done, it will wait for the
918 * VMs to stop, and set the windows service status to SERVICE_STOPPED
919 * and return.
920 */
921 int rc = RTSemEventMultiSignal(g_hSupSvcWinEvent);
922 if (RT_FAILURE(rc)) /** @todo r=andy Don't we want to report back an error here to SCM? */
923 autostartSvcLogErrorRc(rc, "SERVICE_CONTROL_STOP: RTSemEventMultiSignal failed, %Rrc\n", rc);
924
925 return NO_ERROR;
926 }
927
928 default:
929 /*
930 * We only expect to receive controls we explicitly listed
931 * in SERVICE_STATUS::dwControlsAccepted. Logged in hex
932 * b/c WinSvc.h defines them in hex
933 */
934 autostartSvcLogWarning("Unexpected service control message 0x%RX64\n", (uint64_t)dwControl);
935 break;
936 }
937
938 return ERROR_CALL_NOT_IMPLEMENTED;
939}
940
941static int autostartStartVMs(void)
942{
943 int rc = autostartSetup();
944 if (RT_FAILURE(rc))
945 return rc;
946
947 const char *pszConfigFile = RTEnvGet("VBOXAUTOSTART_CONFIG");
948 if (!pszConfigFile)
949 return autostartSvcLogErrorRc(VERR_ENV_VAR_NOT_FOUND,
950 "Starting VMs failed. VBOXAUTOSTART_CONFIG environment variable is not defined.\n");
951 bool fAllow = false;
952
953 PCFGAST pCfgAst = NULL;
954 rc = autostartParseConfig(pszConfigFile, &pCfgAst);
955 if (RT_FAILURE(rc))
956 return autostartSvcLogErrorRc(rc, "Starting VMs failed. Failed to parse the config file. Check the access permissions and file structure.\n");
957 PCFGAST pCfgAstPolicy = autostartConfigAstGetByName(pCfgAst, "default_policy");
958 /* Check default policy. */
959 if (pCfgAstPolicy)
960 {
961 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
962 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow")
963 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "deny")))
964 {
965 if (!RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow"))
966 fAllow = true;
967 }
968 else
969 {
970 autostartConfigAstDestroy(pCfgAst);
971 return autostartSvcLogErrorRc(VERR_INVALID_PARAMETER, "'default_policy' must be either 'allow' or 'deny'.\n");
972 }
973 }
974
975 com::Utf8Str sUser;
976 rc = autostartGetProcessDomainUser(sUser);
977 if (RT_FAILURE(rc))
978 {
979 autostartConfigAstDestroy(pCfgAst);
980 return autostartSvcLogErrorRc(rc, "Failed to query username of the process (%Rrc).\n", rc);
981 }
982
983 PCFGAST pCfgAstUser = NULL;
984 for (unsigned i = 0; i < pCfgAst->u.Compound.cAstNodes; i++)
985 {
986 PCFGAST pNode = pCfgAst->u.Compound.apAstNodes[i];
987 com::Utf8Str sDomain;
988 com::Utf8Str sUserTmp;
989 rc = autostartGetDomainAndUser(pNode->pszKey, sDomain, sUserTmp);
990 if (RT_FAILURE(rc))
991 continue;
992 com::Utf8StrFmt sDomainUser("%s\\%s", sDomain.c_str(), sUserTmp.c_str());
993 if (sDomainUser == sUser)
994 {
995 pCfgAstUser = pNode;
996 break;
997 }
998 }
999
1000 if ( pCfgAstUser
1001 && pCfgAstUser->enmType == CFGASTNODETYPE_COMPOUND)
1002 {
1003 pCfgAstPolicy = autostartConfigAstGetByName(pCfgAstUser, "allow");
1004 if (pCfgAstPolicy)
1005 {
1006 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
1007 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true")
1008 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "false")))
1009 fAllow = RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true") == 0;
1010 else
1011 {
1012 autostartConfigAstDestroy(pCfgAst);
1013 return autostartSvcLogErrorRc(VERR_INVALID_PARAMETER, "'allow' must be either 'true' or 'false'.\n");
1014 }
1015 }
1016 }
1017 else if (pCfgAstUser)
1018 {
1019 autostartConfigAstDestroy(pCfgAst);
1020 return autostartSvcLogErrorRc(VERR_INVALID_PARAMETER, "Invalid config, user is not a compound node.\n");
1021 }
1022
1023 if (!fAllow)
1024 {
1025 autostartConfigAstDestroy(pCfgAst);
1026 return autostartSvcLogErrorRc(VERR_INVALID_PARAMETER, "User is not allowed to autostart VMs.\n");
1027 }
1028
1029 if (RT_SUCCESS(rc))
1030 rc = autostartStartMain(pCfgAstUser);
1031
1032 autostartConfigAstDestroy(pCfgAst);
1033
1034 return rc;
1035}
1036
1037/**
1038 * Windows Service Main.
1039 *
1040 * This is invoked when the service is started and should not return until
1041 * the service has been stopped.
1042 *
1043 * @param cArgs Argument count.
1044 * @param papwszArgs Argument vector.
1045 */
1046static VOID WINAPI autostartSvcWinServiceMain(DWORD cArgs, LPWSTR *papwszArgs)
1047{
1048 RT_NOREF(cArgs, papwszArgs);
1049 LogFlowFuncEnter();
1050
1051 /* Give this thread a name in the logs. */
1052 RTThreadAdopt(RTTHREADTYPE_DEFAULT, 0, "service", NULL);
1053
1054#if 0
1055 for (size_t i = 0; i < cArgs; ++i)
1056 LogRel(("arg[%zu] = %ls\n", i, papwszArgs[i]));
1057#endif
1058
1059 DWORD dwErr = ERROR_GEN_FAILURE;
1060
1061 /*
1062 * Register the control handler function for the service and report to SCM.
1063 */
1064 Assert(g_u32SupSvcWinStatus == SERVICE_STOPPED);
1065 g_hSupSvcWinCtrlHandler = RegisterServiceCtrlHandlerExW(g_bstrServiceName.raw(), autostartSvcWinServiceCtrlHandlerEx, NULL);
1066 if (g_hSupSvcWinCtrlHandler)
1067 {
1068 if (autostartSvcWinSetServiceStatus(SERVICE_START_PENDING, 3000, NO_ERROR))
1069 {
1070 /*
1071 * Create the event semaphore we'll be waiting on and
1072 * then instantiate the actual services.
1073 */
1074 int rc = RTSemEventMultiCreate(&g_hSupSvcWinEvent);
1075 if (RT_SUCCESS(rc))
1076 {
1077 /*
1078 * Update the status and enter the work loop.
1079 */
1080 if (autostartSvcWinSetServiceStatus(SERVICE_RUNNING, 0, 0))
1081 {
1082 LogFlow(("autostartSvcWinServiceMain: calling autostartStartVMs\n"));
1083
1084 /* check if we should stopped already, e.g. windows shutdown */
1085 rc = RTSemEventMultiWait(g_hSupSvcWinEvent, 1);
1086 if (RT_FAILURE(rc))
1087 {
1088 /* No one signaled us to stop */
1089 rc = autostartStartVMs();
1090 }
1091 autostartShutdown();
1092 }
1093 else
1094 {
1095 dwErr = GetLastError();
1096 autostartSvcLogError("SetServiceStatus failed, rc=%Rrc (%#x)\n", RTErrConvertFromWin32(dwErr), dwErr);
1097 }
1098
1099 RTSemEventMultiDestroy(g_hSupSvcWinEvent);
1100 g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
1101 }
1102 else
1103 autostartSvcLogError("RTSemEventMultiCreate failed, rc=%Rrc\n", rc);
1104 }
1105 else
1106 {
1107 dwErr = GetLastError();
1108 autostartSvcLogError("SetServiceStatus failed, rc=%Rrc (%#x)\n", RTErrConvertFromWin32(dwErr), dwErr);
1109 }
1110 autostartSvcWinSetServiceStatus(SERVICE_STOPPED, 0, dwErr);
1111 }
1112 /* else error will be handled by the caller. */
1113}
1114
1115
1116/**
1117 * Handle the 'runit' action.
1118 *
1119 * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
1120 * @param argc The action argument count.
1121 * @param argv The action argument vector.
1122 */
1123static RTEXITCODE autostartSvcWinRunIt(int argc, char **argv)
1124{
1125 int vrc;
1126
1127 LogFlowFuncEnter();
1128
1129 /*
1130 * Init com here for first main thread initialization.
1131 * Service main function called in another thread
1132 * created by service manager.
1133 */
1134 HRESULT hrc = com::Initialize();
1135# ifdef VBOX_WITH_XPCOM
1136 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
1137 {
1138 char szHome[RTPATH_MAX] = "";
1139 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
1140 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1141 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
1142 }
1143# endif
1144 if (FAILED(hrc))
1145 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM (%Rhrc)!", hrc);
1146 /*
1147 * Initialize release logging, do this early. This means command
1148 * line options (like --logfile &c) can't be introduced to affect
1149 * the log file parameters, but the user can't change them easily
1150 * anyway and is better off using environment variables.
1151 */
1152 do
1153 {
1154 char szLogFile[RTPATH_MAX];
1155 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile),
1156 /* :fCreateDir */ false);
1157 if (RT_FAILURE(vrc))
1158 {
1159 autostartSvcLogError("Failed to get VirtualBox user home directory: %Rrc\n", vrc);
1160 break;
1161 }
1162
1163 if (!RTDirExists(szLogFile)) /* vbox user home dir */
1164 {
1165 autostartSvcLogError("%s doesn't exist\n", szLogFile);
1166 break;
1167 }
1168
1169 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxAutostart.log");
1170 if (RT_FAILURE(vrc))
1171 {
1172 autostartSvcLogError( "Failed to construct release log file name: %Rrc\n", vrc);
1173 break;
1174 }
1175
1176 vrc = com::VBoxLogRelCreate(AUTOSTART_SERVICE_NAME,
1177 szLogFile,
1178 RTLOGFLAGS_PREFIX_THREAD
1179 | RTLOGFLAGS_PREFIX_TIME_PROG,
1180 "all",
1181 "VBOXAUTOSTART_RELEASE_LOG",
1182 RTLOGDEST_FILE,
1183 UINT32_MAX /* cMaxEntriesPerGroup */,
1184 g_cHistory,
1185 g_uHistoryFileTime,
1186 g_uHistoryFileSize,
1187 NULL);
1188 if (RT_FAILURE(vrc))
1189 autostartSvcLogError("Failed to create release log file: %Rrc\n", vrc);
1190 } while (0);
1191
1192 /*
1193 * Parse the arguments.
1194 */
1195 static const RTGETOPTDEF s_aOptions[] =
1196 {
1197 /* Common options first. */
1198 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
1199 { "--service", 's', RTGETOPT_REQ_STRING },
1200 };
1201
1202 const char *pszServiceName = NULL;
1203 int ch;
1204 RTGETOPTUNION ValueUnion;
1205 RTGETOPTSTATE GetState;
1206 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1207 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1208 {
1209 switch (ch)
1210 {
1211 /* Common options first. */
1212 case 'v':
1213 g_cVerbosity++;
1214 break;
1215 case 's':
1216 pszServiceName = ValueUnion.psz;
1217 try
1218 {
1219 g_bstrServiceName = com::Bstr(ValueUnion.psz);
1220 }
1221 catch (...)
1222 {
1223 autostartSvcLogError("runit failed, service name is not valid UTF-8 string or out of memory\n");
1224 return RTEXITCODE_FAILURE;
1225 }
1226 break;
1227
1228 default:
1229 return autostartSvcDisplayGetOptError("runit", ch, &ValueUnion);
1230 }
1231 }
1232
1233 if (!pszServiceName)
1234 {
1235 autostartSvcLogError("runit failed, service name is missing\n");
1236 return RTEXITCODE_SYNTAX;
1237 }
1238
1239 autostartSvcLogInfo("Starting service %ls\n", g_bstrServiceName.raw());
1240
1241 /*
1242 * Register the service with the service control manager
1243 * and start dispatching requests from it (all done by the API).
1244 */
1245 SERVICE_TABLE_ENTRYW const s_aServiceStartTable[] =
1246 {
1247 { g_bstrServiceName.raw(), autostartSvcWinServiceMain },
1248 { NULL, NULL}
1249 };
1250
1251 if (StartServiceCtrlDispatcherW(&s_aServiceStartTable[0]))
1252 {
1253 LogFlowFuncLeave();
1254 return RTEXITCODE_SUCCESS; /* told to quit, so quit. */
1255 }
1256
1257 DWORD const dwErr = GetLastError();
1258 switch (dwErr)
1259 {
1260 case ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
1261 autostartSvcLogWarning("Cannot run a service from the command line. Use the 'start' action to start it the right way.\n");
1262 autostartSvcWinServiceMain(0 /* cArgs */, NULL /* papwszArgs */);
1263 break;
1264 default:
1265 autostartSvcLogError("StartServiceCtrlDispatcher failed, rc=%Rrc (%#x)\n", RTErrConvertFromWin32(dwErr), dwErr);
1266 break;
1267 }
1268
1269 com::Shutdown();
1270
1271 return RTEXITCODE_FAILURE;
1272}
1273
1274
1275/**
1276 * Show the version info.
1277 *
1278 * @returns RTEXITCODE_SUCCESS.
1279 */
1280static RTEXITCODE autostartSvcWinShowVersion(int argc, char **argv)
1281{
1282 /*
1283 * Parse the arguments.
1284 */
1285 bool fBrief = false;
1286 static const RTGETOPTDEF s_aOptions[] =
1287 {
1288 { "--brief", 'b', RTGETOPT_REQ_NOTHING }
1289 };
1290 int ch;
1291 RTGETOPTUNION Value;
1292 RTGETOPTSTATE GetState;
1293 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1294 while ((ch = RTGetOpt(&GetState, &Value)))
1295 switch (ch)
1296 {
1297 case 'b': fBrief = true; break;
1298 default: return autostartSvcDisplayGetOptError("version", ch, &Value);
1299 }
1300
1301 /*
1302 * Do the printing.
1303 */
1304 autostartSvcShowVersion(fBrief);
1305
1306 return RTEXITCODE_SUCCESS;
1307}
1308
1309
1310/**
1311 * Show the usage help screen.
1312 *
1313 * @returns RTEXITCODE_SUCCESS.
1314 */
1315static RTEXITCODE autostartSvcWinShowHelp(void)
1316{
1317 autostartSvcShowHeader();
1318
1319 const char *pszExe = RTPathFilename(RTProcExecutablePath());
1320
1321 RTPrintf("Usage:\n"
1322 "\n"
1323 "%s [global-options] [command] [command-options]\n"
1324 "\n"
1325 "Global options:\n"
1326 " -v\n"
1327 " Increases the verbosity. Can be specified multiple times."
1328 "\n\n"
1329 "No command given:\n"
1330 " Runs the service.\n"
1331 "Options:\n"
1332 " --service <name>\n"
1333 " Specifies the service name to run.\n"
1334 "\n"
1335 "Command </help|help|-?|-h|--help> [...]\n"
1336 " Displays this help screen.\n"
1337 "\n"
1338 "Command </version|version|-V|--version> [-brief]\n"
1339 " Displays the version.\n"
1340 "\n"
1341 "Command </i|install|/RegServer> --user <username> --password-file <...>\n"
1342 " Installs the service.\n"
1343 "Options:\n"
1344 " --user <username>\n"
1345 " Specifies the user name the service should be installed for.\n"
1346 " --password-file <path/to/file>\n"
1347 " Specifies the file for user password to use for installation.\n"
1348 "\n"
1349 "Command </u|uninstall|delete|/UnregServer>\n"
1350 " Uninstalls the service.\n"
1351 " --user <username>\n"
1352 " Specifies the user name the service should will be deleted for.\n",
1353 pszExe);
1354 return RTEXITCODE_SUCCESS;
1355}
1356
1357
1358/**
1359 * VBoxAutostart main(), Windows edition.
1360 *
1361 *
1362 * @returns 0 on success.
1363 *
1364 * @param argc Number of arguments in argv.
1365 * @param argv Argument vector.
1366 */
1367int main(int argc, char **argv)
1368{
1369 /*
1370 * Initialize the IPRT first of all.
1371 */
1372 int rc = RTR3InitExe(argc, &argv, 0);
1373 if (RT_FAILURE(rc))
1374 {
1375 autostartSvcLogError("RTR3InitExe failed with rc=%Rrc\n", rc);
1376 return RTEXITCODE_FAILURE;
1377 }
1378
1379 /*
1380 * Parse the initial arguments to determine the desired action.
1381 */
1382 enum
1383 {
1384 kAutoSvcAction_RunIt, /* Default action, also called by SCM. */
1385
1386 kAutoSvcAction_Create,
1387 kAutoSvcAction_Delete,
1388
1389 kAutoSvcAction_Enable,
1390 kAutoSvcAction_Disable,
1391 kAutoSvcAction_QueryConfig,
1392 kAutoSvcAction_QueryDescription,
1393
1394 kAutoSvcAction_Start,
1395 kAutoSvcAction_Pause,
1396 kAutoSvcAction_Continue,
1397 kAutoSvcAction_Stop,
1398 kAutoSvcAction_Interrogate,
1399
1400 kAutoSvcAction_End
1401 } enmAction = kAutoSvcAction_RunIt;
1402 int iArg = 1;
1403 if (argc > 1)
1404 {
1405 if ( !stricmp(argv[iArg], "/RegServer")
1406 || !stricmp(argv[iArg], "install")
1407 || !stricmp(argv[iArg], "/i"))
1408 enmAction = kAutoSvcAction_Create;
1409 else if ( !stricmp(argv[iArg], "/UnregServer")
1410 || !stricmp(argv[iArg], "/u")
1411 || !stricmp(argv[iArg], "uninstall")
1412 || !stricmp(argv[iArg], "delete"))
1413 enmAction = kAutoSvcAction_Delete;
1414
1415 else if (!stricmp(argv[iArg], "enable"))
1416 enmAction = kAutoSvcAction_Enable;
1417 else if (!stricmp(argv[iArg], "disable"))
1418 enmAction = kAutoSvcAction_Disable;
1419 else if (!stricmp(argv[iArg], "qconfig"))
1420 enmAction = kAutoSvcAction_QueryConfig;
1421 else if (!stricmp(argv[iArg], "qdescription"))
1422 enmAction = kAutoSvcAction_QueryDescription;
1423
1424 else if ( !stricmp(argv[iArg], "start")
1425 || !stricmp(argv[iArg], "/t"))
1426 enmAction = kAutoSvcAction_Start;
1427 else if (!stricmp(argv[iArg], "pause"))
1428 enmAction = kAutoSvcAction_Start;
1429 else if (!stricmp(argv[iArg], "continue"))
1430 enmAction = kAutoSvcAction_Continue;
1431 else if (!stricmp(argv[iArg], "stop"))
1432 enmAction = kAutoSvcAction_Stop;
1433 else if (!stricmp(argv[iArg], "interrogate"))
1434 enmAction = kAutoSvcAction_Interrogate;
1435 else if ( !stricmp(argv[iArg], "help")
1436 || !stricmp(argv[iArg], "?")
1437 || !stricmp(argv[iArg], "/?")
1438 || !stricmp(argv[iArg], "-?")
1439 || !stricmp(argv[iArg], "/h")
1440 || !stricmp(argv[iArg], "-h")
1441 || !stricmp(argv[iArg], "/help")
1442 || !stricmp(argv[iArg], "-help")
1443 || !stricmp(argv[iArg], "--help"))
1444 return autostartSvcWinShowHelp();
1445 else if ( !stricmp(argv[iArg], "version")
1446 || !stricmp(argv[iArg], "/ver")
1447 || !stricmp(argv[iArg], "-V") /* Note: "-v" is used for specifying the verbosity. */
1448 || !stricmp(argv[iArg], "/version")
1449 || !stricmp(argv[iArg], "-version")
1450 || !stricmp(argv[iArg], "--version"))
1451 return autostartSvcWinShowVersion(argc - iArg - 1, argv + iArg + 1);
1452 else
1453 iArg--;
1454 iArg++;
1455 }
1456
1457 /*
1458 * Dispatch it.
1459 */
1460 switch (enmAction)
1461 {
1462 case kAutoSvcAction_RunIt:
1463 {
1464 RTEXITCODE const rcExit = autostartSvcWinRunIt(argc - iArg, argv + iArg);
1465 if (rcExit == RTEXITCODE_SYNTAX) /* When called by a user (e.g. w/o specifying any command, print our syntax help. */
1466 autostartSvcWinShowHelp();
1467 return rcExit;
1468 }
1469
1470 case kAutoSvcAction_Create:
1471 return autostartSvcWinCreate(argc - iArg, argv + iArg);
1472 case kAutoSvcAction_Delete:
1473 return autostartSvcWinDelete(argc - iArg, argv + iArg);
1474
1475 case kAutoSvcAction_Enable:
1476 return autostartSvcWinEnable(argc - iArg, argv + iArg);
1477 case kAutoSvcAction_Disable:
1478 return autostartSvcWinDisable(argc - iArg, argv + iArg);
1479 case kAutoSvcAction_QueryConfig:
1480 return autostartSvcWinQueryConfig(argc - iArg, argv + iArg);
1481 case kAutoSvcAction_QueryDescription:
1482 return autostartSvcWinQueryDescription(argc - iArg, argv + iArg);
1483
1484 case kAutoSvcAction_Start:
1485 return autostartSvcWinStart(argc - iArg, argv + iArg);
1486 case kAutoSvcAction_Pause:
1487 return autostartSvcWinPause(argc - iArg, argv + iArg);
1488 case kAutoSvcAction_Continue:
1489 return autostartSvcWinContinue(argc - iArg, argv + iArg);
1490 case kAutoSvcAction_Stop:
1491 return autostartSvcWinStop(argc - iArg, argv + iArg);
1492 case kAutoSvcAction_Interrogate:
1493 return autostartSvcWinInterrogate(argc - iArg, argv + iArg);
1494
1495 default:
1496 AssertMsgFailed(("enmAction=%d\n", enmAction));
1497 }
1498
1499 return RTEXITCODE_FAILURE;
1500}
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