VirtualBox

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

Last change on this file since 59967 was 58579, checked in by vboxsync, 9 years ago

Main/src-server/xpcom/server.cpp: switch from raw XPCOM event queue use to using NativeEventQueue glue code, which processes Darwin's system events, too.

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