VirtualBox

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

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

Web service: multithreading fix

  • 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 qlock.release();
397
398 WebLog("Request %llu on socket %d queued for processing\n", i, s);
399 // unblock one of the worker threads
400 RTSemEventSignal(soapq.m_event);
401
402 // we have to process main event queue
403 int vrc = com::EventQueue::getMainEventQueue()->processEventQueue(0);
404 }
405 }
406 soap_done(&soap); // close master socket and detach environment
407}
408
409/**
410 * Start up the webservice server. This keeps running and waits
411 * for incoming SOAP connections; for each request that comes in,
412 * it calls method implementation code, most of it in the generated
413 * code in methodmaps.cpp.
414 *
415 * @param argc
416 * @param argv[]
417 * @return
418 */
419int main(int argc, char* argv[])
420{
421 int rc;
422
423 // intialize runtime
424 RTR3Init();
425
426 RTStrmPrintf(g_pStdErr, VBOX_PRODUCT " web service version " VBOX_VERSION_STRING "\n"
427 "(C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
428 "All rights reserved.\n");
429
430 int c;
431 RTGETOPTUNION ValueUnion;
432 RTGETOPTSTATE GetState;
433 RTGetOptInit(&GetState, argc, argv, g_aOptions, RT_ELEMENTS(g_aOptions), 1, 0 /* fFlags */);
434 while ((c = RTGetOpt(&GetState, &ValueUnion)))
435 {
436 switch (c)
437 {
438 case 'H':
439 g_pcszBindToHost = ValueUnion.psz;
440 break;
441
442 case 'p':
443 g_uBindToPort = ValueUnion.u32;
444 break;
445
446 case 't':
447 g_iWatchdogTimeoutSecs = ValueUnion.u32;
448 break;
449
450 case 'i':
451 g_iWatchdogCheckInterval = ValueUnion.u32;
452 break;
453
454 case 'F':
455 {
456 int rc2 = RTStrmOpen(ValueUnion.psz, "a", &g_pstrLog);
457 if (rc2)
458 {
459 RTPrintf("Error: Cannot open log file \"%s\" for writing, error %d.\n", ValueUnion.psz, rc2);
460 exit(2);
461 }
462
463 WebLog("Sun VirtualBox Webservice Version %s\n"
464 "Opened log file \"%s\"\n", VBOX_VERSION_STRING, ValueUnion.psz);
465 }
466 break;
467
468 case 'h':
469 DisplayHelp();
470 exit(0);
471 break;
472
473 case 'v':
474 g_fVerbose = true;
475 break;
476
477#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
478 case 'b':
479 g_fDaemonize = true;
480 break;
481#endif
482 case VINF_GETOPT_NOT_OPTION:
483 RTStrmPrintf(g_pStdErr, "unhandled parameter: %s\n", ValueUnion.psz);
484 return 1;
485
486 default:
487 if (c > 0)
488 {
489 if (RT_C_IS_GRAPH(c))
490 RTStrmPrintf(g_pStdErr, "unhandled option: -%c", c);
491 else
492 RTStrmPrintf(g_pStdErr, "unhandled option: %i", c);
493 }
494 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
495 RTStrmPrintf(g_pStdErr, "unknown option: %s", ValueUnion.psz);
496 else if (ValueUnion.pDef)
497 RTStrmPrintf(g_pStdErr, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
498 else
499 RTStrmPrintf(g_pStdErr, "%Rrs", c);
500 exit(1);
501 break;
502 }
503 }
504
505#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
506 if (g_fDaemonize)
507 {
508 rc = RTProcDaemonize(false /* fNoChDir */, false /* fNoClose */,
509 NULL);
510 if (RT_FAILURE(rc))
511 {
512 RTStrmPrintf(g_pStdErr, "vboxwebsrv: failed to daemonize, rc=%Rrc. exiting.\n", rc);
513 exit(1);
514 }
515 }
516#endif
517
518 // intialize COM/XPCOM
519 rc = com::Initialize();
520 if (FAILED(rc))
521 {
522 RTPrintf("ERROR: failed to initialize COM!\n");
523 return rc;
524 }
525
526 ComPtr<ISession> session;
527
528 rc = g_pVirtualBox.createLocalObject(CLSID_VirtualBox);
529 if (FAILED(rc))
530 RTPrintf("ERROR: failed to create the VirtualBox object!\n");
531 else
532 {
533 rc = session.createInprocObject(CLSID_Session);
534 if (FAILED(rc))
535 RTPrintf("ERROR: failed to create a session object!\n");
536 }
537
538 if (FAILED(rc))
539 {
540 com::ErrorInfo info;
541 if (!info.isFullAvailable() && !info.isBasicAvailable())
542 {
543 com::GluePrintRCMessage(rc);
544 RTPrintf("Most likely, the VirtualBox COM server is not running or failed to start.\n");
545 }
546 else
547 com::GluePrintErrorInfo(info);
548 return rc;
549 }
550
551 // create the global mutexes
552 g_pAuthLibLockHandle = new util::RWLockHandle(util::LOCKCLASS_OBJECTSTATE);
553 g_pSessionsLockHandle = new util::RWLockHandle(util::LOCKCLASS_OBJECTSTATE);
554
555 if (g_iWatchdogTimeoutSecs > 0)
556 {
557 // start our watchdog thread
558 RTTHREAD tWatchdog;
559 if (RTThreadCreate(&tWatchdog,
560 fntWatchdog,
561 NULL,
562 32*1024,
563 RTTHREADTYPE_MAIN_WORKER,
564 0,
565 "Watchdog"))
566 {
567 RTStrmPrintf(g_pStdErr, "[!] Cannot start watchdog thread\n");
568 exit(1);
569 }
570 }
571
572 beginProcessing();
573
574 com::Shutdown();
575}
576
577/****************************************************************************
578 *
579 * Watchdog thread
580 *
581 ****************************************************************************/
582
583/**
584 * Watchdog thread, runs in the background while the webservice is alive.
585 *
586 * This gets started by main() and runs in the background to check all sessions
587 * for whether they have been no requests in a configurable timeout period. In
588 * that case, the session is automatically logged off.
589 */
590int fntWatchdog(RTTHREAD ThreadSelf, void *pvUser)
591{
592 WEBDEBUG(("Watchdog thread started\n"));
593
594 while (1)
595 {
596 WEBDEBUG(("Watchdog: sleeping %d seconds\n", g_iWatchdogCheckInterval));
597 RTThreadSleep(g_iWatchdogCheckInterval * 1000);
598
599 time_t tNow;
600 time(&tNow);
601
602 // lock the sessions while we're iterating; this blocks
603 // out the COM code from messing with it
604 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
605 WEBDEBUG(("Watchdog: checking %d sessions\n", g_mapSessions.size()));
606
607 SessionsMap::iterator it = g_mapSessions.begin(),
608 itEnd = g_mapSessions.end();
609 while (it != itEnd)
610 {
611 WebServiceSession *pSession = it->second;
612 WEBDEBUG(("Watchdog: tNow: %d, session timestamp: %d\n", tNow, pSession->getLastObjectLookup()));
613 if ( tNow
614 > pSession->getLastObjectLookup() + g_iWatchdogTimeoutSecs
615 )
616 {
617 WEBDEBUG(("Watchdog: Session %llX timed out, deleting\n", pSession->getID()));
618 delete pSession;
619 it = g_mapSessions.begin();
620 }
621 else
622 ++it;
623 }
624 }
625
626 WEBDEBUG(("Watchdog thread ending\n"));
627 return 0;
628}
629
630/****************************************************************************
631 *
632 * SOAP exceptions
633 *
634 ****************************************************************************/
635
636/**
637 * Helper function to raise a SOAP fault. Called by the other helper
638 * functions, which raise specific SOAP faults.
639 *
640 * @param soap
641 * @param str
642 * @param extype
643 * @param ex
644 */
645void RaiseSoapFault(struct soap *soap,
646 const char *pcsz,
647 int extype,
648 void *ex)
649{
650 // raise the fault
651 soap_sender_fault(soap, pcsz, NULL);
652
653 struct SOAP_ENV__Detail *pDetail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
654
655 // without the following, gSOAP crashes miserably when sending out the
656 // data because it will try to serialize all fields (stupid documentation)
657 memset(pDetail, 0, sizeof(struct SOAP_ENV__Detail));
658
659 // fill extended info depending on SOAP version
660 if (soap->version == 2) // SOAP 1.2 is used
661 {
662 soap->fault->SOAP_ENV__Detail = pDetail;
663 soap->fault->SOAP_ENV__Detail->__type = extype;
664 soap->fault->SOAP_ENV__Detail->fault = ex;
665 soap->fault->SOAP_ENV__Detail->__any = NULL; // no other XML data
666 }
667 else
668 {
669 soap->fault->detail = pDetail;
670 soap->fault->detail->__type = extype;
671 soap->fault->detail->fault = ex;
672 soap->fault->detail->__any = NULL; // no other XML data
673 }
674}
675
676/**
677 * Raises a SOAP fault that signals that an invalid object was passed.
678 *
679 * @param soap
680 * @param obj
681 */
682void RaiseSoapInvalidObjectFault(struct soap *soap,
683 WSDLT_ID obj)
684{
685 _vbox__InvalidObjectFault *ex = soap_new__vbox__InvalidObjectFault(soap, 1);
686 ex->badObjectID = obj;
687
688 std::string str("VirtualBox error: ");
689 str += "Invalid managed object reference \"" + obj + "\"";
690
691 RaiseSoapFault(soap,
692 str.c_str(),
693 SOAP_TYPE__vbox__InvalidObjectFault,
694 ex);
695}
696
697/**
698 * Return a safe C++ string from the given COM string,
699 * without crashing if the COM string is empty.
700 * @param bstr
701 * @return
702 */
703std::string ConvertComString(const com::Bstr &bstr)
704{
705 com::Utf8Str ustr(bstr);
706 const char *pcsz;
707 if ((pcsz = ustr.raw()))
708 return pcsz;
709 return "";
710}
711
712/**
713 * Return a safe C++ string from the given COM UUID,
714 * without crashing if the UUID is empty.
715 * @param bstr
716 * @return
717 */
718std::string ConvertComString(const com::Guid &uuid)
719{
720 com::Utf8Str ustr(uuid.toString());
721 const char *pcsz;
722 if ((pcsz = ustr.raw()))
723 return pcsz;
724 return "";
725}
726
727/**
728 * Raises a SOAP runtime fault.
729 *
730 * @param pObj
731 */
732void RaiseSoapRuntimeFault(struct soap *soap,
733 HRESULT apirc,
734 IUnknown *pObj)
735{
736 com::ErrorInfo info(pObj);
737
738 WEBDEBUG((" error, raising SOAP exception\n"));
739
740 RTStrmPrintf(g_pStdErr, "API return code: 0x%08X (%Rhrc)\n", apirc, apirc);
741 RTStrmPrintf(g_pStdErr, "COM error info result code: 0x%lX\n", info.getResultCode());
742 RTStrmPrintf(g_pStdErr, "COM error info text: %ls\n", info.getText().raw());
743
744 // allocated our own soap fault struct
745 _vbox__RuntimeFault *ex = soap_new__vbox__RuntimeFault(soap, 1);
746 ex->resultCode = info.getResultCode();
747 ex->text = ConvertComString(info.getText());
748 ex->component = ConvertComString(info.getComponent());
749 ex->interfaceID = ConvertComString(info.getInterfaceID());
750
751 // compose descriptive message
752 com::Utf8StrFmt str("VirtualBox error: %s (0x%RU32)", ex->text.c_str(), ex->resultCode);
753
754 RaiseSoapFault(soap,
755 str.c_str(),
756 SOAP_TYPE__vbox__RuntimeFault,
757 ex);
758}
759
760/****************************************************************************
761 *
762 * splitting and merging of object IDs
763 *
764 ****************************************************************************/
765
766uint64_t str2ulonglong(const char *pcsz)
767{
768 uint64_t u = 0;
769 RTStrToUInt64Full(pcsz, 16, &u);
770 return u;
771}
772
773/**
774 * Splits a managed object reference (in string form, as
775 * passed in from a SOAP method call) into two integers for
776 * session and object IDs, respectively.
777 *
778 * @param id
779 * @param sessid
780 * @param objid
781 * @return
782 */
783bool SplitManagedObjectRef(const WSDLT_ID &id,
784 uint64_t *pSessid,
785 uint64_t *pObjid)
786{
787 // 64-bit numbers in hex have 16 digits; hence
788 // the object-ref string must have 16 + "-" + 16 characters
789 std::string str;
790 if ( (id.length() == 33)
791 && (id[16] == '-')
792 )
793 {
794 char psz[34];
795 memcpy(psz, id.c_str(), 34);
796 psz[16] = '\0';
797 if (pSessid)
798 *pSessid = str2ulonglong(psz);
799 if (pObjid)
800 *pObjid = str2ulonglong(psz + 17);
801 return true;
802 }
803
804 return false;
805}
806
807/**
808 * Creates a managed object reference (in string form) from
809 * two integers representing a session and object ID, respectively.
810 *
811 * @param sz Buffer with at least 34 bytes space to receive MOR string.
812 * @param sessid
813 * @param objid
814 * @return
815 */
816void MakeManagedObjectRef(char *sz,
817 uint64_t &sessid,
818 uint64_t &objid)
819{
820 RTStrFormatNumber(sz, sessid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
821 sz[16] = '-';
822 RTStrFormatNumber(sz + 17, objid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
823}
824
825/****************************************************************************
826 *
827 * class WebServiceSession
828 *
829 ****************************************************************************/
830
831class WebServiceSessionPrivate
832{
833 public:
834 ManagedObjectsMapById _mapManagedObjectsById;
835 ManagedObjectsMapByPtr _mapManagedObjectsByPtr;
836};
837
838/**
839 * Constructor for the session object.
840 *
841 * Preconditions: Caller must have locked g_pSessionsLockHandle in write mode.
842 *
843 * @param username
844 * @param password
845 */
846WebServiceSession::WebServiceSession()
847 : _fDestructing(false),
848 _pISession(NULL),
849 _tLastObjectLookup(0)
850{
851 _pp = new WebServiceSessionPrivate;
852 _uSessionID = RTRandU64();
853
854 // register this session globally
855 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
856 g_mapSessions[_uSessionID] = this;
857}
858
859/**
860 * Destructor. Cleans up and destroys all contained managed object references on the way.
861 *
862 * Preconditions: Caller must have locked g_pSessionsLockHandle in write mode.
863 */
864WebServiceSession::~WebServiceSession()
865{
866 // delete us from global map first so we can't be found
867 // any more while we're cleaning up
868 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
869 g_mapSessions.erase(_uSessionID);
870
871 // notify ManagedObjectRef destructor so it won't
872 // remove itself from the maps; this avoids rebalancing
873 // the map's tree on every delete as well
874 _fDestructing = true;
875
876 // if (_pISession)
877 // {
878 // delete _pISession;
879 // _pISession = NULL;
880 // }
881
882 ManagedObjectsMapById::iterator it,
883 end = _pp->_mapManagedObjectsById.end();
884 for (it = _pp->_mapManagedObjectsById.begin();
885 it != end;
886 ++it)
887 {
888 ManagedObjectRef *pRef = it->second;
889 delete pRef; // this frees the contained ComPtr as well
890 }
891
892 delete _pp;
893}
894
895/**
896 * Authenticate the username and password against an authentification authority.
897 *
898 * @return 0 if the user was successfully authenticated, or an error code
899 * otherwise.
900 */
901
902int WebServiceSession::authenticate(const char *pcszUsername,
903 const char *pcszPassword)
904{
905 int rc = VERR_WEB_NOT_AUTHENTICATED;
906
907 util::AutoReadLock lock(g_pAuthLibLockHandle COMMA_LOCKVAL_SRC_POS);
908
909 static bool fAuthLibLoaded = false;
910 static PVRDPAUTHENTRY pfnAuthEntry = NULL;
911 static PVRDPAUTHENTRY2 pfnAuthEntry2 = NULL;
912
913 if (!fAuthLibLoaded)
914 {
915 // retrieve authentication library from system properties
916 ComPtr<ISystemProperties> systemProperties;
917 g_pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
918
919 com::Bstr authLibrary;
920 systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
921 com::Utf8Str filename = authLibrary;
922
923 WEBDEBUG(("external authentication library is '%ls'\n", authLibrary.raw()));
924
925 if (filename == "null")
926 // authentication disabled, let everyone in:
927 fAuthLibLoaded = true;
928 else
929 {
930 RTLDRMOD hlibAuth = 0;
931 do
932 {
933 rc = RTLdrLoad(filename.raw(), &hlibAuth);
934 if (RT_FAILURE(rc))
935 {
936 WEBDEBUG(("%s() Failed to load external authentication library. Error code: %Rrc\n", __FUNCTION__, rc));
937 break;
938 }
939
940 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, "VRDPAuth2", (void**)&pfnAuthEntry2)))
941 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, "VRDPAuth2", rc));
942
943 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, "VRDPAuth", (void**)&pfnAuthEntry)))
944 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, "VRDPAuth", rc));
945
946 if (pfnAuthEntry || pfnAuthEntry2)
947 fAuthLibLoaded = true;
948
949 } while (0);
950 }
951 }
952
953 rc = VERR_WEB_NOT_AUTHENTICATED;
954 VRDPAuthResult result;
955 if (pfnAuthEntry2)
956 {
957 result = pfnAuthEntry2(NULL, VRDPAuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
958 WEBDEBUG(("%s(): result of VRDPAuth2(): %d\n", __FUNCTION__, result));
959 if (result == VRDPAuthAccessGranted)
960 rc = 0;
961 }
962 else if (pfnAuthEntry)
963 {
964 result = pfnAuthEntry(NULL, VRDPAuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
965 WEBDEBUG(("%s(): result of VRDPAuth(%s, [%d]): %d\n", __FUNCTION__, pcszUsername, strlen(pcszPassword), result));
966 if (result == VRDPAuthAccessGranted)
967 rc = 0;
968 }
969 else if (fAuthLibLoaded)
970 // fAuthLibLoaded = true but both pointers are NULL:
971 // then the authlib was "null" and auth was disabled
972 rc = 0;
973 else
974 {
975 WEBDEBUG(("Could not resolve VRDPAuth2 or VRDPAuth entry point"));
976 }
977
978 lock.release();
979
980 if (!rc)
981 {
982 do
983 {
984 // now create the ISession object that this webservice session can use
985 // (and of which IWebsessionManager::getSessionObject returns a managed object reference)
986 ComPtr<ISession> session;
987 if (FAILED(rc = session.createInprocObject(CLSID_Session)))
988 {
989 WEBDEBUG(("ERROR: cannot create session object!"));
990 break;
991 }
992
993 _pISession = new ManagedObjectRef(*this, g_pcszISession, session);
994
995 if (g_fVerbose)
996 {
997 ISession *p = session;
998 std::string strMOR = _pISession->toWSDL();
999 WEBDEBUG((" * %s: created session object with comptr 0x%lX, MOR = %s\n", __FUNCTION__, p, strMOR.c_str()));
1000 }
1001 } while (0);
1002 }
1003
1004 return rc;
1005}
1006
1007/**
1008 * Look up, in this session, whether a ManagedObjectRef has already been
1009 * created for the given COM pointer.
1010 *
1011 * Note how we require that a ComPtr<IUnknown> is passed, which causes a
1012 * queryInterface call when the caller passes in a different type, since
1013 * a ComPtr<IUnknown> will point to something different than a
1014 * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
1015 * our private hash table, we must search for one too.
1016 *
1017 * Preconditions: Caller must have locked g_pSessionsLockHandle in read mode.
1018 *
1019 * @param pcu pointer to a COM object.
1020 * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
1021 */
1022ManagedObjectRef* WebServiceSession::findRefFromPtr(const ComPtr<IUnknown> &pcu)
1023{
1024 // Assert(g_pSessionsLockHandle->isReadLockOnCurrentThread()); // @todo
1025
1026 IUnknown *p = pcu;
1027 uintptr_t ulp = (uintptr_t)p;
1028 ManagedObjectRef *pRef;
1029 // WEBDEBUG((" %s: looking up 0x%lX\n", __FUNCTION__, ulp));
1030 ManagedObjectsMapByPtr::iterator it = _pp->_mapManagedObjectsByPtr.find(ulp);
1031 if (it != _pp->_mapManagedObjectsByPtr.end())
1032 {
1033 pRef = it->second;
1034 WSDLT_ID id = pRef->toWSDL();
1035 WEBDEBUG((" %s: found existing ref %s for COM obj 0x%lX\n", __FUNCTION__, id.c_str(), ulp));
1036 }
1037 else
1038 pRef = NULL;
1039 return pRef;
1040}
1041
1042/**
1043 * Static method which attempts to find the session for which the given managed
1044 * object reference was created, by splitting the reference into the session and
1045 * object IDs and then looking up the session object for that session ID.
1046 *
1047 * Preconditions: Caller must have locked g_pSessionsLockHandle in read mode.
1048 *
1049 * @param id Managed object reference (with combined session and object IDs).
1050 * @return
1051 */
1052WebServiceSession* WebServiceSession::findSessionFromRef(const WSDLT_ID &id)
1053{
1054 // Assert(g_pSessionsLockHandle->isReadLockOnCurrentThread()); // @todo
1055
1056 WebServiceSession *pSession = NULL;
1057 uint64_t sessid;
1058 if (SplitManagedObjectRef(id,
1059 &sessid,
1060 NULL))
1061 {
1062 SessionsMapIterator it = g_mapSessions.find(sessid);
1063 if (it != g_mapSessions.end())
1064 pSession = it->second;
1065 }
1066 return pSession;
1067}
1068
1069/**
1070 *
1071 */
1072WSDLT_ID WebServiceSession::getSessionObject() const
1073{
1074 return _pISession->toWSDL();
1075}
1076
1077/**
1078 * Touches the webservice session to prevent it from timing out.
1079 *
1080 * Each webservice session has an internal timestamp that records
1081 * the last request made to it from the client that started it.
1082 * If no request was made within a configurable timeframe, then
1083 * the client is logged off automatically,
1084 * by calling IWebsessionManager::logoff()
1085 */
1086void WebServiceSession::touch()
1087{
1088 time(&_tLastObjectLookup);
1089}
1090
1091/**
1092 *
1093 */
1094void WebServiceSession::DumpRefs()
1095{
1096 WEBDEBUG((" dumping object refs:\n"));
1097 ManagedObjectsIteratorById
1098 iter = _pp->_mapManagedObjectsById.begin(),
1099 end = _pp->_mapManagedObjectsById.end();
1100 for (;
1101 iter != end;
1102 ++iter)
1103 {
1104 ManagedObjectRef *pRef = iter->second;
1105 uint64_t id = pRef->getID();
1106 void *p = pRef->getComPtr();
1107 WEBDEBUG((" objid %llX: comptr 0x%lX\n", id, p));
1108 }
1109}
1110
1111/****************************************************************************
1112 *
1113 * class ManagedObjectRef
1114 *
1115 ****************************************************************************/
1116
1117/**
1118 * Constructor, which assigns a unique ID to this managed object
1119 * reference and stores it two global hashes:
1120 *
1121 * a) G_mapManagedObjectsById, which maps ManagedObjectID's to
1122 * instances of this class; this hash is then used by the
1123 * findObjectFromRef() template function in vboxweb.h
1124 * to quickly retrieve the COM object from its managed
1125 * object ID (mostly in the context of the method mappers
1126 * in methodmaps.cpp, when a web service client passes in
1127 * a managed object ID);
1128 *
1129 * b) G_mapManagedObjectsByComPtr, which maps COM pointers to
1130 * instances of this class; this hash is used by
1131 * createRefFromObject() to quickly figure out whether an
1132 * instance already exists for a given COM pointer.
1133 *
1134 * This does _not_ check whether another instance already
1135 * exists in the hash. This gets called only from the
1136 * createRefFromObject() template function in vboxweb.h, which
1137 * does perform that check.
1138 *
1139 * Preconditions: Caller must have locked g_pSessionsLockHandle in write mode.
1140 *
1141 * @param pObj
1142 */
1143ManagedObjectRef::ManagedObjectRef(WebServiceSession &session,
1144 const char *pcszInterface,
1145 const ComPtr<IUnknown> &pc)
1146 : _session(session),
1147 _pObj(pc),
1148 _pcszInterface(pcszInterface)
1149{
1150 ComPtr<IUnknown> pcUnknown(pc);
1151 _ulp = (uintptr_t)(IUnknown*)pcUnknown;
1152
1153 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1154 _id = ++g_iMaxManagedObjectID;
1155 // and count globally
1156 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
1157
1158 char sz[34];
1159 MakeManagedObjectRef(sz, session._uSessionID, _id);
1160 _strID = sz;
1161
1162 session._pp->_mapManagedObjectsById[_id] = this;
1163 session._pp->_mapManagedObjectsByPtr[_ulp] = this;
1164
1165 session.touch();
1166
1167 WEBDEBUG((" * %s: MOR created for ulp 0x%lX (%s), new ID is %llX; now %lld objects total\n", __FUNCTION__, _ulp, pcszInterface, _id, cTotal));
1168}
1169
1170/**
1171 * Destructor; removes the instance from the global hash of
1172 * managed objects.
1173 *
1174 * Preconditions: Caller must have locked g_pSessionsLockHandle in write mode.
1175 */
1176ManagedObjectRef::~ManagedObjectRef()
1177{
1178 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1179 ULONG64 cTotal = --g_cManagedObjects;
1180
1181 WEBDEBUG((" * %s: deleting MOR for ID %llX (%s); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cTotal));
1182
1183 // if we're being destroyed from the session's destructor,
1184 // then that destructor is iterating over the maps, so
1185 // don't remove us there! (data integrity + speed)
1186 if (!_session._fDestructing)
1187 {
1188 WEBDEBUG((" * %s: removing from session maps\n", __FUNCTION__));
1189 _session._pp->_mapManagedObjectsById.erase(_id);
1190 if (_session._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
1191 WEBDEBUG((" WARNING: could not find %llX in _mapManagedObjectsByPtr\n", _ulp));
1192 }
1193}
1194
1195/**
1196 * Converts the ID of this managed object reference to string
1197 * form, for returning with SOAP data or similar.
1198 *
1199 * @return The ID in string form.
1200 */
1201WSDLT_ID ManagedObjectRef::toWSDL() const
1202{
1203 return _strID;
1204}
1205
1206/**
1207 * Static helper method for findObjectFromRef() template that actually
1208 * looks up the object from a given integer ID.
1209 *
1210 * This has been extracted into this non-template function to reduce
1211 * code bloat as we have the actual STL map lookup only in this function.
1212 *
1213 * This also "touches" the timestamp in the session whose ID is encoded
1214 * in the given integer ID, in order to prevent the session from timing
1215 * out.
1216 *
1217 * Preconditions: Caller must have locked g_mutexSessions.
1218 *
1219 * @param strId
1220 * @param iter
1221 * @return
1222 */
1223int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
1224 ManagedObjectRef **pRef,
1225 bool fNullAllowed)
1226{
1227 int rc = 0;
1228
1229 do
1230 {
1231 // allow NULL (== empty string) input reference, which should return a NULL pointer
1232 if (!id.length() && fNullAllowed)
1233 {
1234 *pRef = NULL;
1235 return 0;
1236 }
1237
1238 uint64_t sessid;
1239 uint64_t objid;
1240 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
1241 if (!SplitManagedObjectRef(id,
1242 &sessid,
1243 &objid))
1244 {
1245 rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
1246 break;
1247 }
1248
1249 WEBDEBUG((" %s(): sessid %llX, objid %llX\n", __FUNCTION__, sessid, objid));
1250 SessionsMapIterator it = g_mapSessions.find(sessid);
1251 if (it == g_mapSessions.end())
1252 {
1253 WEBDEBUG((" %s: cannot find session for objref %s\n", __FUNCTION__, id.c_str()));
1254 rc = VERR_WEB_INVALID_SESSION_ID;
1255 break;
1256 }
1257
1258 WebServiceSession *pSess = it->second;
1259 // "touch" session to prevent it from timing out
1260 pSess->touch();
1261
1262 ManagedObjectsIteratorById iter = pSess->_pp->_mapManagedObjectsById.find(objid);
1263 if (iter == pSess->_pp->_mapManagedObjectsById.end())
1264 {
1265 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
1266 rc = VERR_WEB_INVALID_OBJECT_ID;
1267 break;
1268 }
1269
1270 *pRef = iter->second;
1271
1272 } while (0);
1273
1274 return rc;
1275}
1276
1277/****************************************************************************
1278 *
1279 * interface IManagedObjectRef
1280 *
1281 ****************************************************************************/
1282
1283/**
1284 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
1285 * that our WSDL promises to our web service clients. This method returns a
1286 * string describing the interface that this managed object reference
1287 * supports, e.g. "IMachine".
1288 *
1289 * @param soap
1290 * @param req
1291 * @param resp
1292 * @return
1293 */
1294int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
1295 struct soap *soap,
1296 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
1297 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
1298{
1299 HRESULT rc = SOAP_OK;
1300 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1301
1302 do {
1303 ManagedObjectRef *pRef;
1304 if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false))
1305 resp->returnval = pRef->getInterfaceName();
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 * This is the hard-coded implementation for the IManagedObjectRef::release()
1317 * that our WSDL promises to our web service clients. This method releases
1318 * a managed object reference and removes it from our stacks.
1319 *
1320 * @param soap
1321 * @param req
1322 * @param resp
1323 * @return
1324 */
1325int __vbox__IManagedObjectRef_USCORErelease(
1326 struct soap *soap,
1327 _vbox__IManagedObjectRef_USCORErelease *req,
1328 _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
1329{
1330 HRESULT rc = SOAP_OK;
1331 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1332
1333 do {
1334 ManagedObjectRef *pRef;
1335 if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false)))
1336 {
1337 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
1338 break;
1339 }
1340
1341 WEBDEBUG((" found reference; deleting!\n"));
1342 delete pRef;
1343 // this removes the object from all stacks; since
1344 // there's a ComPtr<> hidden inside the reference,
1345 // this should also invoke Release() on the COM
1346 // object
1347 } while (0);
1348
1349 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1350 if (FAILED(rc))
1351 return SOAP_FAULT;
1352 return SOAP_OK;
1353}
1354
1355/****************************************************************************
1356 *
1357 * interface IWebsessionManager
1358 *
1359 ****************************************************************************/
1360
1361/**
1362 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
1363 * COM API, this is the first method that a webservice client must call before the
1364 * webservice will do anything useful.
1365 *
1366 * This returns a managed object reference to the global IVirtualBox object; into this
1367 * reference a session ID is encoded which remains constant with all managed object
1368 * references returned by other methods.
1369 *
1370 * This also creates an instance of ISession, which is stored internally with the
1371 * webservice session and can be retrieved with IWebsessionManager::getSessionObject
1372 * (__vbox__IWebsessionManager_USCOREgetSessionObject). In order for the
1373 * VirtualBox web service to do anything useful, one usually needs both a
1374 * VirtualBox and an ISession object, for which these two methods are designed.
1375 *
1376 * When the webservice client is done, it should call IWebsessionManager::logoff. This
1377 * will clean up internally (destroy all remaining managed object references and
1378 * related COM objects used internally).
1379 *
1380 * After logon, an internal timeout ensures that if the webservice client does not
1381 * call any methods, after a configurable number of seconds, the webservice will log
1382 * off the client automatically. This is to ensure that the webservice does not
1383 * drown in managed object references and eventually deny service. Still, it is
1384 * a much better solution, both for performance and cleanliness, for the webservice
1385 * client to clean up itself.
1386 *
1387 * Preconditions: Caller must have locked g_mutexSessions.
1388 * Since this gets called from main() like other SOAP method
1389 * implementations, this is ensured.
1390 *
1391 * @param
1392 * @param vbox__IWebsessionManager_USCORElogon
1393 * @param vbox__IWebsessionManager_USCORElogonResponse
1394 * @return
1395 */
1396int __vbox__IWebsessionManager_USCORElogon(
1397 struct soap*,
1398 _vbox__IWebsessionManager_USCORElogon *req,
1399 _vbox__IWebsessionManager_USCORElogonResponse *resp)
1400{
1401 HRESULT rc = SOAP_OK;
1402 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1403
1404 do {
1405 // WebServiceSession constructor tinkers with global MOR map and requires a write lock
1406 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1407
1408 // create new session; the constructor stores the new session
1409 // in the global map automatically
1410 WebServiceSession *pSession = new WebServiceSession();
1411
1412 // authenticate the user
1413 if (!(pSession->authenticate(req->username.c_str(),
1414 req->password.c_str())))
1415 {
1416 // in the new session, create a managed object reference (moref) for the
1417 // global VirtualBox object; this encodes the session ID in the moref so
1418 // that it will be implicitly be included in all future requests of this
1419 // webservice client
1420 ManagedObjectRef *pRef = new ManagedObjectRef(*pSession, g_pcszIVirtualBox, g_pVirtualBox);
1421 resp->returnval = pRef->toWSDL();
1422 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
1423 }
1424 } while (0);
1425
1426 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1427 if (FAILED(rc))
1428 return SOAP_FAULT;
1429 return SOAP_OK;
1430}
1431
1432/**
1433 * Returns the ISession object that was created for the webservice client
1434 * on logon.
1435 *
1436 * Preconditions: Caller must have locked g_mutexSessions.
1437 * Since this gets called from main() like other SOAP method
1438 * implementations, this is ensured.
1439 */
1440int __vbox__IWebsessionManager_USCOREgetSessionObject(
1441 struct soap*,
1442 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
1443 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
1444{
1445 HRESULT rc = SOAP_OK;
1446 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1447
1448 do {
1449 WebServiceSession* pSession;
1450 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1451 {
1452 resp->returnval = pSession->getSessionObject();
1453 }
1454 } while (0);
1455
1456 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1457 if (FAILED(rc))
1458 return SOAP_FAULT;
1459 return SOAP_OK;
1460}
1461
1462/**
1463 * hard-coded implementation for IWebsessionManager::logoff.
1464 *
1465 * Preconditions: Caller must have locked g_mutexSessions.
1466 * Since this gets called from main() like other SOAP method
1467 * implementations, this is ensured.
1468 *
1469 * @param
1470 * @param vbox__IWebsessionManager_USCORElogon
1471 * @param vbox__IWebsessionManager_USCORElogonResponse
1472 * @return
1473 */
1474int __vbox__IWebsessionManager_USCORElogoff(
1475 struct soap*,
1476 _vbox__IWebsessionManager_USCORElogoff *req,
1477 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
1478{
1479 HRESULT rc = SOAP_OK;
1480 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1481
1482 do {
1483 WebServiceSession* pSession;
1484 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1485 {
1486 delete pSession;
1487 // destructor cleans up
1488
1489 WEBDEBUG(("session destroyed, %d sessions left open\n", g_mapSessions.size()));
1490 }
1491 } while (0);
1492
1493 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1494 if (FAILED(rc))
1495 return SOAP_FAULT;
1496 return SOAP_OK;
1497}
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