VirtualBox

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

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

vboxweb.cpp: warnings (MSC).

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