VirtualBox

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

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

Main: use settings struct for machine user data; remove iprt::MiniString::raw() and change all occurences to c_str()

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