VirtualBox

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

Last change on this file since 33868 was 33842, checked in by vboxsync, 14 years ago

comment typos

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