VirtualBox

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

Last change on this file since 30430 was 30345, checked in by vboxsync, 15 years ago

Main: more events

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.9 KB
Line 
1/* $Id: server.cpp 30345 2010-06-21 16:49:59Z vboxsync $ */
2/** @file
3 * XPCOM server process (VBoxSVC) start point.
4 */
5
6/*
7 * Copyright (C) 2006-2009 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#ifdef XPCOM_GLUE
24# include <nsXPCOMGlue.h>
25#endif
26
27#include <nsEventQueueUtils.h>
28#include <nsGenericFactory.h>
29
30#include "xpcom/server.h"
31
32#include "Logging.h"
33
34#include <VBox/param.h>
35#include <VBox/version.h>
36
37#include <iprt/buildconfig.h>
38#include <iprt/initterm.h>
39#include <iprt/critsect.h>
40#include <iprt/getopt.h>
41#include <iprt/message.h>
42#include <iprt/stream.h>
43#include <iprt/path.h>
44#include <iprt/timer.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
60#include <VirtualBox_XPCOM.h>
61#include <VirtualBoxImpl.h>
62#include <MachineImpl.h>
63#include <VFSExplorerImpl.h>
64#include <ApplianceImpl.h>
65#include <SnapshotImpl.h>
66#include <MediumImpl.h>
67#include <MediumFormatImpl.h>
68#include <ProgressCombinedImpl.h>
69#include <ProgressProxyImpl.h>
70#include <VRDPServerImpl.h>
71#include <SharedFolderImpl.h>
72#include <HostImpl.h>
73#include <HostNetworkInterfaceImpl.h>
74#include <GuestOSTypeImpl.h>
75#include <NetworkAdapterImpl.h>
76#include <NATEngineImpl.h>
77#include <SerialPortImpl.h>
78#include <ParallelPortImpl.h>
79#include <USBControllerImpl.h>
80#include "DHCPServerRunner.h"
81#include "DHCPServerImpl.h"
82#ifdef VBOX_WITH_USB
83# include <HostUSBDeviceImpl.h>
84# include <USBDeviceImpl.h>
85#endif
86#include <StorageControllerImpl.h>
87#include <AudioAdapterImpl.h>
88#include <SystemPropertiesImpl.h>
89#include <EventImpl.h>
90
91/* implement nsISupports parts of our objects with support for nsIClassInfo */
92
93NS_DECL_CLASSINFO(VirtualBox)
94NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VirtualBox, IVirtualBox)
95
96NS_DECL_CLASSINFO(Machine)
97NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Machine, IMachine)
98
99NS_DECL_CLASSINFO(VFSExplorer)
100NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VFSExplorer, IVFSExplorer)
101
102NS_DECL_CLASSINFO(Appliance)
103NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Appliance, IAppliance)
104
105NS_DECL_CLASSINFO(VirtualSystemDescription)
106NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VirtualSystemDescription, IVirtualSystemDescription)
107
108NS_DECL_CLASSINFO(SessionMachine)
109NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
110
111NS_DECL_CLASSINFO(SnapshotMachine)
112NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
113
114NS_DECL_CLASSINFO(Snapshot)
115NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Snapshot, ISnapshot)
116
117NS_DECL_CLASSINFO(Medium)
118NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Medium, IMedium)
119
120NS_DECL_CLASSINFO(MediumFormat)
121NS_IMPL_THREADSAFE_ISUPPORTS1_CI(MediumFormat, IMediumFormat)
122
123NS_DECL_CLASSINFO(MediumAttachment)
124NS_IMPL_THREADSAFE_ISUPPORTS1_CI(MediumAttachment, IMediumAttachment)
125
126NS_DECL_CLASSINFO(Progress)
127NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Progress, IProgress)
128
129NS_DECL_CLASSINFO(CombinedProgress)
130NS_IMPL_THREADSAFE_ISUPPORTS1_CI(CombinedProgress, IProgress)
131
132NS_DECL_CLASSINFO(ProgressProxy)
133NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ProgressProxy, IProgress)
134
135NS_DECL_CLASSINFO(SharedFolder)
136NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SharedFolder, ISharedFolder)
137
138#ifdef VBOX_WITH_VRDP
139NS_DECL_CLASSINFO(VRDPServer)
140NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VRDPServer, IVRDPServer)
141#endif
142
143NS_DECL_CLASSINFO(Host)
144NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Host, IHost)
145
146NS_DECL_CLASSINFO(HostNetworkInterface)
147NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HostNetworkInterface, IHostNetworkInterface)
148
149NS_DECL_CLASSINFO(DHCPServer)
150NS_IMPL_THREADSAFE_ISUPPORTS1_CI(DHCPServer, IDHCPServer)
151
152NS_DECL_CLASSINFO(GuestOSType)
153NS_IMPL_THREADSAFE_ISUPPORTS1_CI(GuestOSType, IGuestOSType)
154
155NS_DECL_CLASSINFO(NetworkAdapter)
156NS_IMPL_THREADSAFE_ISUPPORTS1_CI(NetworkAdapter, INetworkAdapter)
157
158NS_DECL_CLASSINFO(NATEngine)
159NS_IMPL_THREADSAFE_ISUPPORTS1_CI(NATEngine, INATEngine)
160
161
162NS_DECL_CLASSINFO(SerialPort)
163NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SerialPort, ISerialPort)
164
165NS_DECL_CLASSINFO(ParallelPort)
166NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ParallelPort, IParallelPort)
167
168NS_DECL_CLASSINFO(USBController)
169NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBController, IUSBController)
170
171NS_DECL_CLASSINFO(StorageController)
172NS_IMPL_THREADSAFE_ISUPPORTS1_CI(StorageController, IStorageController)
173
174#ifdef VBOX_WITH_USB
175NS_DECL_CLASSINFO(USBDeviceFilter)
176NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBDeviceFilter, IUSBDeviceFilter)
177
178NS_DECL_CLASSINFO(HostUSBDevice)
179NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HostUSBDevice, IUSBDevice, IHostUSBDevice)
180
181NS_DECL_CLASSINFO(HostUSBDeviceFilter)
182NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HostUSBDeviceFilter, IUSBDeviceFilter, IHostUSBDeviceFilter)
183#endif
184
185NS_DECL_CLASSINFO(AudioAdapter)
186NS_IMPL_THREADSAFE_ISUPPORTS1_CI(AudioAdapter, IAudioAdapter)
187
188NS_DECL_CLASSINFO(SystemProperties)
189NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SystemProperties, ISystemProperties)
190
191#ifdef VBOX_WITH_RESOURCE_USAGE_API
192NS_DECL_CLASSINFO(PerformanceCollector)
193NS_IMPL_THREADSAFE_ISUPPORTS1_CI(PerformanceCollector, IPerformanceCollector)
194NS_DECL_CLASSINFO(PerformanceMetric)
195NS_IMPL_THREADSAFE_ISUPPORTS1_CI(PerformanceMetric, IPerformanceMetric)
196#endif /* VBOX_WITH_RESOURCE_USAGE_API */
197
198NS_DECL_CLASSINFO(BIOSSettings)
199NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BIOSSettings, IBIOSSettings)
200
201NS_DECL_CLASSINFO(EventSource)
202NS_IMPL_THREADSAFE_ISUPPORTS1_CI(EventSource, IEventSource)
203
204////////////////////////////////////////////////////////////////////////////////
205
206enum
207{
208 /* Delay before shutting down the VirtualBox server after the last
209 * VirtualBox instance is released, in ms */
210 VBoxSVC_ShutdownDelay = 5000
211};
212
213static bool gAutoShutdown = false;
214
215static nsIEventQueue *gEventQ = nsnull;
216static PRBool volatile gKeepRunning = PR_TRUE;
217
218/////////////////////////////////////////////////////////////////////////////
219
220/**
221 * Simple but smart PLEvent wrapper.
222 *
223 * @note Instances must be always created with <tt>operator new</tt>!
224 */
225class MyEvent
226{
227public:
228
229 MyEvent()
230 {
231 mEv.that = NULL;
232 };
233
234 /**
235 * Posts this event to the given message queue. This method may only be
236 * called once. @note On success, the event will be deleted automatically
237 * after it is delivered and handled. On failure, the event will delete
238 * itself before this method returns! The caller must not delete it in
239 * either case.
240 */
241 nsresult postTo(nsIEventQueue *aEventQ)
242 {
243 AssertReturn(mEv.that == NULL, NS_ERROR_FAILURE);
244 AssertReturn(aEventQ, NS_ERROR_FAILURE);
245 nsresult rv = aEventQ->InitEvent(&mEv.e, NULL,
246 eventHandler, eventDestructor);
247 if (NS_SUCCEEDED(rv))
248 {
249 mEv.that = this;
250 rv = aEventQ->PostEvent(&mEv.e);
251 if (NS_SUCCEEDED(rv))
252 return rv;
253 }
254 delete this;
255 return rv;
256 }
257
258 virtual void *handler() = 0;
259
260private:
261
262 struct Ev
263 {
264 PLEvent e;
265 MyEvent *that;
266 } mEv;
267
268 static void *PR_CALLBACK eventHandler(PLEvent *self)
269 {
270 return reinterpret_cast<Ev *>(self)->that->handler();
271 }
272
273 static void PR_CALLBACK eventDestructor(PLEvent *self)
274 {
275 delete reinterpret_cast<Ev *>(self)->that;
276 }
277};
278
279////////////////////////////////////////////////////////////////////////////////
280
281/**
282 * VirtualBox class factory that destroys the created instance right after
283 * the last reference to it is released by the client, and recreates it again
284 * when necessary (so VirtualBox acts like a singleton object).
285 */
286class VirtualBoxClassFactory : public VirtualBox
287{
288public:
289
290 virtual ~VirtualBoxClassFactory()
291 {
292 LogFlowFunc(("Deleting VirtualBox...\n"));
293
294 FinalRelease();
295 sInstance = NULL;
296
297 LogFlowFunc(("VirtualBox object deleted.\n"));
298 RTPrintf("Informational: VirtualBox object deleted.\n");
299 }
300
301 NS_IMETHOD_(nsrefcnt) Release()
302 {
303 /* we overload Release() to guarantee the VirtualBox destructor is
304 * always called on the main thread */
305
306 nsrefcnt count = VirtualBox::Release();
307
308 if (count == 1)
309 {
310 /* the last reference held by clients is being released
311 * (see GetInstance()) */
312
313 PRBool onMainThread = PR_TRUE;
314 if (gEventQ)
315 gEventQ->IsOnCurrentThread(&onMainThread);
316
317 PRBool timerStarted = PR_FALSE;
318
319 /* sTimer is null if this call originates from FactoryDestructor()*/
320 if (sTimer != NULL)
321 {
322 LogFlowFunc(("Last VirtualBox instance was released.\n"));
323 LogFlowFunc(("Scheduling server shutdown in %d ms...\n",
324 VBoxSVC_ShutdownDelay));
325
326 /* make sure the previous timer (if any) is stopped;
327 * otherwise RTTimerStart() will definitely fail. */
328 RTTimerLRStop(sTimer);
329
330 int vrc = RTTimerLRStart(sTimer, uint64_t(VBoxSVC_ShutdownDelay) * 1000000);
331 AssertRC(vrc);
332 timerStarted = SUCCEEDED(vrc);
333 }
334 else
335 {
336 LogFlowFunc(("Last VirtualBox instance was released "
337 "on XPCOM shutdown.\n"));
338 Assert(onMainThread);
339 }
340
341 if (!timerStarted)
342 {
343 if (!onMainThread)
344 {
345 /* Failed to start the timer, post the shutdown event
346 * manually if not on the main thread alreay. */
347 ShutdownTimer(NULL, NULL, 0);
348 }
349 else
350 {
351 /* Here we come if:
352 *
353 * a) gEventQ is 0 which means either FactoryDestructor() is called
354 * or the IPC/DCONNECT shutdown sequence is initiated by the
355 * XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
356 * happens on the main thread.
357 *
358 * b) gEventQ has reported we're on the main thread. This means
359 * that DestructEventHandler() has been called, but another
360 * client was faster and requested VirtualBox again.
361 *
362 * In either case, there is nothing to do.
363 *
364 * Note: case b) is actually no more valid since we don't
365 * call Release() from DestructEventHandler() in this case
366 * any more. Thus, we assert below.
367 */
368
369 Assert(gEventQ == NULL);
370 }
371 }
372 }
373
374 return count;
375 }
376
377 class MaybeQuitEvent : public MyEvent
378 {
379 /* called on the main thread */
380 void *handler()
381 {
382 LogFlowFunc(("\n"));
383
384 Assert(RTCritSectIsInitialized(&sLock));
385
386 /* stop accepting GetInstance() requests on other threads during
387 * possible destruction */
388 RTCritSectEnter(&sLock);
389
390 nsrefcnt count = 0;
391
392 /* sInstance is NULL here if it was deleted immediately after
393 * creation due to initialization error. See GetInstance(). */
394 if (sInstance != NULL)
395 {
396 /* Release the guard reference added in GetInstance() */
397 count = sInstance->Release();
398 }
399
400 if (count == 0)
401 {
402 if (gAutoShutdown)
403 {
404 Assert(sInstance == NULL);
405 LogFlowFunc(("Terminating the server process...\n"));
406 /* make it leave the event loop */
407 gKeepRunning = PR_FALSE;
408 }
409 }
410 else
411 {
412 /* This condition is quite rare: a new client happened to
413 * connect after this event has been posted to the main queue
414 * but before it started to process it. */
415 LogFlowFunc(("Destruction is canceled (refcnt=%d).\n", count));
416 }
417
418 RTCritSectLeave(&sLock);
419
420 return NULL;
421 }
422 };
423
424 static void ShutdownTimer(RTTIMERLR hTimerLR, void *pvUser, uint64_t /*iTick*/)
425 {
426 NOREF(hTimerLR);
427 NOREF(pvUser);
428
429 /* A "too late" event is theoretically possible if somebody
430 * manually ended the server after a destruction has been scheduled
431 * and this method was so lucky that it got a chance to run before
432 * the timer was killed. */
433 AssertReturnVoid(gEventQ);
434
435 /* post a quit event to the main queue */
436 MaybeQuitEvent *ev = new MaybeQuitEvent();
437 nsresult rv = ev->postTo(gEventQ);
438 NOREF(rv);
439
440 /* A failure above means we've been already stopped (for example
441 * by Ctrl-C). FactoryDestructor() (NS_ShutdownXPCOM())
442 * will do the job. Nothing to do. */
443 }
444
445 static NS_IMETHODIMP FactoryConstructor()
446 {
447 LogFlowFunc(("\n"));
448
449 /* create a critsect to protect object construction */
450 if (RT_FAILURE(RTCritSectInit(&sLock)))
451 return NS_ERROR_OUT_OF_MEMORY;
452
453 int vrc = RTTimerLRCreateEx(&sTimer, 0, 0, ShutdownTimer, NULL);
454 if (RT_FAILURE(vrc))
455 {
456 LogFlowFunc(("Failed to create a timer! (vrc=%Rrc)\n", vrc));
457 return NS_ERROR_FAILURE;
458 }
459
460 return NS_OK;
461 }
462
463 static NS_IMETHODIMP FactoryDestructor()
464 {
465 LogFlowFunc(("\n"));
466
467 RTTimerLRDestroy(sTimer);
468 sTimer = NULL;
469
470 RTCritSectDelete(&sLock);
471
472 if (sInstance != NULL)
473 {
474 /* Either posting a destruction event falied for some reason (most
475 * likely, the quit event has been received before the last release),
476 * or the client has terminated abnormally w/o releasing its
477 * VirtualBox instance (so NS_ShutdownXPCOM() is doing a cleanup).
478 * Release the guard reference we added in GetInstance(). */
479 sInstance->Release();
480 }
481
482 return NS_OK;
483 }
484
485 static nsresult GetInstance(VirtualBox **inst)
486 {
487 LogFlowFunc(("Getting VirtualBox object...\n"));
488
489 RTCritSectEnter(&sLock);
490
491 if (!gKeepRunning)
492 {
493 LogFlowFunc(("Process termination requested first. Refusing.\n"));
494
495 RTCritSectLeave(&sLock);
496
497 /* this rv is what CreateInstance() on the client side returns
498 * when the server process stops accepting events. Do the same
499 * here. The client wrapper should attempt to start a new process in
500 * response to a failure from us. */
501 return NS_ERROR_ABORT;
502 }
503
504 nsresult rv = NS_OK;
505
506 if (sInstance == NULL)
507 {
508 LogFlowFunc (("Creating new VirtualBox object...\n"));
509 sInstance = new VirtualBoxClassFactory();
510 if (sInstance != NULL)
511 {
512 /* make an extra AddRef to take the full control
513 * on the VirtualBox destruction (see FinalRelease()) */
514 sInstance->AddRef();
515
516 sInstance->AddRef(); /* protect FinalConstruct() */
517 rv = sInstance->FinalConstruct();
518 RTPrintf("Informational: VirtualBox object created (rc=%Rhrc).\n", rv);
519 if (NS_FAILED(rv))
520 {
521 /* On failure diring VirtualBox initialization, delete it
522 * immediately on the current thread by releasing all
523 * references in order to properly schedule the server
524 * shutdown. Since the object is fully deleted here, there
525 * is a chance to fix the error and request a new
526 * instantiation before the server terminates. However,
527 * the main reason to maintain the shoutdown delay on
528 * failure is to let the front-end completely fetch error
529 * info from a server-side IVirtualBoxErrorInfo object. */
530 sInstance->Release();
531 sInstance->Release();
532 Assert(sInstance == NULL);
533 }
534 else
535 {
536 /* On success, make sure the previous timer is stopped to
537 * cancel a scheduled server termination (if any). */
538 RTTimerLRStop(sTimer);
539 }
540 }
541 else
542 {
543 rv = NS_ERROR_OUT_OF_MEMORY;
544 }
545 }
546 else
547 {
548 LogFlowFunc(("Using existing VirtualBox object...\n"));
549 nsrefcnt count = sInstance->AddRef();
550 Assert(count > 1);
551
552 if (count == 2)
553 {
554 LogFlowFunc(("Another client has requested a reference to VirtualBox, canceling detruction...\n"));
555
556 /* make sure the previous timer is stopped */
557 RTTimerLRStop(sTimer);
558 }
559 }
560
561 *inst = sInstance;
562
563 RTCritSectLeave(&sLock);
564
565 return rv;
566 }
567
568private:
569
570 /* Don't be confused that sInstance is of the *ClassFactory type. This is
571 * actually a singleton instance (*ClassFactory inherits the singleton
572 * class; we combined them just for "simplicity" and used "static" for
573 * factory methods. *ClassFactory here is necessary for a couple of extra
574 * methods. */
575
576 static VirtualBoxClassFactory *sInstance;
577 static RTCRITSECT sLock;
578
579 static RTTIMERLR sTimer;
580};
581
582VirtualBoxClassFactory *VirtualBoxClassFactory::sInstance = NULL;
583RTCRITSECT VirtualBoxClassFactory::sLock;
584
585RTTIMERLR VirtualBoxClassFactory::sTimer = NIL_RTTIMERLR;
586
587NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR_WITH_RC(VirtualBox, VirtualBoxClassFactory::GetInstance)
588
589////////////////////////////////////////////////////////////////////////////////
590
591typedef NSFactoryDestructorProcPtr NSFactoryConsructorProcPtr;
592
593/**
594 * Enhanced module component information structure.
595 *
596 * nsModuleComponentInfo lacks the factory construction callback, here we add
597 * it. This callback is called by NS_NewGenericFactoryEx() after a
598 * nsGenericFactory instance is successfully created.
599 */
600struct nsModuleComponentInfoEx : nsModuleComponentInfo
601{
602 nsModuleComponentInfoEx() {}
603 nsModuleComponentInfoEx(int) {}
604
605 nsModuleComponentInfoEx(
606 const char* aDescription,
607 const nsCID& aCID,
608 const char* aContractID,
609 NSConstructorProcPtr aConstructor,
610 NSRegisterSelfProcPtr aRegisterSelfProc,
611 NSUnregisterSelfProcPtr aUnregisterSelfProc,
612 NSFactoryDestructorProcPtr aFactoryDestructor,
613 NSGetInterfacesProcPtr aGetInterfacesProc,
614 NSGetLanguageHelperProcPtr aGetLanguageHelperProc,
615 nsIClassInfo ** aClassInfoGlobal,
616 PRUint32 aFlags,
617 NSFactoryConsructorProcPtr aFactoryConstructor)
618 {
619 mDescription = aDescription;
620 mCID = aCID;
621 mContractID = aContractID;
622 mConstructor = aConstructor;
623 mRegisterSelfProc = aRegisterSelfProc;
624 mUnregisterSelfProc = aUnregisterSelfProc;
625 mFactoryDestructor = aFactoryDestructor;
626 mGetInterfacesProc = aGetInterfacesProc;
627 mGetLanguageHelperProc = aGetLanguageHelperProc;
628 mClassInfoGlobal = aClassInfoGlobal;
629 mFlags = aFlags;
630 mFactoryConstructor = aFactoryConstructor;
631 }
632
633 /** (optional) Factory Construction Callback */
634 NSFactoryConsructorProcPtr mFactoryConstructor;
635};
636
637////////////////////////////////////////////////////////////////////////////////
638
639static const nsModuleComponentInfoEx components[] =
640{
641 nsModuleComponentInfoEx(
642 "VirtualBox component",
643 (nsCID) NS_VIRTUALBOX_CID,
644 NS_VIRTUALBOX_CONTRACTID,
645 VirtualBoxConstructor, // constructor funcion
646 NULL, // registration function
647 NULL, // deregistration function
648 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
649 NS_CI_INTERFACE_GETTER_NAME(VirtualBox),
650 NULL, // language helper
651 &NS_CLASSINFO_NAME(VirtualBox),
652 0, // flags
653 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
654 )
655};
656
657/////////////////////////////////////////////////////////////////////////////
658
659/**
660 * Extends NS_NewGenericFactory() by immediately calling
661 * nsModuleComponentInfoEx::mFactoryConstructor before returning to the
662 * caller.
663 */
664nsresult
665NS_NewGenericFactoryEx(nsIGenericFactory **result,
666 const nsModuleComponentInfoEx *info)
667{
668 AssertReturn(result, NS_ERROR_INVALID_POINTER);
669
670 nsresult rv = NS_NewGenericFactory(result, info);
671 if (NS_SUCCEEDED(rv) && info && info->mFactoryConstructor)
672 {
673 rv = info->mFactoryConstructor();
674 if (NS_FAILED(rv))
675 NS_RELEASE(*result);
676 }
677
678 return rv;
679}
680
681/////////////////////////////////////////////////////////////////////////////
682
683/**
684 * Helper function to register self components upon start-up
685 * of the out-of-proc server.
686 */
687static nsresult
688RegisterSelfComponents(nsIComponentRegistrar *registrar,
689 const nsModuleComponentInfoEx *aComponents,
690 PRUint32 count)
691{
692 nsresult rc = NS_OK;
693 const nsModuleComponentInfoEx *info = aComponents;
694 for (PRUint32 i = 0; i < count && NS_SUCCEEDED(rc); i++, info++)
695 {
696 /* skip components w/o a constructor */
697 if (!info->mConstructor)
698 continue;
699 /* create a new generic factory for a component and register it */
700 nsIGenericFactory *factory;
701 rc = NS_NewGenericFactoryEx(&factory, info);
702 if (NS_SUCCEEDED(rc))
703 {
704 rc = registrar->RegisterFactory(info->mCID,
705 info->mDescription,
706 info->mContractID,
707 factory);
708 factory->Release();
709 }
710 }
711 return rc;
712}
713
714/////////////////////////////////////////////////////////////////////////////
715
716static ipcIService *gIpcServ = nsnull;
717static const char *g_pszPidFile = NULL;
718
719class ForceQuitEvent : public MyEvent
720{
721 void *handler()
722 {
723 LogFlowFunc(("\n"));
724
725 gKeepRunning = PR_FALSE;
726
727 if (g_pszPidFile)
728 RTFileDelete(g_pszPidFile);
729
730 return NULL;
731 }
732};
733
734static void signal_handler(int /* sig */)
735{
736 if (gEventQ && gKeepRunning)
737 {
738 /* post a quit event to the queue */
739 ForceQuitEvent *ev = new ForceQuitEvent();
740 ev->postTo(gEventQ);
741 }
742}
743
744int main(int argc, char **argv)
745{
746 /*
747 * Initialize the VBox runtime without loading
748 * the support driver
749 */
750 RTR3Init();
751
752 static const RTGETOPTDEF s_aOptions[] =
753 {
754 { "--automate", 'a', RTGETOPT_REQ_NOTHING },
755 { "--auto-shutdown", 'A', RTGETOPT_REQ_NOTHING },
756 { "--daemonize", 'd', RTGETOPT_REQ_NOTHING },
757 { "--pidfile", 'p', RTGETOPT_REQ_STRING },
758 { "--pipe", 'P', RTGETOPT_REQ_UINT32 },
759 };
760
761 bool fDaemonize = false;
762 int daemon_pipe_wr = -1;
763
764 RTGETOPTSTATE GetOptState;
765 int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
766 AssertRC(vrc);
767
768 RTGETOPTUNION ValueUnion;
769 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
770 {
771 switch (vrc)
772 {
773 case 'a':
774 {
775 /* --automate mode means we are started by XPCOM on
776 * demand. Daemonize ourselves and activate
777 * auto-shutdown. */
778 gAutoShutdown = true;
779 fDaemonize = true;
780 break;
781 }
782
783 /* Used together with '-P', see below. Internal use only. */
784 case 'A':
785 {
786 gAutoShutdown = true;
787 break;
788 }
789
790 case 'd':
791 {
792 fDaemonize = true;
793 break;
794 }
795
796 case 'p':
797 {
798 g_pszPidFile = ValueUnion.psz;
799 break;
800 }
801
802 /* This is just an internal hack for passing the pipe write fd
803 along to the final child. Internal use only. */
804 case 'P':
805 {
806 daemon_pipe_wr = ValueUnion.u32;
807 break;
808 }
809
810 case 'h':
811 {
812 RTPrintf("no help\n");
813 return 1;
814 }
815
816 case 'V':
817 {
818 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
819 return 0;
820 }
821
822 default:
823 return RTGetOptPrintError(vrc, &ValueUnion);
824 }
825 }
826
827#ifdef RT_OS_OS2 /** @todo There is almost no need to make a special case of OS/2 here. Just the execv call needs to be told to create a background process... */
828
829 /* nothing to do here, the process is supposed to be already
830 * started daemonized when it is necessary */
831 NOREF(fDaemonize);
832
833#else // !RT_OS_OS2
834
835 if (fDaemonize)
836 {
837 /* create a pipe for communication between child and parent */
838 int daemon_pipe_fds[2] = {-1, -1};
839 if (pipe(daemon_pipe_fds) < 0)
840 {
841 RTMsgError("pipe() failed (errno = %d)", errno);
842 return 1;
843 }
844 daemon_pipe_wr = daemon_pipe_fds[1];
845 int daemon_pipe_rd = daemon_pipe_fds[0];
846
847 pid_t childpid = fork();
848 if (childpid == -1)
849 {
850 RTMsgError("fork() failed (errno = %d)", errno);
851 return 1;
852 }
853
854 if (childpid != 0)
855 {
856 /* we're the parent process */
857 bool fSuccess = false;
858
859 /* close the writing end of the pipe */
860 close(daemon_pipe_wr);
861
862 /* try to read a message from the pipe */
863 char msg[10 + 1];
864 RT_ZERO(msg); /* initialize so it's NULL terminated */
865 if (read(daemon_pipe_rd, msg, sizeof(msg) - 1) > 0)
866 {
867 if (strcmp(msg, "READY") == 0)
868 fSuccess = true;
869 else
870 RTMsgError("Unknown message from child process (%s)", msg);
871 }
872 else
873 RTMsgError("0 bytes read from child process");
874
875 /* close the reading end of the pipe as well and exit */
876 close(daemon_pipe_rd);
877 return fSuccess ? 0 : 1;
878 }
879 /* we're the child process */
880
881 /* Create a new SID for the child process */
882 pid_t sid = setsid();
883 if (sid < 0)
884 {
885 RTMsgError("setsid() failed (errno = %d)", errno);
886 return 1;
887 }
888
889 /* Need to do another for to get rid of the session leader status.
890 * Otherwise any accidentally opened tty will automatically become a
891 * controlling tty for the daemon process. */
892 childpid = fork();
893 if (childpid == -1)
894 {
895 RTMsgError("second fork() failed (errno = %d)", errno);
896 return 1;
897 }
898
899 if (childpid != 0)
900 {
901 /* we're the parent process, just a dummy so terminate now */
902 exit(0);
903 }
904
905 /* Close all file handles except for the write end of the pipe. */
906 int fdMax;
907 struct rlimit lim;
908 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
909 fdMax = (int)RT_MIN(lim.rlim_cur, 65535); /* paranoia */
910 else
911 fdMax = 1024;
912 for (int fd = 0; fd < fdMax; fd++)
913 if (fd != daemon_pipe_wr)
914 close(fd);
915
916 /* Make sure the pipe isn't any of the standard handles. */
917 if (daemon_pipe_wr <= 2)
918 {
919 if (dup2(daemon_pipe_wr, 3) == 3)
920 {
921 close(daemon_pipe_wr);
922 daemon_pipe_wr = 3;
923 }
924 }
925
926 /* Redirect the standard handles to NULL by opening /dev/null three times. */
927 open("/dev/null", O_RDWR, 0);
928 open("/dev/null", O_RDWR, 0);
929 open("/dev/null", O_RDWR, 0);
930
931 /*
932 * On leopard we're no longer allowed to use some of the core API's
933 * after forking - this will cause us to hit an int3.
934 * So, we'll have to execv VBoxSVC once again and hand it the pipe
935 * and all other relevant options.
936 *
937 * On FreeBSD the fork approach doesn't work. The child fails
938 * during initialization of XPCOM for some unknown reason and
939 * exits making it impossible to autostart VBoxSVC when starting
940 * a frontend (debugger and strace don't contain any useful info).
941 */
942 const char *apszArgs[7 + 2];
943 unsigned i = 0;
944 apszArgs[i++] = argv[0];
945 apszArgs[i++] = "--pipe";
946 char szPipeArg[32];
947 RTStrPrintf(szPipeArg, sizeof(szPipeArg), "%d", daemon_pipe_wr);
948 apszArgs[i++] = szPipeArg;
949 if (g_pszPidFile)
950 {
951 apszArgs[i++] = "--pidfile";
952 apszArgs[i++] = g_pszPidFile;
953 }
954 if (gAutoShutdown)
955 apszArgs[i++] = "--auto-shutdown";
956 apszArgs[i++] = NULL; Assert(i <= RT_ELEMENTS(apszArgs));
957 execv(apszArgs[0], (char * const *)apszArgs);
958 exit(126);
959 }
960
961#endif // !RT_OS_OS2
962
963 nsresult rc;
964
965 do
966 {
967 rc = com::Initialize();
968 if (NS_FAILED(rc))
969 {
970 RTMsgError("Failed to initialize XPCOM! (rc=%Rhrc)\n", rc);
971 break;
972 }
973
974 nsCOMPtr <nsIComponentRegistrar> registrar;
975 rc = NS_GetComponentRegistrar(getter_AddRefs(registrar));
976 if (NS_FAILED(rc))
977 {
978 RTMsgError("Failed to get component registrar! (rc=%Rhrc)", rc);
979 break;
980 }
981
982 registrar->AutoRegister(nsnull);
983 rc = RegisterSelfComponents(registrar, components,
984 NS_ARRAY_LENGTH (components));
985 if (NS_FAILED(rc))
986 {
987 RTMsgError("Failed to register server components! (rc=%Rhrc)", rc);
988 break;
989 }
990
991 /* get the main thread's event queue (afaik, the dconnect service always
992 * gets created upon XPCOM startup, so it will use the main (this)
993 * thread's event queue to receive IPC events) */
994 rc = NS_GetMainEventQ(&gEventQ);
995 if (NS_FAILED(rc))
996 {
997 RTMsgError("Failed to get the main event queue! (rc=%Rhrc)", rc);
998 break;
999 }
1000
1001 nsCOMPtr<ipcIService> ipcServ (do_GetService(IPC_SERVICE_CONTRACTID, &rc));
1002 if (NS_FAILED(rc))
1003 {
1004 RTMsgError("Failed to get IPC service! (rc=%Rhrc)", rc);
1005 break;
1006 }
1007
1008 NS_ADDREF(gIpcServ = ipcServ);
1009
1010 LogFlowFunc(("Will use \"%s\" as server name.\n", VBOXSVC_IPC_NAME));
1011
1012 rc = gIpcServ->AddName(VBOXSVC_IPC_NAME);
1013 if (NS_FAILED(rc))
1014 {
1015 LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
1016 "Is another server already running?\n", rc, rc));
1017
1018 RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
1019 "Is another server already running?\n",
1020 VBOXSVC_IPC_NAME, rc);
1021 NS_RELEASE(gIpcServ);
1022 break;
1023 }
1024
1025 {
1026 /* setup signal handling to convert some signals to a quit event */
1027 struct sigaction sa;
1028 sa.sa_handler = signal_handler;
1029 sigemptyset(&sa.sa_mask);
1030 sa.sa_flags = 0;
1031 sigaction(SIGINT, &sa, NULL);
1032 sigaction(SIGQUIT, &sa, NULL);
1033 sigaction(SIGTERM, &sa, NULL);
1034 sigaction(SIGTRAP, &sa, NULL);
1035 }
1036
1037 {
1038 char szBuf[80];
1039 int iSize;
1040
1041 iSize = RTStrPrintf(szBuf, sizeof(szBuf),
1042 VBOX_PRODUCT" XPCOM Server Version "
1043 VBOX_VERSION_STRING);
1044 for (int i = iSize; i > 0; i--)
1045 putchar('*');
1046 RTPrintf("\n%s\n", szBuf);
1047 RTPrintf("(C) 2008-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
1048 "All rights reserved.\n");
1049#ifdef DEBUG
1050 RTPrintf("Debug version.\n");
1051#endif
1052 }
1053
1054 if (daemon_pipe_wr >= 0)
1055 {
1056 RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
1057 /* now we're ready, signal the parent process */
1058 write(daemon_pipe_wr, "READY", strlen("READY"));
1059 }
1060 else
1061 RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
1062
1063 if (g_pszPidFile)
1064 {
1065 RTFILE hPidFile = NIL_RTFILE;
1066 vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
1067 if (RT_SUCCESS(vrc))
1068 {
1069 char szBuf[32];
1070 const char *lf = "\n";
1071 RTStrFormatNumber(szBuf, getpid(), 10, 0, 0, 0);
1072 RTFileWrite(hPidFile, szBuf, strlen(szBuf), NULL);
1073 RTFileWrite(hPidFile, lf, strlen(lf), NULL);
1074 RTFileClose(hPidFile);
1075 }
1076 }
1077
1078 // Increase the file table size to 10240 or as high as possible.
1079 struct rlimit lim;
1080 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
1081 {
1082 if ( lim.rlim_cur < 10240
1083 && lim.rlim_cur < lim.rlim_max)
1084 {
1085 lim.rlim_cur = RT_MIN(lim.rlim_max, 10240);
1086 if (setrlimit(RLIMIT_NOFILE, &lim) == -1)
1087 RTPrintf("WARNING: failed to increase file descriptor limit. (%d)\n", errno);
1088 }
1089 }
1090 else
1091 RTPrintf("WARNING: failed to obtain per-process file-descriptor limit (%d).\n", errno);
1092
1093 PLEvent *ev;
1094 while (gKeepRunning)
1095 {
1096 gEventQ->WaitForEvent(&ev);
1097 gEventQ->HandleEvent(ev);
1098 }
1099
1100 /* stop accepting new events. Clients that happen to resolve our
1101 * name and issue a CreateInstance() request after this point will
1102 * get NS_ERROR_ABORT once we hande the remaining messages. As a
1103 * result, they should try to start a new server process. */
1104 gEventQ->StopAcceptingEvents();
1105
1106 /* unregister ourselves. After this point, clients will start a new
1107 * process because they won't be able to resolve the server name.*/
1108 gIpcServ->RemoveName(VBOXSVC_IPC_NAME);
1109
1110 /* process any remaining events. These events may include
1111 * CreateInstance() requests received right before we called
1112 * StopAcceptingEvents() above. We will detect this case below,
1113 * restore gKeepRunning and continue to serve. */
1114 gEventQ->ProcessPendingEvents();
1115
1116 RTPrintf("Terminated event loop.\n");
1117 }
1118 while (0); // this scopes the nsCOMPtrs
1119
1120 NS_IF_RELEASE(gIpcServ);
1121 NS_IF_RELEASE(gEventQ);
1122
1123 /* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
1124
1125 LogFlowFunc(("Calling com::Shutdown()...\n"));
1126 rc = com::Shutdown();
1127 LogFlowFunc(("Finished com::Shutdown() (rc=%Rhrc)\n", rc));
1128
1129 if (NS_FAILED(rc))
1130 RTMsgError("Failed to shutdown XPCOM! (rc=%Rhrc)", rc);
1131
1132 RTPrintf("XPCOM server has shutdown.\n");
1133
1134 if (g_pszPidFile)
1135 RTFileDelete(g_pszPidFile);
1136
1137 /* close writing end of the pipe as well */
1138 if (daemon_pipe_wr >= 0)
1139 close(daemon_pipe_wr);
1140
1141 return 0;
1142}
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