VirtualBox

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

Last change on this file since 22266 was 22266, checked in by vboxsync, 15 years ago

Webserice: fixed error code check

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