VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxService.cpp@ 38655

Last change on this file since 38655 was 38636, checked in by vboxsync, 14 years ago

*,IPRT: Redid the ring-3 init to always convert the arguments to UTF-8.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 27.9 KB
Line 
1/* $Id: VBoxService.cpp 38636 2011-09-05 13:49:45Z vboxsync $ */
2/** @file
3 * VBoxService - Guest Additions Service Skeleton.
4 */
5
6/*
7 * Copyright (C) 2007-2011 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19
20/*******************************************************************************
21* Header Files *
22*******************************************************************************/
23/** @todo LOG_GROUP*/
24#ifndef _MSC_VER
25# include <unistd.h>
26#endif
27#include <errno.h>
28#ifndef RT_OS_WINDOWS
29# include <signal.h>
30# ifdef RT_OS_OS2
31# define pthread_sigmask sigprocmask
32# endif
33#endif
34#ifdef RT_OS_FREEBSD
35# include <pthread.h>
36#endif
37
38#include "product-generated.h"
39#include <iprt/asm.h>
40#include <iprt/buildconfig.h>
41#include <iprt/initterm.h>
42#include <iprt/message.h>
43#include <iprt/path.h>
44#include <iprt/semaphore.h>
45#include <iprt/string.h>
46#include <iprt/stream.h>
47#include <iprt/thread.h>
48
49#include <VBox/log.h>
50
51#include "VBoxServiceInternal.h"
52
53
54/*******************************************************************************
55* Global Variables *
56*******************************************************************************/
57/** The program name (derived from argv[0]). */
58char *g_pszProgName = (char *)"";
59/** The current verbosity level. */
60int g_cVerbosity = 0;
61/** Critical section for (debug) logging. */
62#ifdef DEBUG
63 RTCRITSECT g_csLog;
64#endif
65/** The default service interval (the -i | --interval) option). */
66uint32_t g_DefaultInterval = 0;
67#ifdef RT_OS_WINDOWS
68/** Signal shutdown to the Windows service thread. */
69static bool volatile g_fWindowsServiceShutdown;
70/** Event the Windows service thread waits for shutdown. */
71static RTSEMEVENT g_hEvtWindowsService;
72#endif
73
74/**
75 * The details of the services that has been compiled in.
76 */
77static struct
78{
79 /** Pointer to the service descriptor. */
80 PCVBOXSERVICE pDesc;
81 /** The worker thread. NIL_RTTHREAD if it's the main thread. */
82 RTTHREAD Thread;
83 /** Whether Pre-init was called. */
84 bool fPreInited;
85 /** Shutdown indicator. */
86 bool volatile fShutdown;
87 /** Indicator set by the service thread exiting. */
88 bool volatile fStopped;
89 /** Whether the service was started or not. */
90 bool fStarted;
91 /** Whether the service is enabled or not. */
92 bool fEnabled;
93} g_aServices[] =
94{
95#ifdef VBOXSERVICE_CONTROL
96 { &g_Control, NIL_RTTHREAD, false, false, false, false, true },
97#endif
98#ifdef VBOXSERVICE_TIMESYNC
99 { &g_TimeSync, NIL_RTTHREAD, false, false, false, false, true },
100#endif
101#ifdef VBOXSERVICE_CLIPBOARD
102 { &g_Clipboard, NIL_RTTHREAD, false, false, false, false, true },
103#endif
104#ifdef VBOXSERVICE_VMINFO
105 { &g_VMInfo, NIL_RTTHREAD, false, false, false, false, true },
106#endif
107#ifdef VBOXSERVICE_CPUHOTPLUG
108 { &g_CpuHotPlug, NIL_RTTHREAD, false, false, false, false, true },
109#endif
110#ifdef VBOXSERVICE_MANAGEMENT
111# ifdef VBOX_WITH_MEMBALLOON
112 { &g_MemBalloon, NIL_RTTHREAD, false, false, false, false, true },
113# endif
114 { &g_VMStatistics, NIL_RTTHREAD, false, false, false, false, true },
115#endif
116#if defined(VBOX_WITH_PAGE_SHARING) && defined(RT_OS_WINDOWS)
117 { &g_PageSharing, NIL_RTTHREAD, false, false, false, false, true },
118#endif
119#ifdef VBOX_WITH_SHARED_FOLDERS
120 { &g_AutoMount, NIL_RTTHREAD, false, false, false, false, true },
121#endif
122};
123
124
125/**
126 * Displays the program usage message.
127 *
128 * @returns 1.
129 */
130static int vboxServiceUsage(void)
131{
132 RTPrintf("Usage:\n"
133 " %-12s [-f|--foreground] [-v|--verbose] [-i|--interval <seconds>]\n"
134 " [--disable-<service>] [--enable-<service>]\n"
135 " [--only-<service>] [-h|-?|--help]\n", g_pszProgName);
136#ifdef RT_OS_WINDOWS
137 RTPrintf(" [-r|--register] [-u|--unregister]\n");
138#endif
139 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
140 if (g_aServices[j].pDesc->pszUsage)
141 RTPrintf("%s\n", g_aServices[j].pDesc->pszUsage);
142 RTPrintf("\n"
143 "Options:\n"
144 " -i | --interval The default interval.\n"
145 " -f | --foreground Don't daemonize the program. For debugging.\n"
146 " -v | --verbose Increment the verbosity level. For debugging.\n"
147 " -V | --version Show version information.\n"
148 " -h | -? | --help Show this message and exit with status 1.\n"
149 );
150#ifdef RT_OS_WINDOWS
151 RTPrintf(" -r | --register Installs the service.\n"
152 " -u | --unregister Uninstall service.\n");
153#endif
154
155 RTPrintf("\n"
156 "Service-specific options:\n");
157 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
158 {
159 RTPrintf(" --enable-%-14s Enables the %s service. (default)\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
160 RTPrintf(" --disable-%-13s Disables the %s service.\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
161 RTPrintf(" --only-%-16s Only enables the %s service.\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
162 if (g_aServices[j].pDesc->pszOptions)
163 RTPrintf("%s", g_aServices[j].pDesc->pszOptions);
164 }
165 RTPrintf("\n"
166 " Copyright (C) 2009-" VBOX_C_YEAR " " VBOX_VENDOR "\n");
167
168 return 1;
169}
170
171
172/**
173 * Displays a syntax error message.
174 *
175 * @returns RTEXITCODE_SYNTAX.
176 * @param pszFormat The message text.
177 * @param ... Format arguments.
178 */
179RTEXITCODE VBoxServiceSyntax(const char *pszFormat, ...)
180{
181 RTStrmPrintf(g_pStdErr, "%s: syntax error: ", g_pszProgName);
182
183 va_list va;
184 va_start(va, pszFormat);
185 RTStrmPrintfV(g_pStdErr, pszFormat, va);
186 va_end(va);
187
188 return RTEXITCODE_SYNTAX;
189}
190
191
192/**
193 * Displays an error message.
194 *
195 * @returns RTEXITCODE_FAILURE.
196 * @param pszFormat The message text.
197 * @param ... Format arguments.
198 */
199RTEXITCODE VBoxServiceError(const char *pszFormat, ...)
200{
201 RTStrmPrintf(g_pStdErr, "%s: error: ", g_pszProgName);
202
203 va_list va;
204 va_start(va, pszFormat);
205 RTStrmPrintfV(g_pStdErr, pszFormat, va);
206 va_end(va);
207
208 va_start(va, pszFormat);
209 LogRel(("%s: Error: %N", g_pszProgName, pszFormat, &va));
210 va_end(va);
211
212 return RTEXITCODE_FAILURE;
213}
214
215
216/**
217 * Displays a verbose message.
218 *
219 * @returns 1
220 * @param iLevel Minimum log level required to display this message.
221 * @param pszFormat The message text.
222 * @param ... Format arguments.
223 */
224void VBoxServiceVerbose(int iLevel, const char *pszFormat, ...)
225{
226 if (iLevel <= g_cVerbosity)
227 {
228#ifdef DEBUG
229 int rc = RTCritSectEnter(&g_csLog);
230 if (RT_SUCCESS(rc))
231 {
232 const char *pszThreadName = RTThreadSelfName();
233 AssertPtr(pszThreadName);
234 RTStrmPrintf(g_pStdOut, "%s [%s]: ",
235 g_pszProgName, pszThreadName);
236#else
237 RTStrmPrintf(g_pStdOut, "%s: ", g_pszProgName);
238#endif
239 va_list va;
240 va_start(va, pszFormat);
241 RTStrmPrintfV(g_pStdOut, pszFormat, va);
242 va_end(va);
243 va_start(va, pszFormat);
244 LogRel(("%s: %N", g_pszProgName, pszFormat, &va));
245 va_end(va);
246#ifdef DEBUG
247 RTCritSectLeave(&g_csLog);
248 }
249#endif
250 }
251}
252
253
254/**
255 * Reports the current VBoxService status to the host.
256 *
257 * This makes sure that the Failed state is sticky.
258 *
259 * @return IPRT status code.
260 * @param enmStatus Status to report to the host.
261 */
262int VBoxServiceReportStatus(VBoxGuestFacilityStatus enmStatus)
263{
264 /*
265 * VBoxGuestFacilityStatus_Failed is sticky.
266 */
267 static VBoxGuestFacilityStatus s_enmLastStatus = VBoxGuestFacilityStatus_Inactive;
268 VBoxServiceVerbose(4, "Setting VBoxService status to %u\n", enmStatus);
269 if (s_enmLastStatus != VBoxGuestFacilityStatus_Failed)
270 {
271 int rc = VbglR3ReportAdditionsStatus(VBoxGuestFacilityType_VBoxService,
272 enmStatus, 0 /* Flags */);
273 if (RT_FAILURE(rc))
274 {
275 VBoxServiceError("Could not report VBoxService status (%u), rc=%Rrc\n", enmStatus, rc);
276 return rc;
277 }
278 s_enmLastStatus = enmStatus;
279 }
280 return VINF_SUCCESS;
281}
282
283
284/**
285 * Gets a 32-bit value argument.
286 *
287 * @returns 0 on success, non-zero exit code on error.
288 * @param argc The argument count.
289 * @param argv The argument vector
290 * @param psz Where in *pi to start looking for the value argument.
291 * @param pi Where to find and perhaps update the argument index.
292 * @param pu32 Where to store the 32-bit value.
293 * @param u32Min The minimum value.
294 * @param u32Max The maximum value.
295 */
296int VBoxServiceArgUInt32(int argc, char **argv, const char *psz, int *pi, uint32_t *pu32, uint32_t u32Min, uint32_t u32Max)
297{
298 if (*psz == ':' || *psz == '=')
299 psz++;
300 if (!*psz)
301 {
302 if (*pi + 1 >= argc)
303 return VBoxServiceSyntax("Missing value for the '%s' argument\n", argv[*pi]);
304 psz = argv[++*pi];
305 }
306
307 char *pszNext;
308 int rc = RTStrToUInt32Ex(psz, &pszNext, 0, pu32);
309 if (RT_FAILURE(rc) || *pszNext)
310 return VBoxServiceSyntax("Failed to convert interval '%s' to a number.\n", psz);
311 if (*pu32 < u32Min || *pu32 > u32Max)
312 return VBoxServiceSyntax("The timesync interval of %RU32 seconds is out of range [%RU32..%RU32].\n",
313 *pu32, u32Min, u32Max);
314 return 0;
315}
316
317
318/**
319 * The service thread.
320 *
321 * @returns Whatever the worker function returns.
322 * @param ThreadSelf My thread handle.
323 * @param pvUser The service index.
324 */
325static DECLCALLBACK(int) vboxServiceThread(RTTHREAD ThreadSelf, void *pvUser)
326{
327 const unsigned i = (uintptr_t)pvUser;
328
329#ifndef RT_OS_WINDOWS
330 /*
331 * Block all signals for this thread. Only the main thread will handle signals.
332 */
333 sigset_t signalMask;
334 sigfillset(&signalMask);
335 pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
336#endif
337
338 int rc = g_aServices[i].pDesc->pfnWorker(&g_aServices[i].fShutdown);
339 ASMAtomicXchgBool(&g_aServices[i].fShutdown, true);
340 RTThreadUserSignal(ThreadSelf);
341 return rc;
342}
343
344
345/**
346 * Lazily calls the pfnPreInit method on each service.
347 *
348 * @returns VBox status code, error message displayed.
349 */
350static RTEXITCODE vboxServiceLazyPreInit(void)
351{
352 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
353 if (!g_aServices[j].fPreInited)
354 {
355 int rc = g_aServices[j].pDesc->pfnPreInit();
356 if (RT_FAILURE(rc))
357 return VBoxServiceError("Service '%s' failed pre-init: %Rrc\n", g_aServices[j].pDesc->pszName, rc);
358 g_aServices[j].fPreInited = true;
359 }
360 return RTEXITCODE_SUCCESS;
361}
362
363
364/**
365 * Count the number of enabled services.
366 */
367static unsigned vboxServiceCountEnabledServices(void)
368{
369 unsigned cEnabled = 0;
370 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
371 cEnabled += g_aServices[i].fEnabled;
372 return cEnabled;
373}
374
375
376/**
377 * Starts the service.
378 *
379 * @returns VBox status code, errors are fully bitched.
380 */
381int VBoxServiceStartServices(void)
382{
383 int rc;
384
385 VBoxServiceReportStatus(VBoxGuestFacilityStatus_Init);
386
387 /*
388 * Initialize the services.
389 */
390 VBoxServiceVerbose(2, "Initializing services ...\n");
391 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
392 if (g_aServices[j].fEnabled)
393 {
394 rc = g_aServices[j].pDesc->pfnInit();
395 if (RT_FAILURE(rc))
396 {
397 if (rc != VERR_SERVICE_DISABLED)
398 {
399 VBoxServiceError("Service '%s' failed to initialize: %Rrc\n",
400 g_aServices[j].pDesc->pszName, rc);
401 VBoxServiceReportStatus(VBoxGuestFacilityStatus_Failed);
402 return rc;
403 }
404 g_aServices[j].fEnabled = false;
405 VBoxServiceVerbose(0, "Service '%s' was disabled because of missing functionality\n",
406 g_aServices[j].pDesc->pszName);
407
408 }
409 }
410
411 /*
412 * Start the service(s).
413 */
414 VBoxServiceVerbose(2, "Starting services ...\n");
415 rc = VINF_SUCCESS;
416 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
417 {
418 if (!g_aServices[j].fEnabled)
419 continue;
420
421 VBoxServiceVerbose(2, "Starting service '%s' ...\n", g_aServices[j].pDesc->pszName);
422 rc = RTThreadCreate(&g_aServices[j].Thread, vboxServiceThread, (void *)(uintptr_t)j, 0,
423 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, g_aServices[j].pDesc->pszName);
424 if (RT_FAILURE(rc))
425 {
426 VBoxServiceError("RTThreadCreate failed, rc=%Rrc\n", rc);
427 break;
428 }
429 g_aServices[j].fStarted = true;
430
431 /* Wait for the thread to initialize. */
432 /** @todo There is a race between waiting and checking
433 * the fShutdown flag of a thread here and processing
434 * the thread's actual worker loop. If the thread decides
435 * to exit the loop before we skipped the fShutdown check
436 * below the service will fail to start! */
437 RTThreadUserWait(g_aServices[j].Thread, 60 * 1000);
438 if (g_aServices[j].fShutdown)
439 {
440 VBoxServiceError("Service '%s' failed to start!\n", g_aServices[j].pDesc->pszName);
441 rc = VERR_GENERAL_FAILURE;
442 }
443 }
444
445 if (RT_SUCCESS(rc))
446 VBoxServiceVerbose(1, "All services started.\n");
447 else
448 {
449 VBoxServiceError("An error occcurred while the services!\n");
450 VBoxServiceReportStatus(VBoxGuestFacilityStatus_Failed);
451 }
452 return rc;
453}
454
455
456/**
457 * Stops and terminates the services.
458 *
459 * This should be called even when VBoxServiceStartServices fails so it can
460 * clean up anything that we succeeded in starting.
461 */
462int VBoxServiceStopServices(void)
463{
464 VBoxServiceReportStatus(VBoxGuestFacilityStatus_Terminating);
465
466 /*
467 * Signal all the services.
468 */
469 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
470 ASMAtomicWriteBool(&g_aServices[j].fShutdown, true);
471
472 /*
473 * Do the pfnStop callback on all running services.
474 */
475 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
476 if (g_aServices[j].fStarted)
477 {
478 VBoxServiceVerbose(3, "Calling stop function for service '%s' ...\n", g_aServices[j].pDesc->pszName);
479 g_aServices[j].pDesc->pfnStop();
480 }
481
482 /*
483 * Wait for all the service threads to complete.
484 */
485 int rc = VINF_SUCCESS;
486 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
487 {
488 if (!g_aServices[j].fEnabled) /* Only stop services which were started before. */
489 continue;
490 if (g_aServices[j].Thread != NIL_RTTHREAD)
491 {
492 VBoxServiceVerbose(2, "Waiting for service '%s' to stop ...\n", g_aServices[j].pDesc->pszName);
493 int rc2 = VINF_SUCCESS;
494 for (int i = 0; i < 30; i++) /* Wait 30 seconds in total */
495 {
496 rc2 = RTThreadWait(g_aServices[j].Thread, 1000 /* Wait 1 second */, NULL);
497 if (RT_SUCCESS(rc2))
498 break;
499#ifdef RT_OS_WINDOWS
500 /* Notify SCM that it takes a bit longer ... */
501 VBoxServiceWinSetStopPendingStatus(i + j*32);
502#endif
503 }
504 if (RT_FAILURE(rc2))
505 {
506 VBoxServiceError("Service '%s' failed to stop. (%Rrc)\n", g_aServices[j].pDesc->pszName, rc2);
507 rc = rc2;
508 }
509 }
510 VBoxServiceVerbose(3, "Terminating service '%s' (%d) ...\n", g_aServices[j].pDesc->pszName, j);
511 g_aServices[j].pDesc->pfnTerm();
512 }
513
514#ifdef RT_OS_WINDOWS
515 /*
516 * Wake up and tell the main() thread that we're shutting down (it's
517 * sleeping in VBoxServiceMainWait).
518 */
519 ASMAtomicWriteBool(&g_fWindowsServiceShutdown, true);
520 if (g_hEvtWindowsService != NIL_RTSEMEVENT)
521 {
522 VBoxServiceVerbose(3, "Stopping the main thread...\n");
523 int rc2 = RTSemEventSignal(g_hEvtWindowsService);
524 AssertRC(rc2);
525 }
526#endif
527
528 VBoxServiceVerbose(2, "Stopping services returning: %Rrc\n", rc);
529 VBoxServiceReportStatus(RT_SUCCESS(rc) ? VBoxGuestFacilityStatus_Paused : VBoxGuestFacilityStatus_Failed);
530 return rc;
531}
532
533
534/**
535 * Block the main thread until the service shuts down.
536 */
537void VBoxServiceMainWait(void)
538{
539 int rc;
540
541 VBoxServiceReportStatus(VBoxGuestFacilityStatus_Active);
542
543#ifdef RT_OS_WINDOWS
544 /*
545 * Wait for the semaphore to be signalled.
546 */
547 VBoxServiceVerbose(1, "Waiting in main thread\n");
548 rc = RTSemEventCreate(&g_hEvtWindowsService);
549 AssertRC(rc);
550 while (!ASMAtomicReadBool(&g_fWindowsServiceShutdown))
551 {
552 rc = RTSemEventWait(g_hEvtWindowsService, RT_INDEFINITE_WAIT);
553 AssertRC(rc);
554 }
555 RTSemEventDestroy(g_hEvtWindowsService);
556 g_hEvtWindowsService = NIL_RTSEMEVENT;
557
558#else
559 /*
560 * Wait explicitly for a HUP, INT, QUIT, ABRT or TERM signal, blocking
561 * all important signals.
562 *
563 * The annoying EINTR/ERESTART loop is for the benefit of Solaris where
564 * sigwait returns when we receive a SIGCHLD. Kind of makes sense since
565 */
566 sigset_t signalMask;
567 sigemptyset(&signalMask);
568 sigaddset(&signalMask, SIGHUP);
569 sigaddset(&signalMask, SIGINT);
570 sigaddset(&signalMask, SIGQUIT);
571 sigaddset(&signalMask, SIGABRT);
572 sigaddset(&signalMask, SIGTERM);
573 pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
574
575 int iSignal;
576 do
577 {
578 iSignal = -1;
579 rc = sigwait(&signalMask, &iSignal);
580 }
581 while ( rc == EINTR
582# ifdef ERESTART
583 || rc == ERESTART
584# endif
585 );
586
587 VBoxServiceVerbose(3, "VBoxServiceMainWait: Received signal %d (rc=%d)\n", iSignal, rc);
588#endif /* !RT_OS_WINDOWS */
589}
590
591
592int main(int argc, char **argv)
593{
594 RTEXITCODE rcExit;
595
596 /*
597 * Init globals and such.
598 */
599 int rc = RTR3InitExe(argc, &argv, 0);
600 if (RT_FAILURE(rc))
601 return RTMsgInitFailure(rc);
602 g_pszProgName = RTPathFilename(argv[0]);
603#ifdef DEBUG
604 rc = RTCritSectInit(&g_csLog);
605 AssertRC(rc);
606#endif
607
608#ifdef VBOXSERVICE_TOOLBOX
609 /*
610 * Run toolbox code before all other stuff since these things are simpler
611 * shell/file/text utility like programs that just happens to be inside
612 * VBoxService and shouldn't be subject to /dev/vboxguest, pid-files and
613 * global mutex restrictions.
614 */
615 if (VBoxServiceToolboxMain(argc, argv, &rcExit))
616 return rcExit;
617#endif
618
619 /*
620 * Connect to the kernel part before daemonizing so we can fail and
621 * complain if there is some kind of problem. We need to initialize the
622 * guest lib *before* we do the pre-init just in case one of services needs
623 * do to some initial stuff with it.
624 */
625 VBoxServiceVerbose(2, "Calling VbgR3Init()\n");
626 rc = VbglR3Init();
627 if (RT_FAILURE(rc))
628 {
629 if (rc == VERR_ACCESS_DENIED)
630 return VBoxServiceError("Insufficient privileges to start %s! Please start with Administrator/root privileges!\n",
631 g_pszProgName);
632 return VBoxServiceError("VbglR3Init failed with rc=%Rrc.\n", rc);
633 }
634
635#ifdef RT_OS_WINDOWS
636 /*
637 * Check if we're the specially spawned VBoxService.exe process that
638 * handles page fusion. This saves an extra executable.
639 */
640 if ( argc == 2
641 && !strcmp(argv[1], "--pagefusionfork"))
642 return VBoxServicePageSharingInitFork();
643#endif
644
645 /*
646 * Parse the arguments.
647 *
648 * Note! This code predates RTGetOpt, thus the manual parsing.
649 */
650 bool fDaemonize = true;
651 bool fDaemonized = false;
652 for (int i = 1; i < argc; i++)
653 {
654 const char *psz = argv[i];
655 if (*psz != '-')
656 return VBoxServiceSyntax("Unknown argument '%s'\n", psz);
657 psz++;
658
659 /* translate long argument to short */
660 if (*psz == '-')
661 {
662 psz++;
663 size_t cch = strlen(psz);
664#define MATCHES(strconst) ( cch == sizeof(strconst) - 1 \
665 && !memcmp(psz, strconst, sizeof(strconst) - 1) )
666 if (MATCHES("foreground"))
667 psz = "f";
668 else if (MATCHES("verbose"))
669 psz = "v";
670 else if (MATCHES("version"))
671 psz = "V";
672 else if (MATCHES("help"))
673 psz = "h";
674 else if (MATCHES("interval"))
675 psz = "i";
676#ifdef RT_OS_WINDOWS
677 else if (MATCHES("register"))
678 psz = "r";
679 else if (MATCHES("unregister"))
680 psz = "u";
681#endif
682 else if (MATCHES("daemonized"))
683 {
684 fDaemonized = true;
685 continue;
686 }
687 else
688 {
689 bool fFound = false;
690
691 if (cch > sizeof("enable-") && !memcmp(psz, "enable-", sizeof("enable-") - 1))
692 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
693 if ((fFound = !RTStrICmp(psz + sizeof("enable-") - 1, g_aServices[j].pDesc->pszName)))
694 g_aServices[j].fEnabled = true;
695
696 if (cch > sizeof("disable-") && !memcmp(psz, "disable-", sizeof("disable-") - 1))
697 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
698 if ((fFound = !RTStrICmp(psz + sizeof("disable-") - 1, g_aServices[j].pDesc->pszName)))
699 g_aServices[j].fEnabled = false;
700
701 if (cch > sizeof("only-") && !memcmp(psz, "only-", sizeof("only-") - 1))
702 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
703 g_aServices[j].fEnabled = !RTStrICmp(psz + sizeof("only-") - 1, g_aServices[j].pDesc->pszName);
704
705 if (!fFound)
706 {
707 rcExit = vboxServiceLazyPreInit();
708 if (rcExit != RTEXITCODE_SUCCESS)
709 return rcExit;
710
711 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
712 {
713 rc = g_aServices[j].pDesc->pfnOption(NULL, argc, argv, &i);
714 fFound = rc == 0;
715 if (fFound)
716 break;
717 if (rc != -1)
718 return rc;
719 }
720 }
721 if (!fFound)
722 return VBoxServiceSyntax("Unknown option '%s'\n", argv[i]);
723 continue;
724 }
725#undef MATCHES
726 }
727
728 /* handle the string of short options. */
729 do
730 {
731 switch (*psz)
732 {
733 case 'i':
734 rc = VBoxServiceArgUInt32(argc, argv, psz + 1, &i,
735 &g_DefaultInterval, 1, (UINT32_MAX / 1000) - 1);
736 if (rc)
737 return rc;
738 psz = NULL;
739 break;
740
741 case 'f':
742 fDaemonize = false;
743 break;
744
745 case 'v':
746 g_cVerbosity++;
747 break;
748
749 case 'V':
750 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
751 return RTEXITCODE_SUCCESS;
752
753 case 'h':
754 case '?':
755 return vboxServiceUsage();
756
757#ifdef RT_OS_WINDOWS
758 case 'r':
759 return VBoxServiceWinInstall();
760
761 case 'u':
762 return VBoxServiceWinUninstall();
763#endif
764
765 default:
766 {
767 rcExit = vboxServiceLazyPreInit();
768 if (rcExit != RTEXITCODE_SUCCESS)
769 return rcExit;
770
771 bool fFound = false;
772 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
773 {
774 rc = g_aServices[j].pDesc->pfnOption(&psz, argc, argv, &i);
775 fFound = rc == VINF_SUCCESS;
776 if (fFound)
777 break;
778 if (rc != -1)
779 return rc;
780 }
781 if (!fFound)
782 return VBoxServiceSyntax("Unknown option '%c' (%s)\n", *psz, argv[i]);
783 break;
784 }
785 }
786 } while (psz && *++psz);
787 }
788
789 /* Check that at least one service is enabled. */
790 if (vboxServiceCountEnabledServices() == 0)
791 return VBoxServiceSyntax("At least one service must be enabled.\n");
792
793 /* Call pre-init if we didn't do it already. */
794 rcExit = vboxServiceLazyPreInit();
795 if (rcExit != RTEXITCODE_SUCCESS)
796 return rcExit;
797
798#ifdef RT_OS_WINDOWS
799 /*
800 * Make sure only one instance of VBoxService runs at a time. Create a
801 * global mutex for that.
802 *
803 * Note! The \\Global\ namespace was introduced with Win2K, thus the
804 * version check.
805 * Note! If the mutex exists CreateMutex will open it and set last error to
806 * ERROR_ALREADY_EXISTS.
807 */
808 OSVERSIONINFOEX OSInfoEx;
809 RT_ZERO(OSInfoEx);
810 OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
811
812 SetLastError(NO_ERROR);
813 HANDLE hMutexAppRunning;
814 if ( GetVersionEx((LPOSVERSIONINFO)&OSInfoEx)
815 && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
816 && OSInfoEx.dwMajorVersion >= 5 /* NT 5.0 a.k.a W2K */)
817 hMutexAppRunning = CreateMutex(NULL, FALSE, "Global\\" VBOXSERVICE_NAME);
818 else
819 hMutexAppRunning = CreateMutex(NULL, FALSE, VBOXSERVICE_NAME);
820 if (hMutexAppRunning == NULL)
821 {
822 VBoxServiceError("CreateMutex failed with last error %u! Terminating", GetLastError());
823 return RTEXITCODE_FAILURE;
824 }
825 if (GetLastError() == ERROR_ALREADY_EXISTS)
826 {
827 VBoxServiceError("%s is already running! Terminating.", g_pszProgName);
828 CloseHandle(hMutexAppRunning);
829 return RTEXITCODE_FAILURE;
830 }
831#else /* !RT_OS_WINDOWS */
832 /** @todo Add PID file creation here? */
833#endif /* !RT_OS_WINDOWS */
834
835 VBoxServiceVerbose(0, "%s r%s started. Verbose level = %d\n",
836 RTBldCfgVersion(), RTBldCfgRevisionStr(), g_cVerbosity);
837
838 /*
839 * Daemonize if requested.
840 */
841 if (fDaemonize && !fDaemonized)
842 {
843#ifdef RT_OS_WINDOWS
844 VBoxServiceVerbose(2, "Starting service dispatcher ...\n");
845 rcExit = VBoxServiceWinEnterCtrlDispatcher();
846#else
847 VBoxServiceVerbose(1, "Daemonizing...\n");
848 rc = VbglR3Daemonize(false /* fNoChDir */, false /* fNoClose */);
849 if (RT_FAILURE(rc))
850 return VBoxServiceError("Daemon failed: %Rrc\n", rc);
851 /* in-child */
852#endif
853 }
854#ifdef RT_OS_WINDOWS
855 else
856#endif
857 {
858 /*
859 * Windows: We're running the service as a console application now. Start the
860 * services, enter the main thread's run loop and stop them again
861 * when it returns.
862 *
863 * POSIX: This is used for both daemons and console runs. Start all services
864 * and return immediately.
865 */
866 rc = VBoxServiceStartServices();
867 rcExit = RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
868 if (RT_SUCCESS(rc))
869 VBoxServiceMainWait();
870 VBoxServiceStopServices();
871 }
872 VBoxServiceReportStatus(VBoxGuestFacilityStatus_Terminated);
873
874#ifdef RT_OS_WINDOWS
875 /*
876 * Cleanup mutex.
877 */
878 CloseHandle(hMutexAppRunning);
879#endif
880
881 VBoxServiceVerbose(0, "Ended.\n");
882
883#ifdef DEBUG
884 RTCritSectDelete(&g_csLog);
885#endif
886 return rcExit;
887}
888
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