VirtualBox

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

Last change on this file since 59621 was 57439, checked in by vboxsync, 9 years ago

DECLCALLBACK

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