VirtualBox

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

Last change on this file since 43677 was 41100, checked in by vboxsync, 12 years ago

better error report if the global settings directory is not accessible

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