VirtualBox

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

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

6813 src-all/ProgressImp.cpp + some formatting/line length sorting

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