VirtualBox

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

Last change on this file since 57632 was 57428, checked in by vboxsync, 9 years ago

DECLCALLBACK

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