VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/xpcom/server.cpp@ 96399

Last change on this file since 96399 was 96399, checked in by vboxsync, 3 years ago

/Config.kmk and many other places: Change VBOX_VENDOR to the official copyright holder text, needs follow-up changes and equivalent adjustments elsewhere.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.2 KB
Line 
1/* $Id: server.cpp 96399 2022-08-22 14:47:39Z vboxsync $ */
2/** @file
3 * XPCOM server process (VBoxSVC) start point.
4 */
5
6/*
7 * Copyright (C) 2004-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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#define LOG_GROUP LOG_GROUP_MAIN_VBOXSVC
19#include <ipcIService.h>
20#include <ipcCID.h>
21
22#include <nsIComponentRegistrar.h>
23
24#include <nsGenericFactory.h>
25
26#include "prio.h"
27#include "prproces.h"
28
29#include "server.h"
30
31#include "LoggingNew.h"
32
33#include <VBox/param.h>
34#include <VBox/version.h>
35
36#include <iprt/buildconfig.h>
37#include <iprt/initterm.h>
38#include <iprt/critsect.h>
39#include <iprt/getopt.h>
40#include <iprt/message.h>
41#include <iprt/string.h>
42#include <iprt/stream.h>
43#include <iprt/path.h>
44#include <iprt/timer.h>
45#include <iprt/env.h>
46
47#include <signal.h> // for the signal handler
48#include <stdlib.h>
49#include <unistd.h>
50#include <errno.h>
51#include <fcntl.h>
52#include <sys/stat.h>
53#include <sys/resource.h>
54
55/////////////////////////////////////////////////////////////////////////////
56// VirtualBox component instantiation
57/////////////////////////////////////////////////////////////////////////////
58
59#include <nsIGenericFactory.h>
60#include <VBox/com/VirtualBox.h>
61
62#include "VBox/com/NativeEventQueue.h"
63
64#include "ApplianceImpl.h"
65#include "AudioAdapterImpl.h"
66#include "BandwidthControlImpl.h"
67#include "BandwidthGroupImpl.h"
68#include "NetworkServiceRunner.h"
69#include "DHCPServerImpl.h"
70#include "GuestOSTypeImpl.h"
71#include "HostImpl.h"
72#include "HostNetworkInterfaceImpl.h"
73#include "MachineImpl.h"
74#include "MediumFormatImpl.h"
75#include "MediumImpl.h"
76#include "NATEngineImpl.h"
77#include "NetworkAdapterImpl.h"
78#include "ParallelPortImpl.h"
79#include "ProgressProxyImpl.h"
80#include "SerialPortImpl.h"
81#include "SharedFolderImpl.h"
82#include "SnapshotImpl.h"
83#include "StorageControllerImpl.h"
84#include "SystemPropertiesImpl.h"
85#include "USBControllerImpl.h"
86#include "USBDeviceFiltersImpl.h"
87#include "VFSExplorerImpl.h"
88#include "VirtualBoxImpl.h"
89#include "VRDEServerImpl.h"
90#ifdef VBOX_WITH_USB
91# include "HostUSBDeviceImpl.h"
92# include "USBDeviceFilterImpl.h"
93# include "USBDeviceImpl.h"
94#endif
95#ifdef VBOX_WITH_EXTPACK
96# include "ExtPackManagerImpl.h"
97#endif
98# include "NATNetworkImpl.h"
99
100// This needs to stay - it is needed by the service registration below, and
101// is defined in the automatically generated VirtualBoxWrap.cpp
102extern nsIClassInfo *NS_CLASSINFO_NAME(VirtualBoxWrap);
103NS_DECL_CI_INTERFACE_GETTER(VirtualBoxWrap)
104
105////////////////////////////////////////////////////////////////////////////////
106
107static bool gAutoShutdown = false;
108/** Delay before shutting down the VirtualBox server after the last
109 * VirtualBox instance is released, in ms */
110static uint32_t gShutdownDelayMs = 5000;
111
112static com::NativeEventQueue *gEventQ = NULL;
113static PRBool volatile gKeepRunning = PR_TRUE;
114static PRBool volatile gAllowSigUsrQuit = PR_TRUE;
115
116/////////////////////////////////////////////////////////////////////////////
117
118/**
119 * VirtualBox class factory that destroys the created instance right after
120 * the last reference to it is released by the client, and recreates it again
121 * when necessary (so VirtualBox acts like a singleton object).
122 */
123class VirtualBoxClassFactory : public VirtualBox
124{
125public:
126
127 virtual ~VirtualBoxClassFactory()
128 {
129 LogFlowFunc(("Deleting VirtualBox...\n"));
130
131 FinalRelease();
132 sInstance = NULL;
133
134 LogFlowFunc(("VirtualBox object deleted.\n"));
135 RTPrintf("Informational: VirtualBox object deleted.\n");
136 }
137
138 NS_IMETHOD_(nsrefcnt) Release()
139 {
140 /* we overload Release() to guarantee the VirtualBox destructor is
141 * always called on the main thread */
142
143 nsrefcnt count = VirtualBox::Release();
144
145 if (count == 1)
146 {
147 /* the last reference held by clients is being released
148 * (see GetInstance()) */
149
150 bool onMainThread = RTThreadIsMain(RTThreadSelf());
151 PRBool timerStarted = PR_FALSE;
152
153 /* sTimer is null if this call originates from FactoryDestructor()*/
154 if (sTimer != NULL)
155 {
156 LogFlowFunc(("Last VirtualBox instance was released.\n"));
157 LogFlowFunc(("Scheduling server shutdown in %u ms...\n",
158 gShutdownDelayMs));
159
160 /* make sure the previous timer (if any) is stopped;
161 * otherwise RTTimerStart() will definitely fail. */
162 RTTimerLRStop(sTimer);
163
164 int vrc = RTTimerLRStart(sTimer, gShutdownDelayMs * RT_NS_1MS_64);
165 AssertRC(vrc);
166 timerStarted = RT_BOOL(RT_SUCCESS(vrc));
167 }
168 else
169 {
170 LogFlowFunc(("Last VirtualBox instance was released "
171 "on XPCOM shutdown.\n"));
172 Assert(onMainThread);
173 }
174
175 gAllowSigUsrQuit = PR_TRUE;
176
177 if (!timerStarted)
178 {
179 if (!onMainThread)
180 {
181 /* Failed to start the timer, post the shutdown event
182 * manually if not on the main thread already. */
183 ShutdownTimer(NULL, NULL, 0);
184 }
185 else
186 {
187 /* Here we come if:
188 *
189 * a) gEventQ is 0 which means either FactoryDestructor() is called
190 * or the IPC/DCONNECT shutdown sequence is initiated by the
191 * XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
192 * happens on the main thread.
193 *
194 * b) gEventQ has reported we're on the main thread. This means
195 * that DestructEventHandler() has been called, but another
196 * client was faster and requested VirtualBox again.
197 *
198 * In either case, there is nothing to do.
199 *
200 * Note: case b) is actually no more valid since we don't
201 * call Release() from DestructEventHandler() in this case
202 * any more. Thus, we assert below.
203 */
204
205 Assert(!gEventQ);
206 }
207 }
208 }
209
210 return count;
211 }
212
213 class MaybeQuitEvent : public NativeEvent
214 {
215 public:
216 MaybeQuitEvent() :
217 m_fSignal(false)
218 {
219 }
220
221 MaybeQuitEvent(bool fSignal) :
222 m_fSignal(fSignal)
223 {
224 }
225
226 private:
227 /* called on the main thread */
228 void *handler()
229 {
230 LogFlowFuncEnter();
231
232 Assert(RTCritSectIsInitialized(&sLock));
233
234 /* stop accepting GetInstance() requests on other threads during
235 * possible destruction */
236 RTCritSectEnter(&sLock);
237
238 nsrefcnt count = 1;
239
240 /* sInstance is NULL here if it was deleted immediately after
241 * creation due to initialization error. See GetInstance(). */
242 if (sInstance != NULL)
243 {
244 /* Safe way to get current refcount is by first increasing and
245 * then decreasing. Keep in mind that the Release is overloaded
246 * (see VirtualBoxClassFactory::Release) and will start the
247 * timer again if the returned count is 1. It won't do harm,
248 * but also serves no purpose, so stop it ASAP. */
249 sInstance->AddRef();
250 count = sInstance->Release();
251 if (count == 1)
252 {
253 RTTimerLRStop(sTimer);
254 /* Release the guard reference added in GetInstance() */
255 sInstance->Release();
256 }
257 }
258
259 if (count == 1)
260 {
261 if (gAutoShutdown || m_fSignal)
262 {
263 Assert(sInstance == NULL);
264 LogFlowFunc(("Terminating the server process...\n"));
265 /* make it leave the event loop */
266 gKeepRunning = PR_FALSE;
267 }
268 else
269 LogFlowFunc(("No automatic shutdown.\n"));
270 }
271 else
272 {
273 /* This condition is quite rare: a new client happened to
274 * connect after this event has been posted to the main queue
275 * but before it started to process it. */
276 LogRel(("Destruction is canceled (refcnt=%d).\n", count));
277 }
278
279 RTCritSectLeave(&sLock);
280
281 LogFlowFuncLeave();
282 return NULL;
283 }
284
285 bool m_fSignal;
286 };
287
288 static DECLCALLBACK(void) ShutdownTimer(RTTIMERLR hTimerLR, void *pvUser, uint64_t /*iTick*/)
289 {
290 NOREF(hTimerLR);
291 NOREF(pvUser);
292
293 /* A "too late" event is theoretically possible if somebody
294 * manually ended the server after a destruction has been scheduled
295 * and this method was so lucky that it got a chance to run before
296 * the timer was killed. */
297 com::NativeEventQueue *q = gEventQ;
298 AssertReturnVoid(q);
299
300 /* post a quit event to the main queue */
301 MaybeQuitEvent *ev = new MaybeQuitEvent(false /* fSignal */);
302 if (!q->postEvent(ev))
303 delete ev;
304
305 /* A failure above means we've been already stopped (for example
306 * by Ctrl-C). FactoryDestructor() (NS_ShutdownXPCOM())
307 * will do the job. Nothing to do. */
308 }
309
310 static NS_IMETHODIMP FactoryConstructor()
311 {
312 LogFlowFunc(("\n"));
313
314 /* create a critsect to protect object construction */
315 if (RT_FAILURE(RTCritSectInit(&sLock)))
316 return NS_ERROR_OUT_OF_MEMORY;
317
318 int vrc = RTTimerLRCreateEx(&sTimer, 0, 0, ShutdownTimer, NULL);
319 if (RT_FAILURE(vrc))
320 {
321 LogFlowFunc(("Failed to create a timer! (vrc=%Rrc)\n", vrc));
322 return NS_ERROR_FAILURE;
323 }
324
325 return NS_OK;
326 }
327
328 static NS_IMETHODIMP FactoryDestructor()
329 {
330 LogFlowFunc(("\n"));
331
332 RTTimerLRDestroy(sTimer);
333 sTimer = NULL;
334
335 if (sInstance != NULL)
336 {
337 /* Either posting a destruction event failed for some reason (most
338 * likely, the quit event has been received before the last release),
339 * or the client has terminated abnormally w/o releasing its
340 * VirtualBox instance (so NS_ShutdownXPCOM() is doing a cleanup).
341 * Release the guard reference we added in GetInstance(). */
342 sInstance->Release();
343 }
344
345 /* Destroy lock after releasing the VirtualBox instance, otherwise
346 * there are races with cleanup. */
347 RTCritSectDelete(&sLock);
348
349 return NS_OK;
350 }
351
352 static nsresult GetInstance(VirtualBox **inst)
353 {
354 LogFlowFunc(("Getting VirtualBox object...\n"));
355
356 RTCritSectEnter(&sLock);
357
358 if (!gKeepRunning)
359 {
360 LogFlowFunc(("Process termination requested first. Refusing.\n"));
361
362 RTCritSectLeave(&sLock);
363
364 /* this rv is what CreateInstance() on the client side returns
365 * when the server process stops accepting events. Do the same
366 * here. The client wrapper should attempt to start a new process in
367 * response to a failure from us. */
368 return NS_ERROR_ABORT;
369 }
370
371 nsresult rv = NS_OK;
372
373 if (sInstance == NULL)
374 {
375 LogFlowFunc(("Creating new VirtualBox object...\n"));
376 sInstance = new VirtualBoxClassFactory();
377 if (sInstance != NULL)
378 {
379 /* make an extra AddRef to take the full control
380 * on the VirtualBox destruction (see FinalRelease()) */
381 sInstance->AddRef();
382
383 sInstance->AddRef(); /* protect FinalConstruct() */
384 rv = sInstance->FinalConstruct();
385 RTPrintf("Informational: VirtualBox object created (rc=%Rhrc).\n", rv);
386 if (NS_FAILED(rv))
387 {
388 /* On failure diring VirtualBox initialization, delete it
389 * immediately on the current thread by releasing all
390 * references in order to properly schedule the server
391 * shutdown. Since the object is fully deleted here, there
392 * is a chance to fix the error and request a new
393 * instantiation before the server terminates. However,
394 * the main reason to maintain the shutdown delay on
395 * failure is to let the front-end completely fetch error
396 * info from a server-side IVirtualBoxErrorInfo object. */
397 sInstance->Release();
398 sInstance->Release();
399 Assert(sInstance == NULL);
400 }
401 else
402 {
403 /* On success, make sure the previous timer is stopped to
404 * cancel a scheduled server termination (if any). */
405 gAllowSigUsrQuit = PR_FALSE;
406 RTTimerLRStop(sTimer);
407 }
408 }
409 else
410 {
411 rv = NS_ERROR_OUT_OF_MEMORY;
412 }
413 }
414 else
415 {
416 LogFlowFunc(("Using existing VirtualBox object...\n"));
417 nsrefcnt count = sInstance->AddRef();
418 Assert(count > 1);
419
420 if (count >= 2)
421 {
422 LogFlowFunc(("Another client has requested a reference to VirtualBox, canceling destruction...\n"));
423
424 /* make sure the previous timer is stopped */
425 gAllowSigUsrQuit = PR_FALSE;
426 RTTimerLRStop(sTimer);
427 }
428 }
429
430 *inst = sInstance;
431
432 RTCritSectLeave(&sLock);
433
434 return rv;
435 }
436
437private:
438
439 /* Don't be confused that sInstance is of the *ClassFactory type. This is
440 * actually a singleton instance (*ClassFactory inherits the singleton
441 * class; we combined them just for "simplicity" and used "static" for
442 * factory methods. *ClassFactory here is necessary for a couple of extra
443 * methods. */
444
445 static VirtualBoxClassFactory *sInstance;
446 static RTCRITSECT sLock;
447
448 static RTTIMERLR sTimer;
449};
450
451VirtualBoxClassFactory *VirtualBoxClassFactory::sInstance = NULL;
452RTCRITSECT VirtualBoxClassFactory::sLock;
453
454RTTIMERLR VirtualBoxClassFactory::sTimer = NIL_RTTIMERLR;
455
456NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR_WITH_RC(VirtualBox, VirtualBoxClassFactory::GetInstance)
457
458////////////////////////////////////////////////////////////////////////////////
459
460typedef NSFactoryDestructorProcPtr NSFactoryConstructorProcPtr;
461
462/**
463 * Enhanced module component information structure.
464 *
465 * nsModuleComponentInfo lacks the factory construction callback, here we add
466 * it. This callback is called straight after a nsGenericFactory instance is
467 * successfully created in RegisterSelfComponents.
468 */
469struct nsModuleComponentInfoPlusFactoryConstructor
470{
471 /** standard module component information */
472 const nsModuleComponentInfo *mpModuleComponentInfo;
473 /** (optional) Factory Construction Callback */
474 NSFactoryConstructorProcPtr mFactoryConstructor;
475};
476
477/////////////////////////////////////////////////////////////////////////////
478
479/**
480 * Helper function to register self components upon start-up
481 * of the out-of-proc server.
482 */
483static nsresult
484RegisterSelfComponents(nsIComponentRegistrar *registrar,
485 const nsModuleComponentInfoPlusFactoryConstructor *aComponents,
486 PRUint32 count)
487{
488 nsresult rc = NS_OK;
489 const nsModuleComponentInfoPlusFactoryConstructor *info = aComponents;
490 for (PRUint32 i = 0; i < count && NS_SUCCEEDED(rc); i++, info++)
491 {
492 /* skip components w/o a constructor */
493 if (!info->mpModuleComponentInfo->mConstructor)
494 continue;
495 /* create a new generic factory for a component and register it */
496 nsIGenericFactory *factory;
497 rc = NS_NewGenericFactory(&factory, info->mpModuleComponentInfo);
498 if (NS_SUCCEEDED(rc) && info->mFactoryConstructor)
499 {
500 rc = info->mFactoryConstructor();
501 if (NS_FAILED(rc))
502 NS_RELEASE(factory);
503 }
504 if (NS_SUCCEEDED(rc))
505 {
506 rc = registrar->RegisterFactory(info->mpModuleComponentInfo->mCID,
507 info->mpModuleComponentInfo->mDescription,
508 info->mpModuleComponentInfo->mContractID,
509 factory);
510 NS_RELEASE(factory);
511 }
512 }
513 return rc;
514}
515
516/////////////////////////////////////////////////////////////////////////////
517
518static ipcIService *gIpcServ = nsnull;
519static const char *g_pszPidFile = NULL;
520
521class ForceQuitEvent : public NativeEvent
522{
523 void *handler()
524 {
525 LogFlowFunc(("\n"));
526
527 gKeepRunning = PR_FALSE;
528
529 if (g_pszPidFile)
530 RTFileDelete(g_pszPidFile);
531
532 return NULL;
533 }
534};
535
536static void signal_handler(int sig)
537{
538 com::NativeEventQueue *q = gEventQ;
539 if (q && gKeepRunning)
540 {
541 if (sig == SIGUSR1)
542 {
543 if (gAllowSigUsrQuit)
544 {
545 /* terminate the server process if it is idle */
546 VirtualBoxClassFactory::MaybeQuitEvent *ev = new VirtualBoxClassFactory::MaybeQuitEvent(true /* fSignal */);
547 if (!q->postEvent(ev))
548 delete ev;
549 }
550 /* else do nothing */
551 }
552 else
553 {
554 /* post a force quit event to the queue */
555 ForceQuitEvent *ev = new ForceQuitEvent();
556 if (!q->postEvent(ev))
557 delete ev;
558 }
559 }
560}
561
562static nsresult vboxsvcSpawnDaemonByReExec(const char *pszPath, bool fAutoShutdown, const char *pszPidFile)
563{
564 PRFileDesc *readable = nsnull, *writable = nsnull;
565 PRProcessAttr *attr = nsnull;
566 nsresult rv = NS_ERROR_FAILURE;
567 PRFileDesc *devNull;
568 unsigned args_index = 0;
569 // The ugly casts are necessary because the PR_CreateProcessDetached has
570 // a const array of writable strings as a parameter. It won't write. */
571 char * args[1 + 1 + 2 + 1];
572 args[args_index++] = (char *)pszPath;
573 if (fAutoShutdown)
574 args[args_index++] = (char *)"--auto-shutdown";
575 if (pszPidFile)
576 {
577 args[args_index++] = (char *)"--pidfile";
578 args[args_index++] = (char *)pszPidFile;
579 }
580 args[args_index++] = 0;
581
582 // Use a pipe to determine when the daemon process is in the position
583 // to actually process requests. The daemon will write "READY" to the pipe.
584 if (PR_CreatePipe(&readable, &writable) != PR_SUCCESS)
585 goto end;
586 PR_SetFDInheritable(writable, PR_TRUE);
587
588 attr = PR_NewProcessAttr();
589 if (!attr)
590 goto end;
591
592 if (PR_ProcessAttrSetInheritableFD(attr, writable, VBOXSVC_STARTUP_PIPE_NAME) != PR_SUCCESS)
593 goto end;
594
595 devNull = PR_Open("/dev/null", PR_RDWR, 0);
596 if (!devNull)
597 goto end;
598
599 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardInput, devNull);
600 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardOutput, devNull);
601 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardError, devNull);
602
603 if (PR_CreateProcessDetached(pszPath, (char * const *)args, nsnull, attr) != PR_SUCCESS)
604 goto end;
605
606 // Close /dev/null
607 PR_Close(devNull);
608 // Close the child end of the pipe to make it the only owner of the
609 // file descriptor, so that unexpected closing can be detected.
610 PR_Close(writable);
611 writable = nsnull;
612
613 char msg[10];
614 memset(msg, '\0', sizeof(msg));
615 if ( PR_Read(readable, msg, sizeof(msg)-1) != 5
616 || strcmp(msg, "READY"))
617 goto end;
618
619 rv = NS_OK;
620
621end:
622 if (readable)
623 PR_Close(readable);
624 if (writable)
625 PR_Close(writable);
626 if (attr)
627 PR_DestroyProcessAttr(attr);
628 return rv;
629}
630
631static void showUsage(const char *pcszFileName)
632{
633 RTPrintf(VBOX_PRODUCT " VBoxSVC "
634 VBOX_VERSION_STRING "\n"
635 "Copyright (C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n\n");
636 RTPrintf("By default the service will be started in the background.\n"
637 "\n");
638 RTPrintf("Usage:\n"
639 "\n");
640 RTPrintf(" %s\n", pcszFileName);
641 RTPrintf("\n");
642 RTPrintf("Options:\n");
643 RTPrintf(" -a, --automate Start XPCOM on demand and daemonize.\n");
644 RTPrintf(" -A, --auto-shutdown Shuts down service if no longer in use.\n");
645 RTPrintf(" -d, --daemonize Starts service in background.\n");
646 RTPrintf(" -D, --shutdown-delay <ms> Sets shutdown delay in ms.\n");
647 RTPrintf(" -h, --help Displays this help.\n");
648 RTPrintf(" -p, --pidfile <path> Uses a specific pidfile.\n");
649 RTPrintf(" -F, --logfile <path> Uses a specific logfile.\n");
650 RTPrintf(" -R, --logrotate <count> Number of old log files to keep.\n");
651 RTPrintf(" -S, --logsize <bytes> Maximum size of a log file before rotating.\n");
652 RTPrintf(" -I, --loginterval <s> Maximum amount of time to put in a log file.\n");
653
654 RTPrintf("\n");
655}
656
657int main(int argc, char **argv)
658{
659 /*
660 * Initialize the VBox runtime without loading
661 * the support driver
662 */
663 int vrc = RTR3InitExe(argc, &argv, 0);
664 if (RT_FAILURE(vrc))
665 return RTMsgInitFailure(vrc);
666
667 static const RTGETOPTDEF s_aOptions[] =
668 {
669 { "--automate", 'a', RTGETOPT_REQ_NOTHING },
670 { "--auto-shutdown", 'A', RTGETOPT_REQ_NOTHING },
671 { "--daemonize", 'd', RTGETOPT_REQ_NOTHING },
672 { "--help", 'h', RTGETOPT_REQ_NOTHING },
673 { "--shutdown-delay", 'D', RTGETOPT_REQ_UINT32 },
674 { "--pidfile", 'p', RTGETOPT_REQ_STRING },
675 { "--logfile", 'F', RTGETOPT_REQ_STRING },
676 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 },
677 { "--logsize", 'S', RTGETOPT_REQ_UINT64 },
678 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 }
679 };
680
681 const char *pszLogFile = NULL;
682 uint32_t cHistory = 10; // enable log rotation, 10 files
683 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
684 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
685 bool fDaemonize = false;
686 PRFileDesc *daemon_pipe_wr = nsnull;
687
688 RTGETOPTSTATE GetOptState;
689 vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
690 AssertRC(vrc);
691
692 RTGETOPTUNION ValueUnion;
693 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
694 {
695 switch (vrc)
696 {
697 case 'a':
698 /* --automate mode means we are started by XPCOM on
699 * demand. Daemonize ourselves and activate
700 * auto-shutdown. */
701 gAutoShutdown = true;
702 fDaemonize = true;
703 break;
704
705 case 'A':
706 /* --auto-shutdown mode means we're already daemonized. */
707 gAutoShutdown = true;
708 break;
709
710 case 'd':
711 fDaemonize = true;
712 break;
713
714 case 'D':
715 gShutdownDelayMs = ValueUnion.u32;
716 break;
717
718 case 'p':
719 g_pszPidFile = ValueUnion.psz;
720 break;
721
722 case 'F':
723 pszLogFile = ValueUnion.psz;
724 break;
725
726 case 'R':
727 cHistory = ValueUnion.u32;
728 break;
729
730 case 'S':
731 uHistoryFileSize = ValueUnion.u64;
732 break;
733
734 case 'I':
735 uHistoryFileTime = ValueUnion.u32;
736 break;
737
738 case 'h':
739 showUsage(argv[0]);
740 return RTEXITCODE_SYNTAX;
741
742 case 'V':
743 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
744 return RTEXITCODE_SUCCESS;
745
746 default:
747 return RTGetOptPrintError(vrc, &ValueUnion);
748 }
749 }
750
751 if (fDaemonize)
752 {
753 vboxsvcSpawnDaemonByReExec(argv[0], gAutoShutdown, g_pszPidFile);
754 exit(126);
755 }
756
757 nsresult rc;
758
759 /** @todo Merge this code with svcmain.cpp (use Logging.cpp?). */
760 char szLogFile[RTPATH_MAX];
761 if (!pszLogFile)
762 {
763 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
764 if (RT_SUCCESS(vrc))
765 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
766 }
767 else
768 {
769 if (!RTStrPrintf(szLogFile, sizeof(szLogFile), "%s", pszLogFile))
770 vrc = VERR_NO_MEMORY;
771 }
772 if (RT_FAILURE(vrc))
773 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to create logging file name, rc=%Rrc", vrc);
774
775 RTERRINFOSTATIC ErrInfo;
776 vrc = com::VBoxLogRelCreate("XPCOM Server", szLogFile,
777 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
778 VBOXSVC_LOG_DEFAULT, "VBOXSVC_RELEASE_LOG",
779 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
780 cHistory, uHistoryFileTime, uHistoryFileSize,
781 RTErrInfoInitStatic(&ErrInfo));
782 if (RT_FAILURE(vrc))
783 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", ErrInfo.Core.pszMsg, vrc);
784
785 /* Set up a build identifier so that it can be seen from core dumps what
786 * exact build was used to produce the core. Same as in Console::i_powerUpThread(). */
787 static char saBuildID[48];
788 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
789 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
790
791 daemon_pipe_wr = PR_GetInheritedFD(VBOXSVC_STARTUP_PIPE_NAME);
792 RTEnvUnset("NSPR_INHERIT_FDS");
793
794 const nsModuleComponentInfo VirtualBoxInfo = {
795 "VirtualBox component",
796 NS_VIRTUALBOX_CID,
797 NS_VIRTUALBOX_CONTRACTID,
798 VirtualBoxConstructor, // constructor function
799 NULL, // registration function
800 NULL, // deregistration function
801 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
802 NS_CI_INTERFACE_GETTER_NAME(VirtualBoxWrap),
803 NULL, // language helper
804 &NS_CLASSINFO_NAME(VirtualBoxWrap),
805 0 // flags
806 };
807
808 const nsModuleComponentInfoPlusFactoryConstructor components[] = {
809 {
810 &VirtualBoxInfo,
811 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
812 }
813 };
814
815 do /* goto avoidance only */
816 {
817 rc = com::Initialize();
818 if (NS_FAILED(rc))
819 {
820 RTMsgError("Failed to initialize XPCOM! (rc=%Rhrc)\n", rc);
821 break;
822 }
823
824 nsCOMPtr<nsIComponentRegistrar> registrar;
825 rc = NS_GetComponentRegistrar(getter_AddRefs(registrar));
826 if (NS_FAILED(rc))
827 {
828 RTMsgError("Failed to get component registrar! (rc=%Rhrc)", rc);
829 break;
830 }
831
832 registrar->AutoRegister(nsnull);
833 rc = RegisterSelfComponents(registrar, components,
834 NS_ARRAY_LENGTH(components));
835 if (NS_FAILED(rc))
836 {
837 RTMsgError("Failed to register server components! (rc=%Rhrc)", rc);
838 break;
839 }
840
841 nsCOMPtr<ipcIService> ipcServ(do_GetService(IPC_SERVICE_CONTRACTID, &rc));
842 if (NS_FAILED(rc))
843 {
844 RTMsgError("Failed to get IPC service! (rc=%Rhrc)", rc);
845 break;
846 }
847
848 NS_ADDREF(gIpcServ = ipcServ);
849
850 LogFlowFunc(("Will use \"%s\" as server name.\n", VBOXSVC_IPC_NAME));
851
852 rc = gIpcServ->AddName(VBOXSVC_IPC_NAME);
853 if (NS_FAILED(rc))
854 {
855 LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
856 "Is another server already running?\n", rc, rc));
857
858 RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
859 "Is another server already running?\n",
860 VBOXSVC_IPC_NAME, rc);
861 NS_RELEASE(gIpcServ);
862 break;
863 }
864
865 {
866 /* setup signal handling to convert some signals to a quit event */
867 struct sigaction sa;
868 sa.sa_handler = signal_handler;
869 sigemptyset(&sa.sa_mask);
870 sa.sa_flags = 0;
871 sigaction(SIGINT, &sa, NULL);
872 sigaction(SIGQUIT, &sa, NULL);
873 sigaction(SIGTERM, &sa, NULL);
874// XXX Temporary allow release assertions to terminate VBoxSVC
875// sigaction(SIGTRAP, &sa, NULL);
876 sigaction(SIGUSR1, &sa, NULL);
877 }
878
879 {
880 char szBuf[80];
881 size_t cSize;
882
883 cSize = RTStrPrintf(szBuf, sizeof(szBuf),
884 VBOX_PRODUCT" XPCOM Server Version "
885 VBOX_VERSION_STRING);
886 for (size_t i = cSize; i > 0; i--)
887 putchar('*');
888 RTPrintf("\n%s\n", szBuf);
889 RTPrintf("Copyright (C) 2004-" VBOX_C_YEAR " " VBOX_VENDOR "\n\n");
890#ifdef DEBUG
891 RTPrintf("Debug version.\n");
892#endif
893 }
894
895 if (daemon_pipe_wr != nsnull)
896 {
897 RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
898 /* now we're ready, signal the parent process */
899 PR_Write(daemon_pipe_wr, RT_STR_TUPLE("READY"));
900 /* close writing end of the pipe, its job is done */
901 PR_Close(daemon_pipe_wr);
902 }
903 else
904 RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
905
906 if (g_pszPidFile)
907 {
908 RTFILE hPidFile = NIL_RTFILE;
909 vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
910 if (RT_SUCCESS(vrc))
911 {
912 char szBuf[64];
913 size_t cchToWrite = RTStrPrintf(szBuf, sizeof(szBuf), "%ld\n", (long)getpid());
914 RTFileWrite(hPidFile, szBuf, cchToWrite, NULL);
915 RTFileClose(hPidFile);
916 }
917 }
918
919 // Increase the file table size to 10240 or as high as possible.
920 struct rlimit lim;
921 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
922 {
923 if ( lim.rlim_cur < 10240
924 && lim.rlim_cur < lim.rlim_max)
925 {
926 lim.rlim_cur = RT_MIN(lim.rlim_max, 10240);
927 if (setrlimit(RLIMIT_NOFILE, &lim) == -1)
928 RTPrintf("WARNING: failed to increase file descriptor limit. (%d)\n", errno);
929 }
930 }
931 else
932 RTPrintf("WARNING: failed to obtain per-process file-descriptor limit (%d).\n", errno);
933
934 /* get the main thread's event queue */
935 gEventQ = com::NativeEventQueue::getMainEventQueue();
936 if (!gEventQ)
937 {
938 RTMsgError("Failed to get the main event queue! (rc=%Rhrc)", rc);
939 break;
940 }
941
942 while (gKeepRunning)
943 {
944 vrc = gEventQ->processEventQueue(RT_INDEFINITE_WAIT);
945 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
946 {
947 LogRel(("Failed to wait for events! (rc=%Rrc)", vrc));
948 break;
949 }
950 }
951
952 gEventQ = NULL;
953 RTPrintf("Terminated event loop.\n");
954
955 /* unregister ourselves. After this point, clients will start a new
956 * process because they won't be able to resolve the server name.*/
957 gIpcServ->RemoveName(VBOXSVC_IPC_NAME);
958 }
959 while (0); // this scopes the nsCOMPtrs
960
961 NS_IF_RELEASE(gIpcServ);
962
963 /* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
964
965 LogFlowFunc(("Calling com::Shutdown()...\n"));
966 rc = com::Shutdown();
967 LogFlowFunc(("Finished com::Shutdown() (rc=%Rhrc)\n", rc));
968
969 if (NS_FAILED(rc))
970 RTMsgError("Failed to shutdown XPCOM! (rc=%Rhrc)", rc);
971
972 RTPrintf("XPCOM server has shutdown.\n");
973
974 if (g_pszPidFile)
975 RTFileDelete(g_pszPidFile);
976
977 return RTEXITCODE_SUCCESS;
978}
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