VirtualBox

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

最後變更 在這個檔案從41045是 41045,由 vboxsync 提交於 13 年 前

Main/webservice: build fix

  • 屬性 filesplitter.c 設為 Makefile.kmk
  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Id Revision
檔案大小: 75.2 KB
 
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) 2007-2012 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.alldomusa.eu.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19// shared webservice header
20#include "vboxweb.h"
21
22// vbox headers
23#include <VBox/com/com.h>
24#include <VBox/com/array.h>
25#include <VBox/com/string.h>
26#include <VBox/com/ErrorInfo.h>
27#include <VBox/com/errorprint.h>
28#include <VBox/com/EventQueue.h>
29#include <VBox/com/listeners.h>
30#include <VBox/VBoxAuth.h>
31#include <VBox/version.h>
32#include <VBox/log.h>
33
34#include <iprt/buildconfig.h>
35#include <iprt/ctype.h>
36#include <iprt/getopt.h>
37#include <iprt/initterm.h>
38#include <iprt/ldr.h>
39#include <iprt/message.h>
40#include <iprt/process.h>
41#include <iprt/rand.h>
42#include <iprt/semaphore.h>
43#include <iprt/critsect.h>
44#include <iprt/string.h>
45#include <iprt/thread.h>
46#include <iprt/time.h>
47#include <iprt/path.h>
48#include <iprt/system.h>
49#include <iprt/base64.h>
50#include <iprt/stream.h>
51#include <iprt/asm.h>
52
53// workaround for compile problems on gcc 4.1
54#ifdef __GNUC__
55#pragma GCC visibility push(default)
56#endif
57
58// gSOAP headers (must come after vbox includes because it checks for conflicting defs)
59#include "soapH.h"
60
61// standard headers
62#include <map>
63#include <list>
64
65#ifdef __GNUC__
66#pragma GCC visibility pop
67#endif
68
69// include generated namespaces table
70#include "vboxwebsrv.nsmap"
71
72RT_C_DECLS_BEGIN
73
74// declarations for the generated WSDL text
75extern DECLIMPORT(const unsigned char) g_abVBoxWebWSDL[];
76extern DECLIMPORT(const unsigned) g_cbVBoxWebWSDL;
77
78RT_C_DECLS_END
79
80static void WebLogSoapError(struct soap *soap);
81
82/****************************************************************************
83 *
84 * private typedefs
85 *
86 ****************************************************************************/
87
88typedef std::map<uint64_t, ManagedObjectRef*>
89 ManagedObjectsMapById;
90typedef std::map<uint64_t, ManagedObjectRef*>::iterator
91 ManagedObjectsIteratorById;
92typedef std::map<uintptr_t, ManagedObjectRef*>
93 ManagedObjectsMapByPtr;
94
95typedef std::map<uint64_t, WebServiceSession*>
96 SessionsMap;
97typedef std::map<uint64_t, WebServiceSession*>::iterator
98 SessionsMapIterator;
99
100int fntWatchdog(RTTHREAD ThreadSelf, void *pvUser);
101
102/****************************************************************************
103 *
104 * Read-only global variables
105 *
106 ****************************************************************************/
107
108static ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
109
110// generated strings in methodmaps.cpp
111extern const char *g_pcszISession,
112 *g_pcszIVirtualBox;
113
114// globals for vboxweb command-line arguments
115#define DEFAULT_TIMEOUT_SECS 300
116#define DEFAULT_TIMEOUT_SECS_STRING "300"
117int g_iWatchdogTimeoutSecs = DEFAULT_TIMEOUT_SECS;
118int g_iWatchdogCheckInterval = 5;
119
120const char *g_pcszBindToHost = NULL; // host; NULL = localhost
121unsigned int g_uBindToPort = 18083; // port
122unsigned int g_uBacklog = 100; // backlog = max queue size for requests
123
124#ifdef WITH_OPENSSL
125bool g_fSSL = false; // if SSL is enabled
126const char *g_pcszKeyFile = NULL; // server key file
127const char *g_pcszPassword = NULL; // password for server key
128const char *g_pcszCACert = NULL; // file with trusted CA certificates
129const char *g_pcszCAPath = NULL; // directory with trusted CA certificates
130const char *g_pcszDHFile = NULL; // DH file name or DH key length in bits, NULL=use RSA
131const char *g_pcszRandFile = NULL; // file with random data seed
132const char *g_pcszSID = "vboxwebsrv"; // server ID for SSL session cache
133#endif /* WITH_OPENSSL */
134
135unsigned int g_cMaxWorkerThreads = 100; // max. no. of worker threads
136unsigned int g_cMaxKeepAlive = 100; // maximum number of soap requests in one connection
137
138const char *g_pcszAuthentication = NULL; // web service authentication
139
140uint32_t g_cHistory = 10; // enable log rotation, 10 files
141uint32_t g_uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
142uint64_t g_uHistoryFileSize = 100 * _1M; // max 100MB per file
143bool g_fVerbose = false; // be verbose
144
145bool g_fDaemonize = false; // run in background.
146
147const WSDLT_ID g_EmptyWSDLID; // for NULL MORs
148
149/****************************************************************************
150 *
151 * Writeable global variables
152 *
153 ****************************************************************************/
154
155// The one global SOAP queue created by main().
156class SoapQ;
157SoapQ *g_pSoapQ = NULL;
158
159// this mutex protects the auth lib and authentication
160util::WriteLockHandle *g_pAuthLibLockHandle;
161
162// this mutex protects the global VirtualBox reference below
163static util::RWLockHandle *g_pVirtualBoxLockHandle;
164
165static ComPtr<IVirtualBox> g_pVirtualBox = NULL;
166
167// this mutex protects all of the below
168util::WriteLockHandle *g_pSessionsLockHandle;
169
170SessionsMap g_mapSessions;
171ULONG64 g_iMaxManagedObjectID = 0;
172ULONG64 g_cManagedObjects = 0;
173
174// this mutex protects g_mapThreads
175util::RWLockHandle *g_pThreadsLockHandle;
176
177// this mutex synchronizes logging
178util::WriteLockHandle *g_pWebLogLockHandle;
179
180// Threads map, so we can quickly map an RTTHREAD struct to a logger prefix
181typedef std::map<RTTHREAD, com::Utf8Str> ThreadsMap;
182ThreadsMap g_mapThreads;
183
184/****************************************************************************
185 *
186 * Command line help
187 *
188 ****************************************************************************/
189
190static const RTGETOPTDEF g_aOptions[]
191 = {
192 { "--help", 'h', RTGETOPT_REQ_NOTHING }, /* for DisplayHelp() */
193#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
194 { "--background", 'b', RTGETOPT_REQ_NOTHING },
195#endif
196 { "--host", 'H', RTGETOPT_REQ_STRING },
197 { "--port", 'p', RTGETOPT_REQ_UINT32 },
198#ifdef WITH_OPENSSL
199 { "--ssl", 's', RTGETOPT_REQ_NOTHING },
200 { "--keyfile", 'K', RTGETOPT_REQ_STRING },
201 { "--passwordfile", 'a', RTGETOPT_REQ_STRING },
202 { "--cacert", 'c', RTGETOPT_REQ_STRING },
203 { "--capath", 'C', RTGETOPT_REQ_STRING },
204 { "--dhfile", 'D', RTGETOPT_REQ_STRING },
205 { "--randfile", 'r', RTGETOPT_REQ_STRING },
206#endif /* WITH_OPENSSL */
207 { "--timeout", 't', RTGETOPT_REQ_UINT32 },
208 { "--check-interval", 'i', RTGETOPT_REQ_UINT32 },
209 { "--threads", 'T', RTGETOPT_REQ_UINT32 },
210 { "--keepalive", 'k', RTGETOPT_REQ_UINT32 },
211 { "--authentication", 'A', RTGETOPT_REQ_STRING },
212 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
213 { "--pidfile", 'P', RTGETOPT_REQ_STRING },
214 { "--logfile", 'F', RTGETOPT_REQ_STRING },
215 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 },
216 { "--logsize", 'S', RTGETOPT_REQ_UINT64 },
217 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 }
218 };
219
220void DisplayHelp()
221{
222 RTStrmPrintf(g_pStdErr, "\nUsage: vboxwebsrv [options]\n\nSupported options (default values in brackets):\n");
223 for (unsigned i = 0;
224 i < RT_ELEMENTS(g_aOptions);
225 ++i)
226 {
227 std::string str(g_aOptions[i].pszLong);
228 str += ", -";
229 str += g_aOptions[i].iShort;
230 str += ":";
231
232 const char *pcszDescr = "";
233
234 switch (g_aOptions[i].iShort)
235 {
236 case 'h':
237 pcszDescr = "Print this help message and exit.";
238 break;
239
240#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
241 case 'b':
242 pcszDescr = "Run in background (daemon mode).";
243 break;
244#endif
245
246 case 'H':
247 pcszDescr = "The host to bind to (localhost).";
248 break;
249
250 case 'p':
251 pcszDescr = "The port to bind to (18083).";
252 break;
253
254#ifdef WITH_OPENSSL
255 case 's':
256 pcszDescr = "Enable SSL/TLS encryption.";
257 break;
258
259 case 'K':
260 pcszDescr = "Server key and certificate file, PEM format (\"\").";
261 break;
262
263 case 'a':
264 pcszDescr = "File name for password to server key (\"\").";
265 break;
266
267 case 'c':
268 pcszDescr = "CA certificate file, PEM format (\"\").";
269 break;
270
271 case 'C':
272 pcszDescr = "CA certificate path (\"\").";
273 break;
274
275 case 'D':
276 pcszDescr = "DH file name or DH key length in bits (\"\").";
277 break;
278
279 case 'r':
280 pcszDescr = "File containing seed for random number generator (\"\").";
281 break;
282#endif /* WITH_OPENSSL */
283
284 case 't':
285 pcszDescr = "Session timeout in seconds; 0 = disable timeouts (" DEFAULT_TIMEOUT_SECS_STRING ").";
286 break;
287
288 case 'T':
289 pcszDescr = "Maximum number of worker threads to run in parallel (100).";
290 break;
291
292 case 'k':
293 pcszDescr = "Maximum number of requests before a socket will be closed (100).";
294 break;
295
296 case 'A':
297 pcszDescr = "Authentication method for the webservice (\"\").";
298 break;
299
300 case 'i':
301 pcszDescr = "Frequency of timeout checks in seconds (5).";
302 break;
303
304 case 'v':
305 pcszDescr = "Be verbose.";
306 break;
307
308 case 'P':
309 pcszDescr = "Name of the PID file which is created when the daemon was started.";
310 break;
311
312 case 'F':
313 pcszDescr = "Name of file to write log to (no file).";
314 break;
315
316 case 'R':
317 pcszDescr = "Number of log files (0 disables log rotation).";
318 break;
319
320 case 'S':
321 pcszDescr = "Maximum size of a log file to trigger rotation (bytes).";
322 break;
323
324 case 'I':
325 pcszDescr = "Maximum time interval to trigger log rotation (seconds).";
326 break;
327 }
328
329 RTStrmPrintf(g_pStdErr, "%-23s%s\n", str.c_str(), pcszDescr);
330 }
331}
332
333/****************************************************************************
334 *
335 * SoapQ, SoapThread (multithreading)
336 *
337 ****************************************************************************/
338
339class SoapQ;
340
341class SoapThread
342{
343public:
344 /**
345 * Constructor. Creates the new thread and makes it call process() for processing the queue.
346 * @param u Thread number. (So we can count from 1 and be readable.)
347 * @param q SoapQ instance which has the queue to process.
348 * @param soap struct soap instance from main() which we copy here.
349 */
350 SoapThread(size_t u,
351 SoapQ &q,
352 const struct soap *soap)
353 : m_u(u),
354 m_strThread(com::Utf8StrFmt("SQW%02d", m_u)),
355 m_pQ(&q)
356 {
357 // make a copy of the soap struct for the new thread
358 m_soap = soap_copy(soap);
359 m_soap->fget = fnHttpGet;
360
361 /* The soap.max_keep_alive value can be set to the maximum keep-alive calls allowed,
362 * which is important to avoid a client from holding a thread indefinitely.
363 * http://www.cs.fsu.edu/~engelen/soapdoc2.html#sec:keepalive
364 *
365 * Strings with 8-bit content can hold ASCII (default) or UTF8. The latter is
366 * possible by enabling the SOAP_C_UTFSTRING flag.
367 */
368 soap_set_omode(m_soap, SOAP_IO_KEEPALIVE | SOAP_C_UTFSTRING);
369 soap_set_imode(m_soap, SOAP_IO_KEEPALIVE | SOAP_C_UTFSTRING);
370 m_soap->max_keep_alive = g_cMaxKeepAlive;
371
372 int rc = RTThreadCreate(&m_pThread,
373 fntWrapper,
374 this, // pvUser
375 0, // cbStack,
376 RTTHREADTYPE_MAIN_HEAVY_WORKER,
377 0,
378 m_strThread.c_str());
379 if (RT_FAILURE(rc))
380 {
381 RTMsgError("Cannot start worker thread %d: %Rrc\n", u, rc);
382 exit(1);
383 }
384 }
385
386 void process();
387
388 static int fnHttpGet(struct soap *soap)
389 {
390 char *s = strchr(soap->path, '?');
391 if (!s || strcmp(s, "?wsdl"))
392 return SOAP_GET_METHOD;
393 soap_response(soap, SOAP_HTML);
394 soap_send_raw(soap, (const char *)g_abVBoxWebWSDL, g_cbVBoxWebWSDL);
395 soap_end_send(soap);
396 return SOAP_OK;
397 }
398
399 /**
400 * Static function that can be passed to RTThreadCreate and that calls
401 * process() on the SoapThread instance passed as the thread parameter.
402 * @param pThread
403 * @param pvThread
404 * @return
405 */
406 static int fntWrapper(RTTHREAD pThread, void *pvThread)
407 {
408 SoapThread *pst = (SoapThread*)pvThread;
409 pst->process(); // this never returns really
410 return 0;
411 }
412
413 size_t m_u; // thread number
414 com::Utf8Str m_strThread; // thread name ("SoapQWrkXX")
415 SoapQ *m_pQ; // the single SOAP queue that all the threads service
416 struct soap *m_soap; // copy of the soap structure for this thread (from soap_copy())
417 RTTHREAD m_pThread; // IPRT thread struct for this thread
418};
419
420/**
421 * SOAP queue encapsulation. There is only one instance of this, to
422 * which add() adds a queue item (called on the main thread),
423 * and from which get() fetch items, called from each queue thread.
424 */
425class SoapQ
426{
427public:
428
429 /**
430 * Constructor. Creates the soap queue.
431 * @param pSoap
432 */
433 SoapQ(const struct soap *pSoap)
434 : m_soap(pSoap),
435 m_mutex(util::LOCKCLASS_OBJECTSTATE), // lowest lock order, no other may be held while this is held
436 m_cIdleThreads(0)
437 {
438 RTSemEventMultiCreate(&m_event);
439 }
440
441 ~SoapQ()
442 {
443 RTSemEventMultiDestroy(m_event);
444 }
445
446 /**
447 * Adds the given socket to the SOAP queue and posts the
448 * member event sem to wake up the workers. Called on the main thread
449 * whenever a socket has work to do. Creates a new SOAP thread on the
450 * first call or when all existing threads are busy.
451 * @param s Socket from soap_accept() which has work to do.
452 */
453 uint32_t add(int s)
454 {
455 uint32_t cItems;
456 util::AutoWriteLock qlock(m_mutex COMMA_LOCKVAL_SRC_POS);
457
458 // if no threads have yet been created, or if all threads are busy,
459 // create a new SOAP thread
460 if ( !m_cIdleThreads
461 // but only if we're not exceeding the global maximum (default is 100)
462 && (m_llAllThreads.size() < g_cMaxWorkerThreads)
463 )
464 {
465 SoapThread *pst = new SoapThread(m_llAllThreads.size() + 1,
466 *this,
467 m_soap);
468 m_llAllThreads.push_back(pst);
469 util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
470 g_mapThreads[pst->m_pThread] = com::Utf8StrFmt("[%3u]", pst->m_u);
471 ++m_cIdleThreads;
472 }
473
474 // enqueue the socket of this connection and post eventsem so that
475 // one of the threads (possibly the one just created) can pick it up
476 m_llSocketsQ.push_back(s);
477 cItems = m_llSocketsQ.size();
478 qlock.release();
479
480 // unblock one of the worker threads
481 RTSemEventMultiSignal(m_event);
482
483 return cItems;
484 }
485
486 /**
487 * Blocks the current thread until work comes in; then returns
488 * the SOAP socket which has work to do. This reduces m_cIdleThreads
489 * by one, and the caller MUST call done() when it's done processing.
490 * Called from the worker threads.
491 * @param cIdleThreads out: no. of threads which are currently idle (not counting the caller)
492 * @param cThreads out: total no. of SOAP threads running
493 * @return
494 */
495 int get(size_t &cIdleThreads, size_t &cThreads)
496 {
497 while (1)
498 {
499 // wait for something to happen
500 RTSemEventMultiWait(m_event, RT_INDEFINITE_WAIT);
501
502 util::AutoWriteLock qlock(m_mutex COMMA_LOCKVAL_SRC_POS);
503 if (m_llSocketsQ.size())
504 {
505 int socket = m_llSocketsQ.front();
506 m_llSocketsQ.pop_front();
507 cIdleThreads = --m_cIdleThreads;
508 cThreads = m_llAllThreads.size();
509
510 // reset the multi event only if the queue is now empty; otherwise
511 // another thread will also wake up when we release the mutex and
512 // process another one
513 if (m_llSocketsQ.size() == 0)
514 RTSemEventMultiReset(m_event);
515
516 qlock.release();
517
518 return socket;
519 }
520
521 // nothing to do: keep looping
522 }
523 }
524
525 /**
526 * To be called by a worker thread after fetching an item from the
527 * queue via get() and having finished its lengthy processing.
528 */
529 void done()
530 {
531 util::AutoWriteLock qlock(m_mutex COMMA_LOCKVAL_SRC_POS);
532 ++m_cIdleThreads;
533 }
534
535 const struct soap *m_soap; // soap structure created by main(), passed to constructor
536
537 util::WriteLockHandle m_mutex;
538 RTSEMEVENTMULTI m_event; // posted by add(), blocked on by get()
539
540 std::list<SoapThread*> m_llAllThreads; // all the threads created by the constructor
541 size_t m_cIdleThreads; // threads which are currently idle (statistics)
542
543 // A std::list abused as a queue; this contains the actual jobs to do,
544 // each int being a socket from soap_accept()
545 std::list<int> m_llSocketsQ;
546};
547
548/**
549 * Thread function for each of the SOAP queue worker threads. This keeps
550 * running, blocks on the event semaphore in SoapThread.SoapQ and picks
551 * up a socket from the queue therein, which has been put there by
552 * beginProcessing().
553 */
554void SoapThread::process()
555{
556 WebLog("New SOAP thread started\n");
557
558 while (1)
559 {
560 // wait for a socket to arrive on the queue
561 size_t cIdleThreads = 0, cThreads = 0;
562 m_soap->socket = m_pQ->get(cIdleThreads, cThreads);
563
564 WebLog("Processing connection from IP=%lu.%lu.%lu.%lu socket=%d (%d out of %d threads idle)\n",
565 (m_soap->ip >> 24) & 0xFF,
566 (m_soap->ip >> 16) & 0xFF,
567 (m_soap->ip >> 8) & 0xFF,
568 m_soap->ip & 0xFF,
569 m_soap->socket,
570 cIdleThreads,
571 cThreads);
572
573 // Ensure that we don't get stuck indefinitely for connections using
574 // keepalive, otherwise stale connections tie up worker threads.
575 m_soap->send_timeout = 60;
576 m_soap->recv_timeout = 60;
577 // process the request; this goes into the COM code in methodmaps.cpp
578 do {
579#ifdef WITH_OPENSSL
580 if (g_fSSL && soap_ssl_accept(m_soap))
581 {
582 WebLogSoapError(m_soap);
583 break;
584 }
585#endif /* WITH_OPENSSL */
586 soap_serve(m_soap);
587 } while (0);
588
589 soap_destroy(m_soap); // clean up class instances
590 soap_end(m_soap); // clean up everything and close socket
591
592 // tell the queue we're idle again
593 m_pQ->done();
594 }
595}
596
597/****************************************************************************
598 *
599 * VirtualBoxClient event listener
600 *
601 ****************************************************************************/
602
603class VirtualBoxClientEventListener
604{
605public:
606 VirtualBoxClientEventListener()
607 {
608 }
609
610 virtual ~VirtualBoxClientEventListener()
611 {
612 }
613
614 HRESULT init()
615 {
616 return S_OK;
617 }
618
619 void uninit()
620 {
621 }
622
623
624 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
625 {
626 switch (aType)
627 {
628 case VBoxEventType_OnVBoxSVCAvailabilityChanged:
629 {
630 ComPtr<IVBoxSVCAvailabilityChangedEvent> pVSACEv = aEvent;
631 Assert(pVSACEv);
632 BOOL fAvailable = FALSE;
633 pVSACEv->COMGETTER(Available)(&fAvailable);
634 if (!fAvailable)
635 {
636 WebLog("VBoxSVC became unavailable\n");
637 {
638 util::AutoWriteLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
639 g_pVirtualBox = NULL;
640 }
641 {
642 // we're messing with sessions, so lock them
643 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
644 WEBDEBUG(("SVC unavailable: deleting %d sessions\n", g_mapSessions.size()));
645
646 SessionsMap::iterator it = g_mapSessions.begin(),
647 itEnd = g_mapSessions.end();
648 while (it != itEnd)
649 {
650 WebServiceSession *pSession = it->second;
651 WEBDEBUG(("SVC unavailable: Session %llX stale, deleting\n", pSession->getID()));
652 delete pSession;
653 it = g_mapSessions.begin();
654 }
655 }
656 }
657 else
658 {
659 WebLog("VBoxSVC became available\n");
660 util::AutoWriteLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
661 HRESULT hrc = g_pVirtualBoxClient->COMGETTER(VirtualBox)(g_pVirtualBox.asOutParam());
662 AssertComRC(hrc);
663 }
664 break;
665 }
666 default:
667 AssertFailed();
668 }
669
670 return S_OK;
671 }
672
673private:
674};
675
676typedef ListenerImpl<VirtualBoxClientEventListener> VirtualBoxClientEventListenerImpl;
677
678VBOX_LISTENER_DECLARE(VirtualBoxClientEventListenerImpl)
679
680/**
681 * Implementation for WEBLOG macro defined in vboxweb.h; this prints a message
682 * to the console and optionally to the file that may have been given to the
683 * vboxwebsrv command line.
684 * @param pszFormat
685 */
686void WebLog(const char *pszFormat, ...)
687{
688 va_list args;
689 va_start(args, pszFormat);
690 char *psz = NULL;
691 RTStrAPrintfV(&psz, pszFormat, args);
692 va_end(args);
693
694 LogRel(("%s", psz));
695
696 RTStrFree(psz);
697}
698
699/**
700 * Helper for printing SOAP error messages.
701 * @param soap
702 */
703/*static*/
704void WebLogSoapError(struct soap *soap)
705{
706 if (soap_check_state(soap))
707 {
708 WebLog("Error: soap struct not initialized\n");
709 return;
710 }
711
712 const char *pcszFaultString = *soap_faultstring(soap);
713 const char **ppcszDetail = soap_faultcode(soap);
714 WebLog("#### SOAP FAULT: %s [%s]\n",
715 pcszFaultString ? pcszFaultString : "[no fault string available]",
716 (ppcszDetail && *ppcszDetail) ? *ppcszDetail : "no details available");
717}
718
719#ifdef WITH_OPENSSL
720/****************************************************************************
721 *
722 * OpenSSL convenience functions for multithread support
723 *
724 ****************************************************************************/
725
726static RTCRITSECT *g_pSSLMutexes = NULL;
727
728struct CRYPTO_dynlock_value
729{
730 RTCRITSECT mutex;
731};
732
733static unsigned long CRYPTO_id_function()
734{
735 return RTThreadNativeSelf();
736}
737
738static void CRYPTO_locking_function(int mode, int n, const char * /*file*/, int /*line*/)
739{
740 if (mode & CRYPTO_LOCK)
741 RTCritSectEnter(&g_pSSLMutexes[n]);
742 else
743 RTCritSectLeave(&g_pSSLMutexes[n]);
744}
745
746static struct CRYPTO_dynlock_value *CRYPTO_dyn_create_function(const char * /*file*/, int /*line*/)
747{
748 static uint32_t s_iCritSectDynlock = 0;
749 struct CRYPTO_dynlock_value *value = (struct CRYPTO_dynlock_value *)RTMemAlloc(sizeof(struct CRYPTO_dynlock_value));
750 if (value)
751 RTCritSectInitEx(&value->mutex, RTCRITSECT_FLAGS_NO_LOCK_VAL,
752 NIL_RTLOCKVALCLASS, RTLOCKVAL_SUB_CLASS_NONE,
753 "openssl-dyn-%u", ASMAtomicIncU32(&s_iCritSectDynlock) - 1);
754
755 return value;
756}
757
758static void CRYPTO_dyn_lock_function(int mode, struct CRYPTO_dynlock_value *value, const char * /*file*/, int /*line*/)
759{
760 if (mode & CRYPTO_LOCK)
761 RTCritSectEnter(&value->mutex);
762 else
763 RTCritSectLeave(&value->mutex);
764}
765
766static void CRYPTO_dyn_destroy_function(struct CRYPTO_dynlock_value *value, const char * /*file*/, int /*line*/)
767{
768 if (value)
769 {
770 RTCritSectDelete(&value->mutex);
771 free(value);
772 }
773}
774
775static int CRYPTO_thread_setup()
776{
777 int num_locks = CRYPTO_num_locks();
778 g_pSSLMutexes = (RTCRITSECT *)RTMemAlloc(num_locks * sizeof(RTCRITSECT));
779 if (!g_pSSLMutexes)
780 return SOAP_EOM;
781
782 for (int i = 0; i < num_locks; i++)
783 {
784 int rc = RTCritSectInitEx(&g_pSSLMutexes[i], RTCRITSECT_FLAGS_NO_LOCK_VAL,
785 NIL_RTLOCKVALCLASS, RTLOCKVAL_SUB_CLASS_NONE,
786 "openssl-%d", i);
787 if (RT_FAILURE(rc))
788 {
789 for ( ; i >= 0; i--)
790 RTCritSectDelete(&g_pSSLMutexes[i]);
791 RTMemFree(g_pSSLMutexes);
792 g_pSSLMutexes = NULL;
793 return SOAP_EOM;
794 }
795 }
796
797 CRYPTO_set_id_callback(CRYPTO_id_function);
798 CRYPTO_set_locking_callback(CRYPTO_locking_function);
799 CRYPTO_set_dynlock_create_callback(CRYPTO_dyn_create_function);
800 CRYPTO_set_dynlock_lock_callback(CRYPTO_dyn_lock_function);
801 CRYPTO_set_dynlock_destroy_callback(CRYPTO_dyn_destroy_function);
802
803 return SOAP_OK;
804}
805
806static void CRYPTO_thread_cleanup()
807{
808 if (!g_pSSLMutexes)
809 return;
810
811 CRYPTO_set_id_callback(NULL);
812 CRYPTO_set_locking_callback(NULL);
813 CRYPTO_set_dynlock_create_callback(NULL);
814 CRYPTO_set_dynlock_lock_callback(NULL);
815 CRYPTO_set_dynlock_destroy_callback(NULL);
816
817 int num_locks = CRYPTO_num_locks();
818 for (int i = 0; i < num_locks; i++)
819 RTCritSectDelete(&g_pSSLMutexes[i]);
820
821 RTMemFree(g_pSSLMutexes);
822 g_pSSLMutexes = NULL;
823}
824#endif /* WITH_OPENSSL */
825
826/****************************************************************************
827 *
828 * SOAP queue pumper thread
829 *
830 ****************************************************************************/
831
832void doQueuesLoop()
833{
834#ifdef WITH_OPENSSL
835 if (g_fSSL && CRYPTO_thread_setup())
836 {
837 WebLog("Failed to set up OpenSSL thread mutex!");
838 exit(RTEXITCODE_FAILURE);
839 }
840#endif /* WITH_OPENSSL */
841
842 // set up gSOAP
843 struct soap soap;
844 soap_init(&soap);
845
846#ifdef WITH_OPENSSL
847 if (g_fSSL && soap_ssl_server_context(&soap, SOAP_SSL_DEFAULT, g_pcszKeyFile,
848 g_pcszPassword, g_pcszCACert, g_pcszCAPath,
849 g_pcszDHFile, g_pcszRandFile, g_pcszSID))
850 {
851 WebLogSoapError(&soap);
852 exit(RTEXITCODE_FAILURE);
853 }
854#endif /* WITH_OPENSSL */
855
856 soap.bind_flags |= SO_REUSEADDR;
857 // avoid EADDRINUSE on bind()
858
859 int m, s; // master and slave sockets
860 m = soap_bind(&soap,
861 g_pcszBindToHost ? g_pcszBindToHost : "localhost", // safe default host
862 g_uBindToPort, // port
863 g_uBacklog); // backlog = max queue size for requests
864 if (m < 0)
865 WebLogSoapError(&soap);
866 else
867 {
868 WebLog("Socket connection successful: host = %s, port = %u, %smaster socket = %d\n",
869 (g_pcszBindToHost) ? g_pcszBindToHost : "default (localhost)",
870 g_uBindToPort,
871#ifdef WITH_OPENSSL
872 g_fSSL ? "SSL, " : "",
873#else /* !WITH_OPENSSL */
874 "",
875#endif /*!WITH_OPENSSL */
876 m);
877
878 // initialize thread queue, mutex and eventsem
879 g_pSoapQ = new SoapQ(&soap);
880
881 for (uint64_t i = 1;
882 ;
883 i++)
884 {
885 // call gSOAP to handle incoming SOAP connection
886 s = soap_accept(&soap);
887 if (s < 0)
888 {
889 WebLogSoapError(&soap);
890 continue;
891 }
892
893 // add the socket to the queue and tell worker threads to
894 // pick up the job
895 size_t cItemsOnQ = g_pSoapQ->add(s);
896 WebLog("Request %llu on socket %d queued for processing (%d items on Q)\n", i, s, cItemsOnQ);
897 }
898 }
899 soap_done(&soap); // close master socket and detach environment
900
901#ifdef WITH_OPENSSL
902 if (g_fSSL)
903 CRYPTO_thread_cleanup();
904#endif /* WITH_OPENSSL */
905}
906
907/**
908 * Thread function for the "queue pumper" thread started from main(). This implements
909 * the loop that takes SOAP calls from HTTP and serves them by handing sockets to the
910 * SOAP queue worker threads.
911 */
912int fntQPumper(RTTHREAD ThreadSelf, void *pvUser)
913{
914 // store a log prefix for this thread
915 util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
916 g_mapThreads[RTThreadSelf()] = "[ P ]";
917 thrLock.release();
918
919 doQueuesLoop();
920
921 return 0;
922}
923
924#ifdef RT_OS_WINDOWS
925// Required for ATL
926static CComModule _Module;
927#endif
928
929
930/**
931 * Start up the webservice server. This keeps running and waits
932 * for incoming SOAP connections; for each request that comes in,
933 * it calls method implementation code, most of it in the generated
934 * code in methodmaps.cpp.
935 *
936 * @param argc
937 * @param argv[]
938 * @return
939 */
940int main(int argc, char *argv[])
941{
942 // initialize runtime
943 int rc = RTR3InitExe(argc, &argv, 0);
944 if (RT_FAILURE(rc))
945 return RTMsgInitFailure(rc);
946
947 // store a log prefix for this thread
948 g_mapThreads[RTThreadSelf()] = "[M ]";
949
950 RTStrmPrintf(g_pStdErr, VBOX_PRODUCT " web service Version " VBOX_VERSION_STRING "\n"
951 "(C) 2007-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
952 "All rights reserved.\n");
953
954 int c;
955 const char *pszLogFile = NULL;
956 const char *pszPidFile = NULL;
957 RTGETOPTUNION ValueUnion;
958 RTGETOPTSTATE GetState;
959 RTGetOptInit(&GetState, argc, argv, g_aOptions, RT_ELEMENTS(g_aOptions), 1, 0 /*fFlags*/);
960 while ((c = RTGetOpt(&GetState, &ValueUnion)))
961 {
962 switch (c)
963 {
964 case 'H':
965 if (!ValueUnion.psz || !*ValueUnion.psz)
966 {
967 /* Normalize NULL/empty string to NULL, which will be
968 * interpreted as "localhost" below. */
969 g_pcszBindToHost = NULL;
970 }
971 else
972 g_pcszBindToHost = ValueUnion.psz;
973 break;
974
975 case 'p':
976 g_uBindToPort = ValueUnion.u32;
977 break;
978
979#ifdef WITH_OPENSSL
980 case 's':
981 g_fSSL = true;
982 break;
983
984 case 'K':
985 g_pcszKeyFile = ValueUnion.psz;
986 break;
987
988 case 'a':
989 if (ValueUnion.psz[0] == '\0')
990 g_pcszPassword = NULL;
991 else
992 {
993 PRTSTREAM StrmIn;
994 if (!strcmp(ValueUnion.psz, "-"))
995 StrmIn = g_pStdIn;
996 else
997 {
998 int vrc = RTStrmOpen(ValueUnion.psz, "r", &StrmIn);
999 if (RT_FAILURE(vrc))
1000 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open password file (%s, %Rrc)", ValueUnion.psz, vrc);
1001 }
1002 char szPasswd[512];
1003 int vrc = RTStrmGetLine(StrmIn, szPasswd, sizeof(szPasswd));
1004 if (RT_FAILURE(vrc))
1005 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to read password (%s, %Rrc)", ValueUnion.psz, vrc);
1006 g_pcszPassword = RTStrDup(szPasswd);
1007 memset(szPasswd, '\0', sizeof(szPasswd));
1008 if (StrmIn != g_pStdIn)
1009 RTStrmClose(StrmIn);
1010 }
1011 break;
1012
1013 case 'c':
1014 g_pcszCACert = ValueUnion.psz;
1015 break;
1016
1017 case 'C':
1018 g_pcszCAPath = ValueUnion.psz;
1019 break;
1020
1021 case 'D':
1022 g_pcszDHFile = ValueUnion.psz;
1023 break;
1024
1025 case 'r':
1026 g_pcszRandFile = ValueUnion.psz;
1027 break;
1028#endif /* WITH_OPENSSL */
1029
1030 case 't':
1031 g_iWatchdogTimeoutSecs = ValueUnion.u32;
1032 break;
1033
1034 case 'i':
1035 g_iWatchdogCheckInterval = ValueUnion.u32;
1036 break;
1037
1038 case 'F':
1039 pszLogFile = ValueUnion.psz;
1040 break;
1041
1042 case 'R':
1043 g_cHistory = ValueUnion.u32;
1044 break;
1045
1046 case 'S':
1047 g_uHistoryFileSize = ValueUnion.u64;
1048 break;
1049
1050 case 'I':
1051 g_uHistoryFileTime = ValueUnion.u32;
1052 break;
1053
1054 case 'P':
1055 pszPidFile = ValueUnion.psz;
1056 break;
1057
1058 case 'T':
1059 g_cMaxWorkerThreads = ValueUnion.u32;
1060 break;
1061
1062 case 'k':
1063 g_cMaxKeepAlive = ValueUnion.u32;
1064 break;
1065
1066 case 'A':
1067 g_pcszAuthentication = ValueUnion.psz;
1068 break;
1069
1070 case 'h':
1071 DisplayHelp();
1072 return 0;
1073
1074 case 'v':
1075 g_fVerbose = true;
1076 break;
1077
1078#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1079 case 'b':
1080 g_fDaemonize = true;
1081 break;
1082#endif
1083 case 'V':
1084 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
1085 return 0;
1086
1087 default:
1088 rc = RTGetOptPrintError(c, &ValueUnion);
1089 return rc;
1090 }
1091 }
1092
1093 /* create release logger, to stdout */
1094 char szError[RTPATH_MAX + 128];
1095 rc = com::VBoxLogRelCreate("web service", g_fDaemonize ? NULL : pszLogFile,
1096 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
1097 "all", "VBOXWEBSRV_RELEASE_LOG",
1098 RTLOGDEST_STDOUT, UINT32_MAX /* cMaxEntriesPerGroup */,
1099 g_cHistory, g_uHistoryFileTime, g_uHistoryFileSize,
1100 szError, sizeof(szError));
1101 if (RT_FAILURE(rc))
1102 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, rc);
1103
1104#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1105 if (g_fDaemonize)
1106 {
1107 /* prepare release logging */
1108 char szLogFile[RTPATH_MAX];
1109
1110 if (!pszLogFile || !*pszLogFile)
1111 {
1112 rc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
1113 if (RT_FAILURE(rc))
1114 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not get base directory for logging: %Rrc", rc);
1115 rc = RTPathAppend(szLogFile, sizeof(szLogFile), "vboxwebsrv.log");
1116 if (RT_FAILURE(rc))
1117 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not construct logging path: %Rrc", rc);
1118 pszLogFile = szLogFile;
1119 }
1120
1121 rc = RTProcDaemonizeUsingFork(false /* fNoChDir */, false /* fNoClose */, pszPidFile);
1122 if (RT_FAILURE(rc))
1123 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to daemonize, rc=%Rrc. exiting.", rc);
1124
1125 /* create release logger, to file */
1126 rc = com::VBoxLogRelCreate("web service", pszLogFile,
1127 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
1128 "all", "VBOXWEBSRV_RELEASE_LOG",
1129 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
1130 g_cHistory, g_uHistoryFileTime, g_uHistoryFileSize,
1131 szError, sizeof(szError));
1132 if (RT_FAILURE(rc))
1133 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, rc);
1134 }
1135#endif
1136
1137 // initialize SOAP SSL support if enabled
1138#ifdef WITH_OPENSSL
1139 if (g_fSSL)
1140 soap_ssl_init();
1141#endif /* WITH_OPENSSL */
1142
1143 // initialize COM/XPCOM
1144 HRESULT hrc = com::Initialize();
1145 if (FAILED(hrc))
1146 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to initialize COM! hrc=%Rhrc\n", hrc);
1147
1148 hrc = g_pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
1149 if (FAILED(hrc))
1150 {
1151 RTMsgError("failed to create the VirtualBoxClient object!");
1152 com::ErrorInfo info;
1153 if (!info.isFullAvailable() && !info.isBasicAvailable())
1154 {
1155 com::GluePrintRCMessage(hrc);
1156 RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
1157 }
1158 else
1159 com::GluePrintErrorInfo(info);
1160 return RTEXITCODE_FAILURE;
1161 }
1162
1163 hrc = g_pVirtualBoxClient->COMGETTER(VirtualBox)(g_pVirtualBox.asOutParam());
1164 if (FAILED(hrc))
1165 {
1166 RTMsgError("Failed to get VirtualBox object (rc=%Rhrc)!", hrc);
1167 return RTEXITCODE_FAILURE;
1168 }
1169
1170 // set the authentication method if requested
1171 if (g_pVirtualBox && g_pcszAuthentication && g_pcszAuthentication[0])
1172 {
1173 ComPtr<ISystemProperties> pSystemProperties;
1174 g_pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
1175 if (pSystemProperties)
1176 pSystemProperties->COMSETTER(WebServiceAuthLibrary)(com::Bstr(g_pcszAuthentication).raw());
1177 }
1178
1179 /* VirtualBoxClient events registration. */
1180 ComPtr<IEventListener> vboxClientListener;
1181 {
1182 ComPtr<IEventSource> pES;
1183 CHECK_ERROR(g_pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1184 ComObjPtr<VirtualBoxClientEventListenerImpl> clientListener;
1185 clientListener.createObject();
1186 clientListener->init(new VirtualBoxClientEventListener());
1187 vboxClientListener = clientListener;
1188 com::SafeArray<VBoxEventType_T> eventTypes;
1189 eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
1190 CHECK_ERROR(pES, RegisterListener(vboxClientListener, ComSafeArrayAsInParam(eventTypes), true));
1191 }
1192
1193 // create the global mutexes
1194 g_pAuthLibLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
1195 g_pVirtualBoxLockHandle = new util::RWLockHandle(util::LOCKCLASS_WEBSERVICE);
1196 g_pSessionsLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
1197 g_pThreadsLockHandle = new util::RWLockHandle(util::LOCKCLASS_OBJECTSTATE);
1198 g_pWebLogLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
1199
1200 // SOAP queue pumper thread
1201 rc = RTThreadCreate(NULL,
1202 fntQPumper,
1203 NULL, // pvUser
1204 0, // cbStack (default)
1205 RTTHREADTYPE_MAIN_WORKER,
1206 0, // flags
1207 "SQPmp");
1208 if (RT_FAILURE(rc))
1209 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot start SOAP queue pumper thread: %Rrc", rc);
1210
1211 // watchdog thread
1212 if (g_iWatchdogTimeoutSecs > 0)
1213 {
1214 // start our watchdog thread
1215 rc = RTThreadCreate(NULL,
1216 fntWatchdog,
1217 NULL,
1218 0,
1219 RTTHREADTYPE_MAIN_WORKER,
1220 0,
1221 "Watchdog");
1222 if (RT_FAILURE(rc))
1223 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot start watchdog thread: %Rrc", rc);
1224 }
1225
1226 com::EventQueue *pQ = com::EventQueue::getMainEventQueue();
1227 for (;;)
1228 {
1229 // we have to process main event queue
1230 WEBDEBUG(("Pumping COM event queue\n"));
1231 rc = pQ->processEventQueue(RT_INDEFINITE_WAIT);
1232 if (RT_FAILURE(rc))
1233 RTMsgError("processEventQueue -> %Rrc", rc);
1234 }
1235
1236 /* VirtualBoxClient events unregistration. */
1237 if (vboxClientListener)
1238 {
1239 ComPtr<IEventSource> pES;
1240 CHECK_ERROR(g_pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1241 if (!pES.isNull())
1242 CHECK_ERROR(pES, UnregisterListener(vboxClientListener));
1243 vboxClientListener.setNull();
1244 }
1245
1246 com::Shutdown();
1247
1248 return 0;
1249}
1250
1251/****************************************************************************
1252 *
1253 * Watchdog thread
1254 *
1255 ****************************************************************************/
1256
1257/**
1258 * Watchdog thread, runs in the background while the webservice is alive.
1259 *
1260 * This gets started by main() and runs in the background to check all sessions
1261 * for whether they have been no requests in a configurable timeout period. In
1262 * that case, the session is automatically logged off.
1263 */
1264int fntWatchdog(RTTHREAD ThreadSelf, void *pvUser)
1265{
1266 // store a log prefix for this thread
1267 util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
1268 g_mapThreads[RTThreadSelf()] = "[W ]";
1269 thrLock.release();
1270
1271 WEBDEBUG(("Watchdog thread started\n"));
1272
1273 while (1)
1274 {
1275 WEBDEBUG(("Watchdog: sleeping %d seconds\n", g_iWatchdogCheckInterval));
1276 RTThreadSleep(g_iWatchdogCheckInterval * 1000);
1277
1278 time_t tNow;
1279 time(&tNow);
1280
1281 // we're messing with sessions, so lock them
1282 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1283 WEBDEBUG(("Watchdog: checking %d sessions\n", g_mapSessions.size()));
1284
1285 SessionsMap::iterator it = g_mapSessions.begin(),
1286 itEnd = g_mapSessions.end();
1287 while (it != itEnd)
1288 {
1289 WebServiceSession *pSession = it->second;
1290 WEBDEBUG(("Watchdog: tNow: %d, session timestamp: %d\n", tNow, pSession->getLastObjectLookup()));
1291 if ( tNow
1292 > pSession->getLastObjectLookup() + g_iWatchdogTimeoutSecs
1293 )
1294 {
1295 WEBDEBUG(("Watchdog: Session %llX timed out, deleting\n", pSession->getID()));
1296 delete pSession;
1297 it = g_mapSessions.begin();
1298 }
1299 else
1300 ++it;
1301 }
1302
1303 // re-set the authentication method in case it has been changed
1304 if (g_pVirtualBox && g_pcszAuthentication && g_pcszAuthentication[0])
1305 {
1306 ComPtr<ISystemProperties> pSystemProperties;
1307 g_pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
1308 if (pSystemProperties)
1309 pSystemProperties->COMSETTER(WebServiceAuthLibrary)(com::Bstr(g_pcszAuthentication).raw());
1310 }
1311 }
1312
1313 WEBDEBUG(("Watchdog thread ending\n"));
1314 return 0;
1315}
1316
1317/****************************************************************************
1318 *
1319 * SOAP exceptions
1320 *
1321 ****************************************************************************/
1322
1323/**
1324 * Helper function to raise a SOAP fault. Called by the other helper
1325 * functions, which raise specific SOAP faults.
1326 *
1327 * @param soap
1328 * @param str
1329 * @param extype
1330 * @param ex
1331 */
1332void RaiseSoapFault(struct soap *soap,
1333 const char *pcsz,
1334 int extype,
1335 void *ex)
1336{
1337 // raise the fault
1338 soap_sender_fault(soap, pcsz, NULL);
1339
1340 struct SOAP_ENV__Detail *pDetail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
1341
1342 // without the following, gSOAP crashes miserably when sending out the
1343 // data because it will try to serialize all fields (stupid documentation)
1344 memset(pDetail, 0, sizeof(struct SOAP_ENV__Detail));
1345
1346 // fill extended info depending on SOAP version
1347 if (soap->version == 2) // SOAP 1.2 is used
1348 {
1349 soap->fault->SOAP_ENV__Detail = pDetail;
1350 soap->fault->SOAP_ENV__Detail->__type = extype;
1351 soap->fault->SOAP_ENV__Detail->fault = ex;
1352 soap->fault->SOAP_ENV__Detail->__any = NULL; // no other XML data
1353 }
1354 else
1355 {
1356 soap->fault->detail = pDetail;
1357 soap->fault->detail->__type = extype;
1358 soap->fault->detail->fault = ex;
1359 soap->fault->detail->__any = NULL; // no other XML data
1360 }
1361}
1362
1363/**
1364 * Raises a SOAP fault that signals that an invalid object was passed.
1365 *
1366 * @param soap
1367 * @param obj
1368 */
1369void RaiseSoapInvalidObjectFault(struct soap *soap,
1370 WSDLT_ID obj)
1371{
1372 _vbox__InvalidObjectFault *ex = soap_new__vbox__InvalidObjectFault(soap, 1);
1373 ex->badObjectID = obj;
1374
1375 std::string str("VirtualBox error: ");
1376 str += "Invalid managed object reference \"" + obj + "\"";
1377
1378 RaiseSoapFault(soap,
1379 str.c_str(),
1380 SOAP_TYPE__vbox__InvalidObjectFault,
1381 ex);
1382}
1383
1384/**
1385 * Return a safe C++ string from the given COM string,
1386 * without crashing if the COM string is empty.
1387 * @param bstr
1388 * @return
1389 */
1390std::string ConvertComString(const com::Bstr &bstr)
1391{
1392 com::Utf8Str ustr(bstr);
1393 return ustr.c_str(); // @todo r=dj since the length is known, we can probably use a better std::string allocator
1394}
1395
1396/**
1397 * Return a safe C++ string from the given COM UUID,
1398 * without crashing if the UUID is empty.
1399 * @param bstr
1400 * @return
1401 */
1402std::string ConvertComString(const com::Guid &uuid)
1403{
1404 com::Utf8Str ustr(uuid.toString());
1405 return ustr.c_str(); // @todo r=dj since the length is known, we can probably use a better std::string allocator
1406}
1407
1408/** Code to handle string <-> byte arrays base64 conversion. */
1409std::string Base64EncodeByteArray(ComSafeArrayIn(BYTE, aData))
1410{
1411
1412 com::SafeArray<BYTE> sfaData(ComSafeArrayInArg(aData));
1413 ssize_t cbData = sfaData.size();
1414
1415 if (cbData == 0)
1416 return "";
1417
1418 ssize_t cchOut = RTBase64EncodedLength(cbData);
1419
1420 RTCString aStr;
1421
1422 aStr.reserve(cchOut+1);
1423 int rc = RTBase64Encode(sfaData.raw(), cbData,
1424 aStr.mutableRaw(), aStr.capacity(),
1425 NULL);
1426 AssertRC(rc);
1427 aStr.jolt();
1428
1429 return aStr.c_str();
1430}
1431
1432void Base64DecodeByteArray(std::string& aStr, ComSafeArrayOut(BYTE, aData))
1433{
1434 const char* pszStr = aStr.c_str();
1435 ssize_t cbOut = RTBase64DecodedSize(pszStr, NULL);
1436
1437 Assert(cbOut > 0);
1438
1439 com::SafeArray<BYTE> result(cbOut);
1440 int rc = RTBase64Decode(pszStr, result.raw(), cbOut, NULL, NULL);
1441 AssertRC(rc);
1442
1443 result.detachTo(ComSafeArrayOutArg(aData));
1444}
1445
1446/**
1447 * Raises a SOAP runtime fault. Implementation for the RaiseSoapRuntimeFault template
1448 * function in vboxweb.h.
1449 *
1450 * @param pObj
1451 */
1452void RaiseSoapRuntimeFault2(struct soap *soap,
1453 HRESULT apirc,
1454 IUnknown *pObj,
1455 const com::Guid &iid)
1456{
1457 com::ErrorInfo info(pObj, iid.ref());
1458
1459 WEBDEBUG((" error, raising SOAP exception\n"));
1460
1461 RTStrmPrintf(g_pStdErr, "API return code: 0x%08X (%Rhrc)\n", apirc, apirc);
1462 RTStrmPrintf(g_pStdErr, "COM error info result code: 0x%lX\n", info.getResultCode());
1463 RTStrmPrintf(g_pStdErr, "COM error info text: %ls\n", info.getText().raw());
1464
1465 // allocated our own soap fault struct
1466 _vbox__RuntimeFault *ex = soap_new__vbox__RuntimeFault(soap, 1);
1467 // some old vbox methods return errors without setting an error in the error info,
1468 // so use the error info code if it's set and the HRESULT from the method otherwise
1469 if (S_OK == (ex->resultCode = info.getResultCode()))
1470 ex->resultCode = apirc;
1471 ex->text = ConvertComString(info.getText());
1472 ex->component = ConvertComString(info.getComponent());
1473 ex->interfaceID = ConvertComString(info.getInterfaceID());
1474
1475 // compose descriptive message
1476 com::Utf8StrFmt str("VirtualBox error: %s (0x%lX)", ex->text.c_str(), ex->resultCode);
1477
1478 RaiseSoapFault(soap,
1479 str.c_str(),
1480 SOAP_TYPE__vbox__RuntimeFault,
1481 ex);
1482}
1483
1484/****************************************************************************
1485 *
1486 * splitting and merging of object IDs
1487 *
1488 ****************************************************************************/
1489
1490uint64_t str2ulonglong(const char *pcsz)
1491{
1492 uint64_t u = 0;
1493 RTStrToUInt64Full(pcsz, 16, &u);
1494 return u;
1495}
1496
1497/**
1498 * Splits a managed object reference (in string form, as
1499 * passed in from a SOAP method call) into two integers for
1500 * session and object IDs, respectively.
1501 *
1502 * @param id
1503 * @param sessid
1504 * @param objid
1505 * @return
1506 */
1507bool SplitManagedObjectRef(const WSDLT_ID &id,
1508 uint64_t *pSessid,
1509 uint64_t *pObjid)
1510{
1511 // 64-bit numbers in hex have 16 digits; hence
1512 // the object-ref string must have 16 + "-" + 16 characters
1513 std::string str;
1514 if ( (id.length() == 33)
1515 && (id[16] == '-')
1516 )
1517 {
1518 char psz[34];
1519 memcpy(psz, id.c_str(), 34);
1520 psz[16] = '\0';
1521 if (pSessid)
1522 *pSessid = str2ulonglong(psz);
1523 if (pObjid)
1524 *pObjid = str2ulonglong(psz + 17);
1525 return true;
1526 }
1527
1528 return false;
1529}
1530
1531/**
1532 * Creates a managed object reference (in string form) from
1533 * two integers representing a session and object ID, respectively.
1534 *
1535 * @param sz Buffer with at least 34 bytes space to receive MOR string.
1536 * @param sessid
1537 * @param objid
1538 * @return
1539 */
1540void MakeManagedObjectRef(char *sz,
1541 uint64_t &sessid,
1542 uint64_t &objid)
1543{
1544 RTStrFormatNumber(sz, sessid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
1545 sz[16] = '-';
1546 RTStrFormatNumber(sz + 17, objid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
1547}
1548
1549/****************************************************************************
1550 *
1551 * class WebServiceSession
1552 *
1553 ****************************************************************************/
1554
1555class WebServiceSessionPrivate
1556{
1557 public:
1558 ManagedObjectsMapById _mapManagedObjectsById;
1559 ManagedObjectsMapByPtr _mapManagedObjectsByPtr;
1560};
1561
1562/**
1563 * Constructor for the session object.
1564 *
1565 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1566 *
1567 * @param username
1568 * @param password
1569 */
1570WebServiceSession::WebServiceSession()
1571 : _fDestructing(false),
1572 _pISession(NULL),
1573 _tLastObjectLookup(0)
1574{
1575 _pp = new WebServiceSessionPrivate;
1576 _uSessionID = RTRandU64();
1577
1578 // register this session globally
1579 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1580 g_mapSessions[_uSessionID] = this;
1581}
1582
1583/**
1584 * Destructor. Cleans up and destroys all contained managed object references on the way.
1585 *
1586 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1587 */
1588WebServiceSession::~WebServiceSession()
1589{
1590 // delete us from global map first so we can't be found
1591 // any more while we're cleaning up
1592 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1593 g_mapSessions.erase(_uSessionID);
1594
1595 // notify ManagedObjectRef destructor so it won't
1596 // remove itself from the maps; this avoids rebalancing
1597 // the map's tree on every delete as well
1598 _fDestructing = true;
1599
1600 // if (_pISession)
1601 // {
1602 // delete _pISession;
1603 // _pISession = NULL;
1604 // }
1605
1606 ManagedObjectsMapById::iterator it,
1607 end = _pp->_mapManagedObjectsById.end();
1608 for (it = _pp->_mapManagedObjectsById.begin();
1609 it != end;
1610 ++it)
1611 {
1612 ManagedObjectRef *pRef = it->second;
1613 delete pRef; // this frees the contained ComPtr as well
1614 }
1615
1616 delete _pp;
1617}
1618
1619/**
1620 * Authenticate the username and password against an authentication authority.
1621 *
1622 * @return 0 if the user was successfully authenticated, or an error code
1623 * otherwise.
1624 */
1625
1626int WebServiceSession::authenticate(const char *pcszUsername,
1627 const char *pcszPassword,
1628 IVirtualBox **ppVirtualBox)
1629{
1630 int rc = VERR_WEB_NOT_AUTHENTICATED;
1631 ComPtr<IVirtualBox> pVirtualBox;
1632 {
1633 util::AutoReadLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
1634 pVirtualBox = g_pVirtualBox;
1635 }
1636 if (pVirtualBox.isNull())
1637 return rc;
1638 pVirtualBox.queryInterfaceTo(ppVirtualBox);
1639
1640 util::AutoReadLock lock(g_pAuthLibLockHandle COMMA_LOCKVAL_SRC_POS);
1641
1642 static bool fAuthLibLoaded = false;
1643 static PAUTHENTRY pfnAuthEntry = NULL;
1644 static PAUTHENTRY2 pfnAuthEntry2 = NULL;
1645 static PAUTHENTRY3 pfnAuthEntry3 = NULL;
1646
1647 if (!fAuthLibLoaded)
1648 {
1649 // retrieve authentication library from system properties
1650 ComPtr<ISystemProperties> systemProperties;
1651 pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
1652
1653 com::Bstr authLibrary;
1654 systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
1655 com::Utf8Str filename = authLibrary;
1656
1657 WEBDEBUG(("external authentication library is '%ls'\n", authLibrary.raw()));
1658
1659 if (filename == "null")
1660 // authentication disabled, let everyone in:
1661 fAuthLibLoaded = true;
1662 else
1663 {
1664 RTLDRMOD hlibAuth = 0;
1665 do
1666 {
1667 rc = RTLdrLoad(filename.c_str(), &hlibAuth);
1668 if (RT_FAILURE(rc))
1669 {
1670 WEBDEBUG(("%s() Failed to load external authentication library. Error code: %Rrc\n", __FUNCTION__, rc));
1671 break;
1672 }
1673
1674 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY3_NAME, (void**)&pfnAuthEntry3)))
1675 {
1676 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY3_NAME, rc));
1677
1678 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY2_NAME, (void**)&pfnAuthEntry2)))
1679 {
1680 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY2_NAME, rc));
1681
1682 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY_NAME, (void**)&pfnAuthEntry)))
1683 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY_NAME, rc));
1684 }
1685 }
1686
1687 if (pfnAuthEntry || pfnAuthEntry2 || pfnAuthEntry3)
1688 fAuthLibLoaded = true;
1689
1690 } while (0);
1691 }
1692 }
1693
1694 rc = VERR_WEB_NOT_AUTHENTICATED;
1695 AuthResult result;
1696 if (pfnAuthEntry3)
1697 {
1698 result = pfnAuthEntry3("webservice", NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1699 WEBDEBUG(("%s(): result of AuthEntry(): %d\n", __FUNCTION__, result));
1700 if (result == AuthResultAccessGranted)
1701 rc = 0;
1702 }
1703 else if (pfnAuthEntry2)
1704 {
1705 result = pfnAuthEntry2(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1706 WEBDEBUG(("%s(): result of VRDPAuth2(): %d\n", __FUNCTION__, result));
1707 if (result == AuthResultAccessGranted)
1708 rc = 0;
1709 }
1710 else if (pfnAuthEntry)
1711 {
1712 result = pfnAuthEntry(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
1713 WEBDEBUG(("%s(): result of VRDPAuth(%s, [%d]): %d\n", __FUNCTION__, pcszUsername, strlen(pcszPassword), result));
1714 if (result == AuthResultAccessGranted)
1715 rc = 0;
1716 }
1717 else if (fAuthLibLoaded)
1718 // fAuthLibLoaded = true but both pointers are NULL:
1719 // then the authlib was "null" and auth was disabled
1720 rc = 0;
1721 else
1722 {
1723 WEBDEBUG(("Could not resolve AuthEntry, VRDPAuth2 or VRDPAuth entry point"));
1724 }
1725
1726 lock.release();
1727
1728 if (!rc)
1729 {
1730 do
1731 {
1732 // now create the ISession object that this webservice session can use
1733 // (and of which IWebsessionManager::getSessionObject returns a managed object reference)
1734 ComPtr<ISession> session;
1735 rc = g_pVirtualBoxClient->COMGETTER(Session)(session.asOutParam());
1736 if (FAILED(rc))
1737 {
1738 WEBDEBUG(("ERROR: cannot create session object!"));
1739 break;
1740 }
1741
1742 ComPtr<IUnknown> p2 = session;
1743 _pISession = new ManagedObjectRef(*this,
1744 p2, // IUnknown *pobjUnknown
1745 session, // void *pobjInterface
1746 com::Guid(COM_IIDOF(ISession)),
1747 g_pcszISession);
1748
1749 if (g_fVerbose)
1750 {
1751 ISession *p = session;
1752 WEBDEBUG((" * %s: created session object with comptr 0x%lX, MOR = %s\n", __FUNCTION__, p, _pISession->getWSDLID().c_str()));
1753 }
1754 } while (0);
1755 }
1756
1757 return rc;
1758}
1759
1760/**
1761 * Look up, in this session, whether a ManagedObjectRef has already been
1762 * created for the given COM pointer.
1763 *
1764 * Note how we require that a ComPtr<IUnknown> is passed, which causes a
1765 * queryInterface call when the caller passes in a different type, since
1766 * a ComPtr<IUnknown> will point to something different than a
1767 * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
1768 * our private hash table, we must search for one too.
1769 *
1770 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1771 *
1772 * @param pcu pointer to a COM object.
1773 * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
1774 */
1775ManagedObjectRef* WebServiceSession::findRefFromPtr(const IUnknown *pObject)
1776{
1777 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1778
1779 uintptr_t ulp = (uintptr_t)pObject;
1780 // WEBDEBUG((" %s: looking up 0x%lX\n", __FUNCTION__, ulp));
1781 ManagedObjectsMapByPtr::iterator it = _pp->_mapManagedObjectsByPtr.find(ulp);
1782 if (it != _pp->_mapManagedObjectsByPtr.end())
1783 {
1784 ManagedObjectRef *pRef = it->second;
1785 WEBDEBUG((" %s: found existing ref %s (%s) for COM obj 0x%lX\n", __FUNCTION__, pRef->getWSDLID().c_str(), pRef->getInterfaceName(), ulp));
1786 return pRef;
1787 }
1788
1789 return NULL;
1790}
1791
1792/**
1793 * Static method which attempts to find the session for which the given managed
1794 * object reference was created, by splitting the reference into the session and
1795 * object IDs and then looking up the session object for that session ID.
1796 *
1797 * Preconditions: Caller must have locked g_pSessionsLockHandle in read mode.
1798 *
1799 * @param id Managed object reference (with combined session and object IDs).
1800 * @return
1801 */
1802WebServiceSession* WebServiceSession::findSessionFromRef(const WSDLT_ID &id)
1803{
1804 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1805
1806 WebServiceSession *pSession = NULL;
1807 uint64_t sessid;
1808 if (SplitManagedObjectRef(id,
1809 &sessid,
1810 NULL))
1811 {
1812 SessionsMapIterator it = g_mapSessions.find(sessid);
1813 if (it != g_mapSessions.end())
1814 pSession = it->second;
1815 }
1816 return pSession;
1817}
1818
1819/**
1820 *
1821 */
1822const WSDLT_ID& WebServiceSession::getSessionWSDLID() const
1823{
1824 return _pISession->getWSDLID();
1825}
1826
1827/**
1828 * Touches the webservice session to prevent it from timing out.
1829 *
1830 * Each webservice session has an internal timestamp that records
1831 * the last request made to it from the client that started it.
1832 * If no request was made within a configurable timeframe, then
1833 * the client is logged off automatically,
1834 * by calling IWebsessionManager::logoff()
1835 */
1836void WebServiceSession::touch()
1837{
1838 time(&_tLastObjectLookup);
1839}
1840
1841
1842/****************************************************************************
1843 *
1844 * class ManagedObjectRef
1845 *
1846 ****************************************************************************/
1847
1848/**
1849 * Constructor, which assigns a unique ID to this managed object
1850 * reference and stores it two global hashes:
1851 *
1852 * a) G_mapManagedObjectsById, which maps ManagedObjectID's to
1853 * instances of this class; this hash is then used by the
1854 * findObjectFromRef() template function in vboxweb.h
1855 * to quickly retrieve the COM object from its managed
1856 * object ID (mostly in the context of the method mappers
1857 * in methodmaps.cpp, when a web service client passes in
1858 * a managed object ID);
1859 *
1860 * b) G_mapManagedObjectsByComPtr, which maps COM pointers to
1861 * instances of this class; this hash is used by
1862 * createRefFromObject() to quickly figure out whether an
1863 * instance already exists for a given COM pointer.
1864 *
1865 * This constructor calls AddRef() on the given COM object, and
1866 * the destructor will call Release(). We require two input pointers
1867 * for that COM object, one generic IUnknown* pointer which is used
1868 * as the map key, and a specific interface pointer (e.g. IMachine*)
1869 * which must support the interface given in guidInterface. All
1870 * three values are returned by getPtr(), which gives future callers
1871 * a chance to reuse the specific interface pointer without having
1872 * to call QueryInterface, which can be expensive.
1873 *
1874 * This does _not_ check whether another instance already
1875 * exists in the hash. This gets called only from the
1876 * createOrFindRefFromComPtr() template function in vboxweb.h, which
1877 * does perform that check.
1878 *
1879 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1880 *
1881 * @param session Session to which the MOR will be added.
1882 * @param pobjUnknown Pointer to IUnknown* interface for the COM object; this will be used in the hashes.
1883 * @param pobjInterface Pointer to a specific interface for the COM object, described by guidInterface.
1884 * @param guidInterface Interface which pobjInterface points to.
1885 * @param pcszInterface String representation of that interface (e.g. "IMachine") for readability and logging.
1886 */
1887ManagedObjectRef::ManagedObjectRef(WebServiceSession &session,
1888 IUnknown *pobjUnknown,
1889 void *pobjInterface,
1890 const com::Guid &guidInterface,
1891 const char *pcszInterface)
1892 : _session(session),
1893 _pobjUnknown(pobjUnknown),
1894 _pobjInterface(pobjInterface),
1895 _guidInterface(guidInterface),
1896 _pcszInterface(pcszInterface)
1897{
1898 Assert(pobjUnknown);
1899 Assert(pobjInterface);
1900
1901 // keep both stubs alive while this MOR exists (matching Release() calls are in destructor)
1902 uint32_t cRefs1 = pobjUnknown->AddRef();
1903 uint32_t cRefs2 = ((IUnknown*)pobjInterface)->AddRef();
1904 _ulp = (uintptr_t)pobjUnknown;
1905
1906 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1907 _id = ++g_iMaxManagedObjectID;
1908 // and count globally
1909 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
1910
1911 char sz[34];
1912 MakeManagedObjectRef(sz, session._uSessionID, _id);
1913 _strID = sz;
1914
1915 session._pp->_mapManagedObjectsById[_id] = this;
1916 session._pp->_mapManagedObjectsByPtr[_ulp] = this;
1917
1918 session.touch();
1919
1920 WEBDEBUG((" * %s: MOR created for %s*=0x%lX (IUnknown*=0x%lX; COM refcount now %RI32/%RI32), new ID is %llX; now %lld objects total\n",
1921 __FUNCTION__,
1922 pcszInterface,
1923 pobjInterface,
1924 pobjUnknown,
1925 cRefs1,
1926 cRefs2,
1927 _id,
1928 cTotal));
1929}
1930
1931/**
1932 * Destructor; removes the instance from the global hash of
1933 * managed objects. Calls Release() on the contained COM object.
1934 *
1935 * Preconditions: Caller must have locked g_pSessionsLockHandle.
1936 */
1937ManagedObjectRef::~ManagedObjectRef()
1938{
1939 Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
1940 ULONG64 cTotal = --g_cManagedObjects;
1941
1942 Assert(_pobjUnknown);
1943 Assert(_pobjInterface);
1944
1945 // we called AddRef() on both interfaces, so call Release() on
1946 // both as well, but in reverse order
1947 uint32_t cRefs2 = ((IUnknown*)_pobjInterface)->Release();
1948 uint32_t cRefs1 = _pobjUnknown->Release();
1949 WEBDEBUG((" * %s: deleting MOR for ID %llX (%s; COM refcount now %RI32/%RI32); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cRefs1, cRefs2, cTotal));
1950
1951 // if we're being destroyed from the session's destructor,
1952 // then that destructor is iterating over the maps, so
1953 // don't remove us there! (data integrity + speed)
1954 if (!_session._fDestructing)
1955 {
1956 WEBDEBUG((" * %s: removing from session maps\n", __FUNCTION__));
1957 _session._pp->_mapManagedObjectsById.erase(_id);
1958 if (_session._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
1959 WEBDEBUG((" WARNING: could not find %llX in _mapManagedObjectsByPtr\n", _ulp));
1960 }
1961}
1962
1963/**
1964 * Static helper method for findObjectFromRef() template that actually
1965 * looks up the object from a given integer ID.
1966 *
1967 * This has been extracted into this non-template function to reduce
1968 * code bloat as we have the actual STL map lookup only in this function.
1969 *
1970 * This also "touches" the timestamp in the session whose ID is encoded
1971 * in the given integer ID, in order to prevent the session from timing
1972 * out.
1973 *
1974 * Preconditions: Caller must have locked g_mutexSessions.
1975 *
1976 * @param strId
1977 * @param iter
1978 * @return
1979 */
1980int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
1981 ManagedObjectRef **pRef,
1982 bool fNullAllowed)
1983{
1984 int rc = 0;
1985
1986 do
1987 {
1988 // allow NULL (== empty string) input reference, which should return a NULL pointer
1989 if (!id.length() && fNullAllowed)
1990 {
1991 *pRef = NULL;
1992 return 0;
1993 }
1994
1995 uint64_t sessid;
1996 uint64_t objid;
1997 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
1998 if (!SplitManagedObjectRef(id,
1999 &sessid,
2000 &objid))
2001 {
2002 rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
2003 break;
2004 }
2005
2006 SessionsMapIterator it = g_mapSessions.find(sessid);
2007 if (it == g_mapSessions.end())
2008 {
2009 WEBDEBUG((" %s: cannot find session for objref %s\n", __FUNCTION__, id.c_str()));
2010 rc = VERR_WEB_INVALID_SESSION_ID;
2011 break;
2012 }
2013
2014 WebServiceSession *pSess = it->second;
2015 // "touch" session to prevent it from timing out
2016 pSess->touch();
2017
2018 ManagedObjectsIteratorById iter = pSess->_pp->_mapManagedObjectsById.find(objid);
2019 if (iter == pSess->_pp->_mapManagedObjectsById.end())
2020 {
2021 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
2022 rc = VERR_WEB_INVALID_OBJECT_ID;
2023 break;
2024 }
2025
2026 *pRef = iter->second;
2027
2028 } while (0);
2029
2030 return rc;
2031}
2032
2033/****************************************************************************
2034 *
2035 * interface IManagedObjectRef
2036 *
2037 ****************************************************************************/
2038
2039/**
2040 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
2041 * that our WSDL promises to our web service clients. This method returns a
2042 * string describing the interface that this managed object reference
2043 * supports, e.g. "IMachine".
2044 *
2045 * @param soap
2046 * @param req
2047 * @param resp
2048 * @return
2049 */
2050int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
2051 struct soap *soap,
2052 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
2053 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
2054{
2055 HRESULT rc = S_OK;
2056 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2057
2058 do
2059 {
2060 // findRefFromId require the lock
2061 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2062
2063 ManagedObjectRef *pRef;
2064 if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false))
2065 resp->returnval = pRef->getInterfaceName();
2066
2067 } while (0);
2068
2069 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
2070 if (FAILED(rc))
2071 return SOAP_FAULT;
2072 return SOAP_OK;
2073}
2074
2075/**
2076 * This is the hard-coded implementation for the IManagedObjectRef::release()
2077 * that our WSDL promises to our web service clients. This method releases
2078 * a managed object reference and removes it from our stacks.
2079 *
2080 * @param soap
2081 * @param req
2082 * @param resp
2083 * @return
2084 */
2085int __vbox__IManagedObjectRef_USCORErelease(
2086 struct soap *soap,
2087 _vbox__IManagedObjectRef_USCORErelease *req,
2088 _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
2089{
2090 HRESULT rc = S_OK;
2091 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2092
2093 do
2094 {
2095 // findRefFromId and the delete call below require the lock
2096 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2097
2098 ManagedObjectRef *pRef;
2099 if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false)))
2100 {
2101 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
2102 break;
2103 }
2104
2105 WEBDEBUG((" found reference; deleting!\n"));
2106 // this removes the object from all stacks; since
2107 // there's a ComPtr<> hidden inside the reference,
2108 // this should also invoke Release() on the COM
2109 // object
2110 delete pRef;
2111 } while (0);
2112
2113 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
2114 if (FAILED(rc))
2115 return SOAP_FAULT;
2116 return SOAP_OK;
2117}
2118
2119/****************************************************************************
2120 *
2121 * interface IWebsessionManager
2122 *
2123 ****************************************************************************/
2124
2125/**
2126 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
2127 * COM API, this is the first method that a webservice client must call before the
2128 * webservice will do anything useful.
2129 *
2130 * This returns a managed object reference to the global IVirtualBox object; into this
2131 * reference a session ID is encoded which remains constant with all managed object
2132 * references returned by other methods.
2133 *
2134 * This also creates an instance of ISession, which is stored internally with the
2135 * webservice session and can be retrieved with IWebsessionManager::getSessionObject
2136 * (__vbox__IWebsessionManager_USCOREgetSessionObject). In order for the
2137 * VirtualBox web service to do anything useful, one usually needs both a
2138 * VirtualBox and an ISession object, for which these two methods are designed.
2139 *
2140 * When the webservice client is done, it should call IWebsessionManager::logoff. This
2141 * will clean up internally (destroy all remaining managed object references and
2142 * related COM objects used internally).
2143 *
2144 * After logon, an internal timeout ensures that if the webservice client does not
2145 * call any methods, after a configurable number of seconds, the webservice will log
2146 * off the client automatically. This is to ensure that the webservice does not
2147 * drown in managed object references and eventually deny service. Still, it is
2148 * a much better solution, both for performance and cleanliness, for the webservice
2149 * client to clean up itself.
2150 *
2151 * @param
2152 * @param vbox__IWebsessionManager_USCORElogon
2153 * @param vbox__IWebsessionManager_USCORElogonResponse
2154 * @return
2155 */
2156int __vbox__IWebsessionManager_USCORElogon(
2157 struct soap *soap,
2158 _vbox__IWebsessionManager_USCORElogon *req,
2159 _vbox__IWebsessionManager_USCORElogonResponse *resp)
2160{
2161 HRESULT rc = S_OK;
2162 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2163
2164 do
2165 {
2166 // WebServiceSession constructor tinkers with global MOR map and requires a write lock
2167 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2168
2169 // create new session; the constructor stores the new session
2170 // in the global map automatically
2171 WebServiceSession *pSession = new WebServiceSession();
2172 ComPtr<IVirtualBox> pVirtualBox;
2173
2174 // authenticate the user
2175 if (!(pSession->authenticate(req->username.c_str(),
2176 req->password.c_str(),
2177 pVirtualBox.asOutParam())))
2178 {
2179 // in the new session, create a managed object reference (MOR) for the
2180 // global VirtualBox object; this encodes the session ID in the MOR so
2181 // that it will be implicitly be included in all future requests of this
2182 // webservice client
2183 ComPtr<IUnknown> p2 = pVirtualBox;
2184 if (pVirtualBox.isNull() || p2.isNull())
2185 {
2186 rc = E_FAIL;
2187 break;
2188 }
2189 ManagedObjectRef *pRef = new ManagedObjectRef(*pSession,
2190 p2, // IUnknown *pobjUnknown
2191 pVirtualBox, // void *pobjInterface
2192 COM_IIDOF(IVirtualBox),
2193 g_pcszIVirtualBox);
2194 resp->returnval = pRef->getWSDLID();
2195 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
2196 }
2197 else
2198 rc = E_FAIL;
2199 } while (0);
2200
2201 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
2202 if (FAILED(rc))
2203 return SOAP_FAULT;
2204 return SOAP_OK;
2205}
2206
2207/**
2208 * Returns the ISession object that was created for the webservice client
2209 * on logon.
2210 */
2211int __vbox__IWebsessionManager_USCOREgetSessionObject(
2212 struct soap*,
2213 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
2214 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
2215{
2216 HRESULT rc = S_OK;
2217 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2218
2219 do
2220 {
2221 // findSessionFromRef needs lock
2222 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2223
2224 WebServiceSession* pSession;
2225 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
2226 resp->returnval = pSession->getSessionWSDLID();
2227
2228 } while (0);
2229
2230 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
2231 if (FAILED(rc))
2232 return SOAP_FAULT;
2233 return SOAP_OK;
2234}
2235
2236/**
2237 * hard-coded implementation for IWebsessionManager::logoff.
2238 *
2239 * @param
2240 * @param vbox__IWebsessionManager_USCORElogon
2241 * @param vbox__IWebsessionManager_USCORElogonResponse
2242 * @return
2243 */
2244int __vbox__IWebsessionManager_USCORElogoff(
2245 struct soap*,
2246 _vbox__IWebsessionManager_USCORElogoff *req,
2247 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
2248{
2249 HRESULT rc = S_OK;
2250 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2251
2252 do
2253 {
2254 // findSessionFromRef and the session destructor require the lock
2255 util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2256
2257 WebServiceSession* pSession;
2258 if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
2259 {
2260 delete pSession;
2261 // destructor cleans up
2262
2263 WEBDEBUG(("session destroyed, %d sessions left open\n", g_mapSessions.size()));
2264 }
2265 } while (0);
2266
2267 WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
2268 if (FAILED(rc))
2269 return SOAP_FAULT;
2270 return SOAP_OK;
2271}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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