VirtualBox

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

Last change on this file since 47743 was 47525, checked in by vboxsync, 11 years ago

control VBoxSVC release logging xtracker id 6787

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