VirtualBox

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

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

Main/webservice: must use a recv/send timeout, otherwise connection keepalive can result in keeping all workers "busy" with idle connections

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