VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxAutostart/VBoxAutostart-posix.cpp@ 83797

Last change on this file since 83797 was 83797, checked in by vboxsync, 5 years ago

VBoxAutostart: VC++ 14.1 adjustments. Removed some unnecessary stdc++ headers and eliminated one silly std::string usage. bugref:8489

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 17.6 KB
Line 
1/* $Id: VBoxAutostart-posix.cpp 83797 2020-04-18 13:52:37Z vboxsync $ */
2/** @file
3 * VBoxAutostart - VirtualBox Autostart service.
4 */
5
6/*
7 * Copyright (C) 2012-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/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#include <VBox/com/com.h>
23#include <VBox/com/string.h>
24#include <VBox/com/Guid.h>
25#include <VBox/com/array.h>
26#include <VBox/com/ErrorInfo.h>
27#include <VBox/com/errorprint.h>
28
29#include <VBox/com/NativeEventQueue.h>
30#include <VBox/com/listeners.h>
31#include <VBox/com/VirtualBox.h>
32
33#include <iprt/errcore.h>
34#include <VBox/log.h>
35#include <VBox/version.h>
36
37#include <package-generated.h>
38
39#include <iprt/asm.h>
40#include <iprt/buildconfig.h>
41#include <iprt/critsect.h>
42#include <iprt/getopt.h>
43#include <iprt/initterm.h>
44#include <iprt/message.h>
45#include <iprt/path.h>
46#include <iprt/process.h>
47#include <iprt/semaphore.h>
48#include <iprt/stream.h>
49#include <iprt/string.h>
50#include <iprt/system.h>
51#include <iprt/time.h>
52#include <iprt/ctype.h>
53#include <iprt/dir.h>
54
55#include <signal.h>
56
57#include "VBoxAutostart.h"
58
59using namespace com;
60
61#if defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD) || defined(RT_OS_DARWIN)
62# define VBOXAUTOSTART_DAEMONIZE
63#endif
64
65ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
66bool g_fVerbose = false;
67ComPtr<IVirtualBox> g_pVirtualBox = NULL;
68ComPtr<ISession> g_pSession = NULL;
69
70/** Logging parameters. */
71static uint32_t g_cHistory = 10; /* Enable log rotation, 10 files. */
72static uint32_t g_uHistoryFileTime = RT_SEC_1DAY; /* Max 1 day per file. */
73static uint64_t g_uHistoryFileSize = 100 * _1M; /* Max 100MB per file. */
74
75/** Run in background. */
76static bool g_fDaemonize = false;
77
78/**
79 * Command line arguments.
80 */
81static const RTGETOPTDEF g_aOptions[] = {
82#ifdef VBOXAUTOSTART_DAEMONIZE
83 { "--background", 'b', RTGETOPT_REQ_NOTHING },
84#endif
85 /** For displayHelp(). */
86 { "--help", 'h', RTGETOPT_REQ_NOTHING },
87 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
88 { "--start", 's', RTGETOPT_REQ_NOTHING },
89 { "--stop", 'd', RTGETOPT_REQ_NOTHING },
90 { "--config", 'c', RTGETOPT_REQ_STRING },
91 { "--logfile", 'F', RTGETOPT_REQ_STRING },
92 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 },
93 { "--logsize", 'S', RTGETOPT_REQ_UINT64 },
94 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 },
95 { "--quiet", 'Q', RTGETOPT_REQ_NOTHING }
96};
97
98/** Set by the signal handler. */
99static volatile bool g_fCanceled = false;
100
101
102/**
103 * Signal handler that sets g_fCanceled.
104 *
105 * This can be executed on any thread in the process, on Windows it may even be
106 * a thread dedicated to delivering this signal. Do not doing anything
107 * unnecessary here.
108 */
109static void showProgressSignalHandler(int iSignal)
110{
111 NOREF(iSignal);
112 ASMAtomicWriteBool(&g_fCanceled, true);
113}
114
115/**
116 * Print out progress on the console.
117 *
118 * This runs the main event queue every now and then to prevent piling up
119 * unhandled things (which doesn't cause real problems, just makes things
120 * react a little slower than in the ideal case).
121 */
122DECLHIDDEN(HRESULT) showProgress(ComPtr<IProgress> progress)
123{
124 using namespace com;
125
126 BOOL fCompleted = FALSE;
127 ULONG ulCurrentPercent = 0;
128 ULONG ulLastPercent = 0;
129
130 Bstr bstrOperationDescription;
131
132 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
133
134 ULONG cOperations = 1;
135 HRESULT hrc = progress->COMGETTER(OperationCount)(&cOperations);
136 if (FAILED(hrc))
137 {
138 RTStrmPrintf(g_pStdErr, "Progress object failure: %Rhrc\n", hrc);
139 RTStrmFlush(g_pStdErr);
140 return hrc;
141 }
142
143 /*
144 * Note: Outputting the progress info to stderr (g_pStdErr) is intentional
145 * to not get intermixed with other (raw) stdout data which might get
146 * written in the meanwhile.
147 */
148 RTStrmPrintf(g_pStdErr, "0%%...");
149 RTStrmFlush(g_pStdErr);
150
151 /* setup signal handling if cancelable */
152 bool fCanceledAlready = false;
153 BOOL fCancelable;
154 hrc = progress->COMGETTER(Cancelable)(&fCancelable);
155 if (FAILED(hrc))
156 fCancelable = FALSE;
157 if (fCancelable)
158 {
159 signal(SIGINT, showProgressSignalHandler);
160#ifdef SIGBREAK
161 signal(SIGBREAK, showProgressSignalHandler);
162#endif
163 }
164
165 hrc = progress->COMGETTER(Completed(&fCompleted));
166 while (SUCCEEDED(hrc))
167 {
168 progress->COMGETTER(Percent(&ulCurrentPercent));
169
170 /* did we cross a 10% mark? */
171 if (ulCurrentPercent / 10 > ulLastPercent / 10)
172 {
173 /* make sure to also print out missed steps */
174 for (ULONG curVal = (ulLastPercent / 10) * 10 + 10; curVal <= (ulCurrentPercent / 10) * 10; curVal += 10)
175 {
176 if (curVal < 100)
177 {
178 RTStrmPrintf(g_pStdErr, "%u%%...", curVal);
179 RTStrmFlush(g_pStdErr);
180 }
181 }
182 ulLastPercent = (ulCurrentPercent / 10) * 10;
183 }
184
185 if (fCompleted)
186 break;
187
188 /* process async cancelation */
189 if (g_fCanceled && !fCanceledAlready)
190 {
191 hrc = progress->Cancel();
192 if (SUCCEEDED(hrc))
193 fCanceledAlready = true;
194 else
195 g_fCanceled = false;
196 }
197
198 /* make sure the loop is not too tight */
199 progress->WaitForCompletion(100);
200
201 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
202 hrc = progress->COMGETTER(Completed(&fCompleted));
203 }
204
205 /* undo signal handling */
206 if (fCancelable)
207 {
208 signal(SIGINT, SIG_DFL);
209#ifdef SIGBREAK
210 signal(SIGBREAK, SIG_DFL);
211#endif
212 }
213
214 /* complete the line. */
215 LONG iRc = E_FAIL;
216 hrc = progress->COMGETTER(ResultCode)(&iRc);
217 if (SUCCEEDED(hrc))
218 {
219 if (SUCCEEDED(iRc))
220 RTStrmPrintf(g_pStdErr, "100%%\n");
221 else if (g_fCanceled)
222 RTStrmPrintf(g_pStdErr, "CANCELED\n");
223 else
224 {
225 RTStrmPrintf(g_pStdErr, "\n");
226 RTStrmPrintf(g_pStdErr, "Progress state: %Rhrc\n", iRc);
227 }
228 hrc = iRc;
229 }
230 else
231 {
232 RTStrmPrintf(g_pStdErr, "\n");
233 RTStrmPrintf(g_pStdErr, "Progress object failure: %Rhrc\n", hrc);
234 }
235 RTStrmFlush(g_pStdErr);
236 return hrc;
237}
238
239DECLHIDDEN(void) autostartSvcOsLogStr(const char *pszMsg, AUTOSTARTLOGTYPE enmLogType)
240{
241 if ( enmLogType == AUTOSTARTLOGTYPE_VERBOSE
242 && !g_fVerbose)
243 return;
244
245 LogRel(("%s", pszMsg));
246}
247
248static void displayHeader()
249{
250 RTStrmPrintf(g_pStdErr, VBOX_PRODUCT " Autostart " VBOX_VERSION_STRING "\n"
251 "(C) " VBOX_C_YEAR " " VBOX_VENDOR "\n"
252 "All rights reserved.\n\n");
253}
254
255/**
256 * Displays the help.
257 *
258 * @param pszImage Name of program name (image).
259 */
260static void displayHelp(const char *pszImage)
261{
262 AssertPtrReturnVoid(pszImage);
263
264 displayHeader();
265
266 RTStrmPrintf(g_pStdErr,
267 "Usage: %s [-v|--verbose] [-h|-?|--help]\n"
268 " [-F|--logfile=<file>] [-R|--logrotate=<num>]\n"
269 " [-S|--logsize=<bytes>] [-I|--loginterval=<seconds>]\n"
270 " [-c|--config=<config file>]\n",
271 pszImage);
272
273 RTStrmPrintf(g_pStdErr,
274 "\n"
275 "Options:\n");
276 for (unsigned i = 0; i < RT_ELEMENTS(g_aOptions); i++)
277 {
278 char szOptions[128];
279 const char *pszOptions = g_aOptions[i].pszLong;
280 if (g_aOptions[i].iShort < 1000) /* Don't show short options which are defined by an ID! */
281 {
282 RTStrPrintf(szOptions, sizeof(szOptions), "%s, -%c", g_aOptions[i].pszLong, g_aOptions[i].iShort);
283 pszOptions = szOptions;
284 }
285
286 const char *pcszDescr = "";
287 switch (g_aOptions[i].iShort)
288 {
289 case 'h':
290 pcszDescr = "Print this help message and exit.";
291 break;
292
293#ifdef VBOXAUTOSTART_DAEMONIZE
294 case 'b':
295 pcszDescr = "Run in background (daemon mode).";
296 break;
297#endif
298
299 case 'F':
300 pcszDescr = "Name of file to write log to (no file).";
301 break;
302
303 case 'R':
304 pcszDescr = "Number of log files (0 disables log rotation).";
305 break;
306
307 case 'S':
308 pcszDescr = "Maximum size of a log file to trigger rotation (bytes).";
309 break;
310
311 case 'I':
312 pcszDescr = "Maximum time interval to trigger log rotation (seconds).";
313 break;
314
315 case 'c':
316 pcszDescr = "Name of the configuration file for the global overrides.";
317 break;
318 }
319
320 RTStrmPrintf(g_pStdErr, "%-23s%s\n", pszOptions, pcszDescr);
321 }
322
323 RTStrmPrintf(g_pStdErr, "\nUse environment variable VBOXAUTOSTART_RELEASE_LOG for logging options.\n");
324}
325
326int main(int argc, char *argv[])
327{
328 /*
329 * Before we do anything, init the runtime without loading
330 * the support driver.
331 */
332 int rc = RTR3InitExe(argc, &argv, 0);
333 if (RT_FAILURE(rc))
334 return RTMsgInitFailure(rc);
335
336 /*
337 * Parse the global options
338 */
339 int c;
340 const char *pszLogFile = NULL;
341 const char *pszConfigFile = NULL;
342 bool fQuiet = false;
343 bool fStart = false;
344 bool fStop = false;
345 RTGETOPTUNION ValueUnion;
346 RTGETOPTSTATE GetState;
347 RTGetOptInit(&GetState, argc, argv,
348 g_aOptions, RT_ELEMENTS(g_aOptions), 1 /* First */, 0 /*fFlags*/);
349 while ((c = RTGetOpt(&GetState, &ValueUnion)))
350 {
351 switch (c)
352 {
353 case 'h':
354 displayHelp(argv[0]);
355 return 0;
356
357 case 'v':
358 g_fVerbose = true;
359 break;
360
361#ifdef VBOXAUTOSTART_DAEMONIZE
362 case 'b':
363 g_fDaemonize = true;
364 break;
365#endif
366 case 'V':
367 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
368 return 0;
369
370 case 'F':
371 pszLogFile = ValueUnion.psz;
372 break;
373
374 case 'R':
375 g_cHistory = ValueUnion.u32;
376 break;
377
378 case 'S':
379 g_uHistoryFileSize = ValueUnion.u64;
380 break;
381
382 case 'I':
383 g_uHistoryFileTime = ValueUnion.u32;
384 break;
385
386 case 'Q':
387 fQuiet = true;
388 break;
389
390 case 'c':
391 pszConfigFile = ValueUnion.psz;
392 break;
393
394 case 's':
395 fStart = true;
396 break;
397
398 case 'd':
399 fStop = true;
400 break;
401
402 default:
403 return RTGetOptPrintError(c, &ValueUnion);
404 }
405 }
406
407 if (!fStart && !fStop)
408 {
409 displayHelp(argv[0]);
410 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Either --start or --stop must be present");
411 }
412 else if (fStart && fStop)
413 {
414 displayHelp(argv[0]);
415 return RTMsgErrorExit(RTEXITCODE_FAILURE, "--start or --stop are mutually exclusive");
416 }
417
418 if (!pszConfigFile)
419 {
420 displayHelp(argv[0]);
421 return RTMsgErrorExit(RTEXITCODE_FAILURE, "--config <config file> is missing");
422 }
423
424 if (!fQuiet)
425 displayHeader();
426
427 PCFGAST pCfgAst = NULL;
428 char *pszUser = NULL;
429 PCFGAST pCfgAstUser = NULL;
430 PCFGAST pCfgAstPolicy = NULL;
431 bool fAllow = false;
432
433 rc = autostartParseConfig(pszConfigFile, &pCfgAst);
434 if (RT_FAILURE(rc))
435 return RTEXITCODE_FAILURE;
436
437 rc = RTProcQueryUsernameA(RTProcSelf(), &pszUser);
438 if (RT_FAILURE(rc))
439 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to query username of the process");
440
441 pCfgAstUser = autostartConfigAstGetByName(pCfgAst, pszUser);
442 pCfgAstPolicy = autostartConfigAstGetByName(pCfgAst, "default_policy");
443
444 /* Check default policy. */
445 if (pCfgAstPolicy)
446 {
447 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
448 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow")
449 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "deny")))
450 {
451 if (!RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "allow"))
452 fAllow = true;
453 }
454 else
455 return RTMsgErrorExit(RTEXITCODE_FAILURE, "'default_policy' must be either 'allow' or 'deny'");
456 }
457
458 if ( pCfgAstUser
459 && pCfgAstUser->enmType == CFGASTNODETYPE_COMPOUND)
460 {
461 pCfgAstPolicy = autostartConfigAstGetByName(pCfgAstUser, "allow");
462 if (pCfgAstPolicy)
463 {
464 if ( pCfgAstPolicy->enmType == CFGASTNODETYPE_KEYVALUE
465 && ( !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true")
466 || !RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "false")))
467 {
468 if (!RTStrCmp(pCfgAstPolicy->u.KeyValue.aszValue, "true"))
469 fAllow = true;
470 else
471 fAllow = false;
472 }
473 else
474 return RTMsgErrorExit(RTEXITCODE_FAILURE, "'allow' must be either 'true' or 'false'");
475 }
476 }
477 else if (pCfgAstUser)
478 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Invalid config, user is not a compound node");
479
480 if (!fAllow)
481 return RTMsgErrorExit(RTEXITCODE_FAILURE, "User is not allowed to autostart VMs");
482
483 RTStrFree(pszUser);
484
485 /* Don't start if the VirtualBox settings directory does not exist. */
486 char szUserHomeDir[RTPATH_MAX];
487 rc = com::GetVBoxUserHomeDirectory(szUserHomeDir, sizeof(szUserHomeDir), false /* fCreateDir */);
488 if (RT_FAILURE(rc))
489 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not get base directory: %Rrc", rc);
490 else if (!RTDirExists(szUserHomeDir))
491 return RTEXITCODE_SUCCESS;
492
493 /* create release logger, to stdout */
494 RTERRINFOSTATIC ErrInfo;
495 rc = com::VBoxLogRelCreate("Autostart", g_fDaemonize ? NULL : pszLogFile,
496 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
497 "all", "VBOXAUTOSTART_RELEASE_LOG",
498 RTLOGDEST_STDOUT, UINT32_MAX /* cMaxEntriesPerGroup */,
499 g_cHistory, g_uHistoryFileTime, g_uHistoryFileSize,
500 RTErrInfoInitStatic(&ErrInfo));
501 if (RT_FAILURE(rc))
502 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", ErrInfo.Core.pszMsg, rc);
503
504#ifdef VBOXAUTOSTART_DAEMONIZE
505 if (g_fDaemonize)
506 {
507 /* prepare release logging */
508 char szLogFile[RTPATH_MAX];
509
510 if (!pszLogFile || !*pszLogFile)
511 {
512 rc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
513 if (RT_FAILURE(rc))
514 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not get base directory for logging: %Rrc", rc);
515 rc = RTPathAppend(szLogFile, sizeof(szLogFile), "vboxautostart.log");
516 if (RT_FAILURE(rc))
517 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not construct logging path: %Rrc", rc);
518 pszLogFile = szLogFile;
519 }
520
521 rc = RTProcDaemonizeUsingFork(false /* fNoChDir */, false /* fNoClose */, NULL);
522 if (RT_FAILURE(rc))
523 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to daemonize, rc=%Rrc. exiting.", rc);
524 /* create release logger, to file */
525 rc = com::VBoxLogRelCreate("Autostart", pszLogFile,
526 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
527 "all", "VBOXAUTOSTART_RELEASE_LOG",
528 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
529 g_cHistory, g_uHistoryFileTime, g_uHistoryFileSize,
530 RTErrInfoInitStatic(&ErrInfo));
531 if (RT_FAILURE(rc))
532 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", ErrInfo.Core.pszMsg, rc);
533 }
534#endif
535
536 /* Set up COM */
537 rc = autostartSetup();
538 if (RT_FAILURE(rc))
539 return RTEXITCODE_FAILURE;
540
541 RTEXITCODE rcExit;
542 if (fStart)
543 rcExit = autostartStartMain(pCfgAstUser);
544 else
545 {
546 Assert(fStop);
547 rcExit = autostartStopMain(pCfgAstUser);
548 }
549
550 autostartConfigAstDestroy(pCfgAst);
551 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
552
553 autostartShutdown();
554 return rcExit;
555}
556
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