VirtualBox

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

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

Main/webservice: when daemonized use a release logger, default log destination is .VirtualBox/vboxwebsrv.log

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

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