VirtualBox

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

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

6813 src-all/ExtPackManagerImpl.cpp

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