VirtualBox

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

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

webservice: introduce global lock for converting method parameters

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