vboxweb.cpp revision 6bace994141628622511ae44b06facc8e31f24fd
/**
* vboxweb.cpp:
* hand-coded parts of the webservice server. This is linked with the
* generated code in out/.../src/VBox/Main/webservice/methodmaps.cpp
* (and static gSOAP server code) to implement the actual webservice
* server, to which clients can connect.
*
* Copyright (C) 2006-2009 Sun Microsystems, Inc.
*
* 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.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
// vbox headers
#include <VBox/VRDPAuth.h>
#include <iprt/initterm.h>
// workaround for compile problems on gcc 4.1
#ifdef __GNUC__
#endif
// gSOAP headers (must come after vbox includes because it checks for conflicting defs)
#include "soapH.h"
// standard headers
#include <map>
#include <sstream>
#ifdef __GNUC__
#endif
// shared webservice header
#include "vboxweb.h"
// include generated namespaces table
#include "vboxwebsrv.nsmap"
/****************************************************************************
*
* private typedefs
*
****************************************************************************/
/****************************************************************************
*
* Read-only global variables
*
****************************************************************************/
// generated strings in methodmaps.cpp
extern const char *g_pcszISession,
#define DEFAULT_TIMEOUT_SECS 300
#define DEFAULT_TIMEOUT_SECS_STRING "300"
int g_iWatchdogCheckInterval = 5;
bool g_fVerbose = false; // be verbose
#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
bool g_fDaemonize = false; // run in background.
#endif
/****************************************************************************
*
* Writeable global variables
*
****************************************************************************/
// this mutex protects all of the below
ULONG64 g_cManagedObjects = 0;
/****************************************************************************
*
* main
*
****************************************************************************/
static const RTGETOPTDEF g_aOptions[]
= {
#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
#endif
};
void DisplayHelp()
{
RTStrmPrintf(g_pStdErr, "\nUsage: vboxwebsrv [options]\n\nSupported options (default values in brackets):\n");
for (unsigned i = 0;
i < RT_ELEMENTS(g_aOptions);
++i)
{
str += ", -";
str += ":";
const char *pcszDescr = "";
switch (g_aOptions[i].iShort)
{
case 'h':
pcszDescr = "Print this help message and exit.";
break;
#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
case 'b':
pcszDescr = "Run in background (daemon mode).";
break;
#endif
case 'H':
pcszDescr = "The host to bind to (localhost).";
break;
case 'p':
pcszDescr = "The port to bind to (18083).";
break;
case 't':
break;
case 'i':
pcszDescr = "Frequency of timeout checks in seconds (5).";
break;
case 'v':
pcszDescr = "Be verbose.";
break;
case 'F':
pcszDescr = "Name of file to write log to (no file).";
break;
}
}
}
{
if (g_pstrLog)
{
}
}
{
if (soap_check_state(soap))
{
WebLog("Error: soap struct not initialized\n");
return;
}
WebLog("#### SOAP FAULT: %s [%s]\n",
}
/**
* Start up the webservice server. This keeps running and waits
* for incoming SOAP connections.
*
* @param argc
* @param argv[]
* @return
*/
{
int rc;
// intialize runtime
RTR3Init();
"(C) 2005-2009 Sun Microsystems, Inc.\n"
"All rights reserved.\n", VBOX_VERSION_STRING);
int c;
{
switch (c)
{
case 'H':
break;
case 'p':
break;
case 't':
break;
case 'i':
break;
case 'F':
{
if (rc2)
{
exit(2);
}
WebLog("Sun VirtualBox Webservice Version %s\n"
}
break;
case 'h':
DisplayHelp();
exit(0);
break;
case 'v':
g_fVerbose = true;
break;
#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
case 'b':
g_fDaemonize = true;
break;
#endif
case VINF_GETOPT_NOT_OPTION:
return 1;
default:
if (c > 0)
{
if (RT_C_IS_GRAPH(c))
else
}
else if (c == VERR_GETOPT_UNKNOWN_OPTION)
else if (ValueUnion.pDef)
else
exit(1);
break;
}
}
#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
if (g_fDaemonize)
{
NULL);
if (RT_FAILURE(rc))
{
exit(1);
}
}
#endif
{
RTPrintf("ERROR: failed to initialize COM!\n");
return rc;
}
RTPrintf("ERROR: failed to create the VirtualBox object!\n");
else
{
RTPrintf("ERROR: failed to create a session object!\n");
}
{
{
RTPrintf("Most likely, the VirtualBox COM server is not running or failed to start.\n");
}
else
return rc;
}
if (g_iWatchdogTimeoutSecs > 0)
{
// start our watchdog thread
if (RTThreadCreate(&tWatchdog,
NULL,
32*1024,
0,
"Watchdog"))
{
exit(1);
}
}
// set up gSOAP
// avoid EADDRINUSE on bind()
int m, s; // master and slave sockets
g_pcszBindToHost, // host: current machine
g_uBindToPort, // port
g_uBacklog); // backlog = max queue size for requests
if (m < 0)
else
{
WebLog("Socket connection successful: host = %s, port = %u, master socket = %d\n",
m);
for (unsigned long long i = 1;
;
i++)
{
s = soap_accept(&soap);
if (s < 0)
{
break;
}
WebLog("%llu: accepted connection from IP=%lu.%lu.%lu.%lu socket=%d... ",
i,
s);
// enclose the entire RPC call in the sessions lock
// so that the watchdog cannot destroy COM objects
// while the RPC is ongoing
// now process the RPC request (this goes into the
// generated code in methodmaps.cpp with all the COM calls)
{
}
WebLog("Request served\n");
}
}
}
/****************************************************************************
*
* Watchdog thread
*
****************************************************************************/
/**
* Watchdog thread, runs in the background while the webservice is alive.
*
* This gets started by main() and runs in the background to check all sessions
* for whether they have been no requests in a configurable timeout period. In
* that case, the session is automatically logged off.
*/
{
WEBDEBUG(("Watchdog thread started\n"));
while (1)
{
{
if ( tNow
)
{
delete pSession;
}
else
++it;
}
}
WEBDEBUG(("Watchdog thread ending\n"));
return 0;
}
/****************************************************************************
*
* SOAP exceptions
*
****************************************************************************/
/**
* Helper function to raise a SOAP fault. Called by the other helper
* functions, which raise specific SOAP faults.
*
* @param soap
* @param str
* @param extype
* @param ex
*/
int extype,
void *ex)
{
// raise the fault
struct SOAP_ENV__Detail *pDetail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
// without the following, gSOAP crashes miserably when sending out the
// data because it will try to serialize all fields (stupid documentation)
// fill extended info depending on SOAP version
{
}
else
{
}
}
/**
* Raises a SOAP fault that signals that an invalid object was passed.
*
* @param soap
* @param obj
*/
{
/* std::ostringstream ostr;
ostr << std::hex << ex->badObjectID; */
str,
ex);
}
/**
* Return a safe C++ string from the given COM string,
* without crashing if the COM string is empty.
* @param bstr
* @return
*/
{
const char *pcsz;
return pcsz;
return "";
}
/**
* Return a safe C++ string from the given COM UUID,
* without crashing if the UUID is empty.
* @param bstr
* @return
*/
{
const char *pcsz;
return pcsz;
return "";
}
/**
* Raises a SOAP runtime fault.
*
* @param pObj
*/
{
WEBDEBUG((" error, raising SOAP exception\n"));
// allocated our own soap fault struct
// compose descriptive message
str += " (0x";
str += ")";
str,
ex);
}
/****************************************************************************
*
* splitting and merging of object IDs
*
****************************************************************************/
{
uint64_t u = 0;
return u;
}
/**
* Splits a managed object reference (in string form, as
* passed in from a SOAP method call) into two integers for
* session and object IDs, respectively.
*
* @param id
* @param sessid
* @param objid
* @return
*/
{
// 64-bit numbers in hex have 16 digits; hence
// the object-ref string must have 16 + "-" + 16 characters
)
{
char psz[34];
if (pSessid)
if (pObjid)
return true;
}
return false;
}
/**
* Creates a managed object reference (in string form) from
* two integers representing a session and object ID, respectively.
*
* @param sz Buffer with at least 34 bytes space to receive MOR string.
* @param sessid
* @param objid
* @return
*/
void MakeManagedObjectRef(char *sz,
{
}
/****************************************************************************
*
* class WebServiceSession
*
****************************************************************************/
class WebServiceSessionPrivate
{
public:
};
/**
* Constructor for the session object.
*
* Preconditions: Caller must have locked g_mutexSessions.
*
* @param username
* @param password
*/
: _fDestructing(false),
{
_pp = new WebServiceSessionPrivate;
_uSessionID = RTRandU64();
// register this session globally
g_mapSessions[_uSessionID] = this;
}
/**
* Destructor. Cleans up and destroys all contained managed object references on the way.
*
* Preconditions: Caller must have locked g_mutexSessions.
*/
{
// delete us from global map first so we can't be found
// any more while we're cleaning up
// notify ManagedObjectRef destructor so it won't
// remove itself from the maps; this avoids rebalancing
// the map's tree on every delete as well
_fDestructing = true;
// if (_pISession)
// {
// delete _pISession;
// _pISession = NULL;
// }
it,
++it)
{
delete pRef; // this frees the contained ComPtr as well
}
delete _pp;
}
/**
* Authenticate the username and password against an authentification authority.
*
* @return 0 if the user was successfully authenticated, or an error code
* otherwise.
*/
const char *pcszPassword)
{
int rc = VERR_WEB_NOT_AUTHENTICATED;
static bool fAuthLibLoaded = false;
if (!fAuthLibLoaded)
{
// retrieve authentication library from system properties
if (filename == "null")
// authentication disabled, let everyone in:
fAuthLibLoaded = true;
else
{
do
{
if (RT_FAILURE(rc))
{
WEBDEBUG(("%s() Failed to load external authentication library. Error code: %Rrc\n", __FUNCTION__, rc));
break;
}
WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, "VRDPAuth2", rc));
WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, "VRDPAuth", rc));
if (pfnAuthEntry || pfnAuthEntry2)
fAuthLibLoaded = true;
} while (0);
}
}
if (pfnAuthEntry2)
{
if (result == VRDPAuthAccessGranted)
rc = 0;
}
else if (pfnAuthEntry)
{
WEBDEBUG(("%s(): result of VRDPAuth(%s, [%d]): %d\n", __FUNCTION__, pcszUsername, strlen(pcszPassword), result));
if (result == VRDPAuthAccessGranted)
rc = 0;
}
else if (fAuthLibLoaded)
// fAuthLibLoaded = true but both pointers are NULL:
// then the authlib was "null" and auth was disabled
rc = 0;
else
{
WEBDEBUG(("Could not resolve VRDPAuth2 or VRDPAuth entry point"));
}
if (!rc)
{
do
{
// now create the ISession object that this webservice session can use
// (and of which IWebsessionManager::getSessionObject returns a managed object reference)
{
WEBDEBUG(("ERROR: cannot create session object!"));
break;
}
if (g_fVerbose)
{
WEBDEBUG((" * %s: created session object with comptr 0x%lX, MOR = %s\n", __FUNCTION__, p, strMOR.c_str()));
}
} while (0);
}
return rc;
}
/**
* Look up, in this session, whether a ManagedObjectRef has already been
* created for the given COM pointer.
*
* Note how we require that a ComPtr<IUnknown> is passed, which causes a
* queryInterface call when the caller passes in a different type, since
* a ComPtr<IUnknown> will point to something different than a
* ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
* our private hash table, we must search for one too.
*
* Preconditions: Caller must have locked g_mutexSessions.
*
* @param pcu pointer to a COM object.
* @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
*/
{
// WEBDEBUG((" %s: looking up 0x%lX\n", __FUNCTION__, ulp));
{
}
else
return pRef;
}
/**
* Static method which attempts to find the session for which the given managed
* object reference was created, by splitting the reference into the session and
* object IDs and then looking up the session object for that session ID.
*
* Preconditions: Caller must have locked g_mutexSessions.
*
* @param id Managed object reference (with combined session and object IDs).
* @return
*/
{
if (SplitManagedObjectRef(id,
&sessid,
NULL))
{
}
return pSession;
}
/**
*
*/
{
return _pISession->toWSDL();
}
/**
* Touches the webservice session to prevent it from timing out.
*
* Each webservice session has an internal timestamp that records
* the last request made to it from the client that started it.
* If no request was made within a configurable timeframe, then
* the client is logged off automatically,
* by calling IWebsessionManager::logoff()
*/
void WebServiceSession::touch()
{
}
/**
*
*/
void WebServiceSession::DumpRefs()
{
WEBDEBUG((" dumping object refs:\n"));
for (;
++iter)
{
}
}
/****************************************************************************
*
* class ManagedObjectRef
*
****************************************************************************/
/**
* Constructor, which assigns a unique ID to this managed object
* reference and stores it two global hashs:
*
* a) G_mapManagedObjectsById, which maps ManagedObjectID's to
* instances of this class; this hash is then used by the
* findObjectFromRef() template function in vboxweb.h
* to quickly retrieve the COM object from its managed
* object ID (mostly in the context of the method mappers
* in methodmaps.cpp, when a web service client passes in
* a managed object ID);
*
* b) G_mapManagedObjectsByComPtr, which maps COM pointers to
* instances of this class; this hash is used by
* createRefFromObject() to quickly figure out whether an
* instance already exists for a given COM pointer.
*
* This does _not_ check whether another instance already
* exists in the hash. This gets called only from the
* createRefFromObject() template function in vboxweb.h, which
* does perform that check.
*
* Preconditions: Caller must have locked g_mutexSessions.
*
* @param pObj
*/
const char *pcszInterface,
{
_id = ++g_iMaxManagedObjectID;
// and count globally
ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
char sz[34];
WEBDEBUG((" * %s: MOR created for ulp 0x%lX (%s), new ID is %llX; now %lld objects total\n", __FUNCTION__, _ulp, pcszInterface, _id, cTotal));
}
/**
* Destructor; removes the instance from the global hash of
* managed objects.
*
* Preconditions: Caller must have locked g_mutexSessions.
*/
{
WEBDEBUG((" * %s: deleting MOR for ID %llX (%s); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cTotal));
// if we're being destroyed from the session's destructor,
// then that destructor is iterating over the maps, so
// don't remove us there! (data integrity + speed)
if (!_session._fDestructing)
{
}
}
/**
* Converts the ID of this managed object reference to string
* form, for returning with SOAP data or similar.
*
* @return The ID in string form.
*/
{
return _strID;
}
/**
* Static helper method for findObjectFromRef() template that actually
* looks up the object from a given integer ID.
*
* This has been extracted into this non-template function to reduce
* code bloat as we have the actual STL map lookup only in this function.
*
* This also "touches" the timestamp in the session whose ID is encoded
* in the given integer ID, in order to prevent the session from timing
* out.
*
* Preconditions: Caller must have locked g_mutexSessions.
*
* @param strId
* @param iter
* @return
*/
bool fNullAllowed)
{
int rc = 0;
do
{
// allow NULL (== empty string) input reference, which should return a NULL pointer
{
return 0;
}
if (!SplitManagedObjectRef(id,
&sessid,
&objid))
{
break;
}
{
break;
}
// "touch" session to prevent it from timing out
{
break;
}
} while (0);
return rc;
}
/****************************************************************************
*
* interface IManagedObjectRef
*
****************************************************************************/
/**
* This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
* that our WSDL promises to our web service clients. This method returns a
* string describing the interface that this managed object reference
* supports, e.g. "IMachine".
*
* @param soap
* @param req
* @param resp
* @return
*/
{
do {
} while (0);
if (rc)
return SOAP_FAULT;
return SOAP_OK;
}
/**
* This is the hard-coded implementation for the IManagedObjectRef::release()
* that our WSDL promises to our web service clients. This method releases
* a managed object reference and removes it from our stacks.
*
* @param soap
* @param req
* @param resp
* @return
*/
{
do {
{
break;
}
WEBDEBUG((" found reference; deleting!\n"));
delete pRef;
// this removes the object from all stacks; since
// there's a ComPtr<> hidden inside the reference,
// this should also invoke Release() on the COM
// object
} while (0);
if (rc)
return SOAP_FAULT;
return SOAP_OK;
}
/****************************************************************************
*
* interface IWebsessionManager
*
****************************************************************************/
/**
* Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
* COM API, this is the first method that a webservice client must call before the
* webservice will do anything useful.
*
* This returns a managed object reference to the global IVirtualBox object; into this
* reference a session ID is encoded which remains constant with all managed object
* references returned by other methods.
*
* This also creates an instance of ISession, which is stored internally with the
* webservice session and can be retrieved with IWebsessionManager::getSessionObject
* (__vbox__IWebsessionManager_USCOREgetSessionObject). In order for the
* VirtualBox web service to do anything useful, one usually needs both a
* VirtualBox and an ISession object, for which these two methods are designed.
*
* When the webservice client is done, it should call IWebsessionManager::logoff. This
* will clean up internally (destroy all remaining managed object references and
* related COM objects used internally).
*
* After logon, an internal timeout ensures that if the webservice client does not
* call any methods, after a configurable number of seconds, the webservice will log
* off the client automatically. This is to ensure that the webservice does not
* drown in managed object references and eventually deny service. Still, it is
* a much better solution, both for performance and cleanliness, for the webservice
* client to clean up itself.
*
* Preconditions: Caller must have locked g_mutexSessions.
* Since this gets called from main() like other SOAP method
* implementations, this is ensured.
*
* @param
* @param vbox__IWebsessionManager_USCORElogon
* @param vbox__IWebsessionManager_USCORElogonResponse
* @return
*/
struct soap*,
{
do {
// create new session; the constructor stores the new session
// in the global map automatically
// authenticate the user
{
// in the new session, create a managed object reference (moref) for the
// global VirtualBox object; this encodes the session ID in the moref so
// that it will be implicitly be included in all future requests of this
// webservice client
}
} while (0);
if (rc)
return SOAP_FAULT;
return SOAP_OK;
}
/**
* Returns the ISession object that was created for the webservice client
* on logon.
*
* Preconditions: Caller must have locked g_mutexSessions.
* Since this gets called from main() like other SOAP method
* implementations, this is ensured.
*/
struct soap*,
{
do {
{
}
} while (0);
if (rc)
return SOAP_FAULT;
return SOAP_OK;
}
/**
* hard-coded implementation for IWebsessionManager::logoff.
*
* Preconditions: Caller must have locked g_mutexSessions.
* Since this gets called from main() like other SOAP method
* implementations, this is ensured.
*
* @param
* @param vbox__IWebsessionManager_USCORElogon
* @param vbox__IWebsessionManager_USCORElogonResponse
* @return
*/
struct soap*,
{
do {
{
delete pSession;
// destructor cleans up
}
} while (0);
if (rc)
return SOAP_FAULT;
return SOAP_OK;
}