VirtualBox

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

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

Webservice: synchronize logging better, add timestamp to each log output

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