VirtualBox

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

Last change on this file since 25776 was 25479, checked in by vboxsync, 15 years ago

VBoxService: Include build version + rev.

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