VirtualBox

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

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

6813 stage 7 VirtualBoxImpl.cpp etc

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