VirtualBox

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

Last change on this file since 26085 was 26061, checked in by vboxsync, 15 years ago

VBoxService,VBoxGuestLib: CPU hot plugging cleanup + review.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 20.1 KB
Line 
1/* $Id: VBoxService.cpp 26061 2010-01-27 10:18:30Z vboxsync $ */
2/** @file
3 * VBoxService - Guest Additions Service Skeleton.
4 */
5
6/*
7 * Copyright (C) 2007-2010 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22
23
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27/** @todo LOG_GROUP*/
28#ifndef _MSC_VER
29# include <unistd.h>
30#endif
31#include <errno.h>
32
33#include <iprt/asm.h>
34#include <iprt/buildconfig.h>
35#include <iprt/initterm.h>
36#include <iprt/path.h>
37#include <iprt/string.h>
38#include <iprt/stream.h>
39#include <iprt/thread.h>
40
41#include <VBox/VBoxGuestLib.h>
42#include <VBox/log.h>
43
44#include "VBoxServiceInternal.h"
45
46
47/*******************************************************************************
48* Global Variables *
49*******************************************************************************/
50/** The program name (derived from argv[0]). */
51char *g_pszProgName = (char *)"";
52/** The current verbosity level. */
53int g_cVerbosity = 0;
54/** The default service interval (the -i | --interval) option). */
55uint32_t g_DefaultInterval = 0;
56/** Shutdown the main thread. (later, for signals.) */
57bool volatile g_fShutdown;
58
59/**
60 * The details of the services that has been compiled in.
61 */
62static struct
63{
64 /** Pointer to the service descriptor. */
65 PCVBOXSERVICE pDesc;
66 /** The worker thread. NIL_RTTHREAD if it's the main thread. */
67 RTTHREAD Thread;
68 /** Shutdown indicator. */
69 bool volatile fShutdown;
70 /** Indicator set by the service thread exiting. */
71 bool volatile fStopped;
72 /** Whether the service was started or not. */
73 bool fStarted;
74 /** Whether the service is enabled or not. */
75 bool fEnabled;
76} g_aServices[] =
77{
78#ifdef VBOXSERVICE_CONTROL
79 { &g_Control, NIL_RTTHREAD, false, false, false, true },
80#endif
81#ifdef VBOXSERVICE_TIMESYNC
82 { &g_TimeSync, NIL_RTTHREAD, false, false, false, true },
83#endif
84#ifdef VBOXSERVICE_CLIPBOARD
85 { &g_Clipboard, NIL_RTTHREAD, false, false, false, true },
86#endif
87#ifdef VBOXSERVICE_VMINFO
88 { &g_VMInfo, NIL_RTTHREAD, false, false, false, true },
89#endif
90#ifdef VBOXSERVICE_EXEC
91 { &g_Exec, NIL_RTTHREAD, false, false, false, true },
92#endif
93#ifdef VBOXSERVICE_CPUHOTPLUG /* Disabled by default. Use --enable-cpuhotplug to enable */
94 { &g_CpuHotPlug, NIL_RTTHREAD, false, false, false, false },
95#endif
96};
97
98
99/**
100 * Displays the program usage message.
101 *
102 * @returns 1.
103 */
104static int VBoxServiceUsage(void)
105{
106 RTPrintf("usage: %s [-f|--foreground] [-v|--verbose] [-i|--interval <seconds>]\n"
107 " [--disable-<service>] [--enable-<service>] [-h|-?|--help]\n", g_pszProgName);
108#ifdef RT_OS_WINDOWS
109 RTPrintf(" [-r|--register] [-u|--unregister]\n");
110#endif
111 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
112 RTPrintf(" %s\n", g_aServices[j].pDesc->pszUsage);
113 RTPrintf("\n"
114 "Options:\n"
115 " -i | --interval The default interval.\n"
116 " -f | --foreground Don't daemonzie the program. For debugging.\n"
117 " -v | --verbose Increment the verbosity level. For debugging.\n"
118 " -h | -? | --help Show this message and exit with status 1.\n"
119 );
120#ifdef RT_OS_WINDOWS
121 RTPrintf(" -r | --register Installs the service.\n"
122 " -u | --unregister Uninstall service.\n");
123#endif
124
125 RTPrintf("\n"
126 "Service specific options:\n");
127 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
128 {
129 RTPrintf(" --enable-%-10s Enables the %s service. (default)\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
130 RTPrintf(" --disable-%-9s Disables the %s service.\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
131 RTPrintf("%s", g_aServices[j].pDesc->pszOptions);
132 }
133 RTPrintf("\n"
134 " Copyright (C) 2009 Sun Microsystems, Inc.\n");
135
136 return 1;
137}
138
139
140/**
141 * Displays a syntax error message.
142 *
143 * @returns 1
144 * @param pszFormat The message text.
145 * @param ... Format arguments.
146 */
147int VBoxServiceSyntax(const char *pszFormat, ...)
148{
149 RTStrmPrintf(g_pStdErr, "%s: syntax error: ", g_pszProgName);
150
151 va_list va;
152 va_start(va, pszFormat);
153 RTStrmPrintfV(g_pStdErr, pszFormat, va);
154 va_end(va);
155
156 return 1;
157}
158
159
160/**
161 * Displays an error message.
162 *
163 * @returns 1
164 * @param pszFormat The message text.
165 * @param ... Format arguments.
166 */
167int VBoxServiceError(const char *pszFormat, ...)
168{
169 RTStrmPrintf(g_pStdErr, "%s: error: ", g_pszProgName);
170
171 va_list va;
172 va_start(va, pszFormat);
173 RTStrmPrintfV(g_pStdErr, pszFormat, va);
174 va_end(va);
175
176 va_start(va, pszFormat);
177 LogRel(("%s: Error: %N", g_pszProgName, pszFormat, &va));
178 va_end(va);
179
180 return 1;
181}
182
183
184/**
185 * Displays a verbose message.
186 *
187 * @returns 1
188 * @param pszFormat The message text.
189 * @param ... Format arguments.
190 */
191void VBoxServiceVerbose(int iLevel, const char *pszFormat, ...)
192{
193 if (iLevel <= g_cVerbosity)
194 {
195 RTStrmPrintf(g_pStdOut, "%s: ", g_pszProgName);
196 va_list va;
197 va_start(va, pszFormat);
198 RTStrmPrintfV(g_pStdOut, pszFormat, va);
199 va_end(va);
200
201 va_start(va, pszFormat);
202 LogRel(("%s: %N", g_pszProgName, pszFormat, &va));
203 va_end(va);
204 }
205}
206
207
208/**
209 * Gets a 32-bit value argument.
210 *
211 * @returns 0 on success, non-zero exit code on error.
212 * @param argc The argument count.
213 * @param argv The argument vector
214 * @param psz Where in *pi to start looking for the value argument.
215 * @param pi Where to find and perhaps update the argument index.
216 * @param pu32 Where to store the 32-bit value.
217 * @param u32Min The minimum value.
218 * @param u32Max The maximum value.
219 */
220int VBoxServiceArgUInt32(int argc, char **argv, const char *psz, int *pi, uint32_t *pu32, uint32_t u32Min, uint32_t u32Max)
221{
222 if (*psz == ':' || *psz == '=')
223 psz++;
224 if (!*psz)
225 {
226 if (*pi + 1 >= argc)
227 return VBoxServiceSyntax("Missing value for the '%s' argument\n", argv[*pi]);
228 psz = argv[++*pi];
229 }
230
231 char *pszNext;
232 int rc = RTStrToUInt32Ex(psz, &pszNext, 0, pu32);
233 if (RT_FAILURE(rc) || *pszNext)
234 return VBoxServiceSyntax("Failed to convert interval '%s' to a number.\n", psz);
235 if (*pu32 < u32Min || *pu32 > u32Max)
236 return VBoxServiceSyntax("The timesync interval of %RU32 secconds is out of range [%RU32..%RU32].\n",
237 *pu32, u32Min, u32Max);
238 return 0;
239}
240
241
242/**
243 * The service thread.
244 *
245 * @returns Whatever the worker function returns.
246 * @param ThreadSelf My thread handle.
247 * @param pvUser The service index.
248 */
249static DECLCALLBACK(int) VBoxServiceThread(RTTHREAD ThreadSelf, void *pvUser)
250{
251 const unsigned i = (uintptr_t)pvUser;
252 int rc = g_aServices[i].pDesc->pfnWorker(&g_aServices[i].fShutdown);
253 ASMAtomicXchgBool(&g_aServices[i].fShutdown, true);
254 RTThreadUserSignal(ThreadSelf);
255 return rc;
256}
257
258
259unsigned VBoxServiceGetStartedServices(void)
260{
261 unsigned iMain = ~0U;
262 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
263 if (g_aServices[j].fEnabled)
264 {
265 iMain = j;
266 break;
267 }
268
269 return iMain; /* Return the index of the main service (must always come last!). */
270}
271
272/**
273 * Starts the service.
274 *
275 * @returns VBox status code, errors are fully bitched.
276 *
277 * @param iMain The index of the service that belongs to the main
278 * thread. Pass ~0U if none does.
279 */
280int VBoxServiceStartServices(unsigned iMain)
281{
282 int rc;
283
284 /*
285 * Initialize the services.
286 */
287 VBoxServiceVerbose(2, "Initializing services ...\n");
288 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
289 if (g_aServices[j].fEnabled)
290 {
291 rc = g_aServices[j].pDesc->pfnInit();
292 if (RT_FAILURE(rc))
293 {
294 VBoxServiceError("Service '%s' failed to initialize: %Rrc\n",
295 g_aServices[j].pDesc->pszName, rc);
296 return rc;
297 }
298 }
299
300 /*
301 * Start the service(s).
302 */
303 VBoxServiceVerbose(2, "Starting services ...\n");
304 rc = VINF_SUCCESS;
305 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
306 {
307 if ( !g_aServices[j].fEnabled
308 || j == iMain)
309 continue;
310
311 VBoxServiceVerbose(2, "Starting service '%s' ...\n", g_aServices[j].pDesc->pszName);
312 rc = RTThreadCreate(&g_aServices[j].Thread, VBoxServiceThread, (void *)(uintptr_t)j, 0,
313 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, g_aServices[j].pDesc->pszName);
314 if (RT_FAILURE(rc))
315 {
316 VBoxServiceError("RTThreadCreate failed, rc=%Rrc\n", rc);
317 break;
318 }
319 g_aServices[j].fStarted = true;
320
321 /* wait for the thread to initialize */
322 RTThreadUserWait(g_aServices[j].Thread, 60 * 1000);
323 if (g_aServices[j].fShutdown)
324 {
325 VBoxServiceError("Service '%s' failed to start!\n", g_aServices[j].pDesc->pszName);
326 rc = VERR_GENERAL_FAILURE;
327 }
328 }
329 if (RT_SUCCESS(rc))
330 {
331 /* The final service runs in the main thread. */
332 VBoxServiceVerbose(1, "Starting '%s' in the main thread\n", g_aServices[iMain].pDesc->pszName);
333 rc = g_aServices[iMain].pDesc->pfnWorker(&g_fShutdown);
334 if (rc != VINF_SUCCESS) /* Only complain if service returned an error. Otherwise the service is a one-timer. */
335 {
336 VBoxServiceError("Service '%s' stopped unexpected; rc=%Rrc\n", g_aServices[iMain].pDesc->pszName, rc);
337 }
338 }
339 return rc;
340}
341
342
343/**
344 * Stops and terminates the services.
345 *
346 * This should be called even when VBoxServiceStartServices fails so it can
347 * clean up anything that we succeeded in starting.
348 */
349int VBoxServiceStopServices(void)
350{
351 int rc = VINF_SUCCESS;
352
353 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
354 ASMAtomicXchgBool(&g_aServices[j].fShutdown, true);
355 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
356 if (g_aServices[j].fStarted)
357 g_aServices[j].pDesc->pfnStop();
358 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
359 if (g_aServices[j].fEnabled)
360 {
361 if (g_aServices[j].Thread != NIL_RTTHREAD)
362 {
363 int rc;
364 VBoxServiceVerbose(2, "Waiting for service '%s' to stop ...\n", g_aServices[j].pDesc->pszName);
365 for (int i=0; i<30; i++) /* Wait 30 seconds in total */
366 {
367 rc = RTThreadWait(g_aServices[j].Thread, 1000 /* Wait 1 second */, NULL);
368 if (RT_SUCCESS(rc))
369 break;
370#ifdef RT_OS_WINDOWS
371 /* Notify SCM that it takes a bit longer ... */
372 VBoxServiceWinSetStatus(SERVICE_STOP_PENDING, i);
373#endif
374 }
375 if (RT_FAILURE(rc))
376 VBoxServiceError("Service '%s' failed to stop. (%Rrc)\n", g_aServices[j].pDesc->pszName, rc);
377 }
378 VBoxServiceVerbose(3, "Terminating service '%s' (%d) ...\n", g_aServices[j].pDesc->pszName, j);
379 g_aServices[j].pDesc->pfnTerm();
380 }
381
382 VBoxServiceVerbose(2, "Stopping services returned: rc=%Rrc\n", rc);
383 return rc;
384}
385
386
387int main(int argc, char **argv)
388{
389 int rc = VINF_SUCCESS;
390 /*
391 * Init globals and such.
392 */
393 RTR3Init();
394
395 /*
396 * Connect to the kernel part before daemonizing so we can fail
397 * and complain if there is some kind of problem. We need to initialize
398 * the guest lib *before* we do the pre-init just in case one of services
399 * needs do to some initial stuff with it.
400 */
401 VBoxServiceVerbose(2, "Calling VbgR3Init()\n");
402 rc = VbglR3Init();
403 if (RT_FAILURE(rc))
404 return VBoxServiceError("VbglR3Init failed with rc=%Rrc.\n", rc);
405
406 /* Do pre-init of services. */
407 g_pszProgName = RTPathFilename(argv[0]);
408 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
409 {
410 rc = g_aServices[j].pDesc->pfnPreInit();
411 if (RT_FAILURE(rc))
412 return VBoxServiceError("Service '%s' failed pre-init: %Rrc\n", g_aServices[j].pDesc->pszName);
413 }
414
415#ifdef RT_OS_WINDOWS
416 /* Make sure only one instance of VBoxService runs at a time. Create a global mutex for that.
417 Do not use a global namespace ("Global\\") for mutex name here, will blow up NT4 compatibility! */
418 HANDLE hMutexAppRunning = CreateMutex (NULL, FALSE, VBOXSERVICE_NAME);
419 if ( hMutexAppRunning != NULL
420 && GetLastError() == ERROR_ALREADY_EXISTS)
421 {
422 VBoxServiceError("%s is already running! Terminating.", g_pszProgName);
423
424 /* Close the mutex for this application instance. */
425 CloseHandle(hMutexAppRunning);
426 hMutexAppRunning = NULL;
427 }
428#endif
429
430 /*
431 * Parse the arguments.
432 */
433 bool fDaemonize = true;
434 bool fDaemonized = false;
435 for (int i = 1; i < argc; i++)
436 {
437 const char *psz = argv[i];
438 if (*psz != '-')
439 return VBoxServiceSyntax("Unknown argument '%s'\n", psz);
440 psz++;
441
442 /* translate long argument to short */
443 if (*psz == '-')
444 {
445 psz++;
446 size_t cch = strlen(psz);
447#define MATCHES(strconst) ( cch == sizeof(strconst) - 1 \
448 && !memcmp(psz, strconst, sizeof(strconst) - 1) )
449 if (MATCHES("foreground"))
450 psz = "f";
451 else if (MATCHES("verbose"))
452 psz = "v";
453 else if (MATCHES("help"))
454 psz = "h";
455 else if (MATCHES("interval"))
456 psz = "i";
457#ifdef RT_OS_WINDOWS
458 else if (MATCHES("register"))
459 psz = "r";
460 else if (MATCHES("unregister"))
461 psz = "u";
462#endif
463 else if (MATCHES("daemonized"))
464 {
465 fDaemonized = true;
466 continue;
467 }
468 else
469 {
470 bool fFound = false;
471
472 if (cch > sizeof("enable-") && !memcmp(psz, "enable-", sizeof("enable-") - 1))
473 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
474 if ((fFound = !RTStrICmp(psz + sizeof("enable-") - 1, g_aServices[j].pDesc->pszName)))
475 g_aServices[j].fEnabled = true;
476
477 if (cch > sizeof("disable-") && !memcmp(psz, "disable-", sizeof("disable-") - 1))
478 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
479 if ((fFound = !RTStrICmp(psz + sizeof("disable-") - 1, g_aServices[j].pDesc->pszName)))
480 g_aServices[j].fEnabled = false;
481
482 if (!fFound)
483 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
484 {
485 rc = g_aServices[j].pDesc->pfnOption(NULL, argc, argv, &i);
486 fFound = rc == 0;
487 if (fFound)
488 break;
489 if (rc != -1)
490 return rc;
491 }
492 if (!fFound)
493 return VBoxServiceSyntax("Unknown option '%s'\n", argv[i]);
494 continue;
495 }
496#undef MATCHES
497 }
498
499 /* handle the string of short options. */
500 do
501 {
502 switch (*psz)
503 {
504 case 'i':
505 rc = VBoxServiceArgUInt32(argc, argv, psz + 1, &i,
506 &g_DefaultInterval, 1, (UINT32_MAX / 1000) - 1);
507 if (rc)
508 return rc;
509 psz = NULL;
510 break;
511
512 case 'f':
513 fDaemonize = false;
514 break;
515
516 case 'v':
517 g_cVerbosity++;
518 break;
519
520 case 'h':
521 case '?':
522 return VBoxServiceUsage();
523
524#ifdef RT_OS_WINDOWS
525 case 'r':
526 return VBoxServiceWinInstall();
527
528 case 'u':
529 return VBoxServiceWinUninstall();
530#endif
531
532 default:
533 {
534 bool fFound = false;
535 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
536 {
537 rc = g_aServices[j].pDesc->pfnOption(&psz, argc, argv, &i);
538 fFound = rc == 0;
539 if (fFound)
540 break;
541 if (rc != -1)
542 return rc;
543 }
544 if (!fFound)
545 return VBoxServiceSyntax("Unknown option '%c' (%s)\n", *psz, argv[i]);
546 break;
547 }
548 }
549 } while (psz && *++psz);
550 }
551 /*
552 * Check that at least one service is enabled.
553 */
554 unsigned iMain = VBoxServiceGetStartedServices();
555 if (iMain == ~0U)
556 return VBoxServiceSyntax("At least one service must be enabled.\n");
557
558 VBoxServiceVerbose(0, "%s r%s started. Verbose level = %d\n",
559 RTBldCfgVersion(), RTBldCfgRevisionStr(), g_cVerbosity);
560
561 /*
562 * Daemonize if requested.
563 */
564 if (fDaemonize && !fDaemonized)
565 {
566#ifdef RT_OS_WINDOWS
567 /** @todo Should do something like VBoxSVC here, OR automatically re-register
568 * the service and start it. Involving VbglR3Daemonize isn't an option
569 * here.
570 *
571 * Also, the idea here, IIRC, was to map the sub service to windows
572 * services. The todo below is for mimicking windows services on
573 * non-windows systems. Not sure if this is doable or not, but in anycase
574 * this code can be moved into -win.
575 *
576 * You should return when StartServiceCtrlDispatcher, btw., not
577 * continue.
578 */
579 VBoxServiceVerbose(2, "Starting service dispatcher ...\n");
580 if (!StartServiceCtrlDispatcher(&g_aServiceTable[0]))
581 return VBoxServiceError("StartServiceCtrlDispatcher: %u. Please start %s with option -f (foreground)!",
582 GetLastError(), g_pszProgName);
583 /* Service now lives in the control dispatcher registered above. */
584#else
585 VBoxServiceVerbose(1, "Daemonizing...\n");
586 rc = VbglR3Daemonize(false /* fNoChDir */, false /* fNoClose */);
587 if (RT_FAILURE(rc))
588 return VBoxServiceError("Daemon failed: %Rrc\n", rc);
589 /* in-child */
590#endif
591 }
592#ifdef RT_OS_WINDOWS
593 else
594 {
595 /* Run the app just like a console one if not daemonized. */
596#endif
597 /** @todo Make the main thread responsive to signal so it can shutdown/restart the threads on non-SIGKILL signals. */
598
599 /*
600 * Start the service, enter the main threads run loop and stop them again when it returns.
601 */
602 rc = VBoxServiceStartServices(iMain);
603 VBoxServiceStopServices();
604#ifdef RT_OS_WINDOWS
605 }
606#endif
607
608#ifdef RT_OS_WINDOWS
609 /*
610 * Release instance mutex if we got it.
611 */
612 if (hMutexAppRunning != NULL)
613 {
614 ::CloseHandle(hMutexAppRunning);
615 hMutexAppRunning = NULL;
616 }
617#endif
618
619 VBoxServiceVerbose(0, "Ended.\n");
620 return RT_SUCCESS(rc) ? 0 : 1;
621}
622
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