VirtualBox

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

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

Main/xpcom: fix server registration breakage, incomplete conversion to wrapper class

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