VirtualBox

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

Last change on this file since 82921 was 82921, checked in by vboxsync, 5 years ago
Main/VBoxSVC: Implemented command line help for XPCOM implementation (-hhelp).
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.4 KB
Line 
1/* $Id: server.cpp 82921 2020-01-30 11:00:45Z vboxsync $ */
2/** @file
3 * XPCOM server process (VBoxSVC) start point.
4 */
5
6/*
7 * Copyright (C) 2004-2019 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#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 = !!(SUCCEEDED(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 "(C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
636 "All rights reserved.\n"
637 "\n");
638 RTPrintf("By default the service will be started in the background.\n"
639 "\n");
640 RTPrintf("Usage:\n"
641 "\n");
642 RTPrintf(" %s\n", pcszFileName);
643 RTPrintf("\n");
644 RTPrintf("Options:\n");
645 RTPrintf(" -a, --automate Start XPCOM on demand and daemonize.\n");
646 RTPrintf(" -A, --auto-shutdown Shuts down service if no longer in use.\n");
647 RTPrintf(" -d, --daemonize Starts service in background.\n");
648 RTPrintf(" -D, --shutdown-delay <ms> Sets shutdown delay in ms.\n");
649 RTPrintf(" -h, --help Displays this help.\n");
650 RTPrintf(" -p, --pidfile <path> Uses a specific pidfile.\n");
651 RTPrintf(" -F, --logfile <path> Uses a specific logfile.\n");
652 RTPrintf(" -R, --logrotate <count> Number of old log files to keep.\n");
653 RTPrintf(" -S, --logsize <bytes> Maximum size of a log file before rotating.\n");
654 RTPrintf(" -I, --loginterval <s> Maximum amount of time to put in a log file.\n");
655
656 RTPrintf("\n");
657}
658
659int main(int argc, char **argv)
660{
661 /*
662 * Initialize the VBox runtime without loading
663 * the support driver
664 */
665 int vrc = RTR3InitExe(argc, &argv, 0);
666 if (RT_FAILURE(vrc))
667 return RTMsgInitFailure(vrc);
668
669 static const RTGETOPTDEF s_aOptions[] =
670 {
671 { "--automate", 'a', RTGETOPT_REQ_NOTHING },
672 { "--auto-shutdown", 'A', RTGETOPT_REQ_NOTHING },
673 { "--daemonize", 'd', RTGETOPT_REQ_NOTHING },
674 { "--help", 'h', RTGETOPT_REQ_NOTHING },
675 { "--shutdown-delay", 'D', RTGETOPT_REQ_UINT32 },
676 { "--pidfile", 'p', RTGETOPT_REQ_STRING },
677 { "--logfile", 'F', RTGETOPT_REQ_STRING },
678 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 },
679 { "--logsize", 'S', RTGETOPT_REQ_UINT64 },
680 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 }
681 };
682
683 const char *pszLogFile = NULL;
684 uint32_t cHistory = 10; // enable log rotation, 10 files
685 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
686 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
687 bool fDaemonize = false;
688 PRFileDesc *daemon_pipe_wr = nsnull;
689
690 RTGETOPTSTATE GetOptState;
691 vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
692 AssertRC(vrc);
693
694 RTGETOPTUNION ValueUnion;
695 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
696 {
697 switch (vrc)
698 {
699 case 'a':
700 /* --automate mode means we are started by XPCOM on
701 * demand. Daemonize ourselves and activate
702 * auto-shutdown. */
703 gAutoShutdown = true;
704 fDaemonize = true;
705 break;
706
707 case 'A':
708 /* --auto-shutdown mode means we're already daemonized. */
709 gAutoShutdown = true;
710 break;
711
712 case 'd':
713 fDaemonize = true;
714 break;
715
716 case 'D':
717 gShutdownDelayMs = ValueUnion.u32;
718 break;
719
720 case 'p':
721 g_pszPidFile = ValueUnion.psz;
722 break;
723
724 case 'F':
725 pszLogFile = ValueUnion.psz;
726 break;
727
728 case 'R':
729 cHistory = ValueUnion.u32;
730 break;
731
732 case 'S':
733 uHistoryFileSize = ValueUnion.u64;
734 break;
735
736 case 'I':
737 uHistoryFileTime = ValueUnion.u32;
738 break;
739
740 case 'h':
741 showUsage(argv[0]);
742 return RTEXITCODE_SYNTAX;
743
744 case 'V':
745 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
746 return RTEXITCODE_SUCCESS;
747
748 default:
749 return RTGetOptPrintError(vrc, &ValueUnion);
750 }
751 }
752
753 if (fDaemonize)
754 {
755 vboxsvcSpawnDaemonByReExec(argv[0], gAutoShutdown, g_pszPidFile);
756 exit(126);
757 }
758
759 nsresult rc;
760
761 /** @todo Merge this code with svcmain.cpp (use Logging.cpp?). */
762 char szLogFile[RTPATH_MAX];
763 if (!pszLogFile)
764 {
765 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
766 if (RT_SUCCESS(vrc))
767 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
768 }
769 else
770 {
771 if (!RTStrPrintf(szLogFile, sizeof(szLogFile), "%s", pszLogFile))
772 vrc = VERR_NO_MEMORY;
773 }
774 if (RT_FAILURE(vrc))
775 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to create logging file name, rc=%Rrc", vrc);
776
777 RTERRINFOSTATIC ErrInfo;
778 vrc = com::VBoxLogRelCreate("XPCOM Server", szLogFile,
779 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
780 VBOXSVC_LOG_DEFAULT, "VBOXSVC_RELEASE_LOG",
781 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
782 cHistory, uHistoryFileTime, uHistoryFileSize,
783 RTErrInfoInitStatic(&ErrInfo));
784 if (RT_FAILURE(vrc))
785 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", ErrInfo.Core.pszMsg, vrc);
786
787 /* Set up a build identifier so that it can be seen from core dumps what
788 * exact build was used to produce the core. Same as in Console::i_powerUpThread(). */
789 static char saBuildID[48];
790 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
791 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
792
793 daemon_pipe_wr = PR_GetInheritedFD(VBOXSVC_STARTUP_PIPE_NAME);
794 RTEnvUnset("NSPR_INHERIT_FDS");
795
796 const nsModuleComponentInfo VirtualBoxInfo = {
797 "VirtualBox component",
798 NS_VIRTUALBOX_CID,
799 NS_VIRTUALBOX_CONTRACTID,
800 VirtualBoxConstructor, // constructor function
801 NULL, // registration function
802 NULL, // deregistration function
803 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
804 NS_CI_INTERFACE_GETTER_NAME(VirtualBoxWrap),
805 NULL, // language helper
806 &NS_CLASSINFO_NAME(VirtualBoxWrap),
807 0 // flags
808 };
809
810 const nsModuleComponentInfoPlusFactoryConstructor components[] = {
811 {
812 &VirtualBoxInfo,
813 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
814 }
815 };
816
817 do /* goto avoidance only */
818 {
819 rc = com::Initialize();
820 if (NS_FAILED(rc))
821 {
822 RTMsgError("Failed to initialize XPCOM! (rc=%Rhrc)\n", rc);
823 break;
824 }
825
826 nsCOMPtr<nsIComponentRegistrar> registrar;
827 rc = NS_GetComponentRegistrar(getter_AddRefs(registrar));
828 if (NS_FAILED(rc))
829 {
830 RTMsgError("Failed to get component registrar! (rc=%Rhrc)", rc);
831 break;
832 }
833
834 registrar->AutoRegister(nsnull);
835 rc = RegisterSelfComponents(registrar, components,
836 NS_ARRAY_LENGTH(components));
837 if (NS_FAILED(rc))
838 {
839 RTMsgError("Failed to register server components! (rc=%Rhrc)", rc);
840 break;
841 }
842
843 nsCOMPtr<ipcIService> ipcServ(do_GetService(IPC_SERVICE_CONTRACTID, &rc));
844 if (NS_FAILED(rc))
845 {
846 RTMsgError("Failed to get IPC service! (rc=%Rhrc)", rc);
847 break;
848 }
849
850 NS_ADDREF(gIpcServ = ipcServ);
851
852 LogFlowFunc(("Will use \"%s\" as server name.\n", VBOXSVC_IPC_NAME));
853
854 rc = gIpcServ->AddName(VBOXSVC_IPC_NAME);
855 if (NS_FAILED(rc))
856 {
857 LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
858 "Is another server already running?\n", rc, rc));
859
860 RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
861 "Is another server already running?\n",
862 VBOXSVC_IPC_NAME, rc);
863 NS_RELEASE(gIpcServ);
864 break;
865 }
866
867 {
868 /* setup signal handling to convert some signals to a quit event */
869 struct sigaction sa;
870 sa.sa_handler = signal_handler;
871 sigemptyset(&sa.sa_mask);
872 sa.sa_flags = 0;
873 sigaction(SIGINT, &sa, NULL);
874 sigaction(SIGQUIT, &sa, NULL);
875 sigaction(SIGTERM, &sa, NULL);
876// XXX Temporary allow release assertions to terminate VBoxSVC
877// sigaction(SIGTRAP, &sa, NULL);
878 sigaction(SIGUSR1, &sa, NULL);
879 }
880
881 {
882 char szBuf[80];
883 size_t cSize;
884
885 cSize = RTStrPrintf(szBuf, sizeof(szBuf),
886 VBOX_PRODUCT" XPCOM Server Version "
887 VBOX_VERSION_STRING);
888 for (size_t i = cSize; i > 0; i--)
889 putchar('*');
890 RTPrintf("\n%s\n", szBuf);
891 RTPrintf("(C) 2004-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
892 "All rights reserved.\n");
893#ifdef DEBUG
894 RTPrintf("Debug version.\n");
895#endif
896 }
897
898 if (daemon_pipe_wr != nsnull)
899 {
900 RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
901 /* now we're ready, signal the parent process */
902 PR_Write(daemon_pipe_wr, RT_STR_TUPLE("READY"));
903 /* close writing end of the pipe, its job is done */
904 PR_Close(daemon_pipe_wr);
905 }
906 else
907 RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
908
909 if (g_pszPidFile)
910 {
911 RTFILE hPidFile = NIL_RTFILE;
912 vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
913 if (RT_SUCCESS(vrc))
914 {
915 char szBuf[32];
916 const char *lf = "\n";
917 RTStrFormatNumber(szBuf, getpid(), 10, 0, 0, 0);
918 RTFileWrite(hPidFile, szBuf, strlen(szBuf), NULL);
919 RTFileWrite(hPidFile, lf, strlen(lf), NULL);
920 RTFileClose(hPidFile);
921 }
922 }
923
924 // Increase the file table size to 10240 or as high as possible.
925 struct rlimit lim;
926 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
927 {
928 if ( lim.rlim_cur < 10240
929 && lim.rlim_cur < lim.rlim_max)
930 {
931 lim.rlim_cur = RT_MIN(lim.rlim_max, 10240);
932 if (setrlimit(RLIMIT_NOFILE, &lim) == -1)
933 RTPrintf("WARNING: failed to increase file descriptor limit. (%d)\n", errno);
934 }
935 }
936 else
937 RTPrintf("WARNING: failed to obtain per-process file-descriptor limit (%d).\n", errno);
938
939 /* get the main thread's event queue */
940 gEventQ = com::NativeEventQueue::getMainEventQueue();
941 if (!gEventQ)
942 {
943 RTMsgError("Failed to get the main event queue! (rc=%Rhrc)", rc);
944 break;
945 }
946
947 while (gKeepRunning)
948 {
949 vrc = gEventQ->processEventQueue(RT_INDEFINITE_WAIT);
950 if (RT_FAILURE(vrc) && vrc != VERR_TIMEOUT)
951 {
952 LogRel(("Failed to wait for events! (rc=%Rrc)", vrc));
953 break;
954 }
955 }
956
957 gEventQ = NULL;
958 RTPrintf("Terminated event loop.\n");
959
960 /* unregister ourselves. After this point, clients will start a new
961 * process because they won't be able to resolve the server name.*/
962 gIpcServ->RemoveName(VBOXSVC_IPC_NAME);
963 }
964 while (0); // this scopes the nsCOMPtrs
965
966 NS_IF_RELEASE(gIpcServ);
967
968 /* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
969
970 LogFlowFunc(("Calling com::Shutdown()...\n"));
971 rc = com::Shutdown();
972 LogFlowFunc(("Finished com::Shutdown() (rc=%Rhrc)\n", rc));
973
974 if (NS_FAILED(rc))
975 RTMsgError("Failed to shutdown XPCOM! (rc=%Rhrc)", rc);
976
977 RTPrintf("XPCOM server has shutdown.\n");
978
979 if (g_pszPidFile)
980 RTFileDelete(g_pszPidFile);
981
982 return RTEXITCODE_SUCCESS;
983}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette