server.cpp revision 326f997d990d56493e7ea37a9f6c8dced6796984
/* $Id$ */
/** @file
* XPCOM server process (VBoxSVC) start point.
*/
/*
* Copyright (C) 2006-2009 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <ipcIService.h>
#include <ipcCID.h>
#include <nsIComponentRegistrar.h>
#ifdef XPCOM_GLUE
# include <nsXPCOMGlue.h>
#endif
#include <nsEventQueueUtils.h>
#include <nsGenericFactory.h>
#include "Logging.h"
#include <iprt/buildconfig.h>
#include <iprt/initterm.h>
#include <iprt/critsect.h>
#include <signal.h> // for the signal handler
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/resource.h>
/////////////////////////////////////////////////////////////////////////////
// VirtualBox component instantiation
/////////////////////////////////////////////////////////////////////////////
#include <nsIGenericFactory.h>
#include <VirtualBox_XPCOM.h>
#include <VirtualBoxImpl.h>
#include <MachineImpl.h>
#include <VFSExplorerImpl.h>
#include <ApplianceImpl.h>
#include <SnapshotImpl.h>
#include <MediumImpl.h>
#include <MediumFormatImpl.h>
#include <ProgressCombinedImpl.h>
#include <ProgressProxyImpl.h>
#include <VRDPServerImpl.h>
#include <SharedFolderImpl.h>
#include <HostImpl.h>
#include <HostNetworkInterfaceImpl.h>
#include <GuestOSTypeImpl.h>
#include <NetworkAdapterImpl.h>
#include <NATEngineImpl.h>
#include <SerialPortImpl.h>
#include <ParallelPortImpl.h>
#include <USBControllerImpl.h>
#include "DHCPServerRunner.h"
#include "DHCPServerImpl.h"
#ifdef VBOX_WITH_USB
# include <HostUSBDeviceImpl.h>
# include <USBDeviceImpl.h>
#endif
#include <StorageControllerImpl.h>
#include <AudioAdapterImpl.h>
#include <SystemPropertiesImpl.h>
/* implement nsISupports parts of our objects with support for nsIClassInfo */
#ifdef VBOX_WITH_VRDP
#endif
#ifdef VBOX_WITH_USB
#endif
#ifdef VBOX_WITH_RESOURCE_USAGE_API
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
////////////////////////////////////////////////////////////////////////////////
enum
{
/* Delay before shutting down the VirtualBox server after the last
* VirtualBox instance is released, in ms */
VBoxSVC_ShutdownDelay = 5000
};
static bool gAutoShutdown = false;
/////////////////////////////////////////////////////////////////////////////
/**
* Simple but smart PLEvent wrapper.
*
* @note Instances must be always created with <tt>operator new</tt>!
*/
class MyEvent
{
public:
MyEvent()
{
};
/**
* Posts this event to the given message queue. This method may only be
* called once. @note On success, the event will be deleted automatically
* after it is delivered and handled. On failure, the event will delete
* itself before this method returns! The caller must not delete it in
* either case.
*/
{
if (NS_SUCCEEDED(rv))
{
if (NS_SUCCEEDED(rv))
return rv;
}
delete this;
return rv;
}
virtual void *handler() = 0;
private:
struct Ev
{
PLEvent e;
} mEv;
{
}
{
}
};
////////////////////////////////////////////////////////////////////////////////
/**
* VirtualBox class factory that destroys the created instance right after
* the last reference to it is released by the client, and recreates it again
* when necessary (so VirtualBox acts like a singleton object).
*/
class VirtualBoxClassFactory : public VirtualBox
{
public:
virtual ~VirtualBoxClassFactory()
{
LogFlowFunc(("Deleting VirtualBox...\n"));
FinalRelease();
LogFlowFunc(("VirtualBox object deleted.\n"));
RTPrintf("Informational: VirtualBox object deleted.\n");
}
{
/* we overload Release() to guarantee the VirtualBox destructor is
* always called on the main thread */
if (count == 1)
{
/* the last reference held by clients is being released
* (see GetInstance()) */
if (gEventQ)
/* sTimer is null if this call originates from FactoryDestructor()*/
{
LogFlowFunc(("Last VirtualBox instance was released.\n"));
LogFlowFunc(("Scheduling server shutdown in %d ms...\n",
/* make sure the previous timer (if any) is stopped;
* otherwise RTTimerStart() will definitely fail. */
}
else
{
LogFlowFunc(("Last VirtualBox instance was released "
"on XPCOM shutdown.\n"));
}
if (!timerStarted)
{
if (!onMainThread)
{
/* Failed to start the timer, post the shutdown event
* manually if not on the main thread alreay. */
}
else
{
/* Here we come if:
*
* a) gEventQ is 0 which means either FactoryDestructor() is called
* XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
* happens on the main thread.
*
* b) gEventQ has reported we're on the main thread. This means
* that DestructEventHandler() has been called, but another
* client was faster and requested VirtualBox again.
*
* In either case, there is nothing to do.
*
* Note: case b) is actually no more valid since we don't
* call Release() from DestructEventHandler() in this case
* any more. Thus, we assert below.
*/
}
}
}
return count;
}
class MaybeQuitEvent : public MyEvent
{
/* called on the main thread */
void *handler()
{
LogFlowFunc(("\n"));
/* stop accepting GetInstance() requests on other threads during
* possible destruction */
/* sInstance is NULL here if it was deleted immediately after
* creation due to initialization error. See GetInstance(). */
{
/* Release the guard reference added in GetInstance() */
}
if (count == 0)
{
if (gAutoShutdown)
{
LogFlowFunc(("Terminating the server process...\n"));
/* make it leave the event loop */
}
}
else
{
/* This condition is quite rare: a new client happened to
* connect after this event has been posted to the main queue
* but before it started to process it. */
}
return NULL;
}
};
{
/* A "too late" event is theoretically possible if somebody
* manually ended the server after a destruction has been scheduled
* and this method was so lucky that it got a chance to run before
* the timer was killed. */
/* post a quit event to the main queue */
/* A failure above means we've been already stopped (for example
* by Ctrl-C). FactoryDestructor() (NS_ShutdownXPCOM())
* will do the job. Nothing to do. */
}
static NS_IMETHODIMP FactoryConstructor()
{
LogFlowFunc(("\n"));
/* create a critsect to protect object construction */
return NS_ERROR_OUT_OF_MEMORY;
if (RT_FAILURE(vrc))
{
return NS_ERROR_FAILURE;
}
return NS_OK;
}
static NS_IMETHODIMP FactoryDestructor()
{
LogFlowFunc(("\n"));
{
/* Either posting a destruction event falied for some reason (most
* likely, the quit event has been received before the last release),
* or the client has terminated abnormally w/o releasing its
* VirtualBox instance (so NS_ShutdownXPCOM() is doing a cleanup).
* Release the guard reference we added in GetInstance(). */
}
return NS_OK;
}
{
LogFlowFunc(("Getting VirtualBox object...\n"));
if (!gKeepRunning)
{
LogFlowFunc(("Process termination requested first. Refusing.\n"));
/* this rv is what CreateInstance() on the client side returns
* when the server process stops accepting events. Do the same
* here. The client wrapper should attempt to start a new process in
* response to a failure from us. */
return NS_ERROR_ABORT;
}
{
LogFlowFunc (("Creating new VirtualBox object...\n"));
sInstance = new VirtualBoxClassFactory();
{
/* make an extra AddRef to take the full control
* on the VirtualBox destruction (see FinalRelease()) */
{
/* On failure diring VirtualBox initialization, delete it
* immediately on the current thread by releasing all
* references in order to properly schedule the server
* shutdown. Since the object is fully deleted here, there
* is a chance to fix the error and request a new
* instantiation before the server terminates. However,
* the main reason to maintain the shoutdown delay on
* failure is to let the front-end completely fetch error
* info from a server-side IVirtualBoxErrorInfo object. */
}
else
{
/* On success, make sure the previous timer is stopped to
* cancel a scheduled server termination (if any). */
}
}
else
{
}
}
else
{
LogFlowFunc(("Using existing VirtualBox object...\n"));
if (count == 2)
{
LogFlowFunc(("Another client has requested a reference to VirtualBox, canceling detruction...\n"));
/* make sure the previous timer is stopped */
}
}
return rv;
}
private:
/* Don't be confused that sInstance is of the *ClassFactory type. This is
* actually a singleton instance (*ClassFactory inherits the singleton
* class; we combined them just for "simplicity" and used "static" for
* factory methods. *ClassFactory here is necessary for a couple of extra
* methods. */
static VirtualBoxClassFactory *sInstance;
static RTCRITSECT sLock;
};
////////////////////////////////////////////////////////////////////////////////
/**
* Enhanced module component information structure.
*
* nsModuleComponentInfo lacks the factory construction callback, here we add
* it. This callback is called by NS_NewGenericFactoryEx() after a
* nsGenericFactory instance is successfully created.
*/
{
nsModuleComponentInfoEx(int) {}
const char* aDescription,
const char* aContractID,
{
}
/** (optional) Factory Construction Callback */
};
////////////////////////////////////////////////////////////////////////////////
static const nsModuleComponentInfoEx components[] =
{
"VirtualBox component",
VirtualBoxConstructor, // constructor funcion
NULL, // registration function
NULL, // deregistration function
NULL, // language helper
0, // flags
)
};
/////////////////////////////////////////////////////////////////////////////
/**
* Extends NS_NewGenericFactory() by immediately calling
* nsModuleComponentInfoEx::mFactoryConstructor before returning to the
* caller.
*/
const nsModuleComponentInfoEx *info)
{
{
NS_RELEASE(*result);
}
return rv;
}
/////////////////////////////////////////////////////////////////////////////
/**
* Helper function to register self components upon start-up
* of the out-of-proc server.
*/
static nsresult
const nsModuleComponentInfoEx *aComponents,
{
{
/* skip components w/o a constructor */
if (!info->mConstructor)
continue;
/* create a new generic factory for a component and register it */
if (NS_SUCCEEDED(rc))
{
factory);
}
}
return rc;
}
/////////////////////////////////////////////////////////////////////////////
static const char *g_pszPidFile = NULL;
class ForceQuitEvent : public MyEvent
{
void *handler()
{
LogFlowFunc(("\n"));
if (g_pszPidFile)
return NULL;
}
};
static void signal_handler(int /* sig */)
{
if (gEventQ && gKeepRunning)
{
/* post a quit event to the queue */
}
}
{
/*
* Initialize the VBox runtime without loading
* the support driver
*/
RTR3Init();
static const RTGETOPTDEF s_aOptions[] =
{
};
bool fDaemonize = false;
int daemon_pipe_wr = -1;
int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
{
switch (vrc)
{
case 'a':
{
/* --automate mode means we are started by XPCOM on
* demand. Daemonize ourselves and activate
* auto-shutdown. */
gAutoShutdown = true;
fDaemonize = true;
break;
}
/* Used together with '-P', see below. Internal use only. */
case 'A':
{
gAutoShutdown = true;
break;
}
case 'd':
{
fDaemonize = true;
break;
}
case 'p':
{
break;
}
/* This is just an internal hack for passing the pipe write fd
along to the final child. Internal use only. */
case 'P':
{
break;
}
case 'h':
{
RTPrintf("no help\n");
return 1;
}
case 'V':
{
return 0;
}
default:
}
}
#ifdef RT_OS_OS2 /** @todo There is almost no need to make a special case of OS/2 here. Just the execv call needs to be told to create a background process... */
/* nothing to do here, the process is supposed to be already
* started daemonized when it is necessary */
#else // !RT_OS_OS2
if (fDaemonize)
{
/* create a pipe for communication between child and parent */
if (pipe(daemon_pipe_fds) < 0)
{
return 1;
}
int daemon_pipe_rd = daemon_pipe_fds[0];
if (childpid == -1)
{
return 1;
}
if (childpid != 0)
{
/* we're the parent process */
bool fSuccess = false;
/* close the writing end of the pipe */
/* try to read a message from the pipe */
{
fSuccess = true;
else
}
else
RTMsgError("0 bytes read from child process");
/* close the reading end of the pipe as well and exit */
return fSuccess ? 0 : 1;
}
/* we're the child process */
/* Create a new SID for the child process */
if (sid < 0)
{
return 1;
}
/* Need to do another for to get rid of the session leader status.
* Otherwise any accidentally opened tty will automatically become a
* controlling tty for the daemon process. */
if (childpid == -1)
{
return 1;
}
if (childpid != 0)
{
/* we're the parent process, just a dummy so terminate now */
exit(0);
}
/* Close all file handles except for the write end of the pipe. */
int fdMax;
else
fdMax = 1024;
if (fd != daemon_pipe_wr)
/* Make sure the pipe isn't any of the standard handles. */
if (daemon_pipe_wr <= 2)
{
{
daemon_pipe_wr = 3;
}
}
/*
* On leopard we're no longer allowed to use some of the core API's
* after forking - this will cause us to hit an int3.
* So, we'll have to execv VBoxSVC once again and hand it the pipe
* and all other relevant options.
*
* On FreeBSD the fork approach doesn't work. The child fails
* during initialization of XPCOM for some unknown reason and
* exits making it impossible to autostart VBoxSVC when starting
* a frontend (debugger and strace don't contain any useful info).
*/
unsigned i = 0;
apszArgs[i++] = "--pipe";
char szPipeArg[32];
if (g_pszPidFile)
{
apszArgs[i++] = "--pidfile";
apszArgs[i++] = g_pszPidFile;
}
if (gAutoShutdown)
apszArgs[i++] = "--auto-shutdown";
exit(126);
}
#endif // !RT_OS_OS2
do
{
{
break;
}
{
break;
}
{
break;
}
/* get the main thread's event queue (afaik, the dconnect service always
* gets created upon XPCOM startup, so it will use the main (this)
* thread's event queue to receive IPC events) */
{
break;
}
{
break;
}
{
LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
"Is another server already running?\n",
break;
}
{
/* setup signal handling to convert some signals to a quit event */
}
{
char szBuf[80];
int iSize;
VBOX_PRODUCT" XPCOM Server Version "
for (int i = iSize; i > 0; i--)
putchar('*');
"All rights reserved.\n");
#ifdef DEBUG
RTPrintf("Debug version.\n");
#endif
}
if (daemon_pipe_wr >= 0)
{
RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
/* now we're ready, signal the parent process */
}
else
RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
if (g_pszPidFile)
{
vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
if (RT_SUCCESS(vrc))
{
char szBuf[32];
const char *lf = "\n";
}
}
// Increase the file table size to 10240 or as high as possible.
{
{
}
}
else
while (gKeepRunning)
{
}
/* stop accepting new events. Clients that happen to resolve our
* name and issue a CreateInstance() request after this point will
* get NS_ERROR_ABORT once we hande the remaining messages. As a
* result, they should try to start a new server process. */
/* unregister ourselves. After this point, clients will start a new
* process because they won't be able to resolve the server name.*/
/* process any remaining events. These events may include
* CreateInstance() requests received right before we called
* StopAcceptingEvents() above. We will detect this case below,
* restore gKeepRunning and continue to serve. */
RTPrintf("Terminated event loop.\n");
}
while (0); // this scopes the nsCOMPtrs
/* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
LogFlowFunc(("Calling com::Shutdown()...\n"));
RTPrintf("XPCOM server has shutdown.\n");
if (g_pszPidFile)
/* close writing end of the pipe as well */
if (daemon_pipe_wr >= 0)
return 0;
}