VirtualBox

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

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

Web service: use multi event sems or else no parallel processing

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