VirtualBox

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

Last change on this file since 27059 was 26517, checked in by vboxsync, 15 years ago

*: RTGetOpt cleanup related to --help and --version (now standard option). Use RTGetOptPrintError.

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