VirtualBox

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

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

reverted: r84411. (need to solve issues with java first.)

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette