VirtualBox

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

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

Forgot include.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette