VirtualBox

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

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

coding style

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