1 | /* $Id: VBoxService.cpp 83974 2020-04-24 16:05:50Z vboxsync $ */
|
---|
2 | /** @file
|
---|
3 | * VBoxService - Guest Additions Service Skeleton.
|
---|
4 | */
|
---|
5 |
|
---|
6 | /*
|
---|
7 | * Copyright (C) 2007-2020 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 | /** @page pg_vgsvc VBoxService
|
---|
20 | *
|
---|
21 | * VBoxService is a root daemon for implementing guest additions features.
|
---|
22 | *
|
---|
23 | * It is structured as one binary that contains many sub-services. The reason
|
---|
24 | * for this is partially historical and partially practical. The practical
|
---|
25 | * reason is that the VBoxService binary is typically statically linked, at
|
---|
26 | * least with IPRT and the guest library, so we save quite a lot of space having
|
---|
27 | * on single binary instead individual binaries for each sub-service and their
|
---|
28 | * helpers (currently up to 9 subservices and 8 helpers). The historical is
|
---|
29 | * simply that it started its life on OS/2 dreaming of conquring Windows next,
|
---|
30 | * so it kind of felt natural to have it all in one binary.
|
---|
31 | *
|
---|
32 | * Even if it's structured as a single binary, it is possible, by using command
|
---|
33 | * line options, to start each subservice as an individual process.
|
---|
34 | *
|
---|
35 | * Subservices:
|
---|
36 | * - @subpage pg_vgsvc_timesync "Time Synchronization"
|
---|
37 | * - @subpage pg_vgsvc_vminfo "VM Information"
|
---|
38 | * - @subpage pg_vgsvc_vmstats "VM Statistics"
|
---|
39 | * - @subpage pg_vgsvc_gstctrl "Guest Control"
|
---|
40 | * - @subpage pg_vgsvc_pagesharing "Page Sharing"
|
---|
41 | * - @subpage pg_vgsvc_memballoon "Memory Balooning"
|
---|
42 | * - @subpage pg_vgsvc_cpuhotplug "CPU Hot-Plugging"
|
---|
43 | * - @subpage pg_vgsvc_automount "Shared Folder Automounting"
|
---|
44 | * - @subpage pg_vgsvc_clipboard "Clipboard (OS/2 only)"
|
---|
45 | *
|
---|
46 | * Now, since the service predates a lot of stuff, including RTGetOpt, we're
|
---|
47 | * currently doing our own version of argument parsing here, which is kind of
|
---|
48 | * stupid. That will hopefully be cleaned up eventually.
|
---|
49 | */
|
---|
50 |
|
---|
51 |
|
---|
52 | /*********************************************************************************************************************************
|
---|
53 | * Header Files *
|
---|
54 | *********************************************************************************************************************************/
|
---|
55 | /** @todo LOG_GROUP*/
|
---|
56 | #ifndef _MSC_VER
|
---|
57 | # include <unistd.h>
|
---|
58 | #endif
|
---|
59 | #include <errno.h>
|
---|
60 | #ifndef RT_OS_WINDOWS
|
---|
61 | # include <signal.h>
|
---|
62 | # ifdef RT_OS_OS2
|
---|
63 | # define pthread_sigmask sigprocmask
|
---|
64 | # endif
|
---|
65 | #endif
|
---|
66 | #ifdef RT_OS_FREEBSD
|
---|
67 | # include <pthread.h>
|
---|
68 | #endif
|
---|
69 |
|
---|
70 | #include <package-generated.h>
|
---|
71 | #include "product-generated.h"
|
---|
72 |
|
---|
73 | #include <iprt/asm.h>
|
---|
74 | #include <iprt/buildconfig.h>
|
---|
75 | #include <iprt/initterm.h>
|
---|
76 | #include <iprt/file.h>
|
---|
77 | #ifdef DEBUG
|
---|
78 | # include <iprt/memtracker.h>
|
---|
79 | #endif
|
---|
80 | #include <iprt/message.h>
|
---|
81 | #include <iprt/path.h>
|
---|
82 | #include <iprt/process.h>
|
---|
83 | #include <iprt/semaphore.h>
|
---|
84 | #include <iprt/string.h>
|
---|
85 | #include <iprt/stream.h>
|
---|
86 | #include <iprt/system.h>
|
---|
87 | #include <iprt/thread.h>
|
---|
88 |
|
---|
89 | #include <VBox/err.h>
|
---|
90 | #include <VBox/log.h>
|
---|
91 |
|
---|
92 | #include "VBoxServiceInternal.h"
|
---|
93 | #ifdef VBOX_WITH_VBOXSERVICE_CONTROL
|
---|
94 | # include "VBoxServiceControl.h"
|
---|
95 | #endif
|
---|
96 | #ifdef VBOX_WITH_VBOXSERVICE_TOOLBOX
|
---|
97 | # include "VBoxServiceToolBox.h"
|
---|
98 | #endif
|
---|
99 |
|
---|
100 |
|
---|
101 | /*********************************************************************************************************************************
|
---|
102 | * Global Variables *
|
---|
103 | *********************************************************************************************************************************/
|
---|
104 | /** The program name (derived from argv[0]). */
|
---|
105 | char *g_pszProgName = (char *)"";
|
---|
106 | /** The current verbosity level. */
|
---|
107 | unsigned g_cVerbosity = 0;
|
---|
108 | char g_szLogFile[RTPATH_MAX + 128] = "";
|
---|
109 | char g_szPidFile[RTPATH_MAX] = "";
|
---|
110 | /** Logging parameters. */
|
---|
111 | /** @todo Make this configurable later. */
|
---|
112 | static PRTLOGGER g_pLoggerRelease = NULL;
|
---|
113 | static uint32_t g_cHistory = 10; /* Enable log rotation, 10 files. */
|
---|
114 | static uint32_t g_uHistoryFileTime = RT_SEC_1DAY; /* Max 1 day per file. */
|
---|
115 | static uint64_t g_uHistoryFileSize = 100 * _1M; /* Max 100MB per file. */
|
---|
116 | /** Critical section for (debug) logging. */
|
---|
117 | #ifdef DEBUG
|
---|
118 | RTCRITSECT g_csLog;
|
---|
119 | #endif
|
---|
120 | /** The default service interval (the -i | --interval) option). */
|
---|
121 | uint32_t g_DefaultInterval = 0;
|
---|
122 | #ifdef RT_OS_WINDOWS
|
---|
123 | /** Signal shutdown to the Windows service thread. */
|
---|
124 | static bool volatile g_fWindowsServiceShutdown;
|
---|
125 | /** Event the Windows service thread waits for shutdown. */
|
---|
126 | static RTSEMEVENT g_hEvtWindowsService;
|
---|
127 | #endif
|
---|
128 |
|
---|
129 | /**
|
---|
130 | * The details of the services that has been compiled in.
|
---|
131 | */
|
---|
132 | static struct
|
---|
133 | {
|
---|
134 | /** Pointer to the service descriptor. */
|
---|
135 | PCVBOXSERVICE pDesc;
|
---|
136 | /** The worker thread. NIL_RTTHREAD if it's the main thread. */
|
---|
137 | RTTHREAD Thread;
|
---|
138 | /** Whether Pre-init was called. */
|
---|
139 | bool fPreInited;
|
---|
140 | /** Shutdown indicator. */
|
---|
141 | bool volatile fShutdown;
|
---|
142 | /** Indicator set by the service thread exiting. */
|
---|
143 | bool volatile fStopped;
|
---|
144 | /** Whether the service was started or not. */
|
---|
145 | bool fStarted;
|
---|
146 | /** Whether the service is enabled or not. */
|
---|
147 | bool fEnabled;
|
---|
148 | } g_aServices[] =
|
---|
149 | {
|
---|
150 | #ifdef VBOX_WITH_VBOXSERVICE_CONTROL
|
---|
151 | { &g_Control, NIL_RTTHREAD, false, false, false, false, true },
|
---|
152 | #endif
|
---|
153 | #ifdef VBOX_WITH_VBOXSERVICE_TIMESYNC
|
---|
154 | { &g_TimeSync, NIL_RTTHREAD, false, false, false, false, true },
|
---|
155 | #endif
|
---|
156 | #ifdef VBOX_WITH_VBOXSERVICE_CLIPBOARD
|
---|
157 | { &g_Clipboard, NIL_RTTHREAD, false, false, false, false, true },
|
---|
158 | #endif
|
---|
159 | #ifdef VBOX_WITH_VBOXSERVICE_VMINFO
|
---|
160 | { &g_VMInfo, NIL_RTTHREAD, false, false, false, false, true },
|
---|
161 | #endif
|
---|
162 | #ifdef VBOX_WITH_VBOXSERVICE_CPUHOTPLUG
|
---|
163 | { &g_CpuHotPlug, NIL_RTTHREAD, false, false, false, false, true },
|
---|
164 | #endif
|
---|
165 | #ifdef VBOX_WITH_VBOXSERVICE_MANAGEMENT
|
---|
166 | # ifdef VBOX_WITH_MEMBALLOON
|
---|
167 | { &g_MemBalloon, NIL_RTTHREAD, false, false, false, false, true },
|
---|
168 | # endif
|
---|
169 | { &g_VMStatistics, NIL_RTTHREAD, false, false, false, false, true },
|
---|
170 | #endif
|
---|
171 | #if defined(VBOX_WITH_VBOXSERVICE_PAGE_SHARING)
|
---|
172 | { &g_PageSharing, NIL_RTTHREAD, false, false, false, false, true },
|
---|
173 | #endif
|
---|
174 | #ifdef VBOX_WITH_SHARED_FOLDERS
|
---|
175 | { &g_AutoMount, NIL_RTTHREAD, false, false, false, false, true },
|
---|
176 | #endif
|
---|
177 | };
|
---|
178 |
|
---|
179 |
|
---|
180 | /*
|
---|
181 | * Default call-backs for services which do not need special behaviour.
|
---|
182 | */
|
---|
183 |
|
---|
184 | /**
|
---|
185 | * @interface_method_impl{VBOXSERVICE,pfnPreInit, Default Implementation}
|
---|
186 | */
|
---|
187 | DECLCALLBACK(int) VGSvcDefaultPreInit(void)
|
---|
188 | {
|
---|
189 | return VINF_SUCCESS;
|
---|
190 | }
|
---|
191 |
|
---|
192 |
|
---|
193 | /**
|
---|
194 | * @interface_method_impl{VBOXSERVICE,pfnOption, Default Implementation}
|
---|
195 | */
|
---|
196 | DECLCALLBACK(int) VGSvcDefaultOption(const char **ppszShort, int argc,
|
---|
197 | char **argv, int *pi)
|
---|
198 | {
|
---|
199 | NOREF(ppszShort);
|
---|
200 | NOREF(argc);
|
---|
201 | NOREF(argv);
|
---|
202 | NOREF(pi);
|
---|
203 |
|
---|
204 | return -1;
|
---|
205 | }
|
---|
206 |
|
---|
207 |
|
---|
208 | /**
|
---|
209 | * @interface_method_impl{VBOXSERVICE,pfnInit, Default Implementation}
|
---|
210 | */
|
---|
211 | DECLCALLBACK(int) VGSvcDefaultInit(void)
|
---|
212 | {
|
---|
213 | return VINF_SUCCESS;
|
---|
214 | }
|
---|
215 |
|
---|
216 |
|
---|
217 | /**
|
---|
218 | * @interface_method_impl{VBOXSERVICE,pfnTerm, Default Implementation}
|
---|
219 | */
|
---|
220 | DECLCALLBACK(void) VGSvcDefaultTerm(void)
|
---|
221 | {
|
---|
222 | return;
|
---|
223 | }
|
---|
224 |
|
---|
225 |
|
---|
226 | /**
|
---|
227 | * @callback_method_impl{FNRTLOGPHASE, Release logger callback}
|
---|
228 | */
|
---|
229 | static DECLCALLBACK(void) vgsvcLogHeaderFooter(PRTLOGGER pLoggerRelease, RTLOGPHASE enmPhase, PFNRTLOGPHASEMSG pfnLog)
|
---|
230 | {
|
---|
231 | /* Some introductory information. */
|
---|
232 | static RTTIMESPEC s_TimeSpec;
|
---|
233 | char szTmp[256];
|
---|
234 | if (enmPhase == RTLOGPHASE_BEGIN)
|
---|
235 | RTTimeNow(&s_TimeSpec);
|
---|
236 | RTTimeSpecToString(&s_TimeSpec, szTmp, sizeof(szTmp));
|
---|
237 |
|
---|
238 | switch (enmPhase)
|
---|
239 | {
|
---|
240 | case RTLOGPHASE_BEGIN:
|
---|
241 | {
|
---|
242 | pfnLog(pLoggerRelease,
|
---|
243 | "VBoxService %s r%s (verbosity: %u) %s (%s %s) release log\n"
|
---|
244 | "Log opened %s\n",
|
---|
245 | RTBldCfgVersion(), RTBldCfgRevisionStr(), g_cVerbosity, VBOX_BUILD_TARGET,
|
---|
246 | __DATE__, __TIME__, szTmp);
|
---|
247 |
|
---|
248 | int vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
|
---|
249 | if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
|
---|
250 | pfnLog(pLoggerRelease, "OS Product: %s\n", szTmp);
|
---|
251 | vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
|
---|
252 | if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
|
---|
253 | pfnLog(pLoggerRelease, "OS Release: %s\n", szTmp);
|
---|
254 | vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
|
---|
255 | if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
|
---|
256 | pfnLog(pLoggerRelease, "OS Version: %s\n", szTmp);
|
---|
257 | vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof(szTmp));
|
---|
258 | if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
|
---|
259 | pfnLog(pLoggerRelease, "OS Service Pack: %s\n", szTmp);
|
---|
260 |
|
---|
261 | /* the package type is interesting for Linux distributions */
|
---|
262 | char szExecName[RTPATH_MAX];
|
---|
263 | char *pszExecName = RTProcGetExecutablePath(szExecName, sizeof(szExecName));
|
---|
264 | pfnLog(pLoggerRelease,
|
---|
265 | "Executable: %s\n"
|
---|
266 | "Process ID: %u\n"
|
---|
267 | "Package type: %s"
|
---|
268 | #ifdef VBOX_OSE
|
---|
269 | " (OSE)"
|
---|
270 | #endif
|
---|
271 | "\n",
|
---|
272 | pszExecName ? pszExecName : "unknown",
|
---|
273 | RTProcSelf(),
|
---|
274 | VBOX_PACKAGE_STRING);
|
---|
275 | break;
|
---|
276 | }
|
---|
277 |
|
---|
278 | case RTLOGPHASE_PREROTATE:
|
---|
279 | pfnLog(pLoggerRelease, "Log rotated - Log started %s\n", szTmp);
|
---|
280 | break;
|
---|
281 |
|
---|
282 | case RTLOGPHASE_POSTROTATE:
|
---|
283 | pfnLog(pLoggerRelease, "Log continuation - Log started %s\n", szTmp);
|
---|
284 | break;
|
---|
285 |
|
---|
286 | case RTLOGPHASE_END:
|
---|
287 | pfnLog(pLoggerRelease, "End of log file - Log started %s\n", szTmp);
|
---|
288 | break;
|
---|
289 |
|
---|
290 | default:
|
---|
291 | /* nothing */
|
---|
292 | break;
|
---|
293 | }
|
---|
294 | }
|
---|
295 |
|
---|
296 |
|
---|
297 | /**
|
---|
298 | * Creates the default release logger outputting to the specified file.
|
---|
299 | *
|
---|
300 | * Pass NULL to disabled logging.
|
---|
301 | *
|
---|
302 | * @return IPRT status code.
|
---|
303 | * @param pszLogFile Filename for log output. NULL disables logging
|
---|
304 | * (r=bird: No, it doesn't!).
|
---|
305 | */
|
---|
306 | int VGSvcLogCreate(const char *pszLogFile)
|
---|
307 | {
|
---|
308 | /* Create release logger (stdout + file). */
|
---|
309 | static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
|
---|
310 | RTUINT fFlags = RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME;
|
---|
311 | #if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
|
---|
312 | fFlags |= RTLOGFLAGS_USECRLF;
|
---|
313 | #endif
|
---|
314 | int rc = RTLogCreateEx(&g_pLoggerRelease, fFlags, "all",
|
---|
315 | #ifdef DEBUG
|
---|
316 | "VBOXSERVICE_LOG",
|
---|
317 | #else
|
---|
318 | "VBOXSERVICE_RELEASE_LOG",
|
---|
319 | #endif
|
---|
320 | RT_ELEMENTS(s_apszGroups), s_apszGroups, UINT32_MAX /*cMaxEntriesPerGroup*/,
|
---|
321 | RTLOGDEST_STDOUT | RTLOGDEST_USER,
|
---|
322 | vgsvcLogHeaderFooter, g_cHistory, g_uHistoryFileSize, g_uHistoryFileTime,
|
---|
323 | NULL /*pErrInfo*/, "%s", pszLogFile ? pszLogFile : "");
|
---|
324 | if (RT_SUCCESS(rc))
|
---|
325 | {
|
---|
326 | /* register this logger as the release logger */
|
---|
327 | RTLogRelSetDefaultInstance(g_pLoggerRelease);
|
---|
328 |
|
---|
329 | /* Explicitly flush the log in case of VBOXSERVICE_RELEASE_LOG=buffered. */
|
---|
330 | RTLogFlush(g_pLoggerRelease);
|
---|
331 | }
|
---|
332 |
|
---|
333 | return rc;
|
---|
334 | }
|
---|
335 |
|
---|
336 |
|
---|
337 | /**
|
---|
338 | * Logs a verbose message.
|
---|
339 | *
|
---|
340 | * @param pszFormat The message text.
|
---|
341 | * @param va Format arguments.
|
---|
342 | */
|
---|
343 | void VGSvcLogV(const char *pszFormat, va_list va)
|
---|
344 | {
|
---|
345 | #ifdef DEBUG
|
---|
346 | int rc = RTCritSectEnter(&g_csLog);
|
---|
347 | if (RT_SUCCESS(rc))
|
---|
348 | {
|
---|
349 | #endif
|
---|
350 | char *psz = NULL;
|
---|
351 | RTStrAPrintfV(&psz, pszFormat, va);
|
---|
352 |
|
---|
353 | AssertPtr(psz);
|
---|
354 | LogRel(("%s", psz));
|
---|
355 |
|
---|
356 | RTStrFree(psz);
|
---|
357 | #ifdef DEBUG
|
---|
358 | RTCritSectLeave(&g_csLog);
|
---|
359 | }
|
---|
360 | #endif
|
---|
361 | }
|
---|
362 |
|
---|
363 |
|
---|
364 | /**
|
---|
365 | * Destroys the currently active logging instance.
|
---|
366 | */
|
---|
367 | void VGSvcLogDestroy(void)
|
---|
368 | {
|
---|
369 | RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
|
---|
370 | }
|
---|
371 |
|
---|
372 |
|
---|
373 | /**
|
---|
374 | * Displays the program usage message.
|
---|
375 | *
|
---|
376 | * @returns 1.
|
---|
377 | */
|
---|
378 | static int vgsvcUsage(void)
|
---|
379 | {
|
---|
380 | RTPrintf("Usage: %s [-f|--foreground] [-v|--verbose] [-l|--logfile <file>]\n"
|
---|
381 | " [-p|--pidfile <file>] [-i|--interval <seconds>]\n"
|
---|
382 | " [--disable-<service>] [--enable-<service>]\n"
|
---|
383 | " [--only-<service>] [-h|-?|--help]\n", g_pszProgName);
|
---|
384 | #ifdef RT_OS_WINDOWS
|
---|
385 | RTPrintf(" [-r|--register] [-u|--unregister]\n");
|
---|
386 | #endif
|
---|
387 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
388 | if (g_aServices[j].pDesc->pszUsage)
|
---|
389 | RTPrintf("%s\n", g_aServices[j].pDesc->pszUsage);
|
---|
390 | RTPrintf("\n"
|
---|
391 | "Options:\n"
|
---|
392 | " -i | --interval The default interval.\n"
|
---|
393 | " -f | --foreground Don't daemonize the program. For debugging.\n"
|
---|
394 | " -l | --logfile <file> Enables logging to a file.\n"
|
---|
395 | " -p | --pidfile <file> Write the process ID to a file.\n"
|
---|
396 | " -v | --verbose Increment the verbosity level. For debugging.\n"
|
---|
397 | " -V | --version Show version information.\n"
|
---|
398 | " -h | -? | --help Show this message and exit with status 1.\n"
|
---|
399 | );
|
---|
400 | #ifdef RT_OS_WINDOWS
|
---|
401 | RTPrintf(" -r | --register Installs the service.\n"
|
---|
402 | " -u | --unregister Uninstall service.\n");
|
---|
403 | #endif
|
---|
404 |
|
---|
405 | RTPrintf("\n"
|
---|
406 | "Service-specific options:\n");
|
---|
407 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
408 | {
|
---|
409 | RTPrintf(" --enable-%-14s Enables the %s service. (default)\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
|
---|
410 | RTPrintf(" --disable-%-13s Disables the %s service.\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
|
---|
411 | RTPrintf(" --only-%-16s Only enables the %s service.\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
|
---|
412 | if (g_aServices[j].pDesc->pszOptions)
|
---|
413 | RTPrintf("%s", g_aServices[j].pDesc->pszOptions);
|
---|
414 | }
|
---|
415 | RTPrintf("\n"
|
---|
416 | " Copyright (C) 2009-" VBOX_C_YEAR " " VBOX_VENDOR "\n");
|
---|
417 |
|
---|
418 | return 1;
|
---|
419 | }
|
---|
420 |
|
---|
421 |
|
---|
422 | /**
|
---|
423 | * Displays an error message.
|
---|
424 | *
|
---|
425 | * @returns RTEXITCODE_FAILURE.
|
---|
426 | * @param pszFormat The message text.
|
---|
427 | * @param ... Format arguments.
|
---|
428 | */
|
---|
429 | RTEXITCODE VGSvcError(const char *pszFormat, ...)
|
---|
430 | {
|
---|
431 | va_list args;
|
---|
432 | va_start(args, pszFormat);
|
---|
433 | char *psz = NULL;
|
---|
434 | RTStrAPrintfV(&psz, pszFormat, args);
|
---|
435 | va_end(args);
|
---|
436 |
|
---|
437 | AssertPtr(psz);
|
---|
438 | LogRel(("Error: %s", psz));
|
---|
439 |
|
---|
440 | RTStrFree(psz);
|
---|
441 |
|
---|
442 | return RTEXITCODE_FAILURE;
|
---|
443 | }
|
---|
444 |
|
---|
445 |
|
---|
446 | /**
|
---|
447 | * Displays a verbose message based on the currently
|
---|
448 | * set global verbosity level.
|
---|
449 | *
|
---|
450 | * @param iLevel Minimum log level required to display this message.
|
---|
451 | * @param pszFormat The message text.
|
---|
452 | * @param ... Format arguments.
|
---|
453 | */
|
---|
454 | void VGSvcVerbose(unsigned iLevel, const char *pszFormat, ...)
|
---|
455 | {
|
---|
456 | if (iLevel <= g_cVerbosity)
|
---|
457 | {
|
---|
458 | va_list va;
|
---|
459 | va_start(va, pszFormat);
|
---|
460 | VGSvcLogV(pszFormat, va);
|
---|
461 | va_end(va);
|
---|
462 | }
|
---|
463 | }
|
---|
464 |
|
---|
465 |
|
---|
466 | /**
|
---|
467 | * Reports the current VBoxService status to the host.
|
---|
468 | *
|
---|
469 | * This makes sure that the Failed state is sticky.
|
---|
470 | *
|
---|
471 | * @return IPRT status code.
|
---|
472 | * @param enmStatus Status to report to the host.
|
---|
473 | */
|
---|
474 | int VGSvcReportStatus(VBoxGuestFacilityStatus enmStatus)
|
---|
475 | {
|
---|
476 | /*
|
---|
477 | * VBoxGuestFacilityStatus_Failed is sticky.
|
---|
478 | */
|
---|
479 | static VBoxGuestFacilityStatus s_enmLastStatus = VBoxGuestFacilityStatus_Inactive;
|
---|
480 | VGSvcVerbose(4, "Setting VBoxService status to %u\n", enmStatus);
|
---|
481 | if (s_enmLastStatus != VBoxGuestFacilityStatus_Failed)
|
---|
482 | {
|
---|
483 | int rc = VbglR3ReportAdditionsStatus(VBoxGuestFacilityType_VBoxService, enmStatus, 0 /* Flags */);
|
---|
484 | if (RT_FAILURE(rc))
|
---|
485 | {
|
---|
486 | VGSvcError("Could not report VBoxService status (%u), rc=%Rrc\n", enmStatus, rc);
|
---|
487 | return rc;
|
---|
488 | }
|
---|
489 | s_enmLastStatus = enmStatus;
|
---|
490 | }
|
---|
491 | return VINF_SUCCESS;
|
---|
492 | }
|
---|
493 |
|
---|
494 |
|
---|
495 | /**
|
---|
496 | * Gets a 32-bit value argument.
|
---|
497 | * @todo Get rid of this and VGSvcArgString() as soon as we have RTOpt handling.
|
---|
498 | *
|
---|
499 | * @returns 0 on success, non-zero exit code on error.
|
---|
500 | * @param argc The argument count.
|
---|
501 | * @param argv The argument vector
|
---|
502 | * @param psz Where in *pi to start looking for the value argument.
|
---|
503 | * @param pi Where to find and perhaps update the argument index.
|
---|
504 | * @param pu32 Where to store the 32-bit value.
|
---|
505 | * @param u32Min The minimum value.
|
---|
506 | * @param u32Max The maximum value.
|
---|
507 | */
|
---|
508 | int VGSvcArgUInt32(int argc, char **argv, const char *psz, int *pi, uint32_t *pu32, uint32_t u32Min, uint32_t u32Max)
|
---|
509 | {
|
---|
510 | if (*psz == ':' || *psz == '=')
|
---|
511 | psz++;
|
---|
512 | if (!*psz)
|
---|
513 | {
|
---|
514 | if (*pi + 1 >= argc)
|
---|
515 | return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Missing value for the '%s' argument\n", argv[*pi]);
|
---|
516 | psz = argv[++*pi];
|
---|
517 | }
|
---|
518 |
|
---|
519 | char *pszNext;
|
---|
520 | int rc = RTStrToUInt32Ex(psz, &pszNext, 0, pu32);
|
---|
521 | if (RT_FAILURE(rc) || *pszNext)
|
---|
522 | return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Failed to convert interval '%s' to a number\n", psz);
|
---|
523 | if (*pu32 < u32Min || *pu32 > u32Max)
|
---|
524 | return RTMsgErrorExit(RTEXITCODE_SYNTAX, "The timesync interval of %RU32 seconds is out of range [%RU32..%RU32]\n",
|
---|
525 | *pu32, u32Min, u32Max);
|
---|
526 | return 0;
|
---|
527 | }
|
---|
528 |
|
---|
529 |
|
---|
530 | /** @todo Get rid of this and VGSvcArgUInt32() as soon as we have RTOpt handling. */
|
---|
531 | static int vgsvcArgString(int argc, char **argv, const char *psz, int *pi, char *pszBuf, size_t cbBuf)
|
---|
532 | {
|
---|
533 | AssertPtrReturn(pszBuf, VERR_INVALID_POINTER);
|
---|
534 | AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
|
---|
535 |
|
---|
536 | if (*psz == ':' || *psz == '=')
|
---|
537 | psz++;
|
---|
538 | if (!*psz)
|
---|
539 | {
|
---|
540 | if (*pi + 1 >= argc)
|
---|
541 | return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Missing string for the '%s' argument\n", argv[*pi]);
|
---|
542 | psz = argv[++*pi];
|
---|
543 | }
|
---|
544 |
|
---|
545 | if (!RTStrPrintf(pszBuf, cbBuf, "%s", psz))
|
---|
546 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "String for '%s' argument too big\n", argv[*pi]);
|
---|
547 | return 0;
|
---|
548 | }
|
---|
549 |
|
---|
550 |
|
---|
551 | /**
|
---|
552 | * The service thread.
|
---|
553 | *
|
---|
554 | * @returns Whatever the worker function returns.
|
---|
555 | * @param ThreadSelf My thread handle.
|
---|
556 | * @param pvUser The service index.
|
---|
557 | */
|
---|
558 | static DECLCALLBACK(int) vgsvcThread(RTTHREAD ThreadSelf, void *pvUser)
|
---|
559 | {
|
---|
560 | const unsigned i = (uintptr_t)pvUser;
|
---|
561 |
|
---|
562 | #ifndef RT_OS_WINDOWS
|
---|
563 | /*
|
---|
564 | * Block all signals for this thread. Only the main thread will handle signals.
|
---|
565 | */
|
---|
566 | sigset_t signalMask;
|
---|
567 | sigfillset(&signalMask);
|
---|
568 | pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
|
---|
569 | #endif
|
---|
570 |
|
---|
571 | int rc = g_aServices[i].pDesc->pfnWorker(&g_aServices[i].fShutdown);
|
---|
572 | ASMAtomicXchgBool(&g_aServices[i].fShutdown, true);
|
---|
573 | RTThreadUserSignal(ThreadSelf);
|
---|
574 | return rc;
|
---|
575 | }
|
---|
576 |
|
---|
577 |
|
---|
578 | /**
|
---|
579 | * Lazily calls the pfnPreInit method on each service.
|
---|
580 | *
|
---|
581 | * @returns VBox status code, error message displayed.
|
---|
582 | */
|
---|
583 | static RTEXITCODE vgsvcLazyPreInit(void)
|
---|
584 | {
|
---|
585 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
586 | if (!g_aServices[j].fPreInited)
|
---|
587 | {
|
---|
588 | int rc = g_aServices[j].pDesc->pfnPreInit();
|
---|
589 | if (RT_FAILURE(rc))
|
---|
590 | return VGSvcError("Service '%s' failed pre-init: %Rrc\n", g_aServices[j].pDesc->pszName, rc);
|
---|
591 | g_aServices[j].fPreInited = true;
|
---|
592 | }
|
---|
593 | return RTEXITCODE_SUCCESS;
|
---|
594 | }
|
---|
595 |
|
---|
596 |
|
---|
597 | /**
|
---|
598 | * Count the number of enabled services.
|
---|
599 | */
|
---|
600 | static unsigned vgsvcCountEnabledServices(void)
|
---|
601 | {
|
---|
602 | unsigned cEnabled = 0;
|
---|
603 | for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
|
---|
604 | cEnabled += g_aServices[i].fEnabled;
|
---|
605 | return cEnabled;
|
---|
606 | }
|
---|
607 |
|
---|
608 |
|
---|
609 | #ifdef RT_OS_WINDOWS
|
---|
610 | /**
|
---|
611 | * Console control event callback.
|
---|
612 | *
|
---|
613 | * @returns TRUE if handled, FALSE if not.
|
---|
614 | * @param dwCtrlType The control event type.
|
---|
615 | *
|
---|
616 | * @remarks This is generally called on a new thread, so we're racing every
|
---|
617 | * other thread in the process.
|
---|
618 | */
|
---|
619 | static BOOL WINAPI vgsvcWinConsoleControlHandler(DWORD dwCtrlType)
|
---|
620 | {
|
---|
621 | int rc = VINF_SUCCESS;
|
---|
622 | bool fEventHandled = FALSE;
|
---|
623 | switch (dwCtrlType)
|
---|
624 | {
|
---|
625 | /* User pressed CTRL+C or CTRL+BREAK or an external event was sent
|
---|
626 | * via GenerateConsoleCtrlEvent(). */
|
---|
627 | case CTRL_BREAK_EVENT:
|
---|
628 | case CTRL_CLOSE_EVENT:
|
---|
629 | case CTRL_C_EVENT:
|
---|
630 | VGSvcVerbose(2, "ControlHandler: Received break/close event\n");
|
---|
631 | rc = VGSvcStopServices();
|
---|
632 | fEventHandled = TRUE;
|
---|
633 | break;
|
---|
634 | default:
|
---|
635 | break;
|
---|
636 | /** @todo Add other events here. */
|
---|
637 | }
|
---|
638 |
|
---|
639 | if (RT_FAILURE(rc))
|
---|
640 | VGSvcError("ControlHandler: Event %ld handled with error rc=%Rrc\n",
|
---|
641 | dwCtrlType, rc);
|
---|
642 | return fEventHandled;
|
---|
643 | }
|
---|
644 | #endif /* RT_OS_WINDOWS */
|
---|
645 |
|
---|
646 |
|
---|
647 | /**
|
---|
648 | * Starts the service.
|
---|
649 | *
|
---|
650 | * @returns VBox status code, errors are fully bitched.
|
---|
651 | *
|
---|
652 | * @remarks Also called from VBoxService-win.cpp, thus not static.
|
---|
653 | */
|
---|
654 | int VGSvcStartServices(void)
|
---|
655 | {
|
---|
656 | int rc;
|
---|
657 |
|
---|
658 | VGSvcReportStatus(VBoxGuestFacilityStatus_Init);
|
---|
659 |
|
---|
660 | /*
|
---|
661 | * Initialize the services.
|
---|
662 | */
|
---|
663 | VGSvcVerbose(2, "Initializing services ...\n");
|
---|
664 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
665 | if (g_aServices[j].fEnabled)
|
---|
666 | {
|
---|
667 | rc = g_aServices[j].pDesc->pfnInit();
|
---|
668 | if (RT_FAILURE(rc))
|
---|
669 | {
|
---|
670 | if (rc != VERR_SERVICE_DISABLED)
|
---|
671 | {
|
---|
672 | VGSvcError("Service '%s' failed to initialize: %Rrc\n", g_aServices[j].pDesc->pszName, rc);
|
---|
673 | VGSvcReportStatus(VBoxGuestFacilityStatus_Failed);
|
---|
674 | return rc;
|
---|
675 | }
|
---|
676 |
|
---|
677 | g_aServices[j].fEnabled = false;
|
---|
678 | VGSvcVerbose(0, "Service '%s' was disabled because of missing functionality\n", g_aServices[j].pDesc->pszName);
|
---|
679 | }
|
---|
680 | }
|
---|
681 |
|
---|
682 | /*
|
---|
683 | * Start the service(s).
|
---|
684 | */
|
---|
685 | VGSvcVerbose(2, "Starting services ...\n");
|
---|
686 | rc = VINF_SUCCESS;
|
---|
687 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
688 | {
|
---|
689 | if (!g_aServices[j].fEnabled)
|
---|
690 | continue;
|
---|
691 |
|
---|
692 | VGSvcVerbose(2, "Starting service '%s' ...\n", g_aServices[j].pDesc->pszName);
|
---|
693 | rc = RTThreadCreate(&g_aServices[j].Thread, vgsvcThread, (void *)(uintptr_t)j, 0,
|
---|
694 | RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, g_aServices[j].pDesc->pszName);
|
---|
695 | if (RT_FAILURE(rc))
|
---|
696 | {
|
---|
697 | VGSvcError("RTThreadCreate failed, rc=%Rrc\n", rc);
|
---|
698 | break;
|
---|
699 | }
|
---|
700 | g_aServices[j].fStarted = true;
|
---|
701 |
|
---|
702 | /* Wait for the thread to initialize. */
|
---|
703 | /** @todo There is a race between waiting and checking
|
---|
704 | * the fShutdown flag of a thread here and processing
|
---|
705 | * the thread's actual worker loop. If the thread decides
|
---|
706 | * to exit the loop before we skipped the fShutdown check
|
---|
707 | * below the service will fail to start! */
|
---|
708 | /** @todo This presumably means either a one-shot service or that
|
---|
709 | * something has gone wrong. In the second case treating it as failure
|
---|
710 | * to start is probably right, so we need a way to signal the first
|
---|
711 | * rather than leaving the idle thread hanging around. A flag in the
|
---|
712 | * service description? */
|
---|
713 | RTThreadUserWait(g_aServices[j].Thread, 60 * 1000);
|
---|
714 | if (g_aServices[j].fShutdown)
|
---|
715 | {
|
---|
716 | VGSvcError("Service '%s' failed to start!\n", g_aServices[j].pDesc->pszName);
|
---|
717 | rc = VERR_GENERAL_FAILURE;
|
---|
718 | }
|
---|
719 | }
|
---|
720 |
|
---|
721 | if (RT_SUCCESS(rc))
|
---|
722 | VGSvcVerbose(1, "All services started.\n");
|
---|
723 | else
|
---|
724 | {
|
---|
725 | VGSvcError("An error occcurred while the services!\n");
|
---|
726 | VGSvcReportStatus(VBoxGuestFacilityStatus_Failed);
|
---|
727 | }
|
---|
728 | return rc;
|
---|
729 | }
|
---|
730 |
|
---|
731 |
|
---|
732 | /**
|
---|
733 | * Stops and terminates the services.
|
---|
734 | *
|
---|
735 | * This should be called even when VBoxServiceStartServices fails so it can
|
---|
736 | * clean up anything that we succeeded in starting.
|
---|
737 | *
|
---|
738 | * @remarks Also called from VBoxService-win.cpp, thus not static.
|
---|
739 | */
|
---|
740 | int VGSvcStopServices(void)
|
---|
741 | {
|
---|
742 | VGSvcReportStatus(VBoxGuestFacilityStatus_Terminating);
|
---|
743 |
|
---|
744 | /*
|
---|
745 | * Signal all the services.
|
---|
746 | */
|
---|
747 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
748 | ASMAtomicWriteBool(&g_aServices[j].fShutdown, true);
|
---|
749 |
|
---|
750 | /*
|
---|
751 | * Do the pfnStop callback on all running services.
|
---|
752 | */
|
---|
753 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
754 | if (g_aServices[j].fStarted)
|
---|
755 | {
|
---|
756 | VGSvcVerbose(3, "Calling stop function for service '%s' ...\n", g_aServices[j].pDesc->pszName);
|
---|
757 | g_aServices[j].pDesc->pfnStop();
|
---|
758 | }
|
---|
759 |
|
---|
760 | VGSvcVerbose(3, "All stop functions for services called\n");
|
---|
761 |
|
---|
762 | /*
|
---|
763 | * Wait for all the service threads to complete.
|
---|
764 | */
|
---|
765 | int rc = VINF_SUCCESS;
|
---|
766 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
767 | {
|
---|
768 | if (!g_aServices[j].fEnabled) /* Only stop services which were started before. */
|
---|
769 | continue;
|
---|
770 | if (g_aServices[j].Thread != NIL_RTTHREAD)
|
---|
771 | {
|
---|
772 | VGSvcVerbose(2, "Waiting for service '%s' to stop ...\n", g_aServices[j].pDesc->pszName);
|
---|
773 | int rc2 = VINF_SUCCESS;
|
---|
774 | for (int i = 0; i < 30; i++) /* Wait 30 seconds in total */
|
---|
775 | {
|
---|
776 | rc2 = RTThreadWait(g_aServices[j].Thread, 1000 /* Wait 1 second */, NULL);
|
---|
777 | if (RT_SUCCESS(rc2))
|
---|
778 | break;
|
---|
779 | #ifdef RT_OS_WINDOWS
|
---|
780 | /* Notify SCM that it takes a bit longer ... */
|
---|
781 | VGSvcWinSetStopPendingStatus(i + j*32);
|
---|
782 | #endif
|
---|
783 | }
|
---|
784 | if (RT_FAILURE(rc2))
|
---|
785 | {
|
---|
786 | VGSvcError("Service '%s' failed to stop. (%Rrc)\n", g_aServices[j].pDesc->pszName, rc2);
|
---|
787 | rc = rc2;
|
---|
788 | }
|
---|
789 | }
|
---|
790 | VGSvcVerbose(3, "Terminating service '%s' (%d) ...\n", g_aServices[j].pDesc->pszName, j);
|
---|
791 | g_aServices[j].pDesc->pfnTerm();
|
---|
792 | }
|
---|
793 |
|
---|
794 | #ifdef RT_OS_WINDOWS
|
---|
795 | /*
|
---|
796 | * Wake up and tell the main() thread that we're shutting down (it's
|
---|
797 | * sleeping in VBoxServiceMainWait).
|
---|
798 | */
|
---|
799 | ASMAtomicWriteBool(&g_fWindowsServiceShutdown, true);
|
---|
800 | if (g_hEvtWindowsService != NIL_RTSEMEVENT)
|
---|
801 | {
|
---|
802 | VGSvcVerbose(3, "Stopping the main thread...\n");
|
---|
803 | int rc2 = RTSemEventSignal(g_hEvtWindowsService);
|
---|
804 | AssertRC(rc2);
|
---|
805 | }
|
---|
806 | #endif
|
---|
807 |
|
---|
808 | VGSvcVerbose(2, "Stopping services returning: %Rrc\n", rc);
|
---|
809 | VGSvcReportStatus(RT_SUCCESS(rc) ? VBoxGuestFacilityStatus_Paused : VBoxGuestFacilityStatus_Failed);
|
---|
810 | return rc;
|
---|
811 | }
|
---|
812 |
|
---|
813 |
|
---|
814 | /**
|
---|
815 | * Block the main thread until the service shuts down.
|
---|
816 | *
|
---|
817 | * @remarks Also called from VBoxService-win.cpp, thus not static.
|
---|
818 | */
|
---|
819 | void VGSvcMainWait(void)
|
---|
820 | {
|
---|
821 | int rc;
|
---|
822 |
|
---|
823 | VGSvcReportStatus(VBoxGuestFacilityStatus_Active);
|
---|
824 |
|
---|
825 | #ifdef RT_OS_WINDOWS
|
---|
826 | /*
|
---|
827 | * Wait for the semaphore to be signalled.
|
---|
828 | */
|
---|
829 | VGSvcVerbose(1, "Waiting in main thread\n");
|
---|
830 | rc = RTSemEventCreate(&g_hEvtWindowsService);
|
---|
831 | AssertRC(rc);
|
---|
832 | while (!ASMAtomicReadBool(&g_fWindowsServiceShutdown))
|
---|
833 | {
|
---|
834 | rc = RTSemEventWait(g_hEvtWindowsService, RT_INDEFINITE_WAIT);
|
---|
835 | AssertRC(rc);
|
---|
836 | }
|
---|
837 | RTSemEventDestroy(g_hEvtWindowsService);
|
---|
838 | g_hEvtWindowsService = NIL_RTSEMEVENT;
|
---|
839 | #else
|
---|
840 | /*
|
---|
841 | * Wait explicitly for a HUP, INT, QUIT, ABRT or TERM signal, blocking
|
---|
842 | * all important signals.
|
---|
843 | *
|
---|
844 | * The annoying EINTR/ERESTART loop is for the benefit of Solaris where
|
---|
845 | * sigwait returns when we receive a SIGCHLD. Kind of makes sense since
|
---|
846 | * the signal has to be delivered... Anyway, darwin (10.9.5) has a much
|
---|
847 | * worse way of dealing with SIGCHLD, apparently it'll just return any
|
---|
848 | * of the signals we're waiting on when SIGCHLD becomes pending on this
|
---|
849 | * thread. So, we wait for SIGCHLD here and ignores it.
|
---|
850 | */
|
---|
851 | sigset_t signalMask;
|
---|
852 | sigemptyset(&signalMask);
|
---|
853 | sigaddset(&signalMask, SIGHUP);
|
---|
854 | sigaddset(&signalMask, SIGINT);
|
---|
855 | sigaddset(&signalMask, SIGQUIT);
|
---|
856 | sigaddset(&signalMask, SIGABRT);
|
---|
857 | sigaddset(&signalMask, SIGTERM);
|
---|
858 | sigaddset(&signalMask, SIGCHLD);
|
---|
859 | pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
|
---|
860 |
|
---|
861 | int iSignal;
|
---|
862 | do
|
---|
863 | {
|
---|
864 | iSignal = -1;
|
---|
865 | rc = sigwait(&signalMask, &iSignal);
|
---|
866 | }
|
---|
867 | while ( rc == EINTR
|
---|
868 | # ifdef ERESTART
|
---|
869 | || rc == ERESTART
|
---|
870 | # endif
|
---|
871 | || iSignal == SIGCHLD
|
---|
872 | );
|
---|
873 |
|
---|
874 | VGSvcVerbose(3, "VGSvcMainWait: Received signal %d (rc=%d)\n", iSignal, rc);
|
---|
875 | #endif /* !RT_OS_WINDOWS */
|
---|
876 | }
|
---|
877 |
|
---|
878 |
|
---|
879 | /**
|
---|
880 | * Report VbglR3InitUser / VbglR3Init failure.
|
---|
881 | *
|
---|
882 | * @returns RTEXITCODE_FAILURE
|
---|
883 | * @param rcVbgl The failing status code.
|
---|
884 | */
|
---|
885 | static RTEXITCODE vbglInitFailure(int rcVbgl)
|
---|
886 | {
|
---|
887 | if (rcVbgl == VERR_ACCESS_DENIED)
|
---|
888 | return RTMsgErrorExit(RTEXITCODE_FAILURE,
|
---|
889 | "Insufficient privileges to start %s! Please start with Administrator/root privileges!\n",
|
---|
890 | g_pszProgName);
|
---|
891 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "VbglR3Init failed with rc=%Rrc\n", rcVbgl);
|
---|
892 | }
|
---|
893 |
|
---|
894 |
|
---|
895 | int main(int argc, char **argv)
|
---|
896 | {
|
---|
897 | RTEXITCODE rcExit;
|
---|
898 |
|
---|
899 | /*
|
---|
900 | * Init globals and such.
|
---|
901 | */
|
---|
902 | int rc = RTR3InitExe(argc, &argv, 0);
|
---|
903 | if (RT_FAILURE(rc))
|
---|
904 | return RTMsgInitFailure(rc);
|
---|
905 | g_pszProgName = RTPathFilename(argv[0]);
|
---|
906 | #ifdef RT_OS_WINDOWS
|
---|
907 | VGSvcWinResolveApis();
|
---|
908 | #endif
|
---|
909 | #ifdef DEBUG
|
---|
910 | rc = RTCritSectInit(&g_csLog);
|
---|
911 | AssertRC(rc);
|
---|
912 | #endif
|
---|
913 |
|
---|
914 | #ifdef VBOX_WITH_VBOXSERVICE_TOOLBOX
|
---|
915 | /*
|
---|
916 | * Run toolbox code before all other stuff since these things are simpler
|
---|
917 | * shell/file/text utility like programs that just happens to be inside
|
---|
918 | * VBoxService and shouldn't be subject to /dev/vboxguest, pid-files and
|
---|
919 | * global mutex restrictions.
|
---|
920 | */
|
---|
921 | if (VGSvcToolboxMain(argc, argv, &rcExit))
|
---|
922 | return rcExit;
|
---|
923 | #endif
|
---|
924 |
|
---|
925 | bool fUserSession = false;
|
---|
926 | #ifdef VBOX_WITH_VBOXSERVICE_CONTROL
|
---|
927 | /*
|
---|
928 | * Check if we're the specially spawned VBoxService.exe process that
|
---|
929 | * handles a guest control session.
|
---|
930 | */
|
---|
931 | if ( argc >= 2
|
---|
932 | && !RTStrICmp(argv[1], VBOXSERVICECTRLSESSION_GETOPT_PREFIX))
|
---|
933 | fUserSession = true;
|
---|
934 | #endif
|
---|
935 |
|
---|
936 | /*
|
---|
937 | * Connect to the kernel part before daemonizing and *before* we do the sub-service
|
---|
938 | * pre-init just in case one of services needs do to some initial stuff with it.
|
---|
939 | *
|
---|
940 | * However, we do not fail till after we've parsed arguments, because that will
|
---|
941 | * prevent useful stuff like --help, --register, --unregister and --version from
|
---|
942 | * working when the driver hasn't been installed/loaded yet.
|
---|
943 | */
|
---|
944 | int const rcVbgl = fUserSession ? VbglR3InitUser() : VbglR3Init();
|
---|
945 |
|
---|
946 | #ifdef RT_OS_WINDOWS
|
---|
947 | /*
|
---|
948 | * Check if we're the specially spawned VBoxService.exe process that
|
---|
949 | * handles page fusion. This saves an extra statically linked executable.
|
---|
950 | */
|
---|
951 | if ( argc == 2
|
---|
952 | && !RTStrICmp(argv[1], "pagefusion"))
|
---|
953 | {
|
---|
954 | if (RT_SUCCESS(rcVbgl))
|
---|
955 | return VGSvcPageSharingWorkerChild();
|
---|
956 | return vbglInitFailure(rcVbgl);
|
---|
957 | }
|
---|
958 | #endif
|
---|
959 |
|
---|
960 | #ifdef VBOX_WITH_VBOXSERVICE_CONTROL
|
---|
961 | /*
|
---|
962 | * Check if we're the specially spawned VBoxService.exe process that
|
---|
963 | * handles a guest control session.
|
---|
964 | */
|
---|
965 | if (fUserSession)
|
---|
966 | {
|
---|
967 | if (RT_SUCCESS(rcVbgl))
|
---|
968 | return VGSvcGstCtrlSessionSpawnInit(argc, argv);
|
---|
969 | return vbglInitFailure(rcVbgl);
|
---|
970 | }
|
---|
971 | #endif
|
---|
972 |
|
---|
973 | /*
|
---|
974 | * Parse the arguments.
|
---|
975 | *
|
---|
976 | * Note! This code predates RTGetOpt, thus the manual parsing.
|
---|
977 | */
|
---|
978 | bool fDaemonize = true;
|
---|
979 | bool fDaemonized = false;
|
---|
980 | for (int i = 1; i < argc; i++)
|
---|
981 | {
|
---|
982 | const char *psz = argv[i];
|
---|
983 | if (*psz != '-')
|
---|
984 | return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown argument '%s'\n", psz);
|
---|
985 | psz++;
|
---|
986 |
|
---|
987 | /* translate long argument to short */
|
---|
988 | if (*psz == '-')
|
---|
989 | {
|
---|
990 | psz++;
|
---|
991 | size_t cch = strlen(psz);
|
---|
992 | #define MATCHES(strconst) ( cch == sizeof(strconst) - 1 \
|
---|
993 | && !memcmp(psz, strconst, sizeof(strconst) - 1) )
|
---|
994 | if (MATCHES("foreground"))
|
---|
995 | psz = "f";
|
---|
996 | else if (MATCHES("verbose"))
|
---|
997 | psz = "v";
|
---|
998 | else if (MATCHES("version"))
|
---|
999 | psz = "V";
|
---|
1000 | else if (MATCHES("help"))
|
---|
1001 | psz = "h";
|
---|
1002 | else if (MATCHES("interval"))
|
---|
1003 | psz = "i";
|
---|
1004 | #ifdef RT_OS_WINDOWS
|
---|
1005 | else if (MATCHES("register"))
|
---|
1006 | psz = "r";
|
---|
1007 | else if (MATCHES("unregister"))
|
---|
1008 | psz = "u";
|
---|
1009 | #endif
|
---|
1010 | else if (MATCHES("logfile"))
|
---|
1011 | psz = "l";
|
---|
1012 | else if (MATCHES("pidfile"))
|
---|
1013 | psz = "p";
|
---|
1014 | else if (MATCHES("daemonized"))
|
---|
1015 | {
|
---|
1016 | fDaemonized = true;
|
---|
1017 | continue;
|
---|
1018 | }
|
---|
1019 | else
|
---|
1020 | {
|
---|
1021 | bool fFound = false;
|
---|
1022 |
|
---|
1023 | if (cch > sizeof("enable-") && !memcmp(psz, RT_STR_TUPLE("enable-")))
|
---|
1024 | for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
|
---|
1025 | if ((fFound = !RTStrICmp(psz + sizeof("enable-") - 1, g_aServices[j].pDesc->pszName)))
|
---|
1026 | g_aServices[j].fEnabled = true;
|
---|
1027 |
|
---|
1028 | if (cch > sizeof("disable-") && !memcmp(psz, RT_STR_TUPLE("disable-")))
|
---|
1029 | for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
|
---|
1030 | if ((fFound = !RTStrICmp(psz + sizeof("disable-") - 1, g_aServices[j].pDesc->pszName)))
|
---|
1031 | g_aServices[j].fEnabled = false;
|
---|
1032 |
|
---|
1033 | if (cch > sizeof("only-") && !memcmp(psz, RT_STR_TUPLE("only-")))
|
---|
1034 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
1035 | {
|
---|
1036 | g_aServices[j].fEnabled = !RTStrICmp(psz + sizeof("only-") - 1, g_aServices[j].pDesc->pszName);
|
---|
1037 | if (g_aServices[j].fEnabled)
|
---|
1038 | fFound = true;
|
---|
1039 | }
|
---|
1040 |
|
---|
1041 | if (!fFound)
|
---|
1042 | {
|
---|
1043 | rcExit = vgsvcLazyPreInit();
|
---|
1044 | if (rcExit != RTEXITCODE_SUCCESS)
|
---|
1045 | return rcExit;
|
---|
1046 | for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
|
---|
1047 | {
|
---|
1048 | rc = g_aServices[j].pDesc->pfnOption(NULL, argc, argv, &i);
|
---|
1049 | fFound = rc == VINF_SUCCESS;
|
---|
1050 | if (fFound)
|
---|
1051 | break;
|
---|
1052 | if (rc != -1)
|
---|
1053 | return rc;
|
---|
1054 | }
|
---|
1055 | }
|
---|
1056 | if (!fFound)
|
---|
1057 | return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown option '%s'\n", argv[i]);
|
---|
1058 | continue;
|
---|
1059 | }
|
---|
1060 | #undef MATCHES
|
---|
1061 | }
|
---|
1062 |
|
---|
1063 | /* handle the string of short options. */
|
---|
1064 | do
|
---|
1065 | {
|
---|
1066 | switch (*psz)
|
---|
1067 | {
|
---|
1068 | case 'i':
|
---|
1069 | rc = VGSvcArgUInt32(argc, argv, psz + 1, &i, &g_DefaultInterval, 1, (UINT32_MAX / 1000) - 1);
|
---|
1070 | if (rc)
|
---|
1071 | return rc;
|
---|
1072 | psz = NULL;
|
---|
1073 | break;
|
---|
1074 |
|
---|
1075 | case 'f':
|
---|
1076 | fDaemonize = false;
|
---|
1077 | break;
|
---|
1078 |
|
---|
1079 | case 'v':
|
---|
1080 | g_cVerbosity++;
|
---|
1081 | break;
|
---|
1082 |
|
---|
1083 | case 'V':
|
---|
1084 | RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
|
---|
1085 | return RTEXITCODE_SUCCESS;
|
---|
1086 |
|
---|
1087 | case 'h':
|
---|
1088 | case '?':
|
---|
1089 | return vgsvcUsage();
|
---|
1090 |
|
---|
1091 | #ifdef RT_OS_WINDOWS
|
---|
1092 | case 'r':
|
---|
1093 | return VGSvcWinInstall();
|
---|
1094 |
|
---|
1095 | case 'u':
|
---|
1096 | return VGSvcWinUninstall();
|
---|
1097 | #endif
|
---|
1098 |
|
---|
1099 | case 'l':
|
---|
1100 | {
|
---|
1101 | rc = vgsvcArgString(argc, argv, psz + 1, &i, g_szLogFile, sizeof(g_szLogFile));
|
---|
1102 | if (rc)
|
---|
1103 | return rc;
|
---|
1104 | psz = NULL;
|
---|
1105 | break;
|
---|
1106 | }
|
---|
1107 |
|
---|
1108 | case 'p':
|
---|
1109 | {
|
---|
1110 | rc = vgsvcArgString(argc, argv, psz + 1, &i, g_szPidFile, sizeof(g_szPidFile));
|
---|
1111 | if (rc)
|
---|
1112 | return rc;
|
---|
1113 | psz = NULL;
|
---|
1114 | break;
|
---|
1115 | }
|
---|
1116 |
|
---|
1117 | default:
|
---|
1118 | {
|
---|
1119 | rcExit = vgsvcLazyPreInit();
|
---|
1120 | if (rcExit != RTEXITCODE_SUCCESS)
|
---|
1121 | return rcExit;
|
---|
1122 |
|
---|
1123 | bool fFound = false;
|
---|
1124 | for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
|
---|
1125 | {
|
---|
1126 | rc = g_aServices[j].pDesc->pfnOption(&psz, argc, argv, &i);
|
---|
1127 | fFound = rc == VINF_SUCCESS;
|
---|
1128 | if (fFound)
|
---|
1129 | break;
|
---|
1130 | if (rc != -1)
|
---|
1131 | return rc;
|
---|
1132 | }
|
---|
1133 | if (!fFound)
|
---|
1134 | return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown option '%c' (%s)\n", *psz, argv[i]);
|
---|
1135 | break;
|
---|
1136 | }
|
---|
1137 | }
|
---|
1138 | } while (psz && *++psz);
|
---|
1139 | }
|
---|
1140 |
|
---|
1141 | /* Now we can report the VBGL failure. */
|
---|
1142 | if (RT_FAILURE(rcVbgl))
|
---|
1143 | return vbglInitFailure(rcVbgl);
|
---|
1144 |
|
---|
1145 | /* Check that at least one service is enabled. */
|
---|
1146 | if (vgsvcCountEnabledServices() == 0)
|
---|
1147 | return RTMsgErrorExit(RTEXITCODE_SYNTAX, "At least one service must be enabled\n");
|
---|
1148 |
|
---|
1149 | rc = VGSvcLogCreate(g_szLogFile[0] ? g_szLogFile : NULL);
|
---|
1150 | if (RT_FAILURE(rc))
|
---|
1151 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to create release log '%s', rc=%Rrc\n",
|
---|
1152 | g_szLogFile[0] ? g_szLogFile : "<None>", rc);
|
---|
1153 |
|
---|
1154 | /* Call pre-init if we didn't do it already. */
|
---|
1155 | rcExit = vgsvcLazyPreInit();
|
---|
1156 | if (rcExit != RTEXITCODE_SUCCESS)
|
---|
1157 | return rcExit;
|
---|
1158 |
|
---|
1159 | #ifdef RT_OS_WINDOWS
|
---|
1160 | /*
|
---|
1161 | * Make sure only one instance of VBoxService runs at a time. Create a
|
---|
1162 | * global mutex for that.
|
---|
1163 | *
|
---|
1164 | * Note! The \\Global\ namespace was introduced with Win2K, thus the
|
---|
1165 | * version check.
|
---|
1166 | * Note! If the mutex exists CreateMutex will open it and set last error to
|
---|
1167 | * ERROR_ALREADY_EXISTS.
|
---|
1168 | */
|
---|
1169 | OSVERSIONINFOEX OSInfoEx;
|
---|
1170 | RT_ZERO(OSInfoEx);
|
---|
1171 | OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
|
---|
1172 |
|
---|
1173 | SetLastError(NO_ERROR);
|
---|
1174 | HANDLE hMutexAppRunning;
|
---|
1175 | if ( GetVersionEx((LPOSVERSIONINFO)&OSInfoEx)
|
---|
1176 | && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
|
---|
1177 | && OSInfoEx.dwMajorVersion >= 5 /* NT 5.0 a.k.a W2K */)
|
---|
1178 | hMutexAppRunning = CreateMutex(NULL, FALSE, "Global\\" VBOXSERVICE_NAME);
|
---|
1179 | else
|
---|
1180 | hMutexAppRunning = CreateMutex(NULL, FALSE, VBOXSERVICE_NAME);
|
---|
1181 | if (hMutexAppRunning == NULL)
|
---|
1182 | {
|
---|
1183 | DWORD dwErr = GetLastError();
|
---|
1184 | if ( dwErr == ERROR_ALREADY_EXISTS
|
---|
1185 | || dwErr == ERROR_ACCESS_DENIED)
|
---|
1186 | {
|
---|
1187 | VGSvcError("%s is already running! Terminating.\n", g_pszProgName);
|
---|
1188 | return RTEXITCODE_FAILURE;
|
---|
1189 | }
|
---|
1190 |
|
---|
1191 | VGSvcError("CreateMutex failed with last error %u! Terminating.\n", GetLastError());
|
---|
1192 | return RTEXITCODE_FAILURE;
|
---|
1193 | }
|
---|
1194 |
|
---|
1195 | #else /* !RT_OS_WINDOWS */
|
---|
1196 | /** @todo Add PID file creation here? */
|
---|
1197 | #endif /* !RT_OS_WINDOWS */
|
---|
1198 |
|
---|
1199 | VGSvcVerbose(0, "%s r%s started. Verbose level = %d\n", RTBldCfgVersion(), RTBldCfgRevisionStr(), g_cVerbosity);
|
---|
1200 |
|
---|
1201 | /*
|
---|
1202 | * Daemonize if requested.
|
---|
1203 | */
|
---|
1204 | if (fDaemonize && !fDaemonized)
|
---|
1205 | {
|
---|
1206 | #ifdef RT_OS_WINDOWS
|
---|
1207 | VGSvcVerbose(2, "Starting service dispatcher ...\n");
|
---|
1208 | rcExit = VGSvcWinEnterCtrlDispatcher();
|
---|
1209 | #else
|
---|
1210 | VGSvcVerbose(1, "Daemonizing...\n");
|
---|
1211 | rc = VbglR3Daemonize(false /* fNoChDir */, false /* fNoClose */,
|
---|
1212 | false /* fRespawn */, NULL /* pcRespawn */);
|
---|
1213 | if (RT_FAILURE(rc))
|
---|
1214 | return VGSvcError("Daemon failed: %Rrc\n", rc);
|
---|
1215 | /* in-child */
|
---|
1216 | #endif
|
---|
1217 | }
|
---|
1218 | #ifdef RT_OS_WINDOWS
|
---|
1219 | else
|
---|
1220 | #endif
|
---|
1221 | {
|
---|
1222 | /*
|
---|
1223 | * Windows: We're running the service as a console application now. Start the
|
---|
1224 | * services, enter the main thread's run loop and stop them again
|
---|
1225 | * when it returns.
|
---|
1226 | *
|
---|
1227 | * POSIX: This is used for both daemons and console runs. Start all services
|
---|
1228 | * and return immediately.
|
---|
1229 | */
|
---|
1230 | #ifdef RT_OS_WINDOWS
|
---|
1231 | # ifndef RT_OS_NT4 /** @todo r=bird: What's RT_OS_NT4??? */
|
---|
1232 | /* Install console control handler. */
|
---|
1233 | if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)vgsvcWinConsoleControlHandler, TRUE /* Add handler */))
|
---|
1234 | {
|
---|
1235 | VGSvcError("Unable to add console control handler, error=%ld\n", GetLastError());
|
---|
1236 | /* Just skip this error, not critical. */
|
---|
1237 | }
|
---|
1238 | # endif /* !RT_OS_NT4 */
|
---|
1239 | #endif /* RT_OS_WINDOWS */
|
---|
1240 | rc = VGSvcStartServices();
|
---|
1241 | RTFILE hPidFile = NIL_RTFILE;
|
---|
1242 | if (RT_SUCCESS(rc))
|
---|
1243 | if (g_szPidFile[0])
|
---|
1244 | rc = VbglR3PidFile(g_szPidFile, &hPidFile);
|
---|
1245 | rcExit = RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
|
---|
1246 | if (RT_SUCCESS(rc))
|
---|
1247 | VGSvcMainWait();
|
---|
1248 | if (g_szPidFile[0] && hPidFile != NIL_RTFILE)
|
---|
1249 | VbglR3ClosePidFile(g_szPidFile, hPidFile);
|
---|
1250 | #ifdef RT_OS_WINDOWS
|
---|
1251 | # ifndef RT_OS_NT4
|
---|
1252 | /* Uninstall console control handler. */
|
---|
1253 | if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)NULL, FALSE /* Remove handler */))
|
---|
1254 | {
|
---|
1255 | VGSvcError("Unable to remove console control handler, error=%ld\n", GetLastError());
|
---|
1256 | /* Just skip this error, not critical. */
|
---|
1257 | }
|
---|
1258 | # endif /* !RT_OS_NT4 */
|
---|
1259 | #else /* !RT_OS_WINDOWS */
|
---|
1260 | /* On Windows - since we're running as a console application - we already stopped all services
|
---|
1261 | * through the console control handler. So only do the stopping of services here on other platforms
|
---|
1262 | * where the break/shutdown/whatever signal was just received. */
|
---|
1263 | VGSvcStopServices();
|
---|
1264 | #endif /* RT_OS_WINDOWS */
|
---|
1265 | }
|
---|
1266 | VGSvcReportStatus(VBoxGuestFacilityStatus_Terminated);
|
---|
1267 |
|
---|
1268 | #ifdef RT_OS_WINDOWS
|
---|
1269 | /*
|
---|
1270 | * Cleanup mutex.
|
---|
1271 | */
|
---|
1272 | CloseHandle(hMutexAppRunning);
|
---|
1273 | #endif
|
---|
1274 |
|
---|
1275 | VGSvcVerbose(0, "Ended.\n");
|
---|
1276 |
|
---|
1277 | #ifdef DEBUG
|
---|
1278 | RTCritSectDelete(&g_csLog);
|
---|
1279 | //RTMemTrackerDumpAllToStdOut();
|
---|
1280 | #endif
|
---|
1281 |
|
---|
1282 | VGSvcLogDestroy();
|
---|
1283 |
|
---|
1284 | return rcExit;
|
---|
1285 | }
|
---|
1286 |
|
---|