VirtualBox

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

Last change on this file since 40257 was 39459, checked in by vboxsync, 13 years ago

VBoxSVC: logging and --shutdown-delay.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.5 KB
Line 
1/* $Id: server.cpp 39459 2011-11-29 14:12:58Z 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/string.h>
46#include <iprt/stream.h>
47#include <iprt/path.h>
48#include <iprt/timer.h>
49#include <iprt/env.h>
50
51#include <signal.h> // for the signal handler
52#include <stdlib.h>
53#include <unistd.h>
54#include <errno.h>
55#include <fcntl.h>
56#include <sys/stat.h>
57#include <sys/resource.h>
58
59/////////////////////////////////////////////////////////////////////////////
60// VirtualBox component instantiation
61/////////////////////////////////////////////////////////////////////////////
62
63#include <nsIGenericFactory.h>
64#include <VirtualBox_XPCOM.h>
65
66#include "ApplianceImpl.h"
67#include "AudioAdapterImpl.h"
68#include "BandwidthControlImpl.h"
69#include "BandwidthGroupImpl.h"
70#include "DHCPServerRunner.h"
71#include "DHCPServerImpl.h"
72#include "GuestOSTypeImpl.h"
73#include "HostImpl.h"
74#include "HostNetworkInterfaceImpl.h"
75#include "MachineImpl.h"
76#include "MediumFormatImpl.h"
77#include "MediumImpl.h"
78#include "NATEngineImpl.h"
79#include "NetworkAdapterImpl.h"
80#include "ParallelPortImpl.h"
81#include "ProgressCombinedImpl.h"
82#include "ProgressProxyImpl.h"
83#include "SerialPortImpl.h"
84#include "SharedFolderImpl.h"
85#include "SnapshotImpl.h"
86#include "StorageControllerImpl.h"
87#include "SystemPropertiesImpl.h"
88#include "USBControllerImpl.h"
89#include "VFSExplorerImpl.h"
90#include "VirtualBoxImpl.h"
91#include "VRDEServerImpl.h"
92#ifdef VBOX_WITH_USB
93# include "HostUSBDeviceImpl.h"
94# include "USBDeviceFilterImpl.h"
95# include "USBDeviceImpl.h"
96#endif
97#ifdef VBOX_WITH_EXTPACK
98# include "ExtPackManagerImpl.h"
99#endif
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(GuestOSType)
161NS_IMPL_THREADSAFE_ISUPPORTS1_CI(GuestOSType, IGuestOSType)
162
163NS_DECL_CLASSINFO(NetworkAdapter)
164NS_IMPL_THREADSAFE_ISUPPORTS1_CI(NetworkAdapter, INetworkAdapter)
165
166NS_DECL_CLASSINFO(NATEngine)
167NS_IMPL_THREADSAFE_ISUPPORTS1_CI(NATEngine, INATEngine)
168
169
170NS_DECL_CLASSINFO(SerialPort)
171NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SerialPort, ISerialPort)
172
173NS_DECL_CLASSINFO(ParallelPort)
174NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ParallelPort, IParallelPort)
175
176NS_DECL_CLASSINFO(USBController)
177NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBController, IUSBController)
178
179NS_DECL_CLASSINFO(StorageController)
180NS_IMPL_THREADSAFE_ISUPPORTS1_CI(StorageController, IStorageController)
181
182#ifdef VBOX_WITH_USB
183NS_DECL_CLASSINFO(USBDeviceFilter)
184NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBDeviceFilter, IUSBDeviceFilter)
185
186NS_DECL_CLASSINFO(HostUSBDevice)
187NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HostUSBDevice, IUSBDevice, IHostUSBDevice)
188
189NS_DECL_CLASSINFO(HostUSBDeviceFilter)
190NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HostUSBDeviceFilter, IUSBDeviceFilter, IHostUSBDeviceFilter)
191#endif
192
193NS_DECL_CLASSINFO(AudioAdapter)
194NS_IMPL_THREADSAFE_ISUPPORTS1_CI(AudioAdapter, IAudioAdapter)
195
196NS_DECL_CLASSINFO(SystemProperties)
197NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SystemProperties, ISystemProperties)
198
199#ifdef VBOX_WITH_RESOURCE_USAGE_API
200NS_DECL_CLASSINFO(PerformanceCollector)
201NS_IMPL_THREADSAFE_ISUPPORTS1_CI(PerformanceCollector, IPerformanceCollector)
202NS_DECL_CLASSINFO(PerformanceMetric)
203NS_IMPL_THREADSAFE_ISUPPORTS1_CI(PerformanceMetric, IPerformanceMetric)
204#endif /* VBOX_WITH_RESOURCE_USAGE_API */
205
206NS_DECL_CLASSINFO(BIOSSettings)
207NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BIOSSettings, IBIOSSettings)
208
209#ifdef VBOX_WITH_EXTPACK
210NS_DECL_CLASSINFO(ExtPackFile)
211NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ExtPackFile, IExtPackFile)
212
213NS_DECL_CLASSINFO(ExtPack)
214NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ExtPack, IExtPack)
215
216NS_DECL_CLASSINFO(ExtPackManager)
217NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ExtPackManager, IExtPackManager)
218#endif
219
220NS_DECL_CLASSINFO(BandwidthGroup)
221NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BandwidthGroup, IBandwidthGroup)
222
223NS_DECL_CLASSINFO(BandwidthControl)
224NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BandwidthControl, IBandwidthControl)
225
226////////////////////////////////////////////////////////////////////////////////
227
228static bool gAutoShutdown = false;
229/** Delay before shutting down the VirtualBox server after the last
230 * VirtualBox instance is released, in ms */
231static uint32_t gShutdownDelayMs = 5000;
232
233static nsIEventQueue *gEventQ = nsnull;
234static PRBool volatile gKeepRunning = PR_TRUE;
235static PRBool volatile gAllowSigUsrQuit = PR_TRUE;
236
237/////////////////////////////////////////////////////////////////////////////
238
239/**
240 * Simple but smart PLEvent wrapper.
241 *
242 * @note Instances must be always created with <tt>operator new</tt>!
243 */
244class MyEvent
245{
246public:
247
248 MyEvent()
249 {
250 mEv.that = NULL;
251 };
252
253 /**
254 * Posts this event to the given message queue. This method may only be
255 * called once. @note On success, the event will be deleted automatically
256 * after it is delivered and handled. On failure, the event will delete
257 * itself before this method returns! The caller must not delete it in
258 * either case.
259 */
260 nsresult postTo(nsIEventQueue *aEventQ)
261 {
262 AssertReturn(mEv.that == NULL, NS_ERROR_FAILURE);
263 AssertReturn(aEventQ, NS_ERROR_FAILURE);
264 nsresult rv = aEventQ->InitEvent(&mEv.e, NULL,
265 eventHandler, eventDestructor);
266 if (NS_SUCCEEDED(rv))
267 {
268 mEv.that = this;
269 rv = aEventQ->PostEvent(&mEv.e);
270 if (NS_SUCCEEDED(rv))
271 return rv;
272 }
273 delete this;
274 return rv;
275 }
276
277 virtual void *handler() = 0;
278
279private:
280
281 struct Ev
282 {
283 PLEvent e;
284 MyEvent *that;
285 } mEv;
286
287 static void *PR_CALLBACK eventHandler(PLEvent *self)
288 {
289 return reinterpret_cast<Ev *>(self)->that->handler();
290 }
291
292 static void PR_CALLBACK eventDestructor(PLEvent *self)
293 {
294 delete reinterpret_cast<Ev *>(self)->that;
295 }
296};
297
298////////////////////////////////////////////////////////////////////////////////
299
300/**
301 * VirtualBox class factory that destroys the created instance right after
302 * the last reference to it is released by the client, and recreates it again
303 * when necessary (so VirtualBox acts like a singleton object).
304 */
305class VirtualBoxClassFactory : public VirtualBox
306{
307public:
308
309 virtual ~VirtualBoxClassFactory()
310 {
311 LogFlowFunc(("Deleting VirtualBox...\n"));
312
313 FinalRelease();
314 sInstance = NULL;
315
316 LogFlowFunc(("VirtualBox object deleted.\n"));
317 RTPrintf("Informational: VirtualBox object deleted.\n");
318 }
319
320 NS_IMETHOD_(nsrefcnt) Release()
321 {
322 /* we overload Release() to guarantee the VirtualBox destructor is
323 * always called on the main thread */
324
325 nsrefcnt count = VirtualBox::Release();
326
327 if (count == 1)
328 {
329 /* the last reference held by clients is being released
330 * (see GetInstance()) */
331
332 PRBool onMainThread = PR_TRUE;
333 if (gEventQ)
334 gEventQ->IsOnCurrentThread(&onMainThread);
335
336 PRBool timerStarted = PR_FALSE;
337
338 /* sTimer is null if this call originates from FactoryDestructor()*/
339 if (sTimer != NULL)
340 {
341 LogFlowFunc(("Last VirtualBox instance was released.\n"));
342 LogFlowFunc(("Scheduling server shutdown in %u ms...\n",
343 gShutdownDelayMs));
344
345 /* make sure the previous timer (if any) is stopped;
346 * otherwise RTTimerStart() will definitely fail. */
347 RTTimerLRStop(sTimer);
348
349 int vrc = RTTimerLRStart(sTimer, gShutdownDelayMs * RT_NS_1MS_64);
350 AssertRC(vrc);
351 timerStarted = SUCCEEDED(vrc);
352 }
353 else
354 {
355 LogFlowFunc(("Last VirtualBox instance was released "
356 "on XPCOM shutdown.\n"));
357 Assert(onMainThread);
358 }
359
360 gAllowSigUsrQuit = PR_TRUE;
361
362 if (!timerStarted)
363 {
364 if (!onMainThread)
365 {
366 /* Failed to start the timer, post the shutdown event
367 * manually if not on the main thread already. */
368 ShutdownTimer(NULL, NULL, 0);
369 }
370 else
371 {
372 /* Here we come if:
373 *
374 * a) gEventQ is 0 which means either FactoryDestructor() is called
375 * or the IPC/DCONNECT shutdown sequence is initiated by the
376 * XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
377 * happens on the main thread.
378 *
379 * b) gEventQ has reported we're on the main thread. This means
380 * that DestructEventHandler() has been called, but another
381 * client was faster and requested VirtualBox again.
382 *
383 * In either case, there is nothing to do.
384 *
385 * Note: case b) is actually no more valid since we don't
386 * call Release() from DestructEventHandler() in this case
387 * any more. Thus, we assert below.
388 */
389
390 Assert(gEventQ == NULL);
391 }
392 }
393 }
394
395 return count;
396 }
397
398 class MaybeQuitEvent : public MyEvent
399 {
400 /* called on the main thread */
401 void *handler()
402 {
403 LogFlowFuncEnter();
404
405 Assert(RTCritSectIsInitialized(&sLock));
406
407 /* stop accepting GetInstance() requests on other threads during
408 * possible destruction */
409 RTCritSectEnter(&sLock);
410
411 nsrefcnt count = 0;
412
413 /* sInstance is NULL here if it was deleted immediately after
414 * creation due to initialization error. See GetInstance(). */
415 if (sInstance != NULL)
416 {
417 /* Release the guard reference added in GetInstance() */
418 count = sInstance->Release();
419 }
420
421 if (count == 0)
422 {
423 if (gAutoShutdown)
424 {
425 Assert(sInstance == NULL);
426 LogFlowFunc(("Terminating the server process...\n"));
427 /* make it leave the event loop */
428 gKeepRunning = PR_FALSE;
429 }
430 else
431 LogFlowFunc(("No automatic shutdown.\n"));
432 }
433 else
434 {
435 /* This condition is quite rare: a new client happened to
436 * connect after this event has been posted to the main queue
437 * but before it started to process it. */
438 LogFlowFunc(("Destruction is canceled (refcnt=%d).\n", count));
439 }
440
441 RTCritSectLeave(&sLock);
442
443 LogFlowFuncLeave();
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, bool fAutoShutdown, const char *pszPidFile)
716{
717 PRFileDesc *readable = nsnull, *writable = nsnull;
718 PRProcessAttr *attr = nsnull;
719 nsresult rv = NS_ERROR_FAILURE;
720 PRFileDesc *devNull;
721 unsigned args_index = 0;
722 // The ugly casts are necessary because the PR_CreateProcessDetached has
723 // a const array of writable strings as a parameter. It won't write. */
724 char * args[1 + 1 + 2 + 1];
725 args[args_index++] = (char *)pszPath;
726 if (fAutoShutdown)
727 args[args_index++] = (char *)"--auto-shutdown";
728 if (pszPidFile)
729 {
730 args[args_index++] = (char *)"--pidfile";
731 args[args_index++] = (char *)pszPidFile;
732 }
733 args[args_index++] = 0;
734
735 // Use a pipe to determine when the daemon process is in the position
736 // to actually process requests. The daemon will write "READY" to the pipe.
737 if (PR_CreatePipe(&readable, &writable) != PR_SUCCESS)
738 goto end;
739 PR_SetFDInheritable(writable, PR_TRUE);
740
741 attr = PR_NewProcessAttr();
742 if (!attr)
743 goto end;
744
745 if (PR_ProcessAttrSetInheritableFD(attr, writable, VBOXSVC_STARTUP_PIPE_NAME) != PR_SUCCESS)
746 goto end;
747
748 devNull = PR_Open("/dev/null", PR_RDWR, 0);
749 if (!devNull)
750 goto end;
751
752 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardInput, devNull);
753 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardOutput, devNull);
754 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardError, devNull);
755
756 if (PR_CreateProcessDetached(pszPath, (char * const *)args, nsnull, attr) != PR_SUCCESS)
757 goto end;
758
759 // Close /dev/null
760 PR_Close(devNull);
761 // Close the child end of the pipe to make it the only owner of the
762 // file descriptor, so that unexpected closing can be detected.
763 PR_Close(writable);
764 writable = nsnull;
765
766 char msg[10];
767 memset(msg, '\0', sizeof(msg));
768 if ( PR_Read(readable, msg, sizeof(msg)-1) != 5
769 || strcmp(msg, "READY"))
770 goto end;
771
772 rv = NS_OK;
773
774end:
775 if (readable)
776 PR_Close(readable);
777 if (writable)
778 PR_Close(writable);
779 if (attr)
780 PR_DestroyProcessAttr(attr);
781 return rv;
782}
783
784int main(int argc, char **argv)
785{
786 /*
787 * Initialize the VBox runtime without loading
788 * the support driver
789 */
790 int vrc = RTR3InitExe(argc, &argv, 0);
791 if (RT_FAILURE(vrc))
792 return RTMsgInitFailure(vrc);
793
794 static const RTGETOPTDEF s_aOptions[] =
795 {
796 { "--automate", 'a', RTGETOPT_REQ_NOTHING },
797 { "--auto-shutdown", 'A', RTGETOPT_REQ_NOTHING },
798 { "--daemonize", 'd', RTGETOPT_REQ_NOTHING },
799 { "--shutdown-delay", 'D', RTGETOPT_REQ_UINT32 },
800 { "--pidfile", 'p', RTGETOPT_REQ_STRING },
801 { "--logfile", 'F', RTGETOPT_REQ_STRING },
802 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 },
803 { "--logsize", 'S', RTGETOPT_REQ_UINT64 },
804 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 }
805 };
806
807 const char *pszLogFile = NULL;
808 uint32_t cHistory = 10; // enable log rotation, 10 files
809 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
810 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
811 bool fDaemonize = false;
812 PRFileDesc *daemon_pipe_wr = nsnull;
813
814 RTGETOPTSTATE GetOptState;
815 vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
816 AssertRC(vrc);
817
818 RTGETOPTUNION ValueUnion;
819 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
820 {
821 switch (vrc)
822 {
823 case 'a':
824 /* --automate mode means we are started by XPCOM on
825 * demand. Daemonize ourselves and activate
826 * auto-shutdown. */
827 gAutoShutdown = true;
828 fDaemonize = true;
829 break;
830
831 case 'A':
832 /* --auto-shutdown mode means we're already daemonized. */
833 gAutoShutdown = true;
834 break;
835
836 case 'd':
837 fDaemonize = true;
838 break;
839
840 case 'D':
841 gShutdownDelayMs = ValueUnion.u32;
842 break;
843
844 case 'p':
845 g_pszPidFile = ValueUnion.psz;
846 break;
847
848 case 'F':
849 pszLogFile = ValueUnion.psz;
850 break;
851
852 case 'R':
853 cHistory = ValueUnion.u32;
854 break;
855
856 case 'S':
857 uHistoryFileSize = ValueUnion.u64;
858 break;
859
860 case 'I':
861 uHistoryFileTime = ValueUnion.u32;
862 break;
863
864 case 'h':
865 RTPrintf("no help\n");
866 return 1;
867
868 case 'V':
869 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
870 return 0;
871
872 default:
873 return RTGetOptPrintError(vrc, &ValueUnion);
874 }
875 }
876
877 if (fDaemonize)
878 {
879 vboxsvcSpawnDaemonByReExec(argv[0], gAutoShutdown, g_pszPidFile);
880 exit(126);
881 }
882
883 nsresult rc;
884
885 if (!pszLogFile)
886 {
887 char szLogFile[RTPATH_MAX];
888 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
889 if (RT_SUCCESS(vrc))
890 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
891 if (RT_SUCCESS(vrc))
892 pszLogFile = RTStrDup(szLogFile);
893 }
894 VBoxSVCLogRelCreate(pszLogFile, cHistory, uHistoryFileTime, uHistoryFileSize);
895
896 daemon_pipe_wr = PR_GetInheritedFD(VBOXSVC_STARTUP_PIPE_NAME);
897 RTEnvUnset("NSPR_INHERIT_FDS");
898
899 const nsModuleComponentInfo VirtualBoxInfo = {
900 "VirtualBox component",
901 NS_VIRTUALBOX_CID,
902 NS_VIRTUALBOX_CONTRACTID,
903 VirtualBoxConstructor, // constructor function
904 NULL, // registration function
905 NULL, // deregistration function
906 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
907 NS_CI_INTERFACE_GETTER_NAME(VirtualBox),
908 NULL, // language helper
909 &NS_CLASSINFO_NAME(VirtualBox),
910 0 // flags
911 };
912
913 const nsModuleComponentInfoPlusFactoryConstructor components[] = {
914 {
915 &VirtualBoxInfo,
916 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
917 }
918 };
919
920 do
921 {
922 rc = com::Initialize();
923 if (NS_FAILED(rc))
924 {
925 RTMsgError("Failed to initialize XPCOM! (rc=%Rhrc)\n", rc);
926 break;
927 }
928
929 nsCOMPtr <nsIComponentRegistrar> registrar;
930 rc = NS_GetComponentRegistrar(getter_AddRefs(registrar));
931 if (NS_FAILED(rc))
932 {
933 RTMsgError("Failed to get component registrar! (rc=%Rhrc)", rc);
934 break;
935 }
936
937 registrar->AutoRegister(nsnull);
938 rc = RegisterSelfComponents(registrar, components,
939 NS_ARRAY_LENGTH(components));
940 if (NS_FAILED(rc))
941 {
942 RTMsgError("Failed to register server components! (rc=%Rhrc)", rc);
943 break;
944 }
945
946 /* get the main thread's event queue (afaik, the dconnect service always
947 * gets created upon XPCOM startup, so it will use the main (this)
948 * thread's event queue to receive IPC events) */
949 rc = NS_GetMainEventQ(&gEventQ);
950 if (NS_FAILED(rc))
951 {
952 RTMsgError("Failed to get the main event queue! (rc=%Rhrc)", rc);
953 break;
954 }
955
956 nsCOMPtr<ipcIService> ipcServ (do_GetService(IPC_SERVICE_CONTRACTID, &rc));
957 if (NS_FAILED(rc))
958 {
959 RTMsgError("Failed to get IPC service! (rc=%Rhrc)", rc);
960 break;
961 }
962
963 NS_ADDREF(gIpcServ = ipcServ);
964
965 LogFlowFunc(("Will use \"%s\" as server name.\n", VBOXSVC_IPC_NAME));
966
967 rc = gIpcServ->AddName(VBOXSVC_IPC_NAME);
968 if (NS_FAILED(rc))
969 {
970 LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
971 "Is another server already running?\n", rc, rc));
972
973 RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
974 "Is another server already running?\n",
975 VBOXSVC_IPC_NAME, rc);
976 NS_RELEASE(gIpcServ);
977 break;
978 }
979
980 {
981 /* setup signal handling to convert some signals to a quit event */
982 struct sigaction sa;
983 sa.sa_handler = signal_handler;
984 sigemptyset(&sa.sa_mask);
985 sa.sa_flags = 0;
986 sigaction(SIGINT, &sa, NULL);
987 sigaction(SIGQUIT, &sa, NULL);
988 sigaction(SIGTERM, &sa, NULL);
989 sigaction(SIGTRAP, &sa, NULL);
990 sigaction(SIGUSR1, &sa, NULL);
991 }
992
993 {
994 char szBuf[80];
995 int iSize;
996
997 iSize = RTStrPrintf(szBuf, sizeof(szBuf),
998 VBOX_PRODUCT" XPCOM Server Version "
999 VBOX_VERSION_STRING);
1000 for (int i = iSize; i > 0; i--)
1001 putchar('*');
1002 RTPrintf("\n%s\n", szBuf);
1003 RTPrintf("(C) 2008-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
1004 "All rights reserved.\n");
1005#ifdef DEBUG
1006 RTPrintf("Debug version.\n");
1007#endif
1008 }
1009
1010 if (daemon_pipe_wr != nsnull)
1011 {
1012 RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
1013 /* now we're ready, signal the parent process */
1014 PR_Write(daemon_pipe_wr, "READY", strlen("READY"));
1015 /* close writing end of the pipe, its job is done */
1016 PR_Close(daemon_pipe_wr);
1017 }
1018 else
1019 RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
1020
1021 if (g_pszPidFile)
1022 {
1023 RTFILE hPidFile = NIL_RTFILE;
1024 vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
1025 if (RT_SUCCESS(vrc))
1026 {
1027 char szBuf[32];
1028 const char *lf = "\n";
1029 RTStrFormatNumber(szBuf, getpid(), 10, 0, 0, 0);
1030 RTFileWrite(hPidFile, szBuf, strlen(szBuf), NULL);
1031 RTFileWrite(hPidFile, lf, strlen(lf), NULL);
1032 RTFileClose(hPidFile);
1033 }
1034 }
1035
1036 // Increase the file table size to 10240 or as high as possible.
1037 struct rlimit lim;
1038 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
1039 {
1040 if ( lim.rlim_cur < 10240
1041 && lim.rlim_cur < lim.rlim_max)
1042 {
1043 lim.rlim_cur = RT_MIN(lim.rlim_max, 10240);
1044 if (setrlimit(RLIMIT_NOFILE, &lim) == -1)
1045 RTPrintf("WARNING: failed to increase file descriptor limit. (%d)\n", errno);
1046 }
1047 }
1048 else
1049 RTPrintf("WARNING: failed to obtain per-process file-descriptor limit (%d).\n", errno);
1050
1051 PLEvent *ev;
1052 while (gKeepRunning)
1053 {
1054 gEventQ->WaitForEvent(&ev);
1055 gEventQ->HandleEvent(ev);
1056 }
1057
1058 /* stop accepting new events. Clients that happen to resolve our
1059 * name and issue a CreateInstance() request after this point will
1060 * get NS_ERROR_ABORT once we handle the remaining messages. As a
1061 * result, they should try to start a new server process. */
1062 gEventQ->StopAcceptingEvents();
1063
1064 /* unregister ourselves. After this point, clients will start a new
1065 * process because they won't be able to resolve the server name.*/
1066 gIpcServ->RemoveName(VBOXSVC_IPC_NAME);
1067
1068 /* process any remaining events. These events may include
1069 * CreateInstance() requests received right before we called
1070 * StopAcceptingEvents() above. We will detect this case below,
1071 * restore gKeepRunning and continue to serve. */
1072 gEventQ->ProcessPendingEvents();
1073
1074 RTPrintf("Terminated event loop.\n");
1075 }
1076 while (0); // this scopes the nsCOMPtrs
1077
1078 NS_IF_RELEASE(gIpcServ);
1079 NS_IF_RELEASE(gEventQ);
1080
1081 /* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
1082
1083 LogFlowFunc(("Calling com::Shutdown()...\n"));
1084 rc = com::Shutdown();
1085 LogFlowFunc(("Finished com::Shutdown() (rc=%Rhrc)\n", rc));
1086
1087 if (NS_FAILED(rc))
1088 RTMsgError("Failed to shutdown XPCOM! (rc=%Rhrc)", rc);
1089
1090 RTPrintf("XPCOM server has shutdown.\n");
1091
1092 if (g_pszPidFile)
1093 RTFileDelete(g_pszPidFile);
1094
1095 return 0;
1096}
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