VirtualBox

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

Last change on this file since 29615 was 29385, checked in by vboxsync, 15 years ago

Main: cleaned up some pedantic warnings.

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