VirtualBox

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

Last change on this file since 51036 was 50919, checked in by vboxsync, 11 years ago

6183 src-all/SharedFolderImpl.cpp

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