VirtualBox

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

Last change on this file since 34900 was 34714, checked in by vboxsync, 14 years ago

ExtPackManager: Added API for opening a tarball prior to installation (does not work yet).

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