VirtualBox

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

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

webservice: add webservice locking class, use critsects instead of rwsems in session locks

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