VirtualBox

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

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

Web service: first attempt at multithreading.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette