VirtualBox

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

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

Frontends/VBoxBalloonCtrl: make the log rotation configurable, change to daily instead of weekly.

  • Property filesplitter.c set to Makefile.kmk
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 67.7 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_1DAY; // max 1 day 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 rotation (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 pszLogFile = ValueUnion.psz;
831 break;
832
833 case 'R':
834 g_cHistory = ValueUnion.u32;
835 break;
836
837 case 'S':
838 g_uHistoryFileSize = ValueUnion.u64;
839 break;
840
841 case 'I':
842 g_uHistoryFileTime = ValueUnion.u32;
843 break;
844
845 case 'P':
846 pszPidFile = ValueUnion.psz;
847 break;
848
849 case 'T':
850 g_cMaxWorkerThreads = ValueUnion.u32;
851 break;
852
853 case 'k':
854 g_cMaxKeepAlive = ValueUnion.u32;
855 break;
856
857 case 'h':
858 DisplayHelp();
859 return 0;
860
861 case 'v':
862 g_fVerbose = true;
863 break;
864
865#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
866 case 'b':
867 g_fDaemonize = true;
868 break;
869#endif
870 case 'V':
871 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
872 return 0;
873
874 default:
875 rc = RTGetOptPrintError(c, &ValueUnion);
876 return rc;
877 }
878 }
879
880 /* create release logger */
881 PRTLOGGER pLoggerRelease;
882 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
883 RTUINT fFlags = RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG;
884#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
885 fFlags |= RTLOGFLAGS_USECRLF;
886#endif
887 char szError[RTPATH_MAX + 128] = "";
888 int vrc = RTLogCreateEx(&pLoggerRelease, fFlags, "all",
889 "VBOXWEBSRV_RELEASE_LOG", RT_ELEMENTS(s_apszGroups), s_apszGroups, RTLOGDEST_STDOUT,
890 WebLogHeaderFooter, g_cHistory, g_uHistoryFileSize, g_uHistoryFileTime,
891 szError, sizeof(szError), pszLogFile);
892 if (RT_SUCCESS(vrc))
893 {
894 /* register this logger as the release logger */
895 RTLogRelSetDefaultInstance(pLoggerRelease);
896
897 /* Explicitly flush the log in case of VBOXWEBSRV_RELEASE_LOG=buffered. */
898 RTLogFlush(pLoggerRelease);
899 }
900 else
901 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, vrc);
902
903#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
904 if (g_fDaemonize)
905 {
906 /* prepare release logging */
907 char szLogFile[RTPATH_MAX];
908
909 rc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
910 if (RT_FAILURE(rc))
911 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not get base directory for logging: %Rrc", rc);
912 rc = RTPathAppend(szLogFile, sizeof(szLogFile), "vboxwebsrv.log");
913 if (RT_FAILURE(rc))
914 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not construct logging path: %Rrc", rc);
915
916 rc = RTProcDaemonizeUsingFork(false /* fNoChDir */, false /* fNoClose */, pszPidFile);
917 if (RT_FAILURE(rc))
918 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to daemonize, rc=%Rrc. exiting.", rc);
919
920 /* create release logger */
921 PRTLOGGER pLoggerReleaseFile;
922 static const char * const s_apszGroupsFile[] = VBOX_LOGGROUP_NAMES;
923 RTUINT fFlagsFile = RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG;
924#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
925 fFlagsFile |= RTLOGFLAGS_USECRLF;
926#endif
927 char szErrorFile[RTPATH_MAX + 128] = "";
928 int vrc = RTLogCreateEx(&pLoggerReleaseFile, fFlagsFile, "all",
929 "VBOXWEBSRV_RELEASE_LOG", RT_ELEMENTS(s_apszGroupsFile), s_apszGroupsFile, RTLOGDEST_FILE,
930 WebLogHeaderFooter, g_cHistory, g_uHistoryFileSize, g_uHistoryFileTime,
931 szErrorFile, sizeof(szErrorFile), szLogFile);
932 if (RT_SUCCESS(vrc))
933 {
934 /* register this logger as the release logger */
935 RTLogRelSetDefaultInstance(pLoggerReleaseFile);
936
937 /* Explicitly flush the log in case of VBOXWEBSRV_RELEASE_LOG=buffered. */
938 RTLogFlush(pLoggerReleaseFile);
939 }
940 else
941 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szErrorFile, vrc);
942 }
943#endif
944
945 // initialize COM/XPCOM
946 HRESULT hrc = com::Initialize();
947 if (FAILED(hrc))
948 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to initialize COM! hrc=%Rhrc\n", hrc);
949
950 hrc = g_pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
951 if (FAILED(hrc))
952 {
953 RTMsgError("failed to create the VirtualBoxClient object!");
954 com::ErrorInfo info;
955 if (!info.isFullAvailable() && !info.isBasicAvailable())
956 {
957 com::GluePrintRCMessage(hrc);
958 RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
959 }
960 else
961 com::GluePrintErrorInfo(info);
962 return RTEXITCODE_FAILURE;
963 }
964
965 hrc = g_pVirtualBoxClient->COMGETTER(VirtualBox)(g_pVirtualBox.asOutParam());
966 if (FAILED(hrc))
967 {
968 RTMsgError("Failed to get VirtualBox object (rc=%Rhrc)!", hrc);
969 return RTEXITCODE_FAILURE;
970 }
971
972 /* VirtualBoxClient events registration. */
973 ComPtr<IEventListener> vboxClientListener;
974 {
975 ComPtr<IEventSource> pES;
976 CHECK_ERROR(g_pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
977 ComObjPtr<VirtualBoxClientEventListenerImpl> clientListener;
978 clientListener.createObject();
979 clientListener->init(new VirtualBoxClientEventListener());
980 vboxClientListener = clientListener;
981 com::SafeArray<VBoxEventType_T> eventTypes;
982 eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
983 CHECK_ERROR(pES, RegisterListener(vboxClientListener, ComSafeArrayAsInParam(eventTypes), true));
984 }
985
986 // create the global mutexes
987 g_pAuthLibLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
988 g_pVirtualBoxLockHandle = new util::RWLockHandle(util::LOCKCLASS_WEBSERVICE);
989 g_pSessionsLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
990 g_pThreadsLockHandle = new util::RWLockHandle(util::LOCKCLASS_OBJECTSTATE);
991 g_pWebLogLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
992
993 // SOAP queue pumper thread
994 rc = RTThreadCreate(NULL,
995 fntQPumper,
996 NULL, // pvUser
997 0, // cbStack (default)
998 RTTHREADTYPE_MAIN_WORKER,
999 0, // flags
1000 "SQPmp");
1001 if (RT_FAILURE(rc))
1002 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot start SOAP queue pumper thread: %Rrc", rc);
1003
1004 // watchdog thread
1005 if (g_iWatchdogTimeoutSecs > 0)
1006 {
1007 // start our watchdog thread
1008 rc = RTThreadCreate(NULL,
1009 fntWatchdog,
1010 NULL,
1011 0,
1012 RTTHREADTYPE_MAIN_WORKER,
1013 0,
1014 "Watchdog");
1015 if (RT_FAILURE(rc))
1016 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot start watchdog thread: %Rrc", rc);
1017 }
1018
1019 com::EventQueue *pQ = com::EventQueue::getMainEventQueue();
1020 for (;;)
1021 {
1022 // we have to process main event queue
1023 WEBDEBUG(("Pumping COM event queue\n"));
1024 rc = pQ->processEventQueue(RT_INDEFINITE_WAIT);
1025 if (RT_FAILURE(rc))
1026 RTMsgError("processEventQueue -> %Rrc", rc);
1027 }
1028
1029 /* VirtualBoxClient events unregistration. */
1030 if (vboxClientListener)
1031 {
1032 ComPtr<IEventSource> pES;
1033 CHECK_ERROR(g_pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1034 if (!pES.isNull())
1035 CHECK_ERROR(pES, UnregisterListener(vboxClientListener));
1036 vboxClientListener.setNull();
1037 }
1038
1039 com::Shutdown();
1040
1041 return 0;
1042}
1043
1044/****************************************************************************
1045 *
1046 * Watchdog thread
1047 *
1048 ****************************************************************************/
1049
1050/**
1051 * Watchdog thread, runs in the background while the webservice is alive.
1052 *
1053 * This gets started by main() and runs in the background to check all sessions
1054 * for whether they have been no requests in a configurable timeout period. In
1055 * that case, the session is automatically logged off.
1056 */
1057int fntWatchdog(RTTHREAD ThreadSelf, void *pvUser)
1058{
1059 // store a log prefix for this thread
1060 util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
1061 g_mapThreads[RTThreadSelf()] = "[W ]";
1062 thrLock.release();
1063
1064 WEBDEBUG(("Watchdog thread started\n"));
1065
1066 while (1)
1067 {
1068 WEBDEBUG(("Watchdog: sleeping %d seconds\n", g_iWatchdogCheckInterval));
1069 RTThreadSleep(g_iWatchdogCheckInterval * 1000);
1070
1071 time_t tNow;
1072 time(&tNow);
1073
1074 // we're messing with sessions, so lock them
1075 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1076 WEBDEBUG(("Watchdog: checking %d sessions\n", g_mapSessions.size()));
1077
1078 SessionsMap::iterator it = g_mapSessions.begin(),
1079 itEnd = g_mapSessions.end();
1080 while (it != itEnd)
1081 {
1082 WebServiceSession *pSession = it->second;
1083 WEBDEBUG(("Watchdog: tNow: %d, session timestamp: %d\n", tNow, pSession->getLastObjectLookup()));
1084 if ( tNow
1085 > pSession->getLastObjectLookup() + g_iWatchdogTimeoutSecs
1086 )
1087 {
1088 WEBDEBUG(("Watchdog: Session %llX timed out, deleting\n", pSession->getID()));
1089 delete pSession;
1090 it = g_mapSessions.begin();
1091 }
1092 else
1093 ++it;
1094 }
1095 }
1096
1097 WEBDEBUG(("Watchdog thread ending\n"));
1098 return 0;
1099}
1100
1101/****************************************************************************
1102 *
1103 * SOAP exceptions
1104 *
1105 ****************************************************************************/
1106
1107/**
1108 * Helper function to raise a SOAP fault. Called by the other helper
1109 * functions, which raise specific SOAP faults.
1110 *
1111 * @param soap
1112 * @param str
1113 * @param extype
1114 * @param ex
1115 */
1116void RaiseSoapFault(struct soap *soap,
1117 const char *pcsz,
1118 int extype,
1119 void *ex)
1120{
1121 // raise the fault
1122 soap_sender_fault(soap, pcsz, NULL);
1123
1124 struct SOAP_ENV__Detail *pDetail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
1125
1126 // without the following, gSOAP crashes miserably when sending out the
1127 // data because it will try to serialize all fields (stupid documentation)
1128 memset(pDetail, 0, sizeof(struct SOAP_ENV__Detail));
1129
1130 // fill extended info depending on SOAP version
1131 if (soap->version == 2) // SOAP 1.2 is used
1132 {
1133 soap->fault->SOAP_ENV__Detail = pDetail;
1134 soap->fault->SOAP_ENV__Detail->__type = extype;
1135 soap->fault->SOAP_ENV__Detail->fault = ex;
1136 soap->fault->SOAP_ENV__Detail->__any = NULL; // no other XML data
1137 }
1138 else
1139 {
1140 soap->fault->detail = pDetail;
1141 soap->fault->detail->__type = extype;
1142 soap->fault->detail->fault = ex;
1143 soap->fault->detail->__any = NULL; // no other XML data
1144 }
1145}
1146
1147/**
1148 * Raises a SOAP fault that signals that an invalid object was passed.
1149 *
1150 * @param soap
1151 * @param obj
1152 */
1153void RaiseSoapInvalidObjectFault(struct soap *soap,
1154 WSDLT_ID obj)
1155{
1156 _vbox__InvalidObjectFault *ex = soap_new__vbox__InvalidObjectFault(soap, 1);
1157 ex->badObjectID = obj;
1158
1159 std::string str("VirtualBox error: ");
1160 str += "Invalid managed object reference \"" + obj + "\"";
1161
1162 RaiseSoapFault(soap,
1163 str.c_str(),
1164 SOAP_TYPE__vbox__InvalidObjectFault,
1165 ex);
1166}
1167
1168/**
1169 * Return a safe C++ string from the given COM string,
1170 * without crashing if the COM string is empty.
1171 * @param bstr
1172 * @return
1173 */
1174std::string ConvertComString(const com::Bstr &bstr)
1175{
1176 com::Utf8Str ustr(bstr);
1177 return ustr.c_str(); // @todo r=dj since the length is known, we can probably use a better std::string allocator
1178}
1179
1180/**
1181 * Return a safe C++ string from the given COM UUID,
1182 * without crashing if the UUID is empty.
1183 * @param bstr
1184 * @return
1185 */
1186std::string ConvertComString(const com::Guid &uuid)
1187{
1188 com::Utf8Str ustr(uuid.toString());
1189 return ustr.c_str(); // @todo r=dj since the length is known, we can probably use a better std::string allocator
1190}
1191
1192/**
1193 * Raises a SOAP runtime fault. Implementation for the RaiseSoapRuntimeFault template
1194 * function in vboxweb.h.
1195 *
1196 * @param pObj
1197 */
1198void RaiseSoapRuntimeFault2(struct soap *soap,
1199 HRESULT apirc,
1200 IUnknown *pObj,
1201 const com::Guid &iid)
1202{
1203 com::ErrorInfo info(pObj, iid.ref());
1204
1205 WEBDEBUG((" error, raising SOAP exception\n"));
1206
1207 RTStrmPrintf(g_pStdErr, "API return code: 0x%08X (%Rhrc)\n", apirc, apirc);
1208 RTStrmPrintf(g_pStdErr, "COM error info result code: 0x%lX\n", info.getResultCode());
1209 RTStrmPrintf(g_pStdErr, "COM error info text: %ls\n", info.getText().raw());
1210
1211 // allocated our own soap fault struct
1212 _vbox__RuntimeFault *ex = soap_new__vbox__RuntimeFault(soap, 1);
1213 // some old vbox methods return errors without setting an error in the error info,
1214 // so use the error info code if it's set and the HRESULT from the method otherwise
1215 if (S_OK == (ex->resultCode = info.getResultCode()))
1216 ex->resultCode = apirc;
1217 ex->text = ConvertComString(info.getText());
1218 ex->component = ConvertComString(info.getComponent());
1219 ex->interfaceID = ConvertComString(info.getInterfaceID());
1220
1221 // compose descriptive message
1222 com::Utf8StrFmt str("VirtualBox error: %s (0x%lX)", ex->text.c_str(), ex->resultCode);
1223
1224 RaiseSoapFault(soap,
1225 str.c_str(),
1226 SOAP_TYPE__vbox__RuntimeFault,
1227 ex);
1228}
1229
1230/****************************************************************************
1231 *
1232 * splitting and merging of object IDs
1233 *
1234 ****************************************************************************/
1235
1236uint64_t str2ulonglong(const char *pcsz)
1237{
1238 uint64_t u = 0;
1239 RTStrToUInt64Full(pcsz, 16, &u);
1240 return u;
1241}
1242
1243/**
1244 * Splits a managed object reference (in string form, as
1245 * passed in from a SOAP method call) into two integers for
1246 * session and object IDs, respectively.
1247 *
1248 * @param id
1249 * @param sessid
1250 * @param objid
1251 * @return
1252 */
1253bool SplitManagedObjectRef(const WSDLT_ID &id,
1254 uint64_t *pSessid,
1255 uint64_t *pObjid)
1256{
1257 // 64-bit numbers in hex have 16 digits; hence
1258 // the object-ref string must have 16 + "-" + 16 characters
1259 std::string str;
1260 if ( (id.length() == 33)
1261 && (id[16] == '-')
1262 )
1263 {
1264 char psz[34];
1265 memcpy(psz, id.c_str(), 34);
1266 psz[16] = '\0';
1267 if (pSessid)
1268 *pSessid = str2ulonglong(psz);
1269 if (pObjid)
1270 *pObjid = str2ulonglong(psz + 17);
1271 return true;
1272 }
1273
1274 return false;
1275}
1276
1277/**
1278 * Creates a managed object reference (in string form) from
1279 * two integers representing a session and object ID, respectively.
1280 *
1281 * @param sz Buffer with at least 34 bytes space to receive MOR string.
1282 * @param sessid
1283 * @param objid
1284 * @return
1285 */
1286void MakeManagedObjectRef(char *sz,
1287 uint64_t &sessid,
1288 uint64_t &objid)
1289{
1290 RTStrFormatNumber(sz, sessid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
1291 sz[16] = '-';
1292 RTStrFormatNumber(sz + 17, objid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
1293}
1294
1295/****************************************************************************
1296 *
1297 * class WebServiceSession
1298 *
1299 ****************************************************************************/
1300
1301class WebServiceSessionPrivate
1302{
1303 public:
1304 ManagedObjectsMapById _mapManagedObjectsById;
1305 ManagedObjectsMapByPtr _mapManagedObjectsByPtr;
1306};
1307
1308/**
1309 * Constructor for the session object.
1310 *
1311 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1312 *
1313 * @param username
1314 * @param password
1315 */
1316WebServiceSession::WebServiceSession()
1317 : _fDestructing(false),
1318 _pISession(NULL),
1319 _tLastObjectLookup(0)
1320{
1321 _pp = new WebServiceSessionPrivate;
1322 _uSessionID = RTRandU64();
1323
1324 // register this session globally
1325 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1326 g_mapSessions[_uSessionID] = this;
1327}
1328
1329/**
1330 * Destructor. Cleans up and destroys all contained managed object references on the way.
1331 *
1332 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1333 */
1334WebServiceSession::~WebServiceSession()
1335{
1336 // delete us from global map first so we can't be found
1337 // any more while we're cleaning up
1338 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1339 g_mapSessions.erase(_uSessionID);
1340
1341 // notify ManagedObjectRef destructor so it won't
1342 // remove itself from the maps; this avoids rebalancing
1343 // the map's tree on every delete as well
1344 _fDestructing = true;
1345
1346 // if (_pISession)
1347 // {
1348 // delete _pISession;
1349 // _pISession = NULL;
1350 // }
1351
1352 ManagedObjectsMapById::iterator it,
1353 end = _pp->_mapManagedObjectsById.end();
1354 for (it = _pp->_mapManagedObjectsById.begin();
1355 it != end;
1356 ++it)
1357 {
1358 ManagedObjectRef *pRef = it->second;
1359 delete pRef; // this frees the contained ComPtr as well
1360 }
1361
1362 delete _pp;
1363}
1364
1365/**
1366 * Authenticate the username and password against an authentication authority.
1367 *
1368 * @return 0 if the user was successfully authenticated, or an error code
1369 * otherwise.
1370 */
1371
1372int WebServiceSession::authenticate(const char *pcszUsername,
1373 const char *pcszPassword,
1374 IVirtualBox **ppVirtualBox)
1375{
1376 int rc = VERR_WEB_NOT_AUTHENTICATED;
1377 ComPtr<IVirtualBox> pVirtualBox;
1378 {
1379 util::AutoReadLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
1380 pVirtualBox = g_pVirtualBox;
1381 }
1382 pVirtualBox.queryInterfaceTo(ppVirtualBox);
1383 if (pVirtualBox.isNull())
1384 return rc;
1385
1386 util::AutoReadLock lock(g_pAuthLibLockHandle COMMA_LOCKVAL_SRC_POS);
1387
1388 static bool fAuthLibLoaded = false;
1389 static PAUTHENTRY pfnAuthEntry = NULL;
1390 static PAUTHENTRY2 pfnAuthEntry2 = NULL;
1391 static PAUTHENTRY3 pfnAuthEntry3 = NULL;
1392
1393 if (!fAuthLibLoaded)
1394 {
1395 // retrieve authentication library from system properties
1396 ComPtr<ISystemProperties> systemProperties;
1397 pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
1398
1399 com::Bstr authLibrary;
1400 systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
1401 com::Utf8Str filename = authLibrary;
1402
1403 WEBDEBUG(("external authentication library is '%ls'\n", authLibrary.raw()));
1404
1405 if (filename == "null")
1406 // authentication disabled, let everyone in:
1407 fAuthLibLoaded = true;
1408 else
1409 {
1410 RTLDRMOD hlibAuth = 0;
1411 do
1412 {
1413 rc = RTLdrLoad(filename.c_str(), &hlibAuth);
1414 if (RT_FAILURE(rc))
1415 {
1416 WEBDEBUG(("%s() Failed to load external authentication library. Error code: %Rrc\n", __FUNCTION__, rc));
1417 break;
1418 }
1419
1420 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY3_NAME, (void**)&pfnAuthEntry3)))
1421 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY3_NAME, rc));
1422
1423 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY2_NAME, (void**)&pfnAuthEntry2)))
1424 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY2_NAME, rc));
1425
1426 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY_NAME, (void**)&pfnAuthEntry)))
1427 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY_NAME, rc));
1428
1429 if (pfnAuthEntry || pfnAuthEntry2 || pfnAuthEntry3)
1430 fAuthLibLoaded = true;
1431
1432 } while (0);
1433 }
1434 }
1435
1436 rc = VERR_WEB_NOT_AUTHENTICATED;
1437 AuthResult result;
1438 if (pfnAuthEntry3)
1439 {
1440 result = pfnAuthEntry3("webservice", NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1441 WEBDEBUG(("%s(): result of AuthEntry(): %d\n", __FUNCTION__, result));
1442 if (result == AuthResultAccessGranted)
1443 rc = 0;
1444 }
1445 else if (pfnAuthEntry2)
1446 {
1447 result = pfnAuthEntry2(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1448 WEBDEBUG(("%s(): result of VRDPAuth2(): %d\n", __FUNCTION__, result));
1449 if (result == AuthResultAccessGranted)
1450 rc = 0;
1451 }
1452 else if (pfnAuthEntry)
1453 {
1454 result = pfnAuthEntry(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
1455 WEBDEBUG(("%s(): result of VRDPAuth(%s, [%d]): %d\n", __FUNCTION__, pcszUsername, strlen(pcszPassword), result));
1456 if (result == AuthResultAccessGranted)
1457 rc = 0;
1458 }
1459 else if (fAuthLibLoaded)
1460 // fAuthLibLoaded = true but both pointers are NULL:
1461 // then the authlib was "null" and auth was disabled
1462 rc = 0;
1463 else
1464 {
1465 WEBDEBUG(("Could not resolve AuthEntry, VRDPAuth2 or VRDPAuth entry point"));
1466 }
1467
1468 lock.release();
1469
1470 if (!rc)
1471 {
1472 do
1473 {
1474 // now create the ISession object that this webservice session can use
1475 // (and of which IWebsessionManager::getSessionObject returns a managed object reference)
1476 ComPtr<ISession> session;
1477 rc = g_pVirtualBoxClient->COMGETTER(Session)(session.asOutParam());
1478 if (FAILED(rc))
1479 {
1480 WEBDEBUG(("ERROR: cannot create session object!"));
1481 break;
1482 }
1483
1484 ComPtr<IUnknown> p2 = session;
1485 _pISession = new ManagedObjectRef(*this,
1486 p2, // IUnknown *pobjUnknown
1487 session, // void *pobjInterface
1488 com::Guid(COM_IIDOF(ISession)),
1489 g_pcszISession);
1490
1491 if (g_fVerbose)
1492 {
1493 ISession *p = session;
1494 WEBDEBUG((" * %s: created session object with comptr 0x%lX, MOR = %s\n", __FUNCTION__, p, _pISession->getWSDLID().c_str()));
1495 }
1496 } while (0);
1497 }
1498
1499 return rc;
1500}
1501
1502/**
1503 * Look up, in this session, whether a ManagedObjectRef has already been
1504 * created for the given COM pointer.
1505 *
1506 * Note how we require that a ComPtr<IUnknown> is passed, which causes a
1507 * queryInterface call when the caller passes in a different type, since
1508 * a ComPtr<IUnknown> will point to something different than a
1509 * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
1510 * our private hash table, we must search for one too.
1511 *
1512 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1513 *
1514 * @param pcu pointer to a COM object.
1515 * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
1516 */
1517ManagedObjectRef* WebServiceSession::findRefFromPtr(const IUnknown *pObject)
1518{
1519 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1520
1521 uintptr_t ulp = (uintptr_t)pObject;
1522 // WEBDEBUG((" %s: looking up 0x%lX\n", __FUNCTION__, ulp));
1523 ManagedObjectsMapByPtr::iterator it = _pp->_mapManagedObjectsByPtr.find(ulp);
1524 if (it != _pp->_mapManagedObjectsByPtr.end())
1525 {
1526 ManagedObjectRef *pRef = it->second;
1527 WEBDEBUG((" %s: found existing ref %s (%s) for COM obj 0x%lX\n", __FUNCTION__, pRef->getWSDLID().c_str(), pRef->getInterfaceName(), ulp));
1528 return pRef;
1529 }
1530
1531 return NULL;
1532}
1533
1534/**
1535 * Static method which attempts to find the session for which the given managed
1536 * object reference was created, by splitting the reference into the session and
1537 * object IDs and then looking up the session object for that session ID.
1538 *
1539 * Preconditions: Caller must have locked g_pSessionsLockHandle in read mode.
1540 *
1541 * @param id Managed object reference (with combined session and object IDs).
1542 * @return
1543 */
1544WebServiceSession* WebServiceSession::findSessionFromRef(const WSDLT_ID &id)
1545{
1546 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1547
1548 WebServiceSession *pSession = NULL;
1549 uint64_t sessid;
1550 if (SplitManagedObjectRef(id,
1551 &sessid,
1552 NULL))
1553 {
1554 SessionsMapIterator it = g_mapSessions.find(sessid);
1555 if (it != g_mapSessions.end())
1556 pSession = it->second;
1557 }
1558 return pSession;
1559}
1560
1561/**
1562 *
1563 */
1564const WSDLT_ID& WebServiceSession::getSessionWSDLID() const
1565{
1566 return _pISession->getWSDLID();
1567}
1568
1569/**
1570 * Touches the webservice session to prevent it from timing out.
1571 *
1572 * Each webservice session has an internal timestamp that records
1573 * the last request made to it from the client that started it.
1574 * If no request was made within a configurable timeframe, then
1575 * the client is logged off automatically,
1576 * by calling IWebsessionManager::logoff()
1577 */
1578void WebServiceSession::touch()
1579{
1580 time(&_tLastObjectLookup);
1581}
1582
1583
1584/****************************************************************************
1585 *
1586 * class ManagedObjectRef
1587 *
1588 ****************************************************************************/
1589
1590/**
1591 * Constructor, which assigns a unique ID to this managed object
1592 * reference and stores it two global hashes:
1593 *
1594 * a) G_mapManagedObjectsById, which maps ManagedObjectID's to
1595 * instances of this class; this hash is then used by the
1596 * findObjectFromRef() template function in vboxweb.h
1597 * to quickly retrieve the COM object from its managed
1598 * object ID (mostly in the context of the method mappers
1599 * in methodmaps.cpp, when a web service client passes in
1600 * a managed object ID);
1601 *
1602 * b) G_mapManagedObjectsByComPtr, which maps COM pointers to
1603 * instances of this class; this hash is used by
1604 * createRefFromObject() to quickly figure out whether an
1605 * instance already exists for a given COM pointer.
1606 *
1607 * This constructor calls AddRef() on the given COM object, and
1608 * the destructor will call Release(). We require two input pointers
1609 * for that COM object, one generic IUnknown* pointer which is used
1610 * as the map key, and a specific interface pointer (e.g. IMachine*)
1611 * which must support the interface given in guidInterface. All
1612 * three values are returned by getPtr(), which gives future callers
1613 * a chance to reuse the specific interface pointer without having
1614 * to call QueryInterface, which can be expensive.
1615 *
1616 * This does _not_ check whether another instance already
1617 * exists in the hash. This gets called only from the
1618 * createOrFindRefFromComPtr() template function in vboxweb.h, which
1619 * does perform that check.
1620 *
1621 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1622 *
1623 * @param session Session to which the MOR will be added.
1624 * @param pobjUnknown Pointer to IUnknown* interface for the COM object; this will be used in the hashes.
1625 * @param pobjInterface Pointer to a specific interface for the COM object, described by guidInterface.
1626 * @param guidInterface Interface which pobjInterface points to.
1627 * @param pcszInterface String representation of that interface (e.g. "IMachine") for readability and logging.
1628 */
1629ManagedObjectRef::ManagedObjectRef(WebServiceSession &session,
1630 IUnknown *pobjUnknown,
1631 void *pobjInterface,
1632 const com::Guid &guidInterface,
1633 const char *pcszInterface)
1634 : _session(session),
1635 _pobjUnknown(pobjUnknown),
1636 _pobjInterface(pobjInterface),
1637 _guidInterface(guidInterface),
1638 _pcszInterface(pcszInterface)
1639{
1640 Assert(pobjUnknown);
1641 Assert(pobjInterface);
1642
1643 // keep both stubs alive while this MOR exists (matching Release() calls are in destructor)
1644 uint32_t cRefs1 = pobjUnknown->AddRef();
1645 uint32_t cRefs2 = ((IUnknown*)pobjInterface)->AddRef();
1646 _ulp = (uintptr_t)pobjUnknown;
1647
1648 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1649 _id = ++g_iMaxManagedObjectID;
1650 // and count globally
1651 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
1652
1653 char sz[34];
1654 MakeManagedObjectRef(sz, session._uSessionID, _id);
1655 _strID = sz;
1656
1657 session._pp->_mapManagedObjectsById[_id] = this;
1658 session._pp->_mapManagedObjectsByPtr[_ulp] = this;
1659
1660 session.touch();
1661
1662 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",
1663 __FUNCTION__,
1664 pcszInterface,
1665 pobjInterface,
1666 pobjUnknown,
1667 cRefs1,
1668 cRefs2,
1669 _id,
1670 cTotal));
1671}
1672
1673/**
1674 * Destructor; removes the instance from the global hash of
1675 * managed objects. Calls Release() on the contained COM object.
1676 *
1677 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1678 */
1679ManagedObjectRef::~ManagedObjectRef()
1680{
1681 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1682 ULONG64 cTotal = --g_cManagedObjects;
1683
1684 Assert(_pobjUnknown);
1685 Assert(_pobjInterface);
1686
1687 // we called AddRef() on both interfaces, so call Release() on
1688 // both as well, but in reverse order
1689 uint32_t cRefs2 = ((IUnknown*)_pobjInterface)->Release();
1690 uint32_t cRefs1 = _pobjUnknown->Release();
1691 WEBDEBUG((" * %s: deleting MOR for ID %llX (%s; COM refcount now %RI32/%RI32); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cRefs1, cRefs2, cTotal));
1692
1693 // if we're being destroyed from the session's destructor,
1694 // then that destructor is iterating over the maps, so
1695 // don't remove us there! (data integrity + speed)
1696 if (!_session._fDestructing)
1697 {
1698 WEBDEBUG((" * %s: removing from session maps\n", __FUNCTION__));
1699 _session._pp->_mapManagedObjectsById.erase(_id);
1700 if (_session._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
1701 WEBDEBUG((" WARNING: could not find %llX in _mapManagedObjectsByPtr\n", _ulp));
1702 }
1703}
1704
1705/**
1706 * Static helper method for findObjectFromRef() template that actually
1707 * looks up the object from a given integer ID.
1708 *
1709 * This has been extracted into this non-template function to reduce
1710 * code bloat as we have the actual STL map lookup only in this function.
1711 *
1712 * This also "touches" the timestamp in the session whose ID is encoded
1713 * in the given integer ID, in order to prevent the session from timing
1714 * out.
1715 *
1716 * Preconditions: Caller must have locked g_mutexSessions.
1717 *
1718 * @param strId
1719 * @param iter
1720 * @return
1721 */
1722int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
1723 ManagedObjectRef **pRef,
1724 bool fNullAllowed)
1725{
1726 int rc = 0;
1727
1728 do
1729 {
1730 // allow NULL (== empty string) input reference, which should return a NULL pointer
1731 if (!id.length() && fNullAllowed)
1732 {
1733 *pRef = NULL;
1734 return 0;
1735 }
1736
1737 uint64_t sessid;
1738 uint64_t objid;
1739 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
1740 if (!SplitManagedObjectRef(id,
1741 &sessid,
1742 &objid))
1743 {
1744 rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
1745 break;
1746 }
1747
1748 SessionsMapIterator it = g_mapSessions.find(sessid);
1749 if (it == g_mapSessions.end())
1750 {
1751 WEBDEBUG((" %s: cannot find session for objref %s\n", __FUNCTION__, id.c_str()));
1752 rc = VERR_WEB_INVALID_SESSION_ID;
1753 break;
1754 }
1755
1756 WebServiceSession *pSess = it->second;
1757 // "touch" session to prevent it from timing out
1758 pSess->touch();
1759
1760 ManagedObjectsIteratorById iter = pSess->_pp->_mapManagedObjectsById.find(objid);
1761 if (iter == pSess->_pp->_mapManagedObjectsById.end())
1762 {
1763 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
1764 rc = VERR_WEB_INVALID_OBJECT_ID;
1765 break;
1766 }
1767
1768 *pRef = iter->second;
1769
1770 } while (0);
1771
1772 return rc;
1773}
1774
1775/****************************************************************************
1776 *
1777 * interface IManagedObjectRef
1778 *
1779 ****************************************************************************/
1780
1781/**
1782 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
1783 * that our WSDL promises to our web service clients. This method returns a
1784 * string describing the interface that this managed object reference
1785 * supports, e.g. "IMachine".
1786 *
1787 * @param soap
1788 * @param req
1789 * @param resp
1790 * @return
1791 */
1792int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
1793 struct soap *soap,
1794 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
1795 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
1796{
1797 HRESULT rc = S_OK;
1798 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1799
1800 do
1801 {
1802 // findRefFromId require the lock
1803 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1804
1805 ManagedObjectRef *pRef;
1806 if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false))
1807 resp->returnval = pRef->getInterfaceName();
1808
1809 } while (0);
1810
1811 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1812 if (FAILED(rc))
1813 return SOAP_FAULT;
1814 return SOAP_OK;
1815}
1816
1817/**
1818 * This is the hard-coded implementation for the IManagedObjectRef::release()
1819 * that our WSDL promises to our web service clients. This method releases
1820 * a managed object reference and removes it from our stacks.
1821 *
1822 * @param soap
1823 * @param req
1824 * @param resp
1825 * @return
1826 */
1827int __vbox__IManagedObjectRef_USCORErelease(
1828 struct soap *soap,
1829 _vbox__IManagedObjectRef_USCORErelease *req,
1830 _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
1831{
1832 HRESULT rc = S_OK;
1833 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1834
1835 do
1836 {
1837 // findRefFromId and the delete call below require the lock
1838 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1839
1840 ManagedObjectRef *pRef;
1841 if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false)))
1842 {
1843 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
1844 break;
1845 }
1846
1847 WEBDEBUG((" found reference; deleting!\n"));
1848 // this removes the object from all stacks; since
1849 // there's a ComPtr<> hidden inside the reference,
1850 // this should also invoke Release() on the COM
1851 // object
1852 delete pRef;
1853 } while (0);
1854
1855 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1856 if (FAILED(rc))
1857 return SOAP_FAULT;
1858 return SOAP_OK;
1859}
1860
1861/****************************************************************************
1862 *
1863 * interface IWebsessionManager
1864 *
1865 ****************************************************************************/
1866
1867/**
1868 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
1869 * COM API, this is the first method that a webservice client must call before the
1870 * webservice will do anything useful.
1871 *
1872 * This returns a managed object reference to the global IVirtualBox object; into this
1873 * reference a session ID is encoded which remains constant with all managed object
1874 * references returned by other methods.
1875 *
1876 * This also creates an instance of ISession, which is stored internally with the
1877 * webservice session and can be retrieved with IWebsessionManager::getSessionObject
1878 * (__vbox__IWebsessionManager_USCOREgetSessionObject). In order for the
1879 * VirtualBox web service to do anything useful, one usually needs both a
1880 * VirtualBox and an ISession object, for which these two methods are designed.
1881 *
1882 * When the webservice client is done, it should call IWebsessionManager::logoff. This
1883 * will clean up internally (destroy all remaining managed object references and
1884 * related COM objects used internally).
1885 *
1886 * After logon, an internal timeout ensures that if the webservice client does not
1887 * call any methods, after a configurable number of seconds, the webservice will log
1888 * off the client automatically. This is to ensure that the webservice does not
1889 * drown in managed object references and eventually deny service. Still, it is
1890 * a much better solution, both for performance and cleanliness, for the webservice
1891 * client to clean up itself.
1892 *
1893 * @param
1894 * @param vbox__IWebsessionManager_USCORElogon
1895 * @param vbox__IWebsessionManager_USCORElogonResponse
1896 * @return
1897 */
1898int __vbox__IWebsessionManager_USCORElogon(
1899 struct soap *soap,
1900 _vbox__IWebsessionManager_USCORElogon *req,
1901 _vbox__IWebsessionManager_USCORElogonResponse *resp)
1902{
1903 HRESULT rc = S_OK;
1904 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1905
1906 do
1907 {
1908 // WebServiceSession constructor tinkers with global MOR map and requires a write lock
1909 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1910
1911 // create new session; the constructor stores the new session
1912 // in the global map automatically
1913 WebServiceSession *pSession = new WebServiceSession();
1914 ComPtr<IVirtualBox> pVirtualBox;
1915
1916 // authenticate the user
1917 if (!(pSession->authenticate(req->username.c_str(),
1918 req->password.c_str(),
1919 pVirtualBox.asOutParam())))
1920 {
1921 // in the new session, create a managed object reference (MOR) for the
1922 // global VirtualBox object; this encodes the session ID in the MOR so
1923 // that it will be implicitly be included in all future requests of this
1924 // webservice client
1925 ComPtr<IUnknown> p2 = pVirtualBox;
1926 if (pVirtualBox.isNull() || p2.isNull())
1927 {
1928 rc = E_FAIL;
1929 break;
1930 }
1931 ManagedObjectRef *pRef = new ManagedObjectRef(*pSession,
1932 p2, // IUnknown *pobjUnknown
1933 pVirtualBox, // void *pobjInterface
1934 COM_IIDOF(IVirtualBox),
1935 g_pcszIVirtualBox);
1936 resp->returnval = pRef->getWSDLID();
1937 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
1938 }
1939 else
1940 rc = E_FAIL;
1941 } while (0);
1942
1943 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1944 if (FAILED(rc))
1945 return SOAP_FAULT;
1946 return SOAP_OK;
1947}
1948
1949/**
1950 * Returns the ISession object that was created for the webservice client
1951 * on logon.
1952 */
1953int __vbox__IWebsessionManager_USCOREgetSessionObject(
1954 struct soap*,
1955 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
1956 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
1957{
1958 HRESULT rc = S_OK;
1959 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1960
1961 do
1962 {
1963 // findSessionFromRef needs lock
1964 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1965
1966 WebServiceSession* pSession;
1967 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
1968 resp->returnval = pSession->getSessionWSDLID();
1969
1970 } while (0);
1971
1972 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
1973 if (FAILED(rc))
1974 return SOAP_FAULT;
1975 return SOAP_OK;
1976}
1977
1978/**
1979 * hard-coded implementation for IWebsessionManager::logoff.
1980 *
1981 * @param
1982 * @param vbox__IWebsessionManager_USCORElogon
1983 * @param vbox__IWebsessionManager_USCORElogonResponse
1984 * @return
1985 */
1986int __vbox__IWebsessionManager_USCORElogoff(
1987 struct soap*,
1988 _vbox__IWebsessionManager_USCORElogoff *req,
1989 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
1990{
1991 HRESULT rc = S_OK;
1992 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
1993
1994 do
1995 {
1996 // findSessionFromRef and the session destructor require the lock
1997 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1998
1999 WebServiceSession* pSession;
2000 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
2001 {
2002 delete pSession;
2003 // destructor cleans up
2004
2005 WEBDEBUG(("session destroyed, %d sessions left open\n", g_mapSessions.size()));
2006 }
2007 } while (0);
2008
2009 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
2010 if (FAILED(rc))
2011 return SOAP_FAULT;
2012 return SOAP_OK;
2013}
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