VirtualBox

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

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

Webservice: adjust to new RTGetOpt

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