VirtualBox

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

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

Webservice: avoid creating empty log files in release builds

  • Property filesplitter.c set to Makefile.kmk
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 52.4 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.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
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::RWLockHandle *g_pAuthLibLockHandle;
122
123// this mutex protects all of the below
124util::RWLockHandle *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),
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::RWLockHandle(util::LOCKCLASS_OBJECTSTATE);
698 g_pSessionsLockHandle = new util::RWLockHandle(util::LOCKCLASS_OBJECTSTATE);
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 // lock the sessions while we're iterating; this blocks
776 // out the COM code from messing with it
777 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
778 WEBDEBUG(("Watchdog: checking %d sessions\n", g_mapSessions.size()));
779
780 SessionsMap::iterator it = g_mapSessions.begin(),
781 itEnd = g_mapSessions.end();
782 while (it != itEnd)
783 {
784 WebServiceSession *pSession = it->second;
785 WEBDEBUG(("Watchdog: tNow: %d, session timestamp: %d\n", tNow, pSession->getLastObjectLookup()));
786 if ( tNow
787 > pSession->getLastObjectLookup() + g_iWatchdogTimeoutSecs
788 )
789 {
790 WEBDEBUG(("Watchdog: Session %llX timed out, deleting\n", pSession->getID()));
791 delete pSession;
792 it = g_mapSessions.begin();
793 }
794 else
795 ++it;
796 }
797 }
798
799 WEBDEBUG(("Watchdog thread ending\n"));
800 return 0;
801}
802
803/****************************************************************************
804 *
805 * SOAP exceptions
806 *
807 ****************************************************************************/
808
809/**
810 * Helper function to raise a SOAP fault. Called by the other helper
811 * functions, which raise specific SOAP faults.
812 *
813 * @param soap
814 * @param str
815 * @param extype
816 * @param ex
817 */
818void RaiseSoapFault(struct soap *soap,
819 const char *pcsz,
820 int extype,
821 void *ex)
822{
823 // raise the fault
824 soap_sender_fault(soap, pcsz, NULL);
825
826 struct SOAP_ENV__Detail *pDetail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
827
828 // without the following, gSOAP crashes miserably when sending out the
829 // data because it will try to serialize all fields (stupid documentation)
830 memset(pDetail, 0, sizeof(struct SOAP_ENV__Detail));
831
832 // fill extended info depending on SOAP version
833 if (soap->version == 2) // SOAP 1.2 is used
834 {
835 soap->fault->SOAP_ENV__Detail = pDetail;
836 soap->fault->SOAP_ENV__Detail->__type = extype;
837 soap->fault->SOAP_ENV__Detail->fault = ex;
838 soap->fault->SOAP_ENV__Detail->__any = NULL; // no other XML data
839 }
840 else
841 {
842 soap->fault->detail = pDetail;
843 soap->fault->detail->__type = extype;
844 soap->fault->detail->fault = ex;
845 soap->fault->detail->__any = NULL; // no other XML data
846 }
847}
848
849/**
850 * Raises a SOAP fault that signals that an invalid object was passed.
851 *
852 * @param soap
853 * @param obj
854 */
855void RaiseSoapInvalidObjectFault(struct soap *soap,
856 WSDLT_ID obj)
857{
858 _vbox__InvalidObjectFault *ex = soap_new__vbox__InvalidObjectFault(soap, 1);
859 ex->badObjectID = obj;
860
861 std::string str("VirtualBox error: ");
862 str += "Invalid managed object reference \"" + obj + "\"";
863
864 RaiseSoapFault(soap,
865 str.c_str(),
866 SOAP_TYPE__vbox__InvalidObjectFault,
867 ex);
868}
869
870/**
871 * Return a safe C++ string from the given COM string,
872 * without crashing if the COM string is empty.
873 * @param bstr
874 * @return
875 */
876std::string ConvertComString(const com::Bstr &bstr)
877{
878 com::Utf8Str ustr(bstr);
879 const char *pcsz;
880 if ((pcsz = ustr.raw()))
881 return pcsz;
882 return "";
883}
884
885/**
886 * Return a safe C++ string from the given COM UUID,
887 * without crashing if the UUID is empty.
888 * @param bstr
889 * @return
890 */
891std::string ConvertComString(const com::Guid &uuid)
892{
893 com::Utf8Str ustr(uuid.toString());
894 const char *pcsz;
895 if ((pcsz = ustr.raw()))
896 return pcsz;
897 return "";
898}
899
900/**
901 * Raises a SOAP runtime fault.
902 *
903 * @param pObj
904 */
905void RaiseSoapRuntimeFault(struct soap *soap,
906 HRESULT apirc,
907 IUnknown *pObj)
908{
909 com::ErrorInfo info(pObj);
910
911 WEBDEBUG((" error, raising SOAP exception\n"));
912
913 RTStrmPrintf(g_pStdErr, "API return code: 0x%08X (%Rhrc)\n", apirc, apirc);
914 RTStrmPrintf(g_pStdErr, "COM error info result code: 0x%lX\n", info.getResultCode());
915 RTStrmPrintf(g_pStdErr, "COM error info text: %ls\n", info.getText().raw());
916
917 // allocated our own soap fault struct
918 _vbox__RuntimeFault *ex = soap_new__vbox__RuntimeFault(soap, 1);
919 // some old vbox methods return errors without setting an error in the error info,
920 // so use the error info code if it's set and the HRESULT from the method otherwise
921 if (S_OK == (ex->resultCode = info.getResultCode()))
922 ex->resultCode = apirc;
923 ex->text = ConvertComString(info.getText());
924 ex->component = ConvertComString(info.getComponent());
925 ex->interfaceID = ConvertComString(info.getInterfaceID());
926
927 // compose descriptive message
928 com::Utf8StrFmt str("VirtualBox error: %s (0x%RU32)", ex->text.c_str(), ex->resultCode);
929
930 RaiseSoapFault(soap,
931 str.c_str(),
932 SOAP_TYPE__vbox__RuntimeFault,
933 ex);
934}
935
936/****************************************************************************
937 *
938 * splitting and merging of object IDs
939 *
940 ****************************************************************************/
941
942uint64_t str2ulonglong(const char *pcsz)
943{
944 uint64_t u = 0;
945 RTStrToUInt64Full(pcsz, 16, &u);
946 return u;
947}
948
949/**
950 * Splits a managed object reference (in string form, as
951 * passed in from a SOAP method call) into two integers for
952 * session and object IDs, respectively.
953 *
954 * @param id
955 * @param sessid
956 * @param objid
957 * @return
958 */
959bool SplitManagedObjectRef(const WSDLT_ID &id,
960 uint64_t *pSessid,
961 uint64_t *pObjid)
962{
963 // 64-bit numbers in hex have 16 digits; hence
964 // the object-ref string must have 16 + "-" + 16 characters
965 std::string str;
966 if ( (id.length() == 33)
967 && (id[16] == '-')
968 )
969 {
970 char psz[34];
971 memcpy(psz, id.c_str(), 34);
972 psz[16] = '\0';
973 if (pSessid)
974 *pSessid = str2ulonglong(psz);
975 if (pObjid)
976 *pObjid = str2ulonglong(psz + 17);
977 return true;
978 }
979
980 return false;
981}
982
983/**
984 * Creates a managed object reference (in string form) from
985 * two integers representing a session and object ID, respectively.
986 *
987 * @param sz Buffer with at least 34 bytes space to receive MOR string.
988 * @param sessid
989 * @param objid
990 * @return
991 */
992void MakeManagedObjectRef(char *sz,
993 uint64_t &sessid,
994 uint64_t &objid)
995{
996 RTStrFormatNumber(sz, sessid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
997 sz[16] = '-';
998 RTStrFormatNumber(sz + 17, objid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
999}
1000
1001/****************************************************************************
1002 *
1003 * class WebServiceSession
1004 *
1005 ****************************************************************************/
1006
1007class WebServiceSessionPrivate
1008{
1009 public:
1010 ManagedObjectsMapById _mapManagedObjectsById;
1011 ManagedObjectsMapByPtr _mapManagedObjectsByPtr;
1012};
1013
1014/**
1015 * Constructor for the session object.
1016 *
1017 * Preconditions: Caller must have locked g_pSessionsLockHandle in write mode.
1018 *
1019 * @param username
1020 * @param password
1021 */
1022WebServiceSession::WebServiceSession()
1023 : _fDestructing(false),
1024 _pISession(NULL),
1025 _tLastObjectLookup(0)
1026{
1027 _pp = new WebServiceSessionPrivate;
1028 _uSessionID = RTRandU64();
1029
1030 // register this session globally
1031 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1032 g_mapSessions[_uSessionID] = this;
1033}
1034
1035/**
1036 * Destructor. Cleans up and destroys all contained managed object references on the way.
1037 *
1038 * Preconditions: Caller must have locked g_pSessionsLockHandle in write mode.
1039 */
1040WebServiceSession::~WebServiceSession()
1041{
1042 // delete us from global map first so we can't be found
1043 // any more while we're cleaning up
1044 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1045 g_mapSessions.erase(_uSessionID);
1046
1047 // notify ManagedObjectRef destructor so it won't
1048 // remove itself from the maps; this avoids rebalancing
1049 // the map's tree on every delete as well
1050 _fDestructing = true;
1051
1052 // if (_pISession)
1053 // {
1054 // delete _pISession;
1055 // _pISession = NULL;
1056 // }
1057
1058 ManagedObjectsMapById::iterator it,
1059 end = _pp->_mapManagedObjectsById.end();
1060 for (it = _pp->_mapManagedObjectsById.begin();
1061 it != end;
1062 ++it)
1063 {
1064 ManagedObjectRef *pRef = it->second;
1065 delete pRef; // this frees the contained ComPtr as well
1066 }
1067
1068 delete _pp;
1069}
1070
1071/**
1072 * Authenticate the username and password against an authentification authority.
1073 *
1074 * @return 0 if the user was successfully authenticated, or an error code
1075 * otherwise.
1076 */
1077
1078int WebServiceSession::authenticate(const char *pcszUsername,
1079 const char *pcszPassword)
1080{
1081 int rc = VERR_WEB_NOT_AUTHENTICATED;
1082
1083 util::AutoReadLock lock(g_pAuthLibLockHandle COMMA_LOCKVAL_SRC_POS);
1084
1085 static bool fAuthLibLoaded = false;
1086 static PVRDPAUTHENTRY pfnAuthEntry = NULL;
1087 static PVRDPAUTHENTRY2 pfnAuthEntry2 = NULL;
1088
1089 if (!fAuthLibLoaded)
1090 {
1091 // retrieve authentication library from system properties
1092 ComPtr<ISystemProperties> systemProperties;
1093 g_pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
1094
1095 com::Bstr authLibrary;
1096 systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
1097 com::Utf8Str filename = authLibrary;
1098
1099 WEBDEBUG(("external authentication library is '%ls'\n", authLibrary.raw()));
1100
1101 if (filename == "null")
1102 // authentication disabled, let everyone in:
1103 fAuthLibLoaded = true;
1104 else
1105 {
1106 RTLDRMOD hlibAuth = 0;
1107 do
1108 {
1109 rc = RTLdrLoad(filename.raw(), &hlibAuth);
1110 if (RT_FAILURE(rc))
1111 {
1112 WEBDEBUG(("%s() Failed to load external authentication library. Error code: %Rrc\n", __FUNCTION__, rc));
1113 break;
1114 }
1115
1116 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, "VRDPAuth2", (void**)&pfnAuthEntry2)))
1117 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, "VRDPAuth2", rc));
1118
1119 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, "VRDPAuth", (void**)&pfnAuthEntry)))
1120 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, "VRDPAuth", rc));
1121
1122 if (pfnAuthEntry || pfnAuthEntry2)
1123 fAuthLibLoaded = true;
1124
1125 } while (0);
1126 }
1127 }
1128
1129 rc = VERR_WEB_NOT_AUTHENTICATED;
1130 VRDPAuthResult result;
1131 if (pfnAuthEntry2)
1132 {
1133 result = pfnAuthEntry2(NULL, VRDPAuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1134 WEBDEBUG(("%s(): result of VRDPAuth2(): %d\n", __FUNCTION__, result));
1135 if (result == VRDPAuthAccessGranted)
1136 rc = 0;
1137 }
1138 else if (pfnAuthEntry)
1139 {
1140 result = pfnAuthEntry(NULL, VRDPAuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
1141 WEBDEBUG(("%s(): result of VRDPAuth(%s, [%d]): %d\n", __FUNCTION__, pcszUsername, strlen(pcszPassword), result));
1142 if (result == VRDPAuthAccessGranted)
1143 rc = 0;
1144 }
1145 else if (fAuthLibLoaded)
1146 // fAuthLibLoaded = true but both pointers are NULL:
1147 // then the authlib was "null" and auth was disabled
1148 rc = 0;
1149 else
1150 {
1151 WEBDEBUG(("Could not resolve VRDPAuth2 or VRDPAuth entry point"));
1152 }
1153
1154 lock.release();
1155
1156 if (!rc)
1157 {
1158 do
1159 {
1160 // now create the ISession object that this webservice session can use
1161 // (and of which IWebsessionManager::getSessionObject returns a managed object reference)
1162 ComPtr<ISession> session;
1163 if (FAILED(rc = session.createInprocObject(CLSID_Session)))
1164 {
1165 WEBDEBUG(("ERROR: cannot create session object!"));
1166 break;
1167 }
1168
1169 _pISession = new ManagedObjectRef(*this, g_pcszISession, session);
1170
1171 if (g_fVerbose)
1172 {
1173 ISession *p = session;
1174 std::string strMOR = _pISession->toWSDL();
1175 WEBDEBUG((" * %s: created session object with comptr 0x%lX, MOR = %s\n", __FUNCTION__, p, strMOR.c_str()));
1176 }
1177 } while (0);
1178 }
1179
1180 return rc;
1181}
1182
1183/**
1184 * Look up, in this session, whether a ManagedObjectRef has already been
1185 * created for the given COM pointer.
1186 *
1187 * Note how we require that a ComPtr<IUnknown> is passed, which causes a
1188 * queryInterface call when the caller passes in a different type, since
1189 * a ComPtr<IUnknown> will point to something different than a
1190 * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
1191 * our private hash table, we must search for one too.
1192 *
1193 * Preconditions: Caller must have locked g_pSessionsLockHandle in read mode.
1194 *
1195 * @param pcu pointer to a COM object.
1196 * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
1197 */
1198ManagedObjectRef* WebServiceSession::findRefFromPtr(const ComPtr<IUnknown> &pcu)
1199{
1200 // Assert(g_pSessionsLockHandle->isReadLockOnCurrentThread()); // @todo
1201
1202 IUnknown *p = pcu;
1203 uintptr_t ulp = (uintptr_t)p;
1204 ManagedObjectRef *pRef;
1205 // WEBDEBUG((" %s: looking up 0x%lX\n", __FUNCTION__, ulp));
1206 ManagedObjectsMapByPtr::iterator it = _pp->_mapManagedObjectsByPtr.find(ulp);
1207 if (it != _pp->_mapManagedObjectsByPtr.end())
1208 {
1209 pRef = it->second;
1210 WSDLT_ID id = pRef->toWSDL();
1211 WEBDEBUG((" %s: found existing ref %s for COM obj 0x%lX\n", __FUNCTION__, id.c_str(), ulp));
1212 }
1213 else
1214 pRef = NULL;
1215 return pRef;
1216}
1217
1218/**
1219 * Static method which attempts to find the session for which the given managed
1220 * object reference was created, by splitting the reference into the session and
1221 * object IDs and then looking up the session object for that session ID.
1222 *
1223 * Preconditions: Caller must have locked g_pSessionsLockHandle in read mode.
1224 *
1225 * @param id Managed object reference (with combined session and object IDs).
1226 * @return
1227 */
1228WebServiceSession* WebServiceSession::findSessionFromRef(const WSDLT_ID &id)
1229{
1230 // Assert(g_pSessionsLockHandle->isReadLockOnCurrentThread()); // @todo
1231
1232 WebServiceSession *pSession = NULL;
1233 uint64_t sessid;
1234 if (SplitManagedObjectRef(id,
1235 &sessid,
1236 NULL))
1237 {
1238 SessionsMapIterator it = g_mapSessions.find(sessid);
1239 if (it != g_mapSessions.end())
1240 pSession = it->second;
1241 }
1242 return pSession;
1243}
1244
1245/**
1246 *
1247 */
1248WSDLT_ID WebServiceSession::getSessionObject() const
1249{
1250 return _pISession->toWSDL();
1251}
1252
1253/**
1254 * Touches the webservice session to prevent it from timing out.
1255 *
1256 * Each webservice session has an internal timestamp that records
1257 * the last request made to it from the client that started it.
1258 * If no request was made within a configurable timeframe, then
1259 * the client is logged off automatically,
1260 * by calling IWebsessionManager::logoff()
1261 */
1262void WebServiceSession::touch()
1263{
1264 time(&_tLastObjectLookup);
1265}
1266
1267/**
1268 *
1269 */
1270void WebServiceSession::DumpRefs()
1271{
1272 WEBDEBUG((" dumping object refs:\n"));
1273 ManagedObjectsIteratorById
1274 iter = _pp->_mapManagedObjectsById.begin(),
1275 end = _pp->_mapManagedObjectsById.end();
1276 for (;
1277 iter != end;
1278 ++iter)
1279 {
1280 ManagedObjectRef *pRef = iter->second;
1281 uint64_t id = pRef->getID();
1282 void *p = pRef->getComPtr();
1283 WEBDEBUG((" objid %llX: comptr 0x%lX\n", id, p));
1284 }
1285}
1286
1287/****************************************************************************
1288 *
1289 * class ManagedObjectRef
1290 *
1291 ****************************************************************************/
1292
1293/**
1294 * Constructor, which assigns a unique ID to this managed object
1295 * reference and stores it two global hashes:
1296 *
1297 * a) G_mapManagedObjectsById, which maps ManagedObjectID's to
1298 * instances of this class; this hash is then used by the
1299 * findObjectFromRef() template function in vboxweb.h
1300 * to quickly retrieve the COM object from its managed
1301 * object ID (mostly in the context of the method mappers
1302 * in methodmaps.cpp, when a web service client passes in
1303 * a managed object ID);
1304 *
1305 * b) G_mapManagedObjectsByComPtr, which maps COM pointers to
1306 * instances of this class; this hash is used by
1307 * createRefFromObject() to quickly figure out whether an
1308 * instance already exists for a given COM pointer.
1309 *
1310 * This does _not_ check whether another instance already
1311 * exists in the hash. This gets called only from the
1312 * createRefFromObject() template function in vboxweb.h, which
1313 * does perform that check.
1314 *
1315 * Preconditions: Caller must have locked g_pSessionsLockHandle in write mode.
1316 *
1317 * @param pObj
1318 */
1319ManagedObjectRef::ManagedObjectRef(WebServiceSession &session,
1320 const char *pcszInterface,
1321 const ComPtr<IUnknown> &pc)
1322 : _session(session),
1323 _pObj(pc),
1324 _pcszInterface(pcszInterface)
1325{
1326 ComPtr<IUnknown> pcUnknown(pc);
1327 _ulp = (uintptr_t)(IUnknown*)pcUnknown;
1328
1329 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1330 _id = ++g_iMaxManagedObjectID;
1331 // and count globally
1332 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
1333
1334 char sz[34];
1335 MakeManagedObjectRef(sz, session._uSessionID, _id);
1336 _strID = sz;
1337
1338 session._pp->_mapManagedObjectsById[_id] = this;
1339 session._pp->_mapManagedObjectsByPtr[_ulp] = this;
1340
1341 session.touch();
1342
1343 WEBDEBUG((" * %s: MOR created for ulp 0x%lX (%s), new ID is %llX; now %lld objects total\n", __FUNCTION__, _ulp, pcszInterface, _id, cTotal));
1344}
1345
1346/**
1347 * Destructor; removes the instance from the global hash of
1348 * managed objects.
1349 *
1350 * Preconditions: Caller must have locked g_pSessionsLockHandle in write mode.
1351 */
1352ManagedObjectRef::~ManagedObjectRef()
1353{
1354 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1355 ULONG64 cTotal = --g_cManagedObjects;
1356
1357 WEBDEBUG((" * %s: deleting MOR for ID %llX (%s); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cTotal));
1358
1359 // if we're being destroyed from the session's destructor,
1360 // then that destructor is iterating over the maps, so
1361 // don't remove us there! (data integrity + speed)
1362 if (!_session._fDestructing)
1363 {
1364 WEBDEBUG((" * %s: removing from session maps\n", __FUNCTION__));
1365 _session._pp->_mapManagedObjectsById.erase(_id);
1366 if (_session._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
1367 WEBDEBUG((" WARNING: could not find %llX in _mapManagedObjectsByPtr\n", _ulp));
1368 }
1369}
1370
1371/**
1372 * Converts the ID of this managed object reference to string
1373 * form, for returning with SOAP data or similar.
1374 *
1375 * @return The ID in string form.
1376 */
1377WSDLT_ID ManagedObjectRef::toWSDL() const
1378{
1379 return _strID;
1380}
1381
1382/**
1383 * Static helper method for findObjectFromRef() template that actually
1384 * looks up the object from a given integer ID.
1385 *
1386 * This has been extracted into this non-template function to reduce
1387 * code bloat as we have the actual STL map lookup only in this function.
1388 *
1389 * This also "touches" the timestamp in the session whose ID is encoded
1390 * in the given integer ID, in order to prevent the session from timing
1391 * out.
1392 *
1393 * Preconditions: Caller must have locked g_mutexSessions.
1394 *
1395 * @param strId
1396 * @param iter
1397 * @return
1398 */
1399int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
1400 ManagedObjectRef **pRef,
1401 bool fNullAllowed)
1402{
1403 int rc = 0;
1404
1405 do
1406 {
1407 // allow NULL (== empty string) input reference, which should return a NULL pointer
1408 if (!id.length() && fNullAllowed)
1409 {
1410 *pRef = NULL;
1411 return 0;
1412 }
1413
1414 uint64_t sessid;
1415 uint64_t objid;
1416 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
1417 if (!SplitManagedObjectRef(id,
1418 &sessid,
1419 &objid))
1420 {
1421 rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
1422 break;
1423 }
1424
1425 WEBDEBUG((" %s(): sessid %llX, objid %llX\n", __FUNCTION__, sessid, objid));
1426 SessionsMapIterator it = g_mapSessions.find(sessid);
1427 if (it == g_mapSessions.end())
1428 {
1429 WEBDEBUG((" %s: cannot find session for objref %s\n", __FUNCTION__, id.c_str()));
1430 rc = VERR_WEB_INVALID_SESSION_ID;
1431 break;
1432 }
1433
1434 WebServiceSession *pSess = it->second;
1435 // "touch" session to prevent it from timing out
1436 pSess->touch();
1437
1438 ManagedObjectsIteratorById iter = pSess->_pp->_mapManagedObjectsById.find(objid);
1439 if (iter == pSess->_pp->_mapManagedObjectsById.end())
1440 {
1441 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
1442 rc = VERR_WEB_INVALID_OBJECT_ID;
1443 break;
1444 }
1445
1446 *pRef = iter->second;
1447
1448 } while (0);
1449
1450 return rc;
1451}
1452
1453/****************************************************************************
1454 *
1455 * interface IManagedObjectRef
1456 *
1457 ****************************************************************************/
1458
1459/**
1460 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
1461 * that our WSDL promises to our web service clients. This method returns a
1462 * string describing the interface that this managed object reference
1463 * supports, e.g. "IMachine".
1464 *
1465 * @param soap
1466 * @param req
1467 * @param resp
1468 * @return
1469 */
1470int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
1471 struct soap *soap,
1472 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
1473 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
1474{
1475 HRESULT rc = SOAP_OK;
1476 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1477
1478 do {
1479 util::AutoReadLock 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(("\n-- entering %s\n", __FUNCTION__));
1510
1511 do {
1512 // findRefFromId needs read lock, and the delete call below requires
1513 // the write lock, so get the write lock here
1514 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1515
1516 ManagedObjectRef *pRef;
1517 if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false)))
1518 {
1519 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
1520 break;
1521 }
1522
1523 WEBDEBUG((" found reference; deleting!\n"));
1524 delete pRef;
1525 // this removes the object from all stacks; since
1526 // there's a ComPtr<> hidden inside the reference,
1527 // this should also invoke Release() on the COM
1528 // object
1529 } while (0);
1530
1531 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1532 if (FAILED(rc))
1533 return SOAP_FAULT;
1534 return SOAP_OK;
1535}
1536
1537/****************************************************************************
1538 *
1539 * interface IWebsessionManager
1540 *
1541 ****************************************************************************/
1542
1543/**
1544 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
1545 * COM API, this is the first method that a webservice client must call before the
1546 * webservice will do anything useful.
1547 *
1548 * This returns a managed object reference to the global IVirtualBox object; into this
1549 * reference a session ID is encoded which remains constant with all managed object
1550 * references returned by other methods.
1551 *
1552 * This also creates an instance of ISession, which is stored internally with the
1553 * webservice session and can be retrieved with IWebsessionManager::getSessionObject
1554 * (__vbox__IWebsessionManager_USCOREgetSessionObject). In order for the
1555 * VirtualBox web service to do anything useful, one usually needs both a
1556 * VirtualBox and an ISession object, for which these two methods are designed.
1557 *
1558 * When the webservice client is done, it should call IWebsessionManager::logoff. This
1559 * will clean up internally (destroy all remaining managed object references and
1560 * related COM objects used internally).
1561 *
1562 * After logon, an internal timeout ensures that if the webservice client does not
1563 * call any methods, after a configurable number of seconds, the webservice will log
1564 * off the client automatically. This is to ensure that the webservice does not
1565 * drown in managed object references and eventually deny service. Still, it is
1566 * a much better solution, both for performance and cleanliness, for the webservice
1567 * client to clean up itself.
1568 *
1569 * @param
1570 * @param vbox__IWebsessionManager_USCORElogon
1571 * @param vbox__IWebsessionManager_USCORElogonResponse
1572 * @return
1573 */
1574int __vbox__IWebsessionManager_USCORElogon(
1575 struct soap*,
1576 _vbox__IWebsessionManager_USCORElogon *req,
1577 _vbox__IWebsessionManager_USCORElogonResponse *resp)
1578{
1579 HRESULT rc = SOAP_OK;
1580 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1581
1582 do {
1583 // WebServiceSession constructor tinkers with global MOR map and requires a write lock
1584 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1585
1586 // create new session; the constructor stores the new session
1587 // in the global map automatically
1588 WebServiceSession *pSession = new WebServiceSession();
1589
1590 // authenticate the user
1591 if (!(pSession->authenticate(req->username.c_str(),
1592 req->password.c_str())))
1593 {
1594 // in the new session, create a managed object reference (MOR) for the
1595 // global VirtualBox object; this encodes the session ID in the MOR so
1596 // that it will be implicitly be included in all future requests of this
1597 // webservice client
1598 ManagedObjectRef *pRef = new ManagedObjectRef(*pSession, g_pcszIVirtualBox, g_pVirtualBox);
1599 resp->returnval = pRef->toWSDL();
1600 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
1601 }
1602 } while (0);
1603
1604 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1605 if (FAILED(rc))
1606 return SOAP_FAULT;
1607 return SOAP_OK;
1608}
1609
1610/**
1611 * Returns the ISession object that was created for the webservice client
1612 * on logon.
1613 */
1614int __vbox__IWebsessionManager_USCOREgetSessionObject(
1615 struct soap*,
1616 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
1617 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
1618{
1619 HRESULT rc = SOAP_OK;
1620 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1621
1622 do {
1623 // findSessionFromRef needs read lock
1624 util::AutoReadLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1625
1626 WebServiceSession* pSession;
1627 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1628 {
1629 resp->returnval = pSession->getSessionObject();
1630 }
1631 } while (0);
1632
1633 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1634 if (FAILED(rc))
1635 return SOAP_FAULT;
1636 return SOAP_OK;
1637}
1638
1639/**
1640 * hard-coded implementation for IWebsessionManager::logoff.
1641 *
1642 * @param
1643 * @param vbox__IWebsessionManager_USCORElogon
1644 * @param vbox__IWebsessionManager_USCORElogonResponse
1645 * @return
1646 */
1647int __vbox__IWebsessionManager_USCORElogoff(
1648 struct soap*,
1649 _vbox__IWebsessionManager_USCORElogoff *req,
1650 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
1651{
1652 HRESULT rc = SOAP_OK;
1653 WEBDEBUG(("\n-- entering %s\n", __FUNCTION__));
1654
1655 do {
1656 // findSessionFromRef needs read lock, and the session destructor requires
1657 // the write lock, so get the write lock here
1658 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1659
1660 WebServiceSession* pSession;
1661 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1662 {
1663 delete pSession;
1664 // destructor cleans up
1665
1666 WEBDEBUG(("session destroyed, %d sessions left open\n", g_mapSessions.size()));
1667 }
1668 } while (0);
1669
1670 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1671 if (FAILED(rc))
1672 return SOAP_FAULT;
1673 return SOAP_OK;
1674}
Note: See TracBrowser for help on using the repository browser.

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