VirtualBox

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

Last change on this file since 44249 was 43967, checked in by vboxsync, 12 years ago

Autostart: More updates for the Windows service

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.5 KB
Line 
1/* $Id: VBoxAutostart-win.cpp 43967 2012-11-26 19:35:33Z vboxsync $ */
2/** @file
3 * VirtualBox Autostart Service - Windows Specific Code.
4 */
5
6/*
7 * Copyright (C) 2012 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27/*******************************************************************************
28* Header Files *
29*******************************************************************************/
30#include <Windows.h>
31
32#include <VBox/com/com.h>
33#include <VBox/com/string.h>
34#include <VBox/com/Guid.h>
35#include <VBox/com/array.h>
36#include <VBox/com/ErrorInfo.h>
37#include <VBox/com/errorprint.h>
38
39#include <VBox/com/EventQueue.h>
40#include <VBox/com/listeners.h>
41#include <VBox/com/VirtualBox.h>
42
43#include <VBox/log.h>
44#include <VBox/version.h>
45#include <iprt/string.h>
46#include <iprt/mem.h>
47#include <iprt/initterm.h>
48#include <iprt/stream.h>
49#include <iprt/getopt.h>
50#include <iprt/semaphore.h>
51#include <iprt/thread.h>
52
53#include "VBoxAutostart.h"
54
55/*******************************************************************************
56* Defined Constants And Macros *
57*******************************************************************************/
58/** The service name. */
59#define AUTOSTART_SERVICE_NAME "VBoxAutostartSvc"
60/** The service display name. */
61#define AUTOSTART_SERVICE_DISPLAY_NAME "VirtualBox Autostart Service"
62
63ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
64bool g_fVerbose = false;
65ComPtr<IVirtualBox> g_pVirtualBox = NULL;
66ComPtr<ISession> g_pSession = NULL;
67
68/*******************************************************************************
69* Global Variables *
70*******************************************************************************/
71/** The service control handler handle. */
72static SERVICE_STATUS_HANDLE g_hSupSvcWinCtrlHandler = NULL;
73/** The service status. */
74static uint32_t volatile g_u32SupSvcWinStatus = SERVICE_STOPPED;
75/** The semaphore the main service thread is waiting on in autostartSvcWinServiceMain. */
76static RTSEMEVENTMULTI g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
77
78
79/*******************************************************************************
80* Internal Functions *
81*******************************************************************************/
82static SC_HANDLE autostartSvcWinOpenSCManager(const char *pszAction, DWORD dwAccess);
83
84/**
85 * Print out progress on the console.
86 *
87 * This runs the main event queue every now and then to prevent piling up
88 * unhandled things (which doesn't cause real problems, just makes things
89 * react a little slower than in the ideal case).
90 */
91DECLHIDDEN(HRESULT) showProgress(ComPtr<IProgress> progress)
92{
93 using namespace com;
94
95 BOOL fCompleted = FALSE;
96 ULONG ulCurrentPercent = 0;
97 ULONG ulLastPercent = 0;
98
99 ULONG ulLastOperationPercent = (ULONG)-1;
100
101 ULONG ulLastOperation = (ULONG)-1;
102 Bstr bstrOperationDescription;
103
104 EventQueue::getMainEventQueue()->processEventQueue(0);
105
106 ULONG cOperations = 1;
107 HRESULT hrc = progress->COMGETTER(OperationCount)(&cOperations);
108 if (FAILED(hrc))
109 return hrc;
110
111 /* setup signal handling if cancelable */
112 bool fCanceledAlready = false;
113 BOOL fCancelable;
114 hrc = progress->COMGETTER(Cancelable)(&fCancelable);
115 if (FAILED(hrc))
116 fCancelable = FALSE;
117
118 hrc = progress->COMGETTER(Completed(&fCompleted));
119 while (SUCCEEDED(hrc))
120 {
121 progress->COMGETTER(Percent(&ulCurrentPercent));
122
123 if (fCompleted)
124 break;
125
126 /* process async cancelation */
127 if (!fCanceledAlready)
128 {
129 hrc = progress->Cancel();
130 if (SUCCEEDED(hrc))
131 fCanceledAlready = true;
132 }
133
134 /* make sure the loop is not too tight */
135 progress->WaitForCompletion(100);
136
137 EventQueue::getMainEventQueue()->processEventQueue(0);
138 hrc = progress->COMGETTER(Completed(&fCompleted));
139 }
140
141 /* complete the line. */
142 LONG iRc = E_FAIL;
143 hrc = progress->COMGETTER(ResultCode)(&iRc);
144 if (SUCCEEDED(hrc))
145 {
146 hrc = iRc;
147 }
148
149 return hrc;
150}
151
152DECLHIDDEN(void) autostartSvcOsLogStr(const char *pszMsg, AUTOSTARTLOGTYPE enmLogType)
153{
154 HANDLE hEventLog = RegisterEventSourceA(NULL /* local computer */, "VBoxAutostartSvc");
155 AssertReturnVoid(hEventLog != NULL);
156 WORD wType = 0;
157 const char *apsz[2];
158 apsz[0] = "VBoxAutostartSvc";
159 apsz[1] = pszMsg;
160
161 switch (enmLogType)
162 {
163 case AUTOSTARTLOGTYPE_INFO:
164 wType = 0;
165 break;
166 case AUTOSTARTLOGTYPE_ERROR:
167 wType = EVENTLOG_ERROR_TYPE;
168 break;
169 case AUTOSTARTLOGTYPE_WARNING:
170 wType = EVENTLOG_WARNING_TYPE;
171 break;
172 case AUTOSTARTLOGTYPE_VERBOSE:
173 if (!g_fVerbose)
174 return;
175 wType = EVENTLOG_INFORMATION_TYPE;
176 break;
177 default:
178 AssertMsgFailed(("Invalid log type %d\n", enmLogType));
179 }
180
181 BOOL fRc = ReportEventA(hEventLog, /* hEventLog */
182 wType, /* wType */
183 0, /* wCategory */
184 0 /** @todo mc */, /* dwEventID */
185 NULL, /* lpUserSid */
186 RT_ELEMENTS(apsz), /* wNumStrings */
187 0, /* dwDataSize */
188 apsz, /* lpStrings */
189 NULL); /* lpRawData */
190 AssertMsg(fRc, ("%d\n", GetLastError()));
191 DeregisterEventSource(hEventLog);
192}
193
194/**
195 * Opens the service control manager.
196 *
197 * When this fails, an error message will be displayed.
198 *
199 * @returns Valid handle on success.
200 * NULL on failure, will display an error message.
201 *
202 * @param pszAction The action which is requesting access to SCM.
203 * @param dwAccess The desired access.
204 */
205static SC_HANDLE autostartSvcWinOpenSCManager(const char *pszAction, DWORD dwAccess)
206{
207 SC_HANDLE hSCM = OpenSCManager(NULL /* lpMachineName*/, NULL /* lpDatabaseName */, dwAccess);
208 if (hSCM == NULL)
209 {
210 DWORD err = GetLastError();
211 switch (err)
212 {
213 case ERROR_ACCESS_DENIED:
214 autostartSvcDisplayError("%s - OpenSCManager failure: access denied\n", pszAction);
215 break;
216 default:
217 autostartSvcDisplayError("%s - OpenSCManager failure: %d\n", pszAction, err);
218 break;
219 }
220 }
221 return hSCM;
222}
223
224
225/**
226 * Opens the service.
227 *
228 * Last error is preserved on failure and set to 0 on success.
229 *
230 * @returns Valid service handle on success.
231 * NULL on failure, will display an error message unless it's ignored.
232 *
233 * @param pszAction The action which is requesting access to the service.
234 * @param dwSCMAccess The service control manager access.
235 * @param dwSVCAccess The desired service access.
236 * @param cIgnoredErrors The number of ignored errors.
237 * @param ... Errors codes that should not cause a message to be displayed.
238 */
239static SC_HANDLE autostartSvcWinOpenService(const char *pszAction, DWORD dwSCMAccess, DWORD dwSVCAccess,
240 unsigned cIgnoredErrors, ...)
241{
242 SC_HANDLE hSCM = autostartSvcWinOpenSCManager(pszAction, dwSCMAccess);
243 if (!hSCM)
244 return NULL;
245
246 SC_HANDLE hSvc = OpenServiceA(hSCM, AUTOSTART_SERVICE_NAME, dwSVCAccess);
247 if (hSvc)
248 {
249 CloseServiceHandle(hSCM);
250 SetLastError(0);
251 }
252 else
253 {
254 DWORD err = GetLastError();
255 bool fIgnored = false;
256 va_list va;
257 va_start(va, cIgnoredErrors);
258 while (!fIgnored && cIgnoredErrors-- > 0)
259 fIgnored = va_arg(va, long) == err;
260 va_end(va);
261 if (!fIgnored)
262 {
263 switch (err)
264 {
265 case ERROR_ACCESS_DENIED:
266 autostartSvcDisplayError("%s - OpenService failure: access denied\n", pszAction);
267 break;
268 case ERROR_SERVICE_DOES_NOT_EXIST:
269 autostartSvcDisplayError("%s - OpenService failure: The service does not exist. Reinstall it.\n", pszAction);
270 break;
271 default:
272 autostartSvcDisplayError("%s - OpenService failure: %d\n", pszAction, err);
273 break;
274 }
275 }
276
277 CloseServiceHandle(hSCM);
278 SetLastError(err);
279 }
280 return hSvc;
281}
282
283static RTEXITCODE autostartSvcWinInterrogate(int argc, char **argv)
284{
285 RTPrintf("VBoxAutostartSvc: The \"interrogate\" action is not implemented.\n");
286 return RTEXITCODE_FAILURE;
287}
288
289
290static RTEXITCODE autostartSvcWinStop(int argc, char **argv)
291{
292 RTPrintf("VBoxAutostartSvc: The \"stop\" action is not implemented.\n");
293 return RTEXITCODE_FAILURE;
294}
295
296
297static RTEXITCODE autostartSvcWinContinue(int argc, char **argv)
298{
299 RTPrintf("VBoxAutostartSvc: The \"continue\" action is not implemented.\n");
300 return RTEXITCODE_FAILURE;
301}
302
303
304static RTEXITCODE autostartSvcWinPause(int argc, char **argv)
305{
306 RTPrintf("VBoxAutostartSvc: The \"pause\" action is not implemented.\n");
307 return RTEXITCODE_FAILURE;
308}
309
310
311static RTEXITCODE autostartSvcWinStart(int argc, char **argv)
312{
313 RTPrintf("VBoxAutostartSvc: The \"start\" action is not implemented.\n");
314 return RTEXITCODE_SUCCESS;
315}
316
317
318static RTEXITCODE autostartSvcWinQueryDescription(int argc, char **argv)
319{
320 RTPrintf("VBoxAutostartSvc: The \"qdescription\" action is not implemented.\n");
321 return RTEXITCODE_FAILURE;
322}
323
324
325static RTEXITCODE autostartSvcWinQueryConfig(int argc, char **argv)
326{
327 RTPrintf("VBoxAutostartSvc: The \"qconfig\" action is not implemented.\n");
328 return RTEXITCODE_FAILURE;
329}
330
331
332static RTEXITCODE autostartSvcWinDisable(int argc, char **argv)
333{
334 RTPrintf("VBoxAutostartSvc: The \"disable\" action is not implemented.\n");
335 return RTEXITCODE_FAILURE;
336}
337
338static RTEXITCODE autostartSvcWinEnable(int argc, char **argv)
339{
340 RTPrintf("VBoxAutostartSvc: The \"enable\" action is not implemented.\n");
341 return RTEXITCODE_FAILURE;
342}
343
344
345/**
346 * Handle the 'delete' action.
347 *
348 * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
349 * @param argc The action argument count.
350 * @param argv The action argument vector.
351 */
352static int autostartSvcWinDelete(int argc, char **argv)
353{
354 /*
355 * Parse the arguments.
356 */
357 bool fVerbose = false;
358 static const RTGETOPTDEF s_aOptions[] =
359 {
360 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
361 };
362 int ch;
363 unsigned iArg = 0;
364 RTGETOPTUNION Value;
365 RTGETOPTSTATE GetState;
366 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
367 while ((ch = RTGetOpt(&GetState, &Value)))
368 {
369 switch (ch)
370 {
371 case 'v':
372 fVerbose = true;
373 break;
374 case VINF_GETOPT_NOT_OPTION:
375 return autostartSvcDisplayTooManyArgsError("delete", argc, argv, iArg);
376 default:
377 return autostartSvcDisplayGetOptError("delete", ch, argc, argv, iArg, &Value);
378 }
379
380 iArg++;
381 }
382
383 /*
384 * Create the service.
385 */
386 int rc = RTEXITCODE_FAILURE;
387 SC_HANDLE hSvc = autostartSvcWinOpenService("delete", SERVICE_CHANGE_CONFIG, DELETE,
388 1, ERROR_SERVICE_DOES_NOT_EXIST);
389 if (hSvc)
390 {
391 if (DeleteService(hSvc))
392 {
393 RTPrintf("Successfully deleted the %s service.\n", AUTOSTART_SERVICE_NAME);
394 rc = RTEXITCODE_SUCCESS;
395 }
396 else
397 autostartSvcDisplayError("delete - DeleteService failed, err=%d.\n", GetLastError());
398 CloseServiceHandle(hSvc);
399 }
400 else if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST)
401 {
402
403 if (fVerbose)
404 RTPrintf("The service %s was not installed, nothing to be done.", AUTOSTART_SERVICE_NAME);
405 else
406 RTPrintf("Successfully deleted the %s service.\n", AUTOSTART_SERVICE_NAME);
407 rc = RTEXITCODE_SUCCESS;
408 }
409 return rc;
410}
411
412
413/**
414 * Handle the 'create' action.
415 *
416 * @returns 0 or 1.
417 * @param argc The action argument count.
418 * @param argv The action argument vector.
419 */
420static RTEXITCODE autostartSvcWinCreate(int argc, char **argv)
421{
422 /*
423 * Parse the arguments.
424 */
425 bool fVerbose = false;
426 const char *pszUser = NULL;
427 const char *pszPwd = NULL;
428 static const RTGETOPTDEF s_aOptions[] =
429 {
430 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
431 { "--user", 'u', RTGETOPT_REQ_STRING },
432 { "--password", 'p', RTGETOPT_REQ_STRING }
433 };
434 int iArg = 0;
435 int ch;
436 RTGETOPTUNION Value;
437 RTGETOPTSTATE GetState;
438 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
439 while ((ch = RTGetOpt(&GetState, &Value)))
440 {
441 switch (ch)
442 {
443 case 'v':
444 fVerbose = true;
445 break;
446 case 'u':
447 pszUser = Value.psz;
448 break;
449 case 'p':
450 pszPwd = Value.psz;
451 break;
452 default:
453 return autostartSvcDisplayGetOptError("create", ch, argc, argv, iArg, &Value);
454 }
455 iArg++;
456 }
457 if (iArg != argc)
458 return autostartSvcDisplayTooManyArgsError("create", argc, argv, iArg);
459
460 /*
461 * Create the service.
462 */
463 RTEXITCODE rc = RTEXITCODE_FAILURE;
464 SC_HANDLE hSCM = autostartSvcWinOpenSCManager("create", SC_MANAGER_CREATE_SERVICE); /*SC_MANAGER_ALL_ACCESS*/
465 if (hSCM)
466 {
467 char szExecPath[MAX_PATH];
468 if (GetModuleFileNameA(NULL /* the executable */, szExecPath, sizeof(szExecPath)))
469 {
470 if (fVerbose)
471 RTPrintf("Creating the %s service, binary \"%s\"...\n",
472 AUTOSTART_SERVICE_NAME, szExecPath); /* yea, the binary name isn't UTF-8, but wtf. */
473
474 SC_HANDLE hSvc = CreateServiceA(hSCM, /* hSCManager */
475 AUTOSTART_SERVICE_NAME, /* lpServiceName */
476 AUTOSTART_SERVICE_DISPLAY_NAME, /* lpDisplayName */
477 SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG, /* dwDesiredAccess */
478 SERVICE_WIN32_OWN_PROCESS, /* dwServiceType ( | SERVICE_INTERACTIVE_PROCESS? ) */
479 SERVICE_AUTO_START, /* dwStartType */
480 SERVICE_ERROR_NORMAL, /* dwErrorControl */
481 szExecPath, /* lpBinaryPathName */
482 NULL, /* lpLoadOrderGroup */
483 NULL, /* lpdwTagId */
484 NULL, /* lpDependencies */
485 pszUser, /* lpServiceStartName (NULL => LocalSystem) */
486 pszPwd); /* lpPassword */
487 if (hSvc)
488 {
489 RTPrintf("Successfully created the %s service.\n", AUTOSTART_SERVICE_NAME);
490 /** @todo Set the service description or it'll look weird in the vista service manager.
491 * Anything else that should be configured? Start access or something? */
492 rc = RTEXITCODE_SUCCESS;
493 CloseServiceHandle(hSvc);
494 }
495 else
496 {
497 DWORD err = GetLastError();
498 switch (err)
499 {
500 case ERROR_SERVICE_EXISTS:
501 autostartSvcDisplayError("create - The service already exists.\n");
502 break;
503 default:
504 autostartSvcDisplayError("create - CreateService failed, err=%d.\n", GetLastError());
505 break;
506 }
507 }
508 CloseServiceHandle(hSvc);
509 }
510 else
511 autostartSvcDisplayError("create - Failed to obtain the executable path: %d\n", GetLastError());
512 }
513 return rc;
514}
515
516
517/**
518 * Sets the service status, just a SetServiceStatus Wrapper.
519 *
520 * @returns See SetServiceStatus.
521 * @param dwStatus The current status.
522 * @param iWaitHint The wait hint, if < 0 then supply a default.
523 * @param dwExitCode The service exit code.
524 */
525static bool autostartSvcWinSetServiceStatus(DWORD dwStatus, int iWaitHint, DWORD dwExitCode)
526{
527 SERVICE_STATUS SvcStatus;
528 SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
529 SvcStatus.dwWin32ExitCode = dwExitCode;
530 SvcStatus.dwServiceSpecificExitCode = 0;
531 SvcStatus.dwWaitHint = iWaitHint >= 0 ? iWaitHint : 3000;
532 SvcStatus.dwCurrentState = dwStatus;
533 LogFlow(("autostartSvcWinSetServiceStatus: %d -> %d\n", g_u32SupSvcWinStatus, dwStatus));
534 g_u32SupSvcWinStatus = dwStatus;
535 switch (dwStatus)
536 {
537 case SERVICE_START_PENDING:
538 SvcStatus.dwControlsAccepted = 0;
539 break;
540 default:
541 SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
542 break;
543 }
544
545 static DWORD dwCheckPoint = 0;
546 switch (dwStatus)
547 {
548 case SERVICE_RUNNING:
549 case SERVICE_STOPPED:
550 SvcStatus.dwCheckPoint = 0;
551 default:
552 SvcStatus.dwCheckPoint = ++dwCheckPoint;
553 break;
554 }
555 return SetServiceStatus(g_hSupSvcWinCtrlHandler, &SvcStatus) != FALSE;
556}
557
558
559/**
560 * Service control handler (extended).
561 *
562 * @returns Windows status (see HandlerEx).
563 * @retval NO_ERROR if handled.
564 * @retval ERROR_CALL_NOT_IMPLEMENTED if not handled.
565 *
566 * @param dwControl The control code.
567 * @param dwEventType Event type. (specific to the control?)
568 * @param pvEventData Event data, specific to the event.
569 * @param pvContext The context pointer registered with the handler.
570 * Currently not used.
571 */
572static DWORD WINAPI autostartSvcWinServiceCtrlHandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID pvEventData, LPVOID pvContext)
573{
574 LogFlow(("autostartSvcWinServiceCtrlHandlerEx: dwControl=%#x dwEventType=%#x pvEventData=%p\n",
575 dwControl, dwEventType, pvEventData));
576
577 switch (dwControl)
578 {
579 /*
580 * Interrogate the service about it's current status.
581 * MSDN says that this should just return NO_ERROR and does
582 * not need to set the status again.
583 */
584 case SERVICE_CONTROL_INTERROGATE:
585 return NO_ERROR;
586
587 /*
588 * Request to stop the service.
589 */
590 case SERVICE_CONTROL_STOP:
591 {
592 /*
593 * Check if the real services can be stopped and then tell them to stop.
594 */
595 autostartSvcWinSetServiceStatus(SERVICE_STOP_PENDING, 3000, NO_ERROR);
596 /*
597 * Notify the main thread that we're done, it will wait for the
598 * VMs to stop, and set the windows service status to SERVICE_STOPPED
599 * and return.
600 */
601 int rc = RTSemEventMultiSignal(g_hSupSvcWinEvent);
602 if (RT_FAILURE(rc))
603 autostartSvcLogError("SERVICE_CONTROL_STOP: RTSemEventMultiSignal failed, %Rrc\n", rc);
604
605 return NO_ERROR;
606 }
607
608 case SERVICE_CONTROL_PAUSE:
609 case SERVICE_CONTROL_CONTINUE:
610 case SERVICE_CONTROL_SHUTDOWN:
611 case SERVICE_CONTROL_PARAMCHANGE:
612 case SERVICE_CONTROL_NETBINDADD:
613 case SERVICE_CONTROL_NETBINDREMOVE:
614 case SERVICE_CONTROL_NETBINDENABLE:
615 case SERVICE_CONTROL_NETBINDDISABLE:
616 case SERVICE_CONTROL_DEVICEEVENT:
617 case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
618 case SERVICE_CONTROL_POWEREVENT:
619 case SERVICE_CONTROL_SESSIONCHANGE:
620#ifdef SERVICE_CONTROL_PRESHUTDOWN /* vista */
621 case SERVICE_CONTROL_PRESHUTDOWN:
622#endif
623 default:
624 return ERROR_CALL_NOT_IMPLEMENTED;
625 }
626
627 NOREF(dwEventType);
628 NOREF(pvEventData);
629 NOREF(pvContext);
630 return NO_ERROR;
631}
632
633static int autostartWorker(RTTHREAD ThreadSelf, void *pvUser)
634{
635 int rc = autostartSetup();
636
637 /** @todo: Implement config options. */
638 rc = autostartStartMain(NULL);
639 if (RT_FAILURE(rc))
640 autostartSvcLogError("Starting VMs failed, rc=%Rrc", rc);
641
642 return rc;
643}
644
645/**
646 * Windows Service Main.
647 *
648 * This is invoked when the service is started and should not return until
649 * the service has been stopped.
650 *
651 * @param cArgs Argument count.
652 * @param papszArgs Argument vector.
653 */
654static VOID WINAPI autostartSvcWinServiceMain(DWORD cArgs, LPTSTR *papszArgs)
655{
656 LogFlowFuncEnter();
657
658 /*
659 * Register the control handler function for the service and report to SCM.
660 */
661 Assert(g_u32SupSvcWinStatus == SERVICE_STOPPED);
662 g_hSupSvcWinCtrlHandler = RegisterServiceCtrlHandlerExA(AUTOSTART_SERVICE_NAME, autostartSvcWinServiceCtrlHandlerEx, NULL);
663 if (g_hSupSvcWinCtrlHandler)
664 {
665 DWORD err = ERROR_GEN_FAILURE;
666 if (autostartSvcWinSetServiceStatus(SERVICE_START_PENDING, 3000, NO_ERROR))
667 {
668 if (cArgs == 1)
669 {
670 /*
671 * Create the event semaphore we'll be waiting on and
672 * then instantiate the actual services.
673 */
674 int rc = RTSemEventMultiCreate(&g_hSupSvcWinEvent);
675 if (RT_SUCCESS(rc))
676 {
677 /*
678 * Update the status and enter the work loop.
679 */
680 if (autostartSvcWinSetServiceStatus(SERVICE_RUNNING, 0, 0))
681 {
682 LogFlow(("autostartSvcWinServiceMain: calling RTSemEventMultiWait\n"));
683 RTTHREAD hWorker;
684 RTThreadCreate(&hWorker, autostartWorker, NULL, 0, RTTHREADTYPE_DEFAULT, 0, "WorkerThread");
685
686 LogFlow(("autostartSvcWinServiceMain: woke up\n"));
687 err = NO_ERROR;
688 rc = RTSemEventMultiWait(g_hSupSvcWinEvent, RT_INDEFINITE_WAIT);
689 if (RT_SUCCESS(rc))
690 {
691 LogFlow(("autostartSvcWinServiceMain: woke up\n"));
692 /** @todo: Autostop part. */
693 err = NO_ERROR;
694 }
695 else
696 autostartSvcLogError("RTSemEventWait failed, rc=%Rrc", rc);
697
698 autostartShutdown();
699 }
700 else
701 {
702 err = GetLastError();
703 autostartSvcLogError("SetServiceStatus failed, err=%d", err);
704 }
705
706 RTSemEventMultiDestroy(g_hSupSvcWinEvent);
707 g_hSupSvcWinEvent = NIL_RTSEMEVENTMULTI;
708 }
709 else
710 autostartSvcLogError("RTSemEventMultiCreate failed, rc=%Rrc", rc);
711 }
712 else
713 autostartSvcLogTooManyArgsError("main", cArgs, NULL, 0);
714 }
715 else
716 {
717 err = GetLastError();
718 autostartSvcLogError("SetServiceStatus failed, err=%d", err);
719 }
720 autostartSvcWinSetServiceStatus(SERVICE_STOPPED, 0, err);
721 }
722 else
723 autostartSvcLogError("RegisterServiceCtrlHandlerEx failed, err=%d", GetLastError());
724
725 LogFlowFuncLeave();
726}
727
728
729/**
730 * Handle the 'create' action.
731 *
732 * @returns RTEXITCODE_SUCCESS or RTEXITCODE_FAILURE.
733 * @param argc The action argument count.
734 * @param argv The action argument vector.
735 */
736static int autostartSvcWinRunIt(int argc, char **argv)
737{
738 LogFlowFuncEnter();
739
740 /*
741 * Initialize release logging.
742 */
743 /** @todo release logging of the system-wide service. */
744
745 /*
746 * Parse the arguments.
747 */
748 static const RTGETOPTDEF s_aOptions[] =
749 {
750 { "--dummy", 'd', RTGETOPT_REQ_NOTHING }
751 };
752 int iArg = 0;
753 int ch;
754 RTGETOPTUNION Value;
755 RTGETOPTSTATE GetState;
756 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
757 while ((ch = RTGetOpt(&GetState, &Value)))
758 switch (ch)
759 {
760 default: return autostartSvcDisplayGetOptError("runit", ch, argc, argv, iArg, &Value);
761 }
762 if (iArg != argc)
763 return autostartSvcDisplayTooManyArgsError("runit", argc, argv, iArg);
764
765 /*
766 * Register the service with the service control manager
767 * and start dispatching requests from it (all done by the API).
768 */
769 static SERVICE_TABLE_ENTRY const s_aServiceStartTable[] =
770 {
771 { _T(AUTOSTART_SERVICE_NAME), autostartSvcWinServiceMain },
772 { NULL, NULL}
773 };
774 if (StartServiceCtrlDispatcher(&s_aServiceStartTable[0]))
775 {
776 LogFlowFuncLeave();
777 return RTEXITCODE_SUCCESS; /* told to quit, so quit. */
778 }
779
780 DWORD err = GetLastError();
781 switch (err)
782 {
783 case ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
784 autostartSvcWinServiceMain(0, NULL);//autostartSvcDisplayError("Cannot run a service from the command line. Use the 'start' action to start it the right way.\n");
785 break;
786 default:
787 autostartSvcLogError("StartServiceCtrlDispatcher failed, err=%d", err);
788 break;
789 }
790 return RTEXITCODE_FAILURE;
791}
792
793
794/**
795 * Show the version info.
796 *
797 * @returns RTEXITCODE_SUCCESS.
798 */
799static RTEXITCODE autostartSvcWinShowVersion(int argc, char **argv)
800{
801 /*
802 * Parse the arguments.
803 */
804 bool fBrief = false;
805 static const RTGETOPTDEF s_aOptions[] =
806 {
807 { "--brief", 'b', RTGETOPT_REQ_NOTHING }
808 };
809 int iArg = 0;
810 int ch;
811 RTGETOPTUNION Value;
812 RTGETOPTSTATE GetState;
813 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
814 while ((ch = RTGetOpt(&GetState, &Value)))
815 switch (ch)
816 {
817 case 'b': fBrief = true; break;
818 default: return autostartSvcDisplayGetOptError("version", ch, argc, argv, iArg, &Value);
819
820 }
821 if (iArg != argc)
822 return autostartSvcDisplayTooManyArgsError("version", argc, argv, iArg);
823
824 /*
825 * Do the printing.
826 */
827 if (fBrief)
828 RTPrintf("%s\n", VBOX_VERSION_STRING);
829 else
830 RTPrintf("VirtualBox Autostart Service Version %s\n"
831 "(C) 2012 Oracle Corporation\n"
832 "All rights reserved.\n",
833 VBOX_VERSION_STRING);
834 return RTEXITCODE_SUCCESS;
835}
836
837
838/**
839 * Show the usage help screen.
840 *
841 * @returns RTEXITCODE_SUCCESS.
842 */
843static RTEXITCODE autostartSvcWinShowHelp(void)
844{
845 RTPrintf("VirtualBox Autostart Service Version %s\n"
846 "(C) 2012 Oracle Corporation\n"
847 "All rights reserved.\n"
848 "\n",
849 VBOX_VERSION_STRING);
850 RTPrintf("Usage:\n"
851 "\n"
852 "VBoxAutostartSvc\n"
853 " Runs the service.\n"
854 "VBoxAutostartSvc <version|-v|--version> [-brief]\n"
855 " Displays the version.\n"
856 "VBoxAutostartSvc <help|-?|-h|--help> [...]\n"
857 " Displays this help screen.\n"
858 "\n"
859 "VBoxAutostartSvc <install|/RegServer|/i>\n"
860 " Installs the service.\n"
861 "VBoxAutostartSvc <uninstall|delete|/UnregServer|/u>\n"
862 " Uninstalls the service.\n"
863 );
864 return RTEXITCODE_SUCCESS;
865}
866
867
868/**
869 * VBoxAutostart main(), Windows edition.
870 *
871 *
872 * @returns 0 on success.
873 *
874 * @param argc Number of arguments in argv.
875 * @param argv Argument vector.
876 */
877int main(int argc, char **argv)
878{
879 /*
880 * Initialize the IPRT first of all.
881 */
882 int rc = RTR3InitExe(argc, &argv, 0);
883 if (RT_FAILURE(rc))
884 {
885 autostartSvcLogError("RTR3InitExe failed with rc=%Rrc", rc);
886 return RTEXITCODE_FAILURE;
887 }
888
889 RTThreadSleep(10 * 1000);
890
891 /*
892 * Parse the initial arguments to determine the desired action.
893 */
894 enum
895 {
896 kAutoSvcAction_RunIt,
897
898 kAutoSvcAction_Create,
899 kAutoSvcAction_Delete,
900
901 kAutoSvcAction_Enable,
902 kAutoSvcAction_Disable,
903 kAutoSvcAction_QueryConfig,
904 kAutoSvcAction_QueryDescription,
905
906 kAutoSvcAction_Start,
907 kAutoSvcAction_Pause,
908 kAutoSvcAction_Continue,
909 kAutoSvcAction_Stop,
910 kAutoSvcAction_Interrogate,
911
912 kAutoSvcAction_End
913 } enmAction = kAutoSvcAction_RunIt;
914 int iArg = 1;
915 if (argc > 1)
916 {
917 if ( !stricmp(argv[iArg], "/RegServer")
918 || !stricmp(argv[iArg], "install")
919 || !stricmp(argv[iArg], "/i"))
920 enmAction = kAutoSvcAction_Create;
921 else if ( !stricmp(argv[iArg], "/UnregServer")
922 || !stricmp(argv[iArg], "/u")
923 || !stricmp(argv[iArg], "uninstall")
924 || !stricmp(argv[iArg], "delete"))
925 enmAction = kAutoSvcAction_Delete;
926
927 else if (!stricmp(argv[iArg], "enable"))
928 enmAction = kAutoSvcAction_Enable;
929 else if (!stricmp(argv[iArg], "disable"))
930 enmAction = kAutoSvcAction_Disable;
931 else if (!stricmp(argv[iArg], "qconfig"))
932 enmAction = kAutoSvcAction_QueryConfig;
933 else if (!stricmp(argv[iArg], "qdescription"))
934 enmAction = kAutoSvcAction_QueryDescription;
935
936 else if ( !stricmp(argv[iArg], "start")
937 || !stricmp(argv[iArg], "/t"))
938 enmAction = kAutoSvcAction_Start;
939 else if (!stricmp(argv[iArg], "pause"))
940 enmAction = kAutoSvcAction_Start;
941 else if (!stricmp(argv[iArg], "continue"))
942 enmAction = kAutoSvcAction_Continue;
943 else if (!stricmp(argv[iArg], "stop"))
944 enmAction = kAutoSvcAction_Stop;
945 else if (!stricmp(argv[iArg], "interrogate"))
946 enmAction = kAutoSvcAction_Interrogate;
947 else if ( !stricmp(argv[iArg], "help")
948 || !stricmp(argv[iArg], "?")
949 || !stricmp(argv[iArg], "/?")
950 || !stricmp(argv[iArg], "-?")
951 || !stricmp(argv[iArg], "/h")
952 || !stricmp(argv[iArg], "-h")
953 || !stricmp(argv[iArg], "/help")
954 || !stricmp(argv[iArg], "-help")
955 || !stricmp(argv[iArg], "--help"))
956 return autostartSvcWinShowHelp();
957 else if ( !stricmp(argv[iArg], "version")
958 || !stricmp(argv[iArg], "/v")
959 || !stricmp(argv[iArg], "-v")
960 || !stricmp(argv[iArg], "/version")
961 || !stricmp(argv[iArg], "-version")
962 || !stricmp(argv[iArg], "--version"))
963 return autostartSvcWinShowVersion(argc - iArg - 1, argv + iArg + 1);
964 else
965 iArg--;
966 iArg++;
967 }
968
969 /*
970 * Dispatch it.
971 */
972 switch (enmAction)
973 {
974 case kAutoSvcAction_RunIt:
975 return autostartSvcWinRunIt(argc - iArg, argv + iArg);
976
977 case kAutoSvcAction_Create:
978 return autostartSvcWinCreate(argc - iArg, argv + iArg);
979 case kAutoSvcAction_Delete:
980 return autostartSvcWinDelete(argc - iArg, argv + iArg);
981
982 case kAutoSvcAction_Enable:
983 return autostartSvcWinEnable(argc - iArg, argv + iArg);
984 case kAutoSvcAction_Disable:
985 return autostartSvcWinDisable(argc - iArg, argv + iArg);
986 case kAutoSvcAction_QueryConfig:
987 return autostartSvcWinQueryConfig(argc - iArg, argv + iArg);
988 case kAutoSvcAction_QueryDescription:
989 return autostartSvcWinQueryDescription(argc - iArg, argv + iArg);
990
991 case kAutoSvcAction_Start:
992 return autostartSvcWinStart(argc - iArg, argv + iArg);
993 case kAutoSvcAction_Pause:
994 return autostartSvcWinPause(argc - iArg, argv + iArg);
995 case kAutoSvcAction_Continue:
996 return autostartSvcWinContinue(argc - iArg, argv + iArg);
997 case kAutoSvcAction_Stop:
998 return autostartSvcWinStop(argc - iArg, argv + iArg);
999 case kAutoSvcAction_Interrogate:
1000 return autostartSvcWinInterrogate(argc - iArg, argv + iArg);
1001
1002 default:
1003 AssertMsgFailed(("enmAction=%d\n", enmAction));
1004 return RTEXITCODE_FAILURE;
1005 }
1006}
1007
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette