VirtualBox

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

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

Webservice: back out r63195

  • 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/****************************************************************************
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);
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 ComPtr<IUnknown> &pcu)
1200{
1201 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1202
1203 IUnknown *p = pcu;
1204 uintptr_t ulp = (uintptr_t)p;
1205 ManagedObjectRef *pRef;
1206 // WEBDEBUG((" %s: looking up 0x%lX\n", __FUNCTION__, ulp));
1207 ManagedObjectsMapByPtr::iterator it = _pp->_mapManagedObjectsByPtr.find(ulp);
1208 if (it != _pp->_mapManagedObjectsByPtr.end())
1209 {
1210 pRef = it->second;
1211 WSDLT_ID id = pRef->toWSDL();
1212 WEBDEBUG((" %s: found existing ref %s (%s) for COM obj 0x%lX\n", __FUNCTION__, id.c_str(), pRef->getInterfaceName(), ulp));
1213 }
1214 else
1215 pRef = NULL;
1216 return pRef;
1217}
1218
1219/**
1220 * Static method which attempts to find the session for which the given managed
1221 * object reference was created, by splitting the reference into the session and
1222 * object IDs and then looking up the session object for that session ID.
1223 *
1224 * Preconditions: Caller must have locked g_pSessionsLockHandle in read mode.
1225 *
1226 * @param id Managed object reference (with combined session and object IDs).
1227 * @return
1228 */
1229WebServiceSession* WebServiceSession::findSessionFromRef(const WSDLT_ID &id)
1230{
1231 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1232
1233 WebServiceSession *pSession = NULL;
1234 uint64_t sessid;
1235 if (SplitManagedObjectRef(id,
1236 &sessid,
1237 NULL))
1238 {
1239 SessionsMapIterator it = g_mapSessions.find(sessid);
1240 if (it != g_mapSessions.end())
1241 pSession = it->second;
1242 }
1243 return pSession;
1244}
1245
1246/**
1247 *
1248 */
1249WSDLT_ID WebServiceSession::getSessionObject() const
1250{
1251 return _pISession->toWSDL();
1252}
1253
1254/**
1255 * Touches the webservice session to prevent it from timing out.
1256 *
1257 * Each webservice session has an internal timestamp that records
1258 * the last request made to it from the client that started it.
1259 * If no request was made within a configurable timeframe, then
1260 * the client is logged off automatically,
1261 * by calling IWebsessionManager::logoff()
1262 */
1263void WebServiceSession::touch()
1264{
1265 time(&_tLastObjectLookup);
1266}
1267
1268/**
1269 *
1270 */
1271void WebServiceSession::DumpRefs()
1272{
1273 WEBDEBUG((" dumping object refs:\n"));
1274 ManagedObjectsIteratorById
1275 iter = _pp->_mapManagedObjectsById.begin(),
1276 end = _pp->_mapManagedObjectsById.end();
1277 for (;
1278 iter != end;
1279 ++iter)
1280 {
1281 ManagedObjectRef *pRef = iter->second;
1282 uint64_t id = pRef->getID();
1283 void *p = pRef->getComPtr();
1284 WEBDEBUG((" objid %llX: comptr 0x%lX\n", id, p));
1285 }
1286}
1287
1288/****************************************************************************
1289 *
1290 * class ManagedObjectRef
1291 *
1292 ****************************************************************************/
1293
1294/**
1295 * Constructor, which assigns a unique ID to this managed object
1296 * reference and stores it two global hashes:
1297 *
1298 * a) G_mapManagedObjectsById, which maps ManagedObjectID's to
1299 * instances of this class; this hash is then used by the
1300 * findObjectFromRef() template function in vboxweb.h
1301 * to quickly retrieve the COM object from its managed
1302 * object ID (mostly in the context of the method mappers
1303 * in methodmaps.cpp, when a web service client passes in
1304 * a managed object ID);
1305 *
1306 * b) G_mapManagedObjectsByComPtr, which maps COM pointers to
1307 * instances of this class; this hash is used by
1308 * createRefFromObject() to quickly figure out whether an
1309 * instance already exists for a given COM pointer.
1310 *
1311 * This does _not_ check whether another instance already
1312 * exists in the hash. This gets called only from the
1313 * createRefFromObject() template function in vboxweb.h, which
1314 * does perform that check.
1315 *
1316 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1317 *
1318 * @param pObj
1319 */
1320ManagedObjectRef::ManagedObjectRef(WebServiceSession &session,
1321 const char *pcszInterface,
1322 const ComPtr<IUnknown> &pc)
1323 : _session(session),
1324 _pObj(pc),
1325 _pcszInterface(pcszInterface)
1326{
1327 ComPtr<IUnknown> pcUnknown(pc);
1328 _ulp = (uintptr_t)(IUnknown*)pcUnknown;
1329
1330 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1331 _id = ++g_iMaxManagedObjectID;
1332 // and count globally
1333 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
1334
1335 char sz[34];
1336 MakeManagedObjectRef(sz, session._uSessionID, _id);
1337 _strID = sz;
1338
1339 session._pp->_mapManagedObjectsById[_id] = this;
1340 session._pp->_mapManagedObjectsByPtr[_ulp] = this;
1341
1342 session.touch();
1343
1344 WEBDEBUG((" * %s: MOR created for ulp 0x%lX (%s), new ID is %llX; now %lld objects total\n", __FUNCTION__, _ulp, pcszInterface, _id, cTotal));
1345}
1346
1347/**
1348 * Destructor; removes the instance from the global hash of
1349 * managed objects.
1350 *
1351 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1352 */
1353ManagedObjectRef::~ManagedObjectRef()
1354{
1355 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1356 ULONG64 cTotal = --g_cManagedObjects;
1357
1358 WEBDEBUG((" * %s: deleting MOR for ID %llX (%s); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cTotal));
1359
1360 // if we're being destroyed from the session's destructor,
1361 // then that destructor is iterating over the maps, so
1362 // don't remove us there! (data integrity + speed)
1363 if (!_session._fDestructing)
1364 {
1365 WEBDEBUG((" * %s: removing from session maps\n", __FUNCTION__));
1366 _session._pp->_mapManagedObjectsById.erase(_id);
1367 if (_session._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
1368 WEBDEBUG((" WARNING: could not find %llX in _mapManagedObjectsByPtr\n", _ulp));
1369 }
1370}
1371
1372/**
1373 * Converts the ID of this managed object reference to string
1374 * form, for returning with SOAP data or similar.
1375 *
1376 * @return The ID in string form.
1377 */
1378WSDLT_ID ManagedObjectRef::toWSDL() const
1379{
1380 return _strID;
1381}
1382
1383/**
1384 * Static helper method for findObjectFromRef() template that actually
1385 * looks up the object from a given integer ID.
1386 *
1387 * This has been extracted into this non-template function to reduce
1388 * code bloat as we have the actual STL map lookup only in this function.
1389 *
1390 * This also "touches" the timestamp in the session whose ID is encoded
1391 * in the given integer ID, in order to prevent the session from timing
1392 * out.
1393 *
1394 * Preconditions: Caller must have locked g_mutexSessions.
1395 *
1396 * @param strId
1397 * @param iter
1398 * @return
1399 */
1400int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
1401 ManagedObjectRef **pRef,
1402 bool fNullAllowed)
1403{
1404 int rc = 0;
1405
1406 do
1407 {
1408 // allow NULL (== empty string) input reference, which should return a NULL pointer
1409 if (!id.length() && fNullAllowed)
1410 {
1411 *pRef = NULL;
1412 return 0;
1413 }
1414
1415 uint64_t sessid;
1416 uint64_t objid;
1417 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
1418 if (!SplitManagedObjectRef(id,
1419 &sessid,
1420 &objid))
1421 {
1422 rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
1423 break;
1424 }
1425
1426 WEBDEBUG((" %s(): sessid %llX, objid %llX\n", __FUNCTION__, sessid, objid));
1427 SessionsMapIterator it = g_mapSessions.find(sessid);
1428 if (it == g_mapSessions.end())
1429 {
1430 WEBDEBUG((" %s: cannot find session for objref %s\n", __FUNCTION__, id.c_str()));
1431 rc = VERR_WEB_INVALID_SESSION_ID;
1432 break;
1433 }
1434
1435 WebServiceSession *pSess = it->second;
1436 // "touch" session to prevent it from timing out
1437 pSess->touch();
1438
1439 ManagedObjectsIteratorById iter = pSess->_pp->_mapManagedObjectsById.find(objid);
1440 if (iter == pSess->_pp->_mapManagedObjectsById.end())
1441 {
1442 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
1443 rc = VERR_WEB_INVALID_OBJECT_ID;
1444 break;
1445 }
1446
1447 *pRef = iter->second;
1448
1449 } while (0);
1450
1451 return rc;
1452}
1453
1454/****************************************************************************
1455 *
1456 * interface IManagedObjectRef
1457 *
1458 ****************************************************************************/
1459
1460/**
1461 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
1462 * that our WSDL promises to our web service clients. This method returns a
1463 * string describing the interface that this managed object reference
1464 * supports, e.g. "IMachine".
1465 *
1466 * @param soap
1467 * @param req
1468 * @param resp
1469 * @return
1470 */
1471int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
1472 struct soap *soap,
1473 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
1474 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
1475{
1476 HRESULT rc = SOAP_OK;
1477 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1478
1479 do {
1480 // findRefFromId require the lock
1481 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1482
1483 ManagedObjectRef *pRef;
1484 if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false))
1485 resp->returnval = pRef->getInterfaceName();
1486
1487 } while (0);
1488
1489 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1490 if (FAILED(rc))
1491 return SOAP_FAULT;
1492 return SOAP_OK;
1493}
1494
1495/**
1496 * This is the hard-coded implementation for the IManagedObjectRef::release()
1497 * that our WSDL promises to our web service clients. This method releases
1498 * a managed object reference and removes it from our stacks.
1499 *
1500 * @param soap
1501 * @param req
1502 * @param resp
1503 * @return
1504 */
1505int __vbox__IManagedObjectRef_USCORErelease(
1506 struct soap *soap,
1507 _vbox__IManagedObjectRef_USCORErelease *req,
1508 _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
1509{
1510 HRESULT rc = SOAP_OK;
1511 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1512
1513 do {
1514 // findRefFromId and the delete call below require the lock
1515 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1516
1517 ManagedObjectRef *pRef;
1518 if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false)))
1519 {
1520 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
1521 break;
1522 }
1523
1524 WEBDEBUG((" found reference; deleting!\n"));
1525 delete pRef;
1526 // this removes the object from all stacks; since
1527 // there's a ComPtr<> hidden inside the reference,
1528 // this should also invoke Release() on the COM
1529 // object
1530 } while (0);
1531
1532 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1533 if (FAILED(rc))
1534 return SOAP_FAULT;
1535 return SOAP_OK;
1536}
1537
1538/****************************************************************************
1539 *
1540 * interface IWebsessionManager
1541 *
1542 ****************************************************************************/
1543
1544/**
1545 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
1546 * COM API, this is the first method that a webservice client must call before the
1547 * webservice will do anything useful.
1548 *
1549 * This returns a managed object reference to the global IVirtualBox object; into this
1550 * reference a session ID is encoded which remains constant with all managed object
1551 * references returned by other methods.
1552 *
1553 * This also creates an instance of ISession, which is stored internally with the
1554 * webservice session and can be retrieved with IWebsessionManager::getSessionObject
1555 * (__vbox__IWebsessionManager_USCOREgetSessionObject). In order for the
1556 * VirtualBox web service to do anything useful, one usually needs both a
1557 * VirtualBox and an ISession object, for which these two methods are designed.
1558 *
1559 * When the webservice client is done, it should call IWebsessionManager::logoff. This
1560 * will clean up internally (destroy all remaining managed object references and
1561 * related COM objects used internally).
1562 *
1563 * After logon, an internal timeout ensures that if the webservice client does not
1564 * call any methods, after a configurable number of seconds, the webservice will log
1565 * off the client automatically. This is to ensure that the webservice does not
1566 * drown in managed object references and eventually deny service. Still, it is
1567 * a much better solution, both for performance and cleanliness, for the webservice
1568 * client to clean up itself.
1569 *
1570 * @param
1571 * @param vbox__IWebsessionManager_USCORElogon
1572 * @param vbox__IWebsessionManager_USCORElogonResponse
1573 * @return
1574 */
1575int __vbox__IWebsessionManager_USCORElogon(
1576 struct soap*,
1577 _vbox__IWebsessionManager_USCORElogon *req,
1578 _vbox__IWebsessionManager_USCORElogonResponse *resp)
1579{
1580 HRESULT rc = SOAP_OK;
1581 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1582
1583 do {
1584 // WebServiceSession constructor tinkers with global MOR map and requires a write lock
1585 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1586
1587 // create new session; the constructor stores the new session
1588 // in the global map automatically
1589 WebServiceSession *pSession = new WebServiceSession();
1590
1591 // authenticate the user
1592 if (!(pSession->authenticate(req->username.c_str(),
1593 req->password.c_str())))
1594 {
1595 // in the new session, create a managed object reference (MOR) for the
1596 // global VirtualBox object; this encodes the session ID in the MOR so
1597 // that it will be implicitly be included in all future requests of this
1598 // webservice client
1599 ManagedObjectRef *pRef = new ManagedObjectRef(*pSession, g_pcszIVirtualBox, g_pVirtualBox);
1600 resp->returnval = pRef->toWSDL();
1601 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
1602 }
1603 } while (0);
1604
1605 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1606 if (FAILED(rc))
1607 return SOAP_FAULT;
1608 return SOAP_OK;
1609}
1610
1611/**
1612 * Returns the ISession object that was created for the webservice client
1613 * on logon.
1614 */
1615int __vbox__IWebsessionManager_USCOREgetSessionObject(
1616 struct soap*,
1617 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
1618 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
1619{
1620 HRESULT rc = SOAP_OK;
1621 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1622
1623 do {
1624 // findSessionFromRef needs lock
1625 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1626
1627 WebServiceSession* pSession;
1628 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1629 resp->returnval = pSession->getSessionObject();
1630
1631 } while (0);
1632
1633 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1634 if (FAILED(rc))
1635 return SOAP_FAULT;
1636 return SOAP_OK;
1637}
1638
1639/**
1640 * hard-coded implementation for IWebsessionManager::logoff.
1641 *
1642 * @param
1643 * @param vbox__IWebsessionManager_USCORElogon
1644 * @param vbox__IWebsessionManager_USCORElogonResponse
1645 * @return
1646 */
1647int __vbox__IWebsessionManager_USCORElogoff(
1648 struct soap*,
1649 _vbox__IWebsessionManager_USCORElogoff *req,
1650 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
1651{
1652 HRESULT rc = SOAP_OK;
1653 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1654
1655 do {
1656 // findSessionFromRef and the session destructor require the lock
1657 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1658
1659 WebServiceSession* pSession;
1660 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1661 {
1662 delete pSession;
1663 // destructor cleans up
1664
1665 WEBDEBUG(("session destroyed, %d sessions left open\n", g_mapSessions.size()));
1666 }
1667 } while (0);
1668
1669 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1670 if (FAILED(rc))
1671 return SOAP_FAULT;
1672 return SOAP_OK;
1673}
Note: See TracBrowser for help on using the repository browser.

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