server.cpp revision c12e254c1838a1b167dd65cf40b90067f136d8ca
/* $Id$ */
/** @file
* XPCOM server process (VBoxSVC) start point.
*/
/*
* Copyright (C) 2006-2011 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 "prio.h"
#include "prproces.h"
#include "server.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 "ApplianceImpl.h"
#include "AudioAdapterImpl.h"
#include "BandwidthControlImpl.h"
#include "BandwidthGroupImpl.h"
#include "DHCPServerRunner.h"
#include "DHCPServerImpl.h"
#include "GuestOSTypeImpl.h"
#include "HostImpl.h"
#include "HostNetworkInterfaceImpl.h"
#include "MachineImpl.h"
#include "MediumFormatImpl.h"
#include "MediumImpl.h"
#include "NATEngineImpl.h"
#include "NetworkAdapterImpl.h"
#include "ParallelPortImpl.h"
#include "ProgressCombinedImpl.h"
#include "ProgressProxyImpl.h"
#include "SerialPortImpl.h"
#include "SharedFolderImpl.h"
#include "SnapshotImpl.h"
#include "StorageControllerImpl.h"
#include "SystemPropertiesImpl.h"
#include "USBControllerImpl.h"
#include "VFSExplorerImpl.h"
#include "VirtualBoxImpl.h"
#include "VRDEServerImpl.h"
#ifdef VBOX_WITH_USB
# include "HostUSBDeviceImpl.h"
# include "USBDeviceFilterImpl.h"
# include "USBDeviceImpl.h"
#endif
#ifdef VBOX_WITH_EXTPACK
# include "ExtPackManagerImpl.h"
#endif
/* implement nsISupports parts of our objects with support for nsIClassInfo */
#ifdef VBOX_WITH_USB
#endif
#ifdef VBOX_WITH_RESOURCE_USAGE_API
#endif /* VBOX_WITH_RESOURCE_USAGE_API */
#ifdef VBOX_WITH_EXTPACK
#endif
////////////////////////////////////////////////////////////////////////////////
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 already. */
}
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 failed 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 shutdown 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 destruction...\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 straight after a nsGenericFactory instance is
* successfully created in RegisterSelfComponents.
*/
{
/** standard module component information */
/** (optional) Factory Construction Callback */
};
/////////////////////////////////////////////////////////////////////////////
/**
* Helper function to register self components upon start-up
* of the out-of-proc server.
*/
static nsresult
{
{
/* skip components w/o a constructor */
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)
{
{
if (gAllowSigUsrQuit)
{
}
/* else do nothing */
}
else
{
/* post a force quit event to the queue */
}
}
}
static nsresult vboxsvcSpawnDaemonByReExec(const char *pszPath, bool fAutoShutdown, const char *pszPidFile)
{
unsigned args_index = 0;
// The ugly casts are necessary because the PR_CreateProcessDetached has
// a const array of writable strings as a parameter. It won't write. */
if (fAutoShutdown)
if (pszPidFile)
{
}
args[args_index++] = 0;
// Use a pipe to determine when the daemon process is in the position
// to actually process requests. The daemon will write "READY" to the pipe.
goto end;
attr = PR_NewProcessAttr();
if (!attr)
goto end;
goto end;
if (!devNull)
goto end;
goto end;
// Close the child end of the pipe to make it the only owner of the
// file descriptor, so that unexpected closing can be detected.
char msg[10];
goto end;
end:
if (readable)
if (writable)
if (attr)
return rv;
}
{
/*
* Initialize the VBox runtime without loading
* the support driver
*/
RTR3Init();
static const RTGETOPTDEF s_aOptions[] =
{
};
const char *pszLogFile = NULL;
bool fDaemonize = false;
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;
}
/* --auto-shutdown mode means we're already daemonized. */
case 'A':
{
gAutoShutdown = true;
break;
}
case 'd':
{
fDaemonize = true;
break;
}
case 'p':
{
break;
}
case 'F':
break;
case 'R':
break;
case 'S':
break;
case 'I':
break;
case 'h':
{
RTPrintf("no help\n");
return 1;
}
case 'V':
{
return 0;
}
default:
}
}
if (fDaemonize)
{
exit(126);
}
if (!pszLogFile)
{
char szLogFile[RTPATH_MAX];
if (RT_SUCCESS(vrc))
if (RT_SUCCESS(vrc))
}
RTEnvUnset("NSPR_INHERIT_FDS");
const nsModuleComponentInfo VirtualBoxInfo = {
"VirtualBox component",
VirtualBoxConstructor, // constructor function
NULL, // registration function
NULL, // deregistration function
NULL, // language helper
0 // flags
};
{
}
};
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 != nsnull)
{
RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
/* now we're ready, signal the parent process */
/* close writing end of the pipe, its job is done */
}
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 handle 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)
return 0;
}