VirtualBox

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

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

*,IPRT: Redid the ring-3 init to always convert the arguments to UTF-8.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.4 KB
Line 
1/* $Id: server.cpp 38636 2011-09-05 13:49:45Z vboxsync $ */
2/** @file
3 * XPCOM server process (VBoxSVC) start point.
4 */
5
6/*
7 * Copyright (C) 2006-2011 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <ipcIService.h>
19#include <ipcCID.h>
20
21#include <nsIComponentRegistrar.h>
22
23#ifdef XPCOM_GLUE
24# include <nsXPCOMGlue.h>
25#endif
26
27#include <nsEventQueueUtils.h>
28#include <nsGenericFactory.h>
29
30#include "prio.h"
31#include "prproces.h"
32
33#include "server.h"
34
35#include "Logging.h"
36
37#include <VBox/param.h>
38#include <VBox/version.h>
39
40#include <iprt/buildconfig.h>
41#include <iprt/initterm.h>
42#include <iprt/critsect.h>
43#include <iprt/getopt.h>
44#include <iprt/message.h>
45#include <iprt/string.h>
46#include <iprt/stream.h>
47#include <iprt/path.h>
48#include <iprt/timer.h>
49#include <iprt/env.h>
50
51#include <signal.h> // for the signal handler
52#include <stdlib.h>
53#include <unistd.h>
54#include <errno.h>
55#include <fcntl.h>
56#include <sys/stat.h>
57#include <sys/resource.h>
58
59/////////////////////////////////////////////////////////////////////////////
60// VirtualBox component instantiation
61/////////////////////////////////////////////////////////////////////////////
62
63#include <nsIGenericFactory.h>
64#include <VirtualBox_XPCOM.h>
65
66#include "ApplianceImpl.h"
67#include "AudioAdapterImpl.h"
68#include "BandwidthControlImpl.h"
69#include "BandwidthGroupImpl.h"
70#include "DHCPServerRunner.h"
71#include "DHCPServerImpl.h"
72#include "GuestOSTypeImpl.h"
73#include "HostImpl.h"
74#include "HostNetworkInterfaceImpl.h"
75#include "MachineImpl.h"
76#include "MediumFormatImpl.h"
77#include "MediumImpl.h"
78#include "NATEngineImpl.h"
79#include "NetworkAdapterImpl.h"
80#include "ParallelPortImpl.h"
81#include "ProgressCombinedImpl.h"
82#include "ProgressProxyImpl.h"
83#include "SerialPortImpl.h"
84#include "SharedFolderImpl.h"
85#include "SnapshotImpl.h"
86#include "StorageControllerImpl.h"
87#include "SystemPropertiesImpl.h"
88#include "USBControllerImpl.h"
89#include "VFSExplorerImpl.h"
90#include "VirtualBoxImpl.h"
91#include "VRDEServerImpl.h"
92#ifdef VBOX_WITH_USB
93# include "HostUSBDeviceImpl.h"
94# include "USBDeviceFilterImpl.h"
95# include "USBDeviceImpl.h"
96#endif
97#ifdef VBOX_WITH_EXTPACK
98# include "ExtPackManagerImpl.h"
99#endif
100
101/* implement nsISupports parts of our objects with support for nsIClassInfo */
102
103NS_DECL_CLASSINFO(VirtualBox)
104NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VirtualBox, IVirtualBox)
105
106NS_DECL_CLASSINFO(Machine)
107NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Machine, IMachine)
108
109NS_DECL_CLASSINFO(VFSExplorer)
110NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VFSExplorer, IVFSExplorer)
111
112NS_DECL_CLASSINFO(Appliance)
113NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Appliance, IAppliance)
114
115NS_DECL_CLASSINFO(VirtualSystemDescription)
116NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VirtualSystemDescription, IVirtualSystemDescription)
117
118NS_DECL_CLASSINFO(SessionMachine)
119NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
120
121NS_DECL_CLASSINFO(SnapshotMachine)
122NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
123
124NS_DECL_CLASSINFO(Snapshot)
125NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Snapshot, ISnapshot)
126
127NS_DECL_CLASSINFO(Medium)
128NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Medium, IMedium)
129
130NS_DECL_CLASSINFO(MediumFormat)
131NS_IMPL_THREADSAFE_ISUPPORTS1_CI(MediumFormat, IMediumFormat)
132
133NS_DECL_CLASSINFO(MediumAttachment)
134NS_IMPL_THREADSAFE_ISUPPORTS1_CI(MediumAttachment, IMediumAttachment)
135
136NS_DECL_CLASSINFO(Progress)
137NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Progress, IProgress)
138
139NS_DECL_CLASSINFO(CombinedProgress)
140NS_IMPL_THREADSAFE_ISUPPORTS1_CI(CombinedProgress, IProgress)
141
142NS_DECL_CLASSINFO(ProgressProxy)
143NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ProgressProxy, IProgress)
144
145NS_DECL_CLASSINFO(SharedFolder)
146NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SharedFolder, ISharedFolder)
147
148NS_DECL_CLASSINFO(VRDEServer)
149NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VRDEServer, IVRDEServer)
150
151NS_DECL_CLASSINFO(Host)
152NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Host, IHost)
153
154NS_DECL_CLASSINFO(HostNetworkInterface)
155NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HostNetworkInterface, IHostNetworkInterface)
156
157NS_DECL_CLASSINFO(DHCPServer)
158NS_IMPL_THREADSAFE_ISUPPORTS1_CI(DHCPServer, IDHCPServer)
159
160NS_DECL_CLASSINFO(GuestOSType)
161NS_IMPL_THREADSAFE_ISUPPORTS1_CI(GuestOSType, IGuestOSType)
162
163NS_DECL_CLASSINFO(NetworkAdapter)
164NS_IMPL_THREADSAFE_ISUPPORTS1_CI(NetworkAdapter, INetworkAdapter)
165
166NS_DECL_CLASSINFO(NATEngine)
167NS_IMPL_THREADSAFE_ISUPPORTS1_CI(NATEngine, INATEngine)
168
169
170NS_DECL_CLASSINFO(SerialPort)
171NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SerialPort, ISerialPort)
172
173NS_DECL_CLASSINFO(ParallelPort)
174NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ParallelPort, IParallelPort)
175
176NS_DECL_CLASSINFO(USBController)
177NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBController, IUSBController)
178
179NS_DECL_CLASSINFO(StorageController)
180NS_IMPL_THREADSAFE_ISUPPORTS1_CI(StorageController, IStorageController)
181
182#ifdef VBOX_WITH_USB
183NS_DECL_CLASSINFO(USBDeviceFilter)
184NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBDeviceFilter, IUSBDeviceFilter)
185
186NS_DECL_CLASSINFO(HostUSBDevice)
187NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HostUSBDevice, IUSBDevice, IHostUSBDevice)
188
189NS_DECL_CLASSINFO(HostUSBDeviceFilter)
190NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HostUSBDeviceFilter, IUSBDeviceFilter, IHostUSBDeviceFilter)
191#endif
192
193NS_DECL_CLASSINFO(AudioAdapter)
194NS_IMPL_THREADSAFE_ISUPPORTS1_CI(AudioAdapter, IAudioAdapter)
195
196NS_DECL_CLASSINFO(SystemProperties)
197NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SystemProperties, ISystemProperties)
198
199#ifdef VBOX_WITH_RESOURCE_USAGE_API
200NS_DECL_CLASSINFO(PerformanceCollector)
201NS_IMPL_THREADSAFE_ISUPPORTS1_CI(PerformanceCollector, IPerformanceCollector)
202NS_DECL_CLASSINFO(PerformanceMetric)
203NS_IMPL_THREADSAFE_ISUPPORTS1_CI(PerformanceMetric, IPerformanceMetric)
204#endif /* VBOX_WITH_RESOURCE_USAGE_API */
205
206NS_DECL_CLASSINFO(BIOSSettings)
207NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BIOSSettings, IBIOSSettings)
208
209#ifdef VBOX_WITH_EXTPACK
210NS_DECL_CLASSINFO(ExtPackFile)
211NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ExtPackFile, IExtPackFile)
212
213NS_DECL_CLASSINFO(ExtPack)
214NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ExtPack, IExtPack)
215
216NS_DECL_CLASSINFO(ExtPackManager)
217NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ExtPackManager, IExtPackManager)
218#endif
219
220NS_DECL_CLASSINFO(BandwidthGroup)
221NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BandwidthGroup, IBandwidthGroup)
222
223NS_DECL_CLASSINFO(BandwidthControl)
224NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BandwidthControl, IBandwidthControl)
225
226////////////////////////////////////////////////////////////////////////////////
227
228enum
229{
230 /* Delay before shutting down the VirtualBox server after the last
231 * VirtualBox instance is released, in ms */
232 VBoxSVC_ShutdownDelay = 5000
233};
234
235static bool gAutoShutdown = false;
236
237static nsIEventQueue *gEventQ = nsnull;
238static PRBool volatile gKeepRunning = PR_TRUE;
239static PRBool volatile gAllowSigUsrQuit = PR_TRUE;
240
241/////////////////////////////////////////////////////////////////////////////
242
243/**
244 * Simple but smart PLEvent wrapper.
245 *
246 * @note Instances must be always created with <tt>operator new</tt>!
247 */
248class MyEvent
249{
250public:
251
252 MyEvent()
253 {
254 mEv.that = NULL;
255 };
256
257 /**
258 * Posts this event to the given message queue. This method may only be
259 * called once. @note On success, the event will be deleted automatically
260 * after it is delivered and handled. On failure, the event will delete
261 * itself before this method returns! The caller must not delete it in
262 * either case.
263 */
264 nsresult postTo(nsIEventQueue *aEventQ)
265 {
266 AssertReturn(mEv.that == NULL, NS_ERROR_FAILURE);
267 AssertReturn(aEventQ, NS_ERROR_FAILURE);
268 nsresult rv = aEventQ->InitEvent(&mEv.e, NULL,
269 eventHandler, eventDestructor);
270 if (NS_SUCCEEDED(rv))
271 {
272 mEv.that = this;
273 rv = aEventQ->PostEvent(&mEv.e);
274 if (NS_SUCCEEDED(rv))
275 return rv;
276 }
277 delete this;
278 return rv;
279 }
280
281 virtual void *handler() = 0;
282
283private:
284
285 struct Ev
286 {
287 PLEvent e;
288 MyEvent *that;
289 } mEv;
290
291 static void *PR_CALLBACK eventHandler(PLEvent *self)
292 {
293 return reinterpret_cast<Ev *>(self)->that->handler();
294 }
295
296 static void PR_CALLBACK eventDestructor(PLEvent *self)
297 {
298 delete reinterpret_cast<Ev *>(self)->that;
299 }
300};
301
302////////////////////////////////////////////////////////////////////////////////
303
304/**
305 * VirtualBox class factory that destroys the created instance right after
306 * the last reference to it is released by the client, and recreates it again
307 * when necessary (so VirtualBox acts like a singleton object).
308 */
309class VirtualBoxClassFactory : public VirtualBox
310{
311public:
312
313 virtual ~VirtualBoxClassFactory()
314 {
315 LogFlowFunc(("Deleting VirtualBox...\n"));
316
317 FinalRelease();
318 sInstance = NULL;
319
320 LogFlowFunc(("VirtualBox object deleted.\n"));
321 RTPrintf("Informational: VirtualBox object deleted.\n");
322 }
323
324 NS_IMETHOD_(nsrefcnt) Release()
325 {
326 /* we overload Release() to guarantee the VirtualBox destructor is
327 * always called on the main thread */
328
329 nsrefcnt count = VirtualBox::Release();
330
331 if (count == 1)
332 {
333 /* the last reference held by clients is being released
334 * (see GetInstance()) */
335
336 PRBool onMainThread = PR_TRUE;
337 if (gEventQ)
338 gEventQ->IsOnCurrentThread(&onMainThread);
339
340 PRBool timerStarted = PR_FALSE;
341
342 /* sTimer is null if this call originates from FactoryDestructor()*/
343 if (sTimer != NULL)
344 {
345 LogFlowFunc(("Last VirtualBox instance was released.\n"));
346 LogFlowFunc(("Scheduling server shutdown in %d ms...\n",
347 VBoxSVC_ShutdownDelay));
348
349 /* make sure the previous timer (if any) is stopped;
350 * otherwise RTTimerStart() will definitely fail. */
351 RTTimerLRStop(sTimer);
352
353 int vrc = RTTimerLRStart(sTimer, uint64_t(VBoxSVC_ShutdownDelay) * 1000000);
354 AssertRC(vrc);
355 timerStarted = SUCCEEDED(vrc);
356 }
357 else
358 {
359 LogFlowFunc(("Last VirtualBox instance was released "
360 "on XPCOM shutdown.\n"));
361 Assert(onMainThread);
362 }
363
364 gAllowSigUsrQuit = PR_TRUE;
365
366 if (!timerStarted)
367 {
368 if (!onMainThread)
369 {
370 /* Failed to start the timer, post the shutdown event
371 * manually if not on the main thread already. */
372 ShutdownTimer(NULL, NULL, 0);
373 }
374 else
375 {
376 /* Here we come if:
377 *
378 * a) gEventQ is 0 which means either FactoryDestructor() is called
379 * or the IPC/DCONNECT shutdown sequence is initiated by the
380 * XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
381 * happens on the main thread.
382 *
383 * b) gEventQ has reported we're on the main thread. This means
384 * that DestructEventHandler() has been called, but another
385 * client was faster and requested VirtualBox again.
386 *
387 * In either case, there is nothing to do.
388 *
389 * Note: case b) is actually no more valid since we don't
390 * call Release() from DestructEventHandler() in this case
391 * any more. Thus, we assert below.
392 */
393
394 Assert(gEventQ == NULL);
395 }
396 }
397 }
398
399 return count;
400 }
401
402 class MaybeQuitEvent : public MyEvent
403 {
404 /* called on the main thread */
405 void *handler()
406 {
407 LogFlowFunc(("\n"));
408
409 Assert(RTCritSectIsInitialized(&sLock));
410
411 /* stop accepting GetInstance() requests on other threads during
412 * possible destruction */
413 RTCritSectEnter(&sLock);
414
415 nsrefcnt count = 0;
416
417 /* sInstance is NULL here if it was deleted immediately after
418 * creation due to initialization error. See GetInstance(). */
419 if (sInstance != NULL)
420 {
421 /* Release the guard reference added in GetInstance() */
422 count = sInstance->Release();
423 }
424
425 if (count == 0)
426 {
427 if (gAutoShutdown)
428 {
429 Assert(sInstance == NULL);
430 LogFlowFunc(("Terminating the server process...\n"));
431 /* make it leave the event loop */
432 gKeepRunning = PR_FALSE;
433 }
434 }
435 else
436 {
437 /* This condition is quite rare: a new client happened to
438 * connect after this event has been posted to the main queue
439 * but before it started to process it. */
440 LogFlowFunc(("Destruction is canceled (refcnt=%d).\n", count));
441 }
442
443 RTCritSectLeave(&sLock);
444
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 { "--pidfile", 'p', RTGETOPT_REQ_STRING },
801 { "--logfile", 'F', RTGETOPT_REQ_STRING },
802 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 },
803 { "--logsize", 'S', RTGETOPT_REQ_UINT64 },
804 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 }
805 };
806
807 const char *pszLogFile = NULL;
808 uint32_t cHistory = 10; // enable log rotation, 10 files
809 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
810 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
811 bool fDaemonize = false;
812 PRFileDesc *daemon_pipe_wr = nsnull;
813
814 RTGETOPTSTATE GetOptState;
815 vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
816 AssertRC(vrc);
817
818 RTGETOPTUNION ValueUnion;
819 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
820 {
821 switch (vrc)
822 {
823 case 'a':
824 {
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
833 /* --auto-shutdown mode means we're already daemonized. */
834 case 'A':
835 {
836 gAutoShutdown = true;
837 break;
838 }
839
840 case 'd':
841 {
842 fDaemonize = true;
843 break;
844 }
845
846 case 'p':
847 {
848 g_pszPidFile = ValueUnion.psz;
849 break;
850 }
851
852 case 'F':
853 pszLogFile = ValueUnion.psz;
854 break;
855
856 case 'R':
857 cHistory = ValueUnion.u32;
858 break;
859
860 case 'S':
861 uHistoryFileSize = ValueUnion.u64;
862 break;
863
864 case 'I':
865 uHistoryFileTime = ValueUnion.u32;
866 break;
867
868 case 'h':
869 {
870 RTPrintf("no help\n");
871 return 1;
872 }
873
874 case 'V':
875 {
876 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
877 return 0;
878 }
879
880 default:
881 return RTGetOptPrintError(vrc, &ValueUnion);
882 }
883 }
884
885 if (fDaemonize)
886 {
887 vboxsvcSpawnDaemonByReExec(argv[0], gAutoShutdown, g_pszPidFile);
888 exit(126);
889 }
890
891 nsresult rc;
892
893 if (!pszLogFile)
894 {
895 char szLogFile[RTPATH_MAX];
896 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
897 if (RT_SUCCESS(vrc))
898 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
899 if (RT_SUCCESS(vrc))
900 pszLogFile = RTStrDup(szLogFile);
901 }
902 VBoxSVCLogRelCreate(pszLogFile, cHistory, uHistoryFileTime, uHistoryFileSize);
903
904 daemon_pipe_wr = PR_GetInheritedFD(VBOXSVC_STARTUP_PIPE_NAME);
905 RTEnvUnset("NSPR_INHERIT_FDS");
906
907 const nsModuleComponentInfo VirtualBoxInfo = {
908 "VirtualBox component",
909 NS_VIRTUALBOX_CID,
910 NS_VIRTUALBOX_CONTRACTID,
911 VirtualBoxConstructor, // constructor function
912 NULL, // registration function
913 NULL, // deregistration function
914 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
915 NS_CI_INTERFACE_GETTER_NAME(VirtualBox),
916 NULL, // language helper
917 &NS_CLASSINFO_NAME(VirtualBox),
918 0 // flags
919 };
920
921 const nsModuleComponentInfoPlusFactoryConstructor components[] = {
922 {
923 &VirtualBoxInfo,
924 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
925 }
926 };
927
928 do
929 {
930 rc = com::Initialize();
931 if (NS_FAILED(rc))
932 {
933 RTMsgError("Failed to initialize XPCOM! (rc=%Rhrc)\n", rc);
934 break;
935 }
936
937 nsCOMPtr <nsIComponentRegistrar> registrar;
938 rc = NS_GetComponentRegistrar(getter_AddRefs(registrar));
939 if (NS_FAILED(rc))
940 {
941 RTMsgError("Failed to get component registrar! (rc=%Rhrc)", rc);
942 break;
943 }
944
945 registrar->AutoRegister(nsnull);
946 rc = RegisterSelfComponents(registrar, components,
947 NS_ARRAY_LENGTH(components));
948 if (NS_FAILED(rc))
949 {
950 RTMsgError("Failed to register server components! (rc=%Rhrc)", rc);
951 break;
952 }
953
954 /* get the main thread's event queue (afaik, the dconnect service always
955 * gets created upon XPCOM startup, so it will use the main (this)
956 * thread's event queue to receive IPC events) */
957 rc = NS_GetMainEventQ(&gEventQ);
958 if (NS_FAILED(rc))
959 {
960 RTMsgError("Failed to get the main event queue! (rc=%Rhrc)", rc);
961 break;
962 }
963
964 nsCOMPtr<ipcIService> ipcServ (do_GetService(IPC_SERVICE_CONTRACTID, &rc));
965 if (NS_FAILED(rc))
966 {
967 RTMsgError("Failed to get IPC service! (rc=%Rhrc)", rc);
968 break;
969 }
970
971 NS_ADDREF(gIpcServ = ipcServ);
972
973 LogFlowFunc(("Will use \"%s\" as server name.\n", VBOXSVC_IPC_NAME));
974
975 rc = gIpcServ->AddName(VBOXSVC_IPC_NAME);
976 if (NS_FAILED(rc))
977 {
978 LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
979 "Is another server already running?\n", rc, rc));
980
981 RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
982 "Is another server already running?\n",
983 VBOXSVC_IPC_NAME, rc);
984 NS_RELEASE(gIpcServ);
985 break;
986 }
987
988 {
989 /* setup signal handling to convert some signals to a quit event */
990 struct sigaction sa;
991 sa.sa_handler = signal_handler;
992 sigemptyset(&sa.sa_mask);
993 sa.sa_flags = 0;
994 sigaction(SIGINT, &sa, NULL);
995 sigaction(SIGQUIT, &sa, NULL);
996 sigaction(SIGTERM, &sa, NULL);
997 sigaction(SIGTRAP, &sa, NULL);
998 sigaction(SIGUSR1, &sa, NULL);
999 }
1000
1001 {
1002 char szBuf[80];
1003 int iSize;
1004
1005 iSize = RTStrPrintf(szBuf, sizeof(szBuf),
1006 VBOX_PRODUCT" XPCOM Server Version "
1007 VBOX_VERSION_STRING);
1008 for (int i = iSize; i > 0; i--)
1009 putchar('*');
1010 RTPrintf("\n%s\n", szBuf);
1011 RTPrintf("(C) 2008-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
1012 "All rights reserved.\n");
1013#ifdef DEBUG
1014 RTPrintf("Debug version.\n");
1015#endif
1016 }
1017
1018 if (daemon_pipe_wr != nsnull)
1019 {
1020 RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
1021 /* now we're ready, signal the parent process */
1022 PR_Write(daemon_pipe_wr, "READY", strlen("READY"));
1023 /* close writing end of the pipe, its job is done */
1024 PR_Close(daemon_pipe_wr);
1025 }
1026 else
1027 RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
1028
1029 if (g_pszPidFile)
1030 {
1031 RTFILE hPidFile = NIL_RTFILE;
1032 vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
1033 if (RT_SUCCESS(vrc))
1034 {
1035 char szBuf[32];
1036 const char *lf = "\n";
1037 RTStrFormatNumber(szBuf, getpid(), 10, 0, 0, 0);
1038 RTFileWrite(hPidFile, szBuf, strlen(szBuf), NULL);
1039 RTFileWrite(hPidFile, lf, strlen(lf), NULL);
1040 RTFileClose(hPidFile);
1041 }
1042 }
1043
1044 // Increase the file table size to 10240 or as high as possible.
1045 struct rlimit lim;
1046 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
1047 {
1048 if ( lim.rlim_cur < 10240
1049 && lim.rlim_cur < lim.rlim_max)
1050 {
1051 lim.rlim_cur = RT_MIN(lim.rlim_max, 10240);
1052 if (setrlimit(RLIMIT_NOFILE, &lim) == -1)
1053 RTPrintf("WARNING: failed to increase file descriptor limit. (%d)\n", errno);
1054 }
1055 }
1056 else
1057 RTPrintf("WARNING: failed to obtain per-process file-descriptor limit (%d).\n", errno);
1058
1059 PLEvent *ev;
1060 while (gKeepRunning)
1061 {
1062 gEventQ->WaitForEvent(&ev);
1063 gEventQ->HandleEvent(ev);
1064 }
1065
1066 /* stop accepting new events. Clients that happen to resolve our
1067 * name and issue a CreateInstance() request after this point will
1068 * get NS_ERROR_ABORT once we handle the remaining messages. As a
1069 * result, they should try to start a new server process. */
1070 gEventQ->StopAcceptingEvents();
1071
1072 /* unregister ourselves. After this point, clients will start a new
1073 * process because they won't be able to resolve the server name.*/
1074 gIpcServ->RemoveName(VBOXSVC_IPC_NAME);
1075
1076 /* process any remaining events. These events may include
1077 * CreateInstance() requests received right before we called
1078 * StopAcceptingEvents() above. We will detect this case below,
1079 * restore gKeepRunning and continue to serve. */
1080 gEventQ->ProcessPendingEvents();
1081
1082 RTPrintf("Terminated event loop.\n");
1083 }
1084 while (0); // this scopes the nsCOMPtrs
1085
1086 NS_IF_RELEASE(gIpcServ);
1087 NS_IF_RELEASE(gEventQ);
1088
1089 /* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
1090
1091 LogFlowFunc(("Calling com::Shutdown()...\n"));
1092 rc = com::Shutdown();
1093 LogFlowFunc(("Finished com::Shutdown() (rc=%Rhrc)\n", rc));
1094
1095 if (NS_FAILED(rc))
1096 RTMsgError("Failed to shutdown XPCOM! (rc=%Rhrc)", rc);
1097
1098 RTPrintf("XPCOM server has shutdown.\n");
1099
1100 if (g_pszPidFile)
1101 RTFileDelete(g_pszPidFile);
1102
1103 return 0;
1104}
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