VirtualBox

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

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

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