VirtualBox

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

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

Webservice: enable separate SOAP queue thread; fix logging

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette