VirtualBox

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

Last change on this file since 35577 was 35571, checked in by vboxsync, 14 years ago

Main/webservice: build fix

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