VirtualBox

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

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

*: Added svn:keywords where missing.

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