VirtualBox

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

最後變更 在這個檔案從49674是 49644,由 vboxsync 提交於 11 年 前

stage 1/8 of 6813 changes

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

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