VirtualBox

source: vbox/trunk/src/VBox/Main/webservice/vboxweb.cpp@ 16120

Last change on this file since 16120 was 16120, checked in by vboxsync, 16 years ago

export webservices to OSE

  • Property filesplitter.c set to Makefile.kmk
  • Property svn:eol-style set to native
File size: 40.7 KB
Line 
1/**
2 * vboxweb.cpp:
3 * hand-coded parts of the webservice server. This is linked with the
4 * generated code in out/.../src/VBox/Main/webservice/methodmaps.cpp
5 * (and static gSOAP server code) to implement the actual webservice
6 * server, to which clients can connect.
7 *
8 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
9 *
10 * Sun Microsystems, Inc. confidential
11 * All rights reserved
12 */
13
14// vbox headers
15#include <VBox/com/com.h>
16#include <VBox/com/string.h>
17#include <VBox/com/Guid.h>
18#include <VBox/com/ErrorInfo.h>
19#include <VBox/com/EventQueue.h>
20#include <VBox/com/VirtualBox.h>
21#include <VBox/err.h>
22#include <VBox/VRDPAuth.h>
23#include <VBox/version.h>
24#include <VBox/log.h>
25
26#include <iprt/lock.h>
27#include <iprt/rand.h>
28#include <iprt/initterm.h>
29#include <iprt/getopt.h>
30#include <iprt/process.h>
31#include <iprt/stream.h>
32#include <iprt/string.h>
33#include <iprt/ldr.h>
34
35// workaround for compile problems on gcc 4.1
36#pragma GCC visibility push(default)
37
38// gSOAP headers (must come after vbox includes because it checks for conflicting defs)
39#include "soapH.h"
40
41// standard headers
42#include <map>
43#include <sstream>
44
45#pragma GCC visibility pop
46
47// shared webservice header
48#include "vboxweb.h"
49
50// include generated namespaces table
51#include "vboxwebsrv.nsmap"
52
53/****************************************************************************
54 *
55 * private typedefs
56 *
57 ****************************************************************************/
58
59typedef std::map<uint64_t, ManagedObjectRef*>
60 ManagedObjectsMapById;
61typedef std::map<uint64_t, ManagedObjectRef*>::iterator
62 ManagedObjectsIteratorById;
63typedef std::map<uintptr_t, ManagedObjectRef*>
64 ManagedObjectsMapByPtr;
65
66typedef std::map<uint64_t, WebServiceSession*>
67 SessionsMap;
68typedef std::map<uint64_t, WebServiceSession*>::iterator
69 SessionsMapIterator;
70
71int fntWatchdog(RTTHREAD ThreadSelf, void *pvUser);
72
73/****************************************************************************
74 *
75 * Read-only global variables
76 *
77 ****************************************************************************/
78
79ComPtr<IVirtualBox> g_pVirtualBox = NULL;
80
81// generated strings in methodmaps.cpp
82extern const char *g_pcszISession,
83 *g_pcszIVirtualBox;
84
85#define DEFAULT_TIMEOUT_SECS 300
86#define DEFAULT_TIMEOUT_SECS_STRING "300"
87
88int g_iWatchdogTimeoutSecs = DEFAULT_TIMEOUT_SECS;
89int g_iWatchdogCheckInterval = 5;
90
91const char *g_pcszBindToHost = NULL; // host; NULL = current machine
92unsigned int g_uBindToPort = 18083; // port
93unsigned int g_uBacklog = 100; // backlog = max queue size for requests
94
95bool g_fVerbose = false; // be verbose
96PRTSTREAM g_pstrLog = NULL;
97
98#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
99bool g_fDaemonize = false; // run in background.
100#endif
101
102/****************************************************************************
103 *
104 * Writeable global variables
105 *
106 ****************************************************************************/
107
108RTLockMtx g_mutexAuthLib;
109
110// this mutex protects all of the below
111RTLockMtx g_mutexSessions;
112
113SessionsMap g_mapSessions;
114ULONG64 g_iMaxManagedObjectID = 0;
115ULONG64 g_cManagedObjects = 0;
116
117/****************************************************************************
118 *
119 * main
120 *
121 ****************************************************************************/
122
123static const RTOPTIONDEF g_aOptions[]
124 = {
125 { "--help", 'h', RTGETOPT_REQ_NOTHING },
126#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
127 { "--background", 'b', RTGETOPT_REQ_NOTHING },
128#endif
129 { "--host", 'H', RTGETOPT_REQ_STRING },
130 { "--port", 'p', RTGETOPT_REQ_UINT32 },
131 { "--timeout", 't', RTGETOPT_REQ_UINT32 },
132 { "--check-interval", 'i', RTGETOPT_REQ_UINT32 },
133 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
134 { "--logfile", 'F', RTGETOPT_REQ_STRING },
135 };
136
137void DisplayHelp()
138{
139 RTStrmPrintf(g_pStdErr, "\nUsage: vboxwebsrv [options]\n\nSupported options (default values in brackets):\n");
140 for (unsigned i = 0;
141 i < RT_ELEMENTS(g_aOptions);
142 ++i)
143 {
144 std::string str(g_aOptions[i].pszLong);
145 str += ", -";
146 str += (char)g_aOptions[i].iShort;
147 str += ":";
148
149 const char *pcszDescr = "";
150
151 switch (g_aOptions[i].iShort)
152 {
153 case 'h':
154 pcszDescr = "Print this help message and exit.";
155 break;
156
157#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
158 case 'b':
159 pcszDescr = "Run in background (daemon mode).";
160 break;
161#endif
162
163 case 'H':
164 pcszDescr = "The host to bind to (localhost).";
165 break;
166
167 case 'p':
168 pcszDescr = "The port to bind to (18083).";
169 break;
170
171 case 't':
172 pcszDescr = "Session timeout in seconds; 0 = disable timeouts (" DEFAULT_TIMEOUT_SECS_STRING ").";
173 break;
174
175 case 'i':
176 pcszDescr = "Frequency of timeout checks in seconds (5).";
177 break;
178
179 case 'v':
180 pcszDescr = "Be verbose.";
181 break;
182
183 case 'F':
184 pcszDescr = "Name of file to write log to (no file).";
185 break;
186 }
187
188 RTStrmPrintf(g_pStdErr, "%-23s%s\n", str.c_str(), pcszDescr);
189 }
190}
191
192void WebLog(const char *pszFormat, ...)
193{
194 va_list args;
195 va_start(args, pszFormat);
196 RTPrintfV(pszFormat, args);
197 va_end(args);
198
199 if (g_pstrLog)
200 {
201 va_list args2;
202 va_start(args2, pszFormat);
203 RTStrmPrintfV(g_pstrLog, pszFormat, args);
204 va_end(args2);
205
206 RTStrmFlush(g_pstrLog);
207 }
208}
209
210void WebLogSoapError(struct soap *soap)
211{
212 if (soap_check_state(soap))
213 {
214 WebLog("Error: soap struct not initialized\n");
215 return;
216 }
217
218 const char *pcszFaultString = *soap_faultstring(soap);
219 const char **ppcszDetail = soap_faultcode(soap);
220 WebLog("#### SOAP FAULT: %s [%s]\n",
221 pcszFaultString ? pcszFaultString : "[no fault string available]",
222 (ppcszDetail && *ppcszDetail) ? *ppcszDetail : "no details available");
223}
224
225
226/**
227 * Start up the webservice server. This keeps running and waits
228 * for incoming SOAP connections.
229 *
230 * @param argc
231 * @param argv[]
232 * @return
233 */
234int main(int argc, char* argv[])
235{
236 int rc;
237
238 RTStrmPrintf(g_pStdErr, "Sun xVM VirtualBox Webservice Version %s\n"
239 "(C) 2005-2009 Sun Microsystems, Inc.\n"
240 "All rights reserved.\n", VBOX_VERSION_STRING);
241
242 // intialize runtime
243 RTR3Init(); /** @todo r=bird: This isn't at top of main(), is it? */
244
245 int c;
246 int i = 1;
247 RTOPTIONUNION ValueUnion;
248 while ((c = RTGetOpt(argc, argv, g_aOptions, RT_ELEMENTS(g_aOptions), &i, &ValueUnion)))
249 {
250 switch (c)
251 {
252 case VERR_GETOPT_UNKNOWN_OPTION:
253 RTStrmPrintf(g_pStdErr, "Unknown option %s\n", argv[i]);
254 exit(1);
255 break;
256
257 case VERR_GETOPT_REQUIRED_ARGUMENT_MISSING:
258 RTStrmPrintf(g_pStdErr, "Option %s requires an argument value\n", ValueUnion.pDef->pszLong);
259 exit(1);
260 break;
261
262 case VERR_GETOPT_INVALID_ARGUMENT_FORMAT:
263 RTStrmPrintf(g_pStdErr, "Argument to option %s has invalid format\n", ValueUnion.pDef->pszLong);
264 exit(1);
265 break;
266
267 default:
268 RTStrmPrintf(g_pStdErr, "RTGetOpt returned %d\n", c);
269 exit(1);
270 break;
271
272 case 'H':
273 g_pcszBindToHost = ValueUnion.psz;
274 break;
275
276 case 'p':
277 g_uBindToPort = ValueUnion.u32;
278 break;
279
280 case 't':
281 g_iWatchdogTimeoutSecs = ValueUnion.u32;
282 break;
283
284 case 'i':
285 g_iWatchdogCheckInterval = ValueUnion.u32;
286 break;
287
288 case 'F':
289 {
290 int rc2 = RTStrmOpen(ValueUnion.psz, "a", &g_pstrLog);
291 if (rc2)
292 {
293 RTPrintf("Error: Cannot open log file \"%s\" for writing, error %d.\n", ValueUnion.psz, rc2);
294 exit(2);
295 }
296
297 WebLog("Opened log file \"%s\"\n", ValueUnion.psz);
298 }
299 break;
300
301 case 'h':
302 DisplayHelp();
303 exit(0);
304 break;
305
306 case 'v':
307 g_fVerbose = true;
308 break;
309
310#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
311 case 'b':
312 g_fDaemonize = true;
313 break;
314#endif
315 }
316 }
317 if (i != argc)
318 {
319 RTStrmPrintf(g_pStdErr, "Unknown option %s\n", argv[i]);
320 exit(1);
321 }
322
323#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
324 if (g_fDaemonize)
325 {
326 rc = RTProcDaemonize(false /* fNoChDir */, false /* fNoClose */,
327 NULL);
328 if (RT_FAILURE(rc))
329 {
330 RTStrmPrintf(g_pStdErr, "vboxwebsrv: failed to daemonize, rc=%Rrc. exiting.\n", rc);
331 exit(1);
332 }
333 }
334#endif
335
336 // intialize COM/XPCOM
337 ComPtr<ISession> session;
338 if ((rc = com::Initialize()))
339 RTStrmPrintf(g_pStdErr, "[!] Failed to initialize COM!\n");
340 else if ((rc = g_pVirtualBox.createLocalObject(CLSID_VirtualBox)))
341 RTStrmPrintf(g_pStdErr, "[!] Failed to create the local VirtualBox object!\n");
342 else if ((rc = session.createInprocObject(CLSID_Session)))
343 RTStrmPrintf(g_pStdErr, "[!] Failed to create the inproc VirtualBox object!\n");
344
345 if (rc)
346 {
347 PRINT_RC_MESSAGE(rc);
348
349 com::ErrorInfo info;
350 if (!info.isFullAvailable() && !info.isBasicAvailable())
351 RTStrmPrintf(g_pStdErr, "[!] Most likely, the VirtualBox COM server is not running or failed to start.\n");
352 else
353 PRINT_ERROR_INFO(info);
354 exit(rc);
355 }
356
357 if (g_iWatchdogTimeoutSecs > 0)
358 {
359 // start our watchdog thread
360 RTTHREAD tWatchdog;
361 if (RTThreadCreate(&tWatchdog,
362 fntWatchdog,
363 NULL,
364 32*1024,
365 RTTHREADTYPE_MAIN_WORKER,
366 0,
367 "Watchdog"))
368 {
369 RTStrmPrintf(g_pStdErr, "[!] Cannot start watchdog thread\n");
370 exit(1);
371 }
372 }
373
374 // set up gSOAP
375 struct soap soap;
376 soap_init(&soap);
377
378 soap.bind_flags |= SO_REUSEADDR;
379 // avoid EADDRINUSE on bind()
380
381 int m, s; // master and slave sockets
382 m = soap_bind(&soap,
383 g_pcszBindToHost, // host: current machine
384 g_uBindToPort, // port
385 g_uBacklog); // backlog = max queue size for requests
386 if (m < 0)
387 WebLogSoapError(&soap);
388 else
389 {
390 WebLog("Socket connection successful: host = %s, port = %u, master socket = %d\n",
391 (g_pcszBindToHost) ? g_pcszBindToHost : "default (localhost)",
392 g_uBindToPort,
393 m);
394
395 for (unsigned long long i = 1;
396 ;
397 i++)
398 {
399 s = soap_accept(&soap);
400 if (s < 0)
401 {
402 WebLogSoapError(&soap);
403 break;
404 }
405
406 WebLog("%llu: accepted connection from IP=%lu.%lu.%lu.%lu socket=%d... ",
407 i,
408 (soap.ip>>24)&0xFF,
409 (soap.ip>>16)&0xFF,
410 (soap.ip>>8)&0xFF,
411 soap.ip&0xFF,
412 s);
413
414 // enclose the entire RPC call in the sessions lock
415 // so that the watchdog cannot destroy COM objects
416 // while the RPC is ongoing
417 RTLock lock(g_mutexSessions);
418 // now process the RPC request (this goes into the
419 // generated code in methodmaps.cpp with all the COM calls)
420 if (soap_serve(&soap) != SOAP_OK)
421 {
422 WebLogSoapError(&soap);
423 }
424 lock.release();
425
426 WebLog("Request served\n");
427
428 soap_destroy(&soap); // clean up class instances
429 soap_end(&soap); // clean up everything and close socket
430 }
431 }
432 soap_done(&soap); // close master socket and detach environment
433
434 com::Shutdown();
435}
436
437/****************************************************************************
438 *
439 * Watchdog thread
440 *
441 ****************************************************************************/
442
443/**
444 * Watchdog thread, runs in the background while the webservice is alive.
445 *
446 * This gets started by main() and runs in the background to check all sessions
447 * for whether they have been no requests in a configurable timeout period. In
448 * that case, the session is automatically logged off.
449 */
450int fntWatchdog(RTTHREAD ThreadSelf, void *pvUser)
451{
452 WEBDEBUG(("Watchdog thread started\n"));
453
454 while (1)
455 {
456 WEBDEBUG(("Watchdog: sleeping %d seconds\n", g_iWatchdogCheckInterval));
457 RTThreadSleep(g_iWatchdogCheckInterval*1000);
458
459 time_t tNow;
460 time(&tNow);
461
462 RTLock lock(g_mutexSessions);
463 WEBDEBUG(("Watchdog: checking %d sessions\n", g_mapSessions.size()));
464
465 SessionsMap::iterator
466 it = g_mapSessions.begin(),
467 itEnd = g_mapSessions.end();
468 while (it != itEnd)
469 {
470 WebServiceSession *pSession = it->second;
471 WEBDEBUG(("Watchdog: tNow: %d, session timestamp: %d\n", tNow, pSession->getLastObjectLookup()));
472 if ( tNow
473 > pSession->getLastObjectLookup() + g_iWatchdogTimeoutSecs
474 )
475 {
476 WEBDEBUG(("Watchdog: Session %llX timed out, deleting\n", pSession->getID()));
477 delete pSession;
478 it = g_mapSessions.begin();
479 }
480 else
481 ++it;
482 }
483 lock.release();
484 }
485
486 WEBDEBUG(("Watchdog thread ending\n"));
487 return 0;
488}
489
490/****************************************************************************
491 *
492 * SOAP exceptions
493 *
494 ****************************************************************************/
495
496/**
497 * Helper function to raise a SOAP fault. Called by the other helper
498 * functions, which raise specific SOAP faults.
499 *
500 * @param soap
501 * @param str
502 * @param extype
503 * @param ex
504 */
505void RaiseSoapFault(struct soap *soap,
506 const std::string &str,
507 int extype,
508 void *ex)
509{
510 // raise the fault
511 soap_sender_fault(soap, str.c_str(), NULL);
512
513 struct SOAP_ENV__Detail *pDetail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
514
515 // without the following, gSOAP crashes miserably when sending out the
516 // data because it will try to serialize all fields (stupid documentation)
517 memset(pDetail, 0, sizeof(struct SOAP_ENV__Detail));
518
519 // fill extended info depending on SOAP version
520 if (soap->version == 2) // SOAP 1.2 is used
521 {
522 soap->fault->SOAP_ENV__Detail = pDetail;
523 soap->fault->SOAP_ENV__Detail->__type = extype;
524 soap->fault->SOAP_ENV__Detail->fault = ex;
525 soap->fault->SOAP_ENV__Detail->__any = NULL; // no other XML data
526 }
527 else
528 {
529 soap->fault->detail = pDetail;
530 soap->fault->detail->__type = extype;
531 soap->fault->detail->fault = ex;
532 soap->fault->detail->__any = NULL; // no other XML data
533 }
534}
535
536/**
537 * Raises a SOAP fault that signals that an invalid object was passed.
538 *
539 * @param soap
540 * @param obj
541 */
542void RaiseSoapInvalidObjectFault(struct soap *soap,
543 WSDLT_ID obj)
544{
545 _vbox__InvalidObjectFault *ex = soap_new__vbox__InvalidObjectFault(soap, 1);
546 ex->badObjectID = obj;
547
548 /* std::ostringstream ostr;
549 ostr << std::hex << ex->badObjectID; */
550
551 std::string str("VirtualBox error: ");
552 str += "Invalid managed object reference \"" + obj + "\"";
553
554 RaiseSoapFault(soap,
555 str,
556 SOAP_TYPE__vbox__InvalidObjectFault,
557 ex);
558}
559
560/**
561 * Return a safe C++ string from the given COM string,
562 * without crashing if the COM string is empty.
563 * @param bstr
564 * @return
565 */
566std::string ConvertComString(const com::Bstr &bstr)
567{
568 com::Utf8Str ustr(bstr);
569 const char *pcsz;
570 if ((pcsz = ustr.raw()))
571 return pcsz;
572 return "";
573}
574
575/**
576 * Return a safe C++ string from the given COM UUID,
577 * without crashing if the UUID is empty.
578 * @param bstr
579 * @return
580 */
581std::string ConvertComString(const com::Guid &bstr)
582{
583 com::Utf8Str ustr(bstr);
584 const char *pcsz;
585 if ((pcsz = ustr.raw()))
586 return pcsz;
587 return "";
588}
589
590/**
591 * Raises a SOAP runtime fault.
592 *
593 * @param pObj
594 */
595void RaiseSoapRuntimeFault(struct soap *soap,
596 HRESULT apirc,
597 IUnknown *pObj)
598{
599 com::ErrorInfo info(pObj);
600
601 WEBDEBUG((" error, raising SOAP exception\n"));
602
603 RTStrmPrintf(g_pStdErr, "API return code: 0x%08X (%Rhrc)\n", apirc, apirc);
604 RTStrmPrintf(g_pStdErr, "COM error info result code: 0x%lX\n", info.getResultCode());
605 RTStrmPrintf(g_pStdErr, "COM error info text: %ls\n", info.getText().raw());
606
607 // allocated our own soap fault struct
608 _vbox__RuntimeFault *ex = soap_new__vbox__RuntimeFault(soap, 1);
609 ex->resultCode = info.getResultCode();
610 ex->text = ConvertComString(info.getText());
611 ex->component = ConvertComString(info.getComponent());
612 ex->interfaceID = ConvertComString(info.getInterfaceID());
613
614 // compose descriptive message
615 std::ostringstream ostr;
616 ostr << std::hex << ex->resultCode;
617
618 std::string str("VirtualBox error: ");
619 str += ex->text;
620 str += " (0x";
621 str += ostr.str();
622 str += ")";
623
624 RaiseSoapFault(soap,
625 str,
626 SOAP_TYPE__vbox__RuntimeFault,
627 ex);
628}
629
630/****************************************************************************
631 *
632 * splitting and merging of object IDs
633 *
634 ****************************************************************************/
635
636uint64_t str2ulonglong(const char *pcsz)
637{
638 uint64_t u = 0;
639 RTStrToUInt64Full(pcsz, 16, &u);
640 return u;
641}
642
643/**
644 * Splits a managed object reference (in string form, as
645 * passed in from a SOAP method call) into two integers for
646 * session and object IDs, respectively.
647 *
648 * @param id
649 * @param sessid
650 * @param objid
651 * @return
652 */
653bool SplitManagedObjectRef(const WSDLT_ID &id,
654 uint64_t *pSessid,
655 uint64_t *pObjid)
656{
657 // 64-bit numbers in hex have 16 digits; hence
658 // the object-ref string must have 16 + "-" + 16 characters
659 std::string str;
660 if ( (id.length() == 33)
661 && (id[16] == '-')
662 )
663 {
664 char psz[34];
665 memcpy(psz, id.c_str(), 34);
666 psz[16] = '\0';
667 if (pSessid)
668 *pSessid = str2ulonglong(psz);
669 if (pObjid)
670 *pObjid = str2ulonglong(psz + 17);
671 return true;
672 }
673
674 return false;
675}
676
677/**
678 * Creates a managed object reference (in string form) from
679 * two integers representing a session and object ID, respectively.
680 *
681 * @param id
682 * @param sessid
683 * @param objid
684 * @return
685 */
686WSDLT_ID MakeManagedObjectRef(uint64_t &sessid,
687 uint64_t &objid)
688{
689 char sz[34];
690 RTStrFormatNumber(sz, sessid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
691 sz[16] = '-';
692 RTStrFormatNumber(sz + 17, objid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
693 return sz;
694}
695
696/****************************************************************************
697 *
698 * class WebServiceSession
699 *
700 ****************************************************************************/
701
702class WebServiceSessionPrivate
703{
704 public:
705 ManagedObjectsMapById _mapManagedObjectsById;
706 ManagedObjectsMapByPtr _mapManagedObjectsByPtr;
707};
708
709/**
710 * Constructor for the session object.
711 *
712 * Preconditions: Caller must have locked g_mutexSessions.
713 *
714 * @param username
715 * @param password
716 */
717WebServiceSession::WebServiceSession()
718 : _fDestructing(false),
719 _pISession(NULL),
720 _tLastObjectLookup(0)
721{
722 _pp = new WebServiceSessionPrivate;
723 _uSessionID = RTRandU64();
724
725 // register this session globally
726 g_mapSessions[_uSessionID] = this;
727}
728
729/**
730 * Destructor. Cleans up and destroys all contained managed object references on the way.
731 *
732 * Preconditions: Caller must have locked g_mutexSessions.
733 */
734WebServiceSession::~WebServiceSession()
735{
736 // delete us from global map first so we can't be found
737 // any more while we're cleaning up
738 g_mapSessions.erase(_uSessionID);
739
740 // notify ManagedObjectRef destructor so it won't
741 // remove itself from the maps; this avoids rebalancing
742 // the map's tree on every delete as well
743 _fDestructing = true;
744
745 // if (_pISession)
746 // {
747 // delete _pISession;
748 // _pISession = NULL;
749 // }
750
751 ManagedObjectsMapById::iterator
752 it,
753 end = _pp->_mapManagedObjectsById.end();
754 for (it = _pp->_mapManagedObjectsById.begin();
755 it != end;
756 ++it)
757 {
758 ManagedObjectRef *pRef = it->second;
759 delete pRef; // this frees the contained ComPtr as well
760 }
761
762 delete _pp;
763}
764
765/**
766 * Authenticate the username and password against an authentification authority.
767 *
768 * @return 0 if the user was successfully authenticated, or an error code
769 * otherwise.
770 */
771
772int WebServiceSession::authenticate(const char *pcszUsername,
773 const char *pcszPassword)
774{
775 int rc = VERR_WEB_NOT_AUTHENTICATED;
776
777 RTLock lock(g_mutexAuthLib);
778
779 static bool fAuthLibLoaded = false;
780 static PVRDPAUTHENTRY pfnAuthEntry = NULL;
781 static PVRDPAUTHENTRY2 pfnAuthEntry2 = NULL;
782
783 if (!fAuthLibLoaded)
784 {
785 // retrieve authentication library from system properties
786 ComPtr<ISystemProperties> systemProperties;
787 g_pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
788
789 com::Bstr authLibrary;
790 systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
791 com::Utf8Str filename = authLibrary;
792
793 WEBDEBUG(("external authentication library is '%ls'\n", authLibrary.raw()));
794
795 if (filename == "null")
796 // authentication disabled, let everyone in:
797 fAuthLibLoaded = true;
798 else
799 {
800 RTLDRMOD hlibAuth = 0;
801 do
802 {
803 rc = RTLdrLoad(filename.raw(), &hlibAuth);
804 if (RT_FAILURE(rc))
805 {
806 WEBDEBUG(("%s() Failed to load external authentication library. Error code: %Rrc\n", __FUNCTION__, rc));
807 break;
808 }
809
810 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, "VRDPAuth2", (void**)&pfnAuthEntry2)))
811 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, "VRDPAuth2", rc));
812
813 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, "VRDPAuth", (void**)&pfnAuthEntry)))
814 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, "VRDPAuth", rc));
815
816 if (pfnAuthEntry || pfnAuthEntry2)
817 fAuthLibLoaded = true;
818
819 } while (0);
820 }
821 }
822
823 rc = VERR_WEB_NOT_AUTHENTICATED;
824 VRDPAuthResult result;
825 if (pfnAuthEntry2)
826 {
827 result = pfnAuthEntry2(NULL, VRDPAuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
828 WEBDEBUG(("%s(): result of VRDPAuth2(): %d\n", __FUNCTION__, result));
829 if (result == VRDPAuthAccessGranted)
830 rc = 0;
831 }
832 else if (pfnAuthEntry)
833 {
834 result = pfnAuthEntry(NULL, VRDPAuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
835 WEBDEBUG(("%s(): result of VRDPAuth(%s, [%d]): %d\n", __FUNCTION__, pcszUsername, strlen(pcszPassword), result));
836 if (result == VRDPAuthAccessGranted)
837 rc = 0;
838 }
839 else if (fAuthLibLoaded)
840 // fAuthLibLoaded = true but both pointers are NULL:
841 // then the authlib was "null" and auth was disabled
842 rc = 0;
843 else
844 {
845 WEBDEBUG(("Could not resolve VRDPAuth2 or VRDPAuth entry point"));
846 }
847
848 if (!rc)
849 {
850 do
851 {
852 // now create the ISession object that this webservice session can use
853 // (and of which IWebsessionManager::getSessionObject returns a managed object reference)
854 ComPtr<ISession> session;
855 CHECK_RC_BREAK(session.createInprocObject(CLSID_Session));
856
857 _pISession = new ManagedObjectRef(*this, g_pcszISession, session);
858
859 if (g_fVerbose)
860 {
861 ISession *p = session;
862 std::string strMOR = _pISession->toWSDL();
863 WEBDEBUG((" * %s: created session object with comptr 0x%lX, MOR = %s\n", __FUNCTION__, p, strMOR.c_str()));
864 }
865 } while (0);
866 }
867
868 return rc;
869}
870
871/**
872 * Look up, in this session, whether a ManagedObjectRef has already been
873 * created for the given COM pointer.
874 *
875 * Note how we require that a ComPtr<IUnknown> is passed, which causes a
876 * queryInterface call when the caller passes in a different type, since
877 * a ComPtr<IUnknown> will point to something different than a
878 * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
879 * our private hash table, we must search for one too.
880 *
881 * Preconditions: Caller must have locked g_mutexSessions.
882 *
883 * @param pcu pointer to a COM object.
884 * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
885 */
886ManagedObjectRef* WebServiceSession::findRefFromPtr(const ComPtr<IUnknown> &pcu)
887{
888 IUnknown *p = pcu;
889 uintptr_t ulp = (uintptr_t)p;
890 ManagedObjectRef *pRef;
891 // WEBDEBUG((" %s: looking up 0x%lX\n", __FUNCTION__, ulp));
892 ManagedObjectsMapByPtr::iterator it = _pp->_mapManagedObjectsByPtr.find(ulp);
893 if (it != _pp->_mapManagedObjectsByPtr.end())
894 {
895 pRef = it->second;
896 WSDLT_ID id = pRef->toWSDL();
897 WEBDEBUG((" %s: found existing ref %s for COM obj 0x%lX\n", __FUNCTION__, id.c_str(), ulp));
898 }
899 else
900 pRef = NULL;
901 return pRef;
902}
903
904/**
905 * Static method which attempts to find the session for which the given managed
906 * object reference was created, by splitting the reference into the session and
907 * object IDs and then looking up the session object for that session ID.
908 *
909 * Preconditions: Caller must have locked g_mutexSessions.
910 *
911 * @param id Managed object reference (with combined session and object IDs).
912 * @return
913 */
914WebServiceSession* WebServiceSession::findSessionFromRef(const WSDLT_ID &id)
915{
916 WebServiceSession *pSession = NULL;
917 uint64_t sessid;
918 if (SplitManagedObjectRef(id,
919 &sessid,
920 NULL))
921 {
922 SessionsMapIterator it = g_mapSessions.find(sessid);
923 if (it != g_mapSessions.end())
924 pSession = it->second;
925 }
926 return pSession;
927}
928
929/**
930 *
931 */
932WSDLT_ID WebServiceSession::getSessionObject() const
933{
934 return _pISession->toWSDL();
935}
936
937/**
938 * Touches the webservice session to prevent it from timing out.
939 *
940 * Each webservice session has an internal timestamp that records
941 * the last request made to it from the client that started it.
942 * If no request was made within a configurable timeframe, then
943 * the client is logged off automatically,
944 * by calling IWebsessionManager::logoff()
945 */
946void WebServiceSession::touch()
947{
948 time(&_tLastObjectLookup);
949}
950
951/**
952 *
953 */
954void WebServiceSession::DumpRefs()
955{
956 WEBDEBUG((" dumping object refs:\n"));
957 ManagedObjectsIteratorById
958 iter = _pp->_mapManagedObjectsById.begin(),
959 end = _pp->_mapManagedObjectsById.end();
960 for (;
961 iter != end;
962 ++iter)
963 {
964 ManagedObjectRef *pRef = iter->second;
965 uint64_t id = pRef->getID();
966 void *p = pRef->getComPtr();
967 WEBDEBUG((" objid %llX: comptr 0x%lX\n", id, p));
968 }
969}
970
971/****************************************************************************
972 *
973 * class ManagedObjectRef
974 *
975 ****************************************************************************/
976
977/**
978 * Constructor, which assigns a unique ID to this managed object
979 * reference and stores it two global hashs:
980 *
981 * a) G_mapManagedObjectsById, which maps ManagedObjectID's to
982 * instances of this class; this hash is then used by the
983 * findObjectFromRef() template function in vboxweb.h
984 * to quickly retrieve the COM object from its managed
985 * object ID (mostly in the context of the method mappers
986 * in methodmaps.cpp, when a web service client passes in
987 * a managed object ID);
988 *
989 * b) G_mapManagedObjectsByComPtr, which maps COM pointers to
990 * instances of this class; this hash is used by
991 * createRefFromObject() to quickly figure out whether an
992 * instance already exists for a given COM pointer.
993 *
994 * This does _not_ check whether another instance already
995 * exists in the hash. This gets called only from the
996 * createRefFromObject() template function in vboxweb.h, which
997 * does perform that check.
998 *
999 * Preconditions: Caller must have locked g_mutexSessions.
1000 *
1001 * @param pObj
1002 */
1003ManagedObjectRef::ManagedObjectRef(WebServiceSession &session,
1004 const char *pcszInterface,
1005 const ComPtr<IUnknown> &pc)
1006 : _session(session),
1007 _pObj(pc),
1008 _pcszInterface(pcszInterface)
1009{
1010 ComPtr<IUnknown> pcUnknown(pc);
1011 _ulp = (uintptr_t)(IUnknown*)pcUnknown;
1012
1013 _id = ++g_iMaxManagedObjectID;
1014 // and count globally
1015 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
1016
1017 _strID = MakeManagedObjectRef(session._uSessionID, _id);
1018
1019 session._pp->_mapManagedObjectsById[_id] = this;
1020 session._pp->_mapManagedObjectsByPtr[_ulp] = this;
1021
1022 session.touch();
1023
1024 WEBDEBUG((" * %s: MOR created for ulp 0x%lX (%s), new ID is %llX; now %lld objects total\n", __FUNCTION__, _ulp, pcszInterface, _id, cTotal));
1025}
1026
1027/**
1028 * Destructor; removes the instance from the global hash of
1029 * managed objects.
1030 *
1031 * Preconditions: Caller must have locked g_mutexSessions.
1032 */
1033ManagedObjectRef::~ManagedObjectRef()
1034{
1035 ULONG64 cTotal = --g_cManagedObjects;
1036
1037 WEBDEBUG((" * %s: deleting MOR for ID %llX (%s); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cTotal));
1038
1039 // if we're being destroyed from the session's destructor,
1040 // then that destructor is iterating over the maps, so
1041 // don't remove us there! (data integrity + speed)
1042 if (!_session._fDestructing)
1043 {
1044 WEBDEBUG((" * %s: removing from session maps\n", __FUNCTION__));
1045 _session._pp->_mapManagedObjectsById.erase(_id);
1046 if (_session._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
1047 WEBDEBUG((" WARNING: could not find %llX in _mapManagedObjectsByPtr\n", _ulp));
1048 }
1049}
1050
1051/**
1052 * Converts the ID of this managed object reference to string
1053 * form, for returning with SOAP data or similar.
1054 *
1055 * @return The ID in string form.
1056 */
1057WSDLT_ID ManagedObjectRef::toWSDL() const
1058{
1059 return _strID;
1060}
1061
1062/**
1063 * Static helper method for findObjectFromRef() template that actually
1064 * looks up the object from a given integer ID.
1065 *
1066 * This has been extracted into this non-template function to reduce
1067 * code bloat as we have the actual STL map lookup only in this function.
1068 *
1069 * This also "touches" the timestamp in the session whose ID is encoded
1070 * in the given integer ID, in order to prevent the session from timing
1071 * out.
1072 *
1073 * Preconditions: Caller must have locked g_mutexSessions.
1074 *
1075 * @param strId
1076 * @param iter
1077 * @return
1078 */
1079int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
1080 ManagedObjectRef **pRef)
1081{
1082 int rc = 0;
1083
1084 do
1085 {
1086 uint64_t sessid;
1087 uint64_t objid;
1088 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
1089 if (!SplitManagedObjectRef(id,
1090 &sessid,
1091 &objid))
1092 {
1093 rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
1094 break;
1095 }
1096
1097 WEBDEBUG((" %s(): sessid %llX, objid %llX\n", __FUNCTION__, sessid, objid));
1098 SessionsMapIterator it = g_mapSessions.find(sessid);
1099 if (it == g_mapSessions.end())
1100 {
1101 WEBDEBUG((" %s: cannot find session for objref %s\n", __FUNCTION__, id.c_str()));
1102 rc = VERR_WEB_INVALID_SESSION_ID;
1103 break;
1104 }
1105
1106 WebServiceSession *pSess = it->second;
1107 // "touch" session to prevent it from timing out
1108 pSess->touch();
1109
1110 ManagedObjectsIteratorById iter = pSess->_pp->_mapManagedObjectsById.find(objid);
1111 if (iter == pSess->_pp->_mapManagedObjectsById.end())
1112 {
1113 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
1114 rc = VERR_WEB_INVALID_OBJECT_ID;
1115 break;
1116 }
1117
1118 *pRef = iter->second;
1119
1120 } while (0);
1121
1122 return rc;
1123}
1124
1125/****************************************************************************
1126 *
1127 * interface IManagedObjectRef
1128 *
1129 ****************************************************************************/
1130
1131/**
1132 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
1133 * that our WSDL promises to our web service clients. This method returns a
1134 * string describing the interface that this managed object reference
1135 * supports, e.g. "IMachine".
1136 *
1137 * @param soap
1138 * @param req
1139 * @param resp
1140 * @return
1141 */
1142int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
1143 struct soap *soap,
1144 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
1145 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
1146{
1147 HRESULT rc = SOAP_OK;
1148 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1149
1150 do {
1151 ManagedObjectRef *pRef;
1152 if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef))
1153 resp->returnval = pRef->getInterfaceName();
1154
1155 } while (0);
1156
1157 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1158 if (rc)
1159 return SOAP_FAULT;
1160 return SOAP_OK;
1161}
1162
1163/**
1164 * This is the hard-coded implementation for the IManagedObjectRef::release()
1165 * that our WSDL promises to our web service clients. This method releases
1166 * a managed object reference and removes it from our stacks.
1167 *
1168 * @param soap
1169 * @param req
1170 * @param resp
1171 * @return
1172 */
1173int __vbox__IManagedObjectRef_USCORErelease(
1174 struct soap *soap,
1175 _vbox__IManagedObjectRef_USCORErelease *req,
1176 _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
1177{
1178 HRESULT rc = SOAP_OK;
1179 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1180
1181 do {
1182 ManagedObjectRef *pRef;
1183 if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef)))
1184 {
1185 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
1186 break;
1187 }
1188
1189 WEBDEBUG((" found reference; deleting!\n"));
1190 delete pRef;
1191 // this removes the object from all stacks; since
1192 // there's a ComPtr<> hidden inside the reference,
1193 // this should also invoke Release() on the COM
1194 // object
1195 } while (0);
1196
1197 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1198 if (rc)
1199 return SOAP_FAULT;
1200 return SOAP_OK;
1201}
1202
1203/****************************************************************************
1204 *
1205 * interface IWebsessionManager
1206 *
1207 ****************************************************************************/
1208
1209/**
1210 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
1211 * COM API, this is the first method that a webservice client must call before the
1212 * webservice will do anything useful.
1213 *
1214 * This returns a managed object reference to the global IVirtualBox object; into this
1215 * reference a session ID is encoded which remains constant with all managed object
1216 * references returned by other methods.
1217 *
1218 * This also creates an instance of ISession, which is stored internally with the
1219 * webservice session and can be retrieved with IWebsessionManager::getSessionObject
1220 * (__vbox__IWebsessionManager_USCOREgetSessionObject). In order for the
1221 * VirtualBox web service to do anything useful, one usually needs both a
1222 * VirtualBox and an ISession object, for which these two methods are designed.
1223 *
1224 * When the webservice client is done, it should call IWebsessionManager::logoff. This
1225 * will clean up internally (destroy all remaining managed object references and
1226 * related COM objects used internally).
1227 *
1228 * After logon, an internal timeout ensures that if the webservice client does not
1229 * call any methods, after a configurable number of seconds, the webservice will log
1230 * off the client automatically. This is to ensure that the webservice does not
1231 * drown in managed object references and eventually deny service. Still, it is
1232 * a much better solution, both for performance and cleanliness, for the webservice
1233 * client to clean up itself.
1234 *
1235 * Preconditions: Caller must have locked g_mutexSessions.
1236 * Since this gets called from main() like other SOAP method
1237 * implementations, this is ensured.
1238 *
1239 * @param
1240 * @param vbox__IWebsessionManager_USCORElogon
1241 * @param vbox__IWebsessionManager_USCORElogonResponse
1242 * @return
1243 */
1244int __vbox__IWebsessionManager_USCORElogon(
1245 struct soap*,
1246 _vbox__IWebsessionManager_USCORElogon *req,
1247 _vbox__IWebsessionManager_USCORElogonResponse *resp)
1248{
1249 HRESULT rc = SOAP_OK;
1250 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1251
1252 do {
1253 // create new session; the constructor stores the new session
1254 // in the global map automatically
1255 WebServiceSession *pSession = new WebServiceSession();
1256
1257 // authenticate the user
1258 if (!(pSession->authenticate(req->username.c_str(),
1259 req->password.c_str())))
1260 {
1261 // in the new session, create a managed object reference (moref) for the
1262 // global VirtualBox object; this encodes the session ID in the moref so
1263 // that it will be implicitly be included in all future requests of this
1264 // webservice client
1265 ManagedObjectRef *pRef = new ManagedObjectRef(*pSession, g_pcszIVirtualBox, g_pVirtualBox);
1266 resp->returnval = pRef->toWSDL();
1267 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
1268 }
1269 } while (0);
1270
1271 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1272 if (rc)
1273 return SOAP_FAULT;
1274 return SOAP_OK;
1275}
1276
1277/**
1278 * Returns the ISession object that was created for the webservice client
1279 * on logon.
1280 *
1281 * Preconditions: Caller must have locked g_mutexSessions.
1282 * Since this gets called from main() like other SOAP method
1283 * implementations, this is ensured.
1284 */
1285int __vbox__IWebsessionManager_USCOREgetSessionObject(
1286 struct soap*,
1287 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
1288 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
1289{
1290 HRESULT rc = SOAP_OK;
1291 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1292
1293 do {
1294 WebServiceSession* pSession;
1295 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1296 {
1297 resp->returnval = pSession->getSessionObject();
1298 }
1299 } while (0);
1300
1301 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1302 if (rc)
1303 return SOAP_FAULT;
1304 return SOAP_OK;
1305}
1306
1307/**
1308 * hard-coded implementation for IWebsessionManager::logoff.
1309 *
1310 * Preconditions: Caller must have locked g_mutexSessions.
1311 * Since this gets called from main() like other SOAP method
1312 * implementations, this is ensured.
1313 *
1314 * @param
1315 * @param vbox__IWebsessionManager_USCORElogon
1316 * @param vbox__IWebsessionManager_USCORElogonResponse
1317 * @return
1318 */
1319int __vbox__IWebsessionManager_USCORElogoff(
1320 struct soap*,
1321 _vbox__IWebsessionManager_USCORElogoff *req,
1322 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
1323{
1324 HRESULT rc = SOAP_OK;
1325 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1326
1327 do {
1328 WebServiceSession* pSession;
1329 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1330 {
1331 delete pSession;
1332 // destructor cleans up
1333
1334 WEBDEBUG(("session destroyed, %d sessions left open\n", g_mapSessions.size()));
1335 }
1336 } while (0);
1337
1338 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1339 if (rc)
1340 return SOAP_FAULT;
1341 return SOAP_OK;
1342}
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