VirtualBox

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

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

Main/src-server/xpcom: build fix for some gcc versions

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.7 KB
Line 
1/* $Id: server.cpp 36478 2011-03-30 18:39:29Z vboxsync $ */
2/** @file
3 * XPCOM server process (VBoxSVC) start point.
4 */
5
6/*
7 * Copyright (C) 2006-2011 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 "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#include <VirtualBox_XPCOM.h>
64
65#include "ApplianceImpl.h"
66#include "AudioAdapterImpl.h"
67#include "BandwidthControlImpl.h"
68#include "BandwidthGroupImpl.h"
69#include "DHCPServerRunner.h"
70#include "DHCPServerImpl.h"
71#include "GuestOSTypeImpl.h"
72#include "HostImpl.h"
73#include "HostNetworkInterfaceImpl.h"
74#include "MachineImpl.h"
75#include "MediumFormatImpl.h"
76#include "MediumImpl.h"
77#include "NATEngineImpl.h"
78#include "NetworkAdapterImpl.h"
79#include "ParallelPortImpl.h"
80#include "ProgressCombinedImpl.h"
81#include "ProgressProxyImpl.h"
82#include "SerialPortImpl.h"
83#include "SharedFolderImpl.h"
84#include "SnapshotImpl.h"
85#include "StorageControllerImpl.h"
86#include "SystemPropertiesImpl.h"
87#include "USBControllerImpl.h"
88#include "VFSExplorerImpl.h"
89#include "VirtualBoxImpl.h"
90#include "VRDEServerImpl.h"
91#ifdef VBOX_WITH_USB
92# include "HostUSBDeviceImpl.h"
93# include "USBDeviceFilterImpl.h"
94# include "USBDeviceImpl.h"
95#endif
96#ifdef VBOX_WITH_EXTPACK
97# include "ExtPackManagerImpl.h"
98#endif
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 NSFactoryConstructorProcPtr;
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 straight after a nsGenericFactory instance is
624 * successfully created in RegisterSelfComponents.
625 */
626struct nsModuleComponentInfoPlusFactoryConstructor
627{
628 /** standard module component information */
629 const nsModuleComponentInfo *mpModuleComponentInfo;
630 /** (optional) Factory Construction Callback */
631 NSFactoryConstructorProcPtr mFactoryConstructor;
632};
633
634/////////////////////////////////////////////////////////////////////////////
635
636/**
637 * Helper function to register self components upon start-up
638 * of the out-of-proc server.
639 */
640static nsresult
641RegisterSelfComponents(nsIComponentRegistrar *registrar,
642 const nsModuleComponentInfoPlusFactoryConstructor *aComponents,
643 PRUint32 count)
644{
645 nsresult rc = NS_OK;
646 const nsModuleComponentInfoPlusFactoryConstructor *info = aComponents;
647 for (PRUint32 i = 0; i < count && NS_SUCCEEDED(rc); i++, info++)
648 {
649 /* skip components w/o a constructor */
650 if (!info->mpModuleComponentInfo->mConstructor)
651 continue;
652 /* create a new generic factory for a component and register it */
653 nsIGenericFactory *factory;
654 rc = NS_NewGenericFactory(&factory, info->mpModuleComponentInfo);
655 if (NS_SUCCEEDED(rc) && info->mFactoryConstructor)
656 {
657 rc = info->mFactoryConstructor();
658 if (NS_FAILED(rc))
659 NS_RELEASE(factory);
660 }
661 if (NS_SUCCEEDED(rc))
662 {
663 rc = registrar->RegisterFactory(info->mpModuleComponentInfo->mCID,
664 info->mpModuleComponentInfo->mDescription,
665 info->mpModuleComponentInfo->mContractID,
666 factory);
667 NS_RELEASE(factory);
668 }
669 }
670 return rc;
671}
672
673/////////////////////////////////////////////////////////////////////////////
674
675static ipcIService *gIpcServ = nsnull;
676static const char *g_pszPidFile = NULL;
677
678class ForceQuitEvent : public MyEvent
679{
680 void *handler()
681 {
682 LogFlowFunc(("\n"));
683
684 gKeepRunning = PR_FALSE;
685
686 if (g_pszPidFile)
687 RTFileDelete(g_pszPidFile);
688
689 return NULL;
690 }
691};
692
693static void signal_handler(int sig)
694{
695 if (gEventQ && gKeepRunning)
696 {
697 if (sig == SIGUSR1)
698 {
699 if (gAllowSigUsrQuit)
700 {
701 VirtualBoxClassFactory::MaybeQuitEvent *ev = new VirtualBoxClassFactory::MaybeQuitEvent();
702 ev->postTo(gEventQ);
703 }
704 /* else do nothing */
705 }
706 else
707 {
708 /* post a force quit event to the queue */
709 ForceQuitEvent *ev = new ForceQuitEvent();
710 ev->postTo(gEventQ);
711 }
712 }
713}
714
715static nsresult vboxsvcSpawnDaemonByReExec(const char *pszPath)
716{
717 PRFileDesc *readable = nsnull, *writable = nsnull;
718 PRProcessAttr *attr = nsnull;
719 nsresult rv = NS_ERROR_FAILURE;
720 PRFileDesc *devNull;
721 // The ugly casts are necessary because the PR_CreateProcessDetached has
722 // a const array of writable strings as a parameter. It won't write. */
723 char * const args[] = { (char *)pszPath, (char *)"--auto-shutdown", 0 };
724
725 // Use a pipe to determine when the daemon process is in the position
726 // to actually process requests. The daemon will write "READY" to the pipe.
727 if (PR_CreatePipe(&readable, &writable) != PR_SUCCESS)
728 goto end;
729 PR_SetFDInheritable(writable, PR_TRUE);
730
731 attr = PR_NewProcessAttr();
732 if (!attr)
733 goto end;
734
735 if (PR_ProcessAttrSetInheritableFD(attr, writable, VBOXSVC_STARTUP_PIPE_NAME) != PR_SUCCESS)
736 goto end;
737
738 devNull = PR_Open("/dev/null", PR_RDWR, 0);
739 if (!devNull)
740 goto end;
741
742 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardInput, devNull);
743 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardOutput, devNull);
744 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardError, devNull);
745
746 if (PR_CreateProcessDetached(pszPath, args, nsnull, attr) != PR_SUCCESS)
747 goto end;
748
749 // Close /dev/null
750 PR_Close(devNull);
751 // Close the child end of the pipe to make it the only owner of the
752 // file descriptor, so that unexpected closing can be detected.
753 PR_Close(writable);
754 writable = nsnull;
755
756 char msg[10];
757 memset(msg, '\0', sizeof(msg));
758 if ( PR_Read(readable, msg, sizeof(msg)-1) != 5
759 || strcmp(msg, "READY"))
760 goto end;
761
762 rv = NS_OK;
763
764end:
765 if (readable)
766 PR_Close(readable);
767 if (writable)
768 PR_Close(writable);
769 if (attr)
770 PR_DestroyProcessAttr(attr);
771 return rv;
772}
773
774int main(int argc, char **argv)
775{
776 /*
777 * Initialize the VBox runtime without loading
778 * the support driver
779 */
780 RTR3Init();
781
782 static const RTGETOPTDEF s_aOptions[] =
783 {
784 { "--automate", 'a', RTGETOPT_REQ_NOTHING },
785 { "--auto-shutdown", 'A', RTGETOPT_REQ_NOTHING },
786 { "--daemonize", 'd', RTGETOPT_REQ_NOTHING },
787 { "--pidfile", 'p', RTGETOPT_REQ_STRING },
788 };
789
790 bool fDaemonize = false;
791 PRFileDesc *daemon_pipe_wr = nsnull;
792
793 RTGETOPTSTATE GetOptState;
794 int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
795 AssertRC(vrc);
796
797 RTGETOPTUNION ValueUnion;
798 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
799 {
800 switch (vrc)
801 {
802 case 'a':
803 {
804 /* --automate mode means we are started by XPCOM on
805 * demand. Daemonize ourselves and activate
806 * auto-shutdown. */
807 gAutoShutdown = true;
808 fDaemonize = true;
809 break;
810 }
811
812 /* Used together with '-P', see below. Internal use only. */
813 case 'A':
814 {
815 gAutoShutdown = true;
816 break;
817 }
818
819 case 'd':
820 {
821 fDaemonize = true;
822 break;
823 }
824
825 case 'p':
826 {
827 g_pszPidFile = ValueUnion.psz;
828 break;
829 }
830
831 case 'h':
832 {
833 RTPrintf("no help\n");
834 return 1;
835 }
836
837 case 'V':
838 {
839 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
840 return 0;
841 }
842
843 default:
844 return RTGetOptPrintError(vrc, &ValueUnion);
845 }
846 }
847
848 if (fDaemonize)
849 {
850 vboxsvcSpawnDaemonByReExec(argv[0]);
851 exit(126);
852 }
853
854 nsresult rc;
855
856 daemon_pipe_wr = PR_GetInheritedFD(VBOXSVC_STARTUP_PIPE_NAME);
857 RTEnvUnset("NSPR_INHERIT_FDS");
858
859 const nsModuleComponentInfo VirtualBoxInfo = {
860 "VirtualBox component",
861 NS_VIRTUALBOX_CID,
862 NS_VIRTUALBOX_CONTRACTID,
863 VirtualBoxConstructor, // constructor function
864 NULL, // registration function
865 NULL, // deregistration function
866 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
867 NS_CI_INTERFACE_GETTER_NAME(VirtualBox),
868 NULL, // language helper
869 &NS_CLASSINFO_NAME(VirtualBox),
870 0 // flags
871 };
872
873 const nsModuleComponentInfoPlusFactoryConstructor components[] = {
874 {
875 &VirtualBoxInfo,
876 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
877 }
878 };
879
880 do
881 {
882 rc = com::Initialize();
883 if (NS_FAILED(rc))
884 {
885 RTMsgError("Failed to initialize XPCOM! (rc=%Rhrc)\n", rc);
886 break;
887 }
888
889 nsCOMPtr <nsIComponentRegistrar> registrar;
890 rc = NS_GetComponentRegistrar(getter_AddRefs(registrar));
891 if (NS_FAILED(rc))
892 {
893 RTMsgError("Failed to get component registrar! (rc=%Rhrc)", rc);
894 break;
895 }
896
897 registrar->AutoRegister(nsnull);
898 rc = RegisterSelfComponents(registrar, components,
899 NS_ARRAY_LENGTH(components));
900 if (NS_FAILED(rc))
901 {
902 RTMsgError("Failed to register server components! (rc=%Rhrc)", rc);
903 break;
904 }
905
906 /* get the main thread's event queue (afaik, the dconnect service always
907 * gets created upon XPCOM startup, so it will use the main (this)
908 * thread's event queue to receive IPC events) */
909 rc = NS_GetMainEventQ(&gEventQ);
910 if (NS_FAILED(rc))
911 {
912 RTMsgError("Failed to get the main event queue! (rc=%Rhrc)", rc);
913 break;
914 }
915
916 nsCOMPtr<ipcIService> ipcServ (do_GetService(IPC_SERVICE_CONTRACTID, &rc));
917 if (NS_FAILED(rc))
918 {
919 RTMsgError("Failed to get IPC service! (rc=%Rhrc)", rc);
920 break;
921 }
922
923 NS_ADDREF(gIpcServ = ipcServ);
924
925 LogFlowFunc(("Will use \"%s\" as server name.\n", VBOXSVC_IPC_NAME));
926
927 rc = gIpcServ->AddName(VBOXSVC_IPC_NAME);
928 if (NS_FAILED(rc))
929 {
930 LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
931 "Is another server already running?\n", rc, rc));
932
933 RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
934 "Is another server already running?\n",
935 VBOXSVC_IPC_NAME, rc);
936 NS_RELEASE(gIpcServ);
937 break;
938 }
939
940 {
941 /* setup signal handling to convert some signals to a quit event */
942 struct sigaction sa;
943 sa.sa_handler = signal_handler;
944 sigemptyset(&sa.sa_mask);
945 sa.sa_flags = 0;
946 sigaction(SIGINT, &sa, NULL);
947 sigaction(SIGQUIT, &sa, NULL);
948 sigaction(SIGTERM, &sa, NULL);
949 sigaction(SIGTRAP, &sa, NULL);
950 sigaction(SIGUSR1, &sa, NULL);
951 }
952
953 {
954 char szBuf[80];
955 int iSize;
956
957 iSize = RTStrPrintf(szBuf, sizeof(szBuf),
958 VBOX_PRODUCT" XPCOM Server Version "
959 VBOX_VERSION_STRING);
960 for (int i = iSize; i > 0; i--)
961 putchar('*');
962 RTPrintf("\n%s\n", szBuf);
963 RTPrintf("(C) 2008-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
964 "All rights reserved.\n");
965#ifdef DEBUG
966 RTPrintf("Debug version.\n");
967#endif
968 }
969
970 if (daemon_pipe_wr != nsnull)
971 {
972 RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
973 /* now we're ready, signal the parent process */
974 PR_Write(daemon_pipe_wr, "READY", strlen("READY"));
975 /* close writing end of the pipe, its job is done */
976 PR_Close(daemon_pipe_wr);
977 }
978 else
979 RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
980
981 if (g_pszPidFile)
982 {
983 RTFILE hPidFile = NIL_RTFILE;
984 vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
985 if (RT_SUCCESS(vrc))
986 {
987 char szBuf[32];
988 const char *lf = "\n";
989 RTStrFormatNumber(szBuf, getpid(), 10, 0, 0, 0);
990 RTFileWrite(hPidFile, szBuf, strlen(szBuf), NULL);
991 RTFileWrite(hPidFile, lf, strlen(lf), NULL);
992 RTFileClose(hPidFile);
993 }
994 }
995
996 // Increase the file table size to 10240 or as high as possible.
997 struct rlimit lim;
998 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
999 {
1000 if ( lim.rlim_cur < 10240
1001 && lim.rlim_cur < lim.rlim_max)
1002 {
1003 lim.rlim_cur = RT_MIN(lim.rlim_max, 10240);
1004 if (setrlimit(RLIMIT_NOFILE, &lim) == -1)
1005 RTPrintf("WARNING: failed to increase file descriptor limit. (%d)\n", errno);
1006 }
1007 }
1008 else
1009 RTPrintf("WARNING: failed to obtain per-process file-descriptor limit (%d).\n", errno);
1010
1011 PLEvent *ev;
1012 while (gKeepRunning)
1013 {
1014 gEventQ->WaitForEvent(&ev);
1015 gEventQ->HandleEvent(ev);
1016 }
1017
1018 /* stop accepting new events. Clients that happen to resolve our
1019 * name and issue a CreateInstance() request after this point will
1020 * get NS_ERROR_ABORT once we handle the remaining messages. As a
1021 * result, they should try to start a new server process. */
1022 gEventQ->StopAcceptingEvents();
1023
1024 /* unregister ourselves. After this point, clients will start a new
1025 * process because they won't be able to resolve the server name.*/
1026 gIpcServ->RemoveName(VBOXSVC_IPC_NAME);
1027
1028 /* process any remaining events. These events may include
1029 * CreateInstance() requests received right before we called
1030 * StopAcceptingEvents() above. We will detect this case below,
1031 * restore gKeepRunning and continue to serve. */
1032 gEventQ->ProcessPendingEvents();
1033
1034 RTPrintf("Terminated event loop.\n");
1035 }
1036 while (0); // this scopes the nsCOMPtrs
1037
1038 NS_IF_RELEASE(gIpcServ);
1039 NS_IF_RELEASE(gEventQ);
1040
1041 /* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
1042
1043 LogFlowFunc(("Calling com::Shutdown()...\n"));
1044 rc = com::Shutdown();
1045 LogFlowFunc(("Finished com::Shutdown() (rc=%Rhrc)\n", rc));
1046
1047 if (NS_FAILED(rc))
1048 RTMsgError("Failed to shutdown XPCOM! (rc=%Rhrc)", rc);
1049
1050 RTPrintf("XPCOM server has shutdown.\n");
1051
1052 if (g_pszPidFile)
1053 RTFileDelete(g_pszPidFile);
1054
1055 return 0;
1056}
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