VirtualBox

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

Last change on this file since 50152 was 49960, checked in by vboxsync, 11 years ago

6813 stage 6 - Make use of server side API wrapper code in all interfaces

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