VirtualBox

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

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

Webservice: avoid calling QueryInterface for every object lookup when interface UUIDs can be more easily compared (this avoids constantly creating and deleting temporary stubs in XPCOM)

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