VirtualBox

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

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

webservice: simplify termination logic, unify between platforms, ATL cleanup

  • Property filesplitter.c set to Makefile.kmk
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 80.0 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-2016 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.215389.xyz. 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 LogRel(("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 LogRel(("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 LogRel(("Processing connection from IP=%RTnaipv4 socket=%d (%d out of %d threads idle)\n",
604 RT_H2N_U32(m_soap->ip), m_soap->socket, cIdleThreads, cThreads));
605
606 // Ensure that we don't get stuck indefinitely for connections using
607 // keepalive, otherwise stale connections tie up worker threads.
608 m_soap->send_timeout = 60;
609 m_soap->recv_timeout = 60;
610 // process the request; this goes into the COM code in methodmaps.cpp
611 do {
612#ifdef WITH_OPENSSL
613 if (g_fSSL && soap_ssl_accept(m_soap))
614 {
615 WebLogSoapError(m_soap);
616 break;
617 }
618#endif /* WITH_OPENSSL */
619 soap_serve(m_soap);
620 } while (0);
621
622 soap_destroy(m_soap); // clean up class instances
623 soap_end(m_soap); // clean up everything and close socket
624
625 // tell the queue we're idle again
626 m_pQ->done();
627 }
628 m_pQ->signoff(this);
629}
630
631/****************************************************************************
632 *
633 * VirtualBoxClient event listener
634 *
635 ****************************************************************************/
636
637class VirtualBoxClientEventListener
638{
639public:
640 VirtualBoxClientEventListener()
641 {
642 }
643
644 virtual ~VirtualBoxClientEventListener()
645 {
646 }
647
648 HRESULT init()
649 {
650 return S_OK;
651 }
652
653 void uninit()
654 {
655 }
656
657
658 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
659 {
660 switch (aType)
661 {
662 case VBoxEventType_OnVBoxSVCAvailabilityChanged:
663 {
664 ComPtr<IVBoxSVCAvailabilityChangedEvent> pVSACEv = aEvent;
665 Assert(pVSACEv);
666 BOOL fAvailable = FALSE;
667 pVSACEv->COMGETTER(Available)(&fAvailable);
668 if (!fAvailable)
669 {
670 LogRel(("VBoxSVC became unavailable\n"));
671 {
672 util::AutoWriteLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
673 g_pVirtualBox.setNull();
674 }
675 {
676 // we're messing with websessions, so lock them
677 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
678 WEBDEBUG(("SVC unavailable: deleting %d websessions\n", g_mapWebsessions.size()));
679
680 WebsessionsMapIterator it = g_mapWebsessions.begin(),
681 itEnd = g_mapWebsessions.end();
682 while (it != itEnd)
683 {
684 WebServiceSession *pWebsession = it->second;
685 WEBDEBUG(("SVC unavailable: websession %#llx stale, deleting\n", pWebsession->getID()));
686 delete pWebsession;
687 it = g_mapWebsessions.begin();
688 }
689 }
690 }
691 else
692 {
693 LogRel(("VBoxSVC became available\n"));
694 util::AutoWriteLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
695 HRESULT hrc = g_pVirtualBoxClient->COMGETTER(VirtualBox)(g_pVirtualBox.asOutParam());
696 AssertComRC(hrc);
697 }
698 break;
699 }
700 default:
701 AssertFailed();
702 }
703
704 return S_OK;
705 }
706
707private:
708};
709
710typedef ListenerImpl<VirtualBoxClientEventListener> VirtualBoxClientEventListenerImpl;
711
712VBOX_LISTENER_DECLARE(VirtualBoxClientEventListenerImpl)
713
714/**
715 * Helper for printing SOAP error messages.
716 * @param soap
717 */
718/*static*/
719void WebLogSoapError(struct soap *soap)
720{
721 if (soap_check_state(soap))
722 {
723 LogRel(("Error: soap struct not initialized\n"));
724 return;
725 }
726
727 const char *pcszFaultString = *soap_faultstring(soap);
728 const char **ppcszDetail = soap_faultcode(soap);
729 LogRel(("#### SOAP FAULT: %s [%s]\n",
730 pcszFaultString ? pcszFaultString : "[no fault string available]",
731 (ppcszDetail && *ppcszDetail) ? *ppcszDetail : "no details available"));
732}
733
734/**
735 * Helper for decoding AuthResult.
736 * @param result AuthResult
737 */
738static const char * decodeAuthResult(AuthResult result)
739{
740 switch (result)
741 {
742 case AuthResultAccessDenied: return "access DENIED";
743 case AuthResultAccessGranted: return "access granted";
744 case AuthResultDelegateToGuest: return "delegated to guest";
745 default: return "unknown AuthResult";
746 }
747}
748
749#ifdef WITH_OPENSSL
750/****************************************************************************
751 *
752 * OpenSSL convenience functions for multithread support
753 *
754 ****************************************************************************/
755
756static RTCRITSECT *g_pSSLMutexes = NULL;
757
758struct CRYPTO_dynlock_value
759{
760 RTCRITSECT mutex;
761};
762
763static unsigned long CRYPTO_id_function()
764{
765 return (unsigned long)RTThreadNativeSelf();
766}
767
768static void CRYPTO_locking_function(int mode, int n, const char * /*file*/, int /*line*/)
769{
770 if (mode & CRYPTO_LOCK)
771 RTCritSectEnter(&g_pSSLMutexes[n]);
772 else
773 RTCritSectLeave(&g_pSSLMutexes[n]);
774}
775
776static struct CRYPTO_dynlock_value *CRYPTO_dyn_create_function(const char * /*file*/, int /*line*/)
777{
778 static uint32_t s_iCritSectDynlock = 0;
779 struct CRYPTO_dynlock_value *value = (struct CRYPTO_dynlock_value *)RTMemAlloc(sizeof(struct CRYPTO_dynlock_value));
780 if (value)
781 RTCritSectInitEx(&value->mutex, RTCRITSECT_FLAGS_NO_LOCK_VAL,
782 NIL_RTLOCKVALCLASS, RTLOCKVAL_SUB_CLASS_NONE,
783 "openssl-dyn-%u", ASMAtomicIncU32(&s_iCritSectDynlock) - 1);
784
785 return value;
786}
787
788static void CRYPTO_dyn_lock_function(int mode, struct CRYPTO_dynlock_value *value, const char * /*file*/, int /*line*/)
789{
790 if (mode & CRYPTO_LOCK)
791 RTCritSectEnter(&value->mutex);
792 else
793 RTCritSectLeave(&value->mutex);
794}
795
796static void CRYPTO_dyn_destroy_function(struct CRYPTO_dynlock_value *value, const char * /*file*/, int /*line*/)
797{
798 if (value)
799 {
800 RTCritSectDelete(&value->mutex);
801 free(value);
802 }
803}
804
805static int CRYPTO_thread_setup()
806{
807 int num_locks = CRYPTO_num_locks();
808 g_pSSLMutexes = (RTCRITSECT *)RTMemAlloc(num_locks * sizeof(RTCRITSECT));
809 if (!g_pSSLMutexes)
810 return SOAP_EOM;
811
812 for (int i = 0; i < num_locks; i++)
813 {
814 int rc = RTCritSectInitEx(&g_pSSLMutexes[i], RTCRITSECT_FLAGS_NO_LOCK_VAL,
815 NIL_RTLOCKVALCLASS, RTLOCKVAL_SUB_CLASS_NONE,
816 "openssl-%d", i);
817 if (RT_FAILURE(rc))
818 {
819 for ( ; i >= 0; i--)
820 RTCritSectDelete(&g_pSSLMutexes[i]);
821 RTMemFree(g_pSSLMutexes);
822 g_pSSLMutexes = NULL;
823 return SOAP_EOM;
824 }
825 }
826
827 CRYPTO_set_id_callback(CRYPTO_id_function);
828 CRYPTO_set_locking_callback(CRYPTO_locking_function);
829 CRYPTO_set_dynlock_create_callback(CRYPTO_dyn_create_function);
830 CRYPTO_set_dynlock_lock_callback(CRYPTO_dyn_lock_function);
831 CRYPTO_set_dynlock_destroy_callback(CRYPTO_dyn_destroy_function);
832
833 return SOAP_OK;
834}
835
836static void CRYPTO_thread_cleanup()
837{
838 if (!g_pSSLMutexes)
839 return;
840
841 CRYPTO_set_id_callback(NULL);
842 CRYPTO_set_locking_callback(NULL);
843 CRYPTO_set_dynlock_create_callback(NULL);
844 CRYPTO_set_dynlock_lock_callback(NULL);
845 CRYPTO_set_dynlock_destroy_callback(NULL);
846
847 int num_locks = CRYPTO_num_locks();
848 for (int i = 0; i < num_locks; i++)
849 RTCritSectDelete(&g_pSSLMutexes[i]);
850
851 RTMemFree(g_pSSLMutexes);
852 g_pSSLMutexes = NULL;
853}
854#endif /* WITH_OPENSSL */
855
856/****************************************************************************
857 *
858 * SOAP queue pumper thread
859 *
860 ****************************************************************************/
861
862static void doQueuesLoop()
863{
864#ifdef WITH_OPENSSL
865 if (g_fSSL && CRYPTO_thread_setup())
866 {
867 LogRel(("Failed to set up OpenSSL thread mutex!"));
868 exit(RTEXITCODE_FAILURE);
869 }
870#endif /* WITH_OPENSSL */
871
872 // set up gSOAP
873 struct soap soap;
874 soap_init(&soap);
875
876#ifdef WITH_OPENSSL
877 if (g_fSSL && soap_ssl_server_context(&soap, SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION | SOAP_TLSv1, g_pcszKeyFile,
878 g_pcszPassword, g_pcszCACert, g_pcszCAPath,
879 g_pcszDHFile, g_pcszRandFile, g_pcszSID))
880 {
881 WebLogSoapError(&soap);
882 exit(RTEXITCODE_FAILURE);
883 }
884#endif /* WITH_OPENSSL */
885
886 soap.bind_flags |= SO_REUSEADDR;
887 // avoid EADDRINUSE on bind()
888
889 SOAP_SOCKET m, s; // master and slave sockets
890 m = soap_bind(&soap,
891 g_pcszBindToHost ? g_pcszBindToHost : "localhost", // safe default host
892 g_uBindToPort, // port
893 g_uBacklog); // backlog = max queue size for requests
894 if (m < 0)
895 WebLogSoapError(&soap);
896 else
897 {
898#ifdef WITH_OPENSSL
899 const char *pszSsl = g_fSSL ? "SSL, " : "";
900#else /* !WITH_OPENSSL */
901 const char *pszSsl = "";
902#endif /*!WITH_OPENSSL */
903 LogRel(("Socket connection successful: host = %s, port = %u, %smaster socket = %d\n",
904 (g_pcszBindToHost) ? g_pcszBindToHost : "default (localhost)",
905 g_uBindToPort, pszSsl, m));
906
907 // initialize thread queue, mutex and eventsem
908 g_pSoapQ = new SoapQ(&soap);
909
910 for (uint64_t i = 1; g_fKeepRunning; i++)
911 {
912 // call gSOAP to handle incoming SOAP connection
913 soap.accept_timeout = 10;
914 s = soap_accept(&soap);
915 if (!soap_valid_socket(s))
916 {
917 if (soap.errnum)
918 WebLogSoapError(&soap);
919 continue;
920 }
921
922 // add the socket to the queue and tell worker threads to
923 // pick up the job
924 size_t cItemsOnQ = g_pSoapQ->add(s);
925 LogRel(("Request %llu on socket %d queued for processing (%d items on Q)\n", i, s, cItemsOnQ));
926 }
927
928 delete g_pSoapQ;
929 g_pSoapQ = NULL;
930
931 LogRel(("ending SOAP request handling\n"));
932
933 delete g_pSoapQ;
934 g_pSoapQ = NULL;
935
936 }
937 soap_done(&soap); // close master socket and detach environment
938
939#ifdef WITH_OPENSSL
940 if (g_fSSL)
941 CRYPTO_thread_cleanup();
942#endif /* WITH_OPENSSL */
943}
944
945/**
946 * Thread function for the "queue pumper" thread started from main(). This implements
947 * the loop that takes SOAP calls from HTTP and serves them by handing sockets to the
948 * SOAP queue worker threads.
949 */
950static DECLCALLBACK(int) fntQPumper(RTTHREAD ThreadSelf, void *pvUser)
951{
952 // store a log prefix for this thread
953 util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
954 g_mapThreads[RTThreadSelf()] = "[ P ]";
955 thrLock.release();
956
957 doQueuesLoop();
958
959 thrLock.acquire();
960 g_mapThreads.erase(RTThreadSelf());
961 return 0;
962}
963
964#ifdef RT_OS_WINDOWS
965// Required for ATL
966static ATL::CComModule _Module;
967
968/**
969 * "Signal" handler for cleanly terminating the event loop.
970 */
971static BOOL WINAPI websrvSignalHandler(DWORD dwCtrlType)
972{
973 bool fEventHandled = FALSE;
974 switch (dwCtrlType)
975 {
976 /* User pressed CTRL+C or CTRL+BREAK or an external event was sent
977 * via GenerateConsoleCtrlEvent(). */
978 case CTRL_BREAK_EVENT:
979 case CTRL_CLOSE_EVENT:
980 case CTRL_C_EVENT:
981 case CTRL_LOGOFF_EVENT:
982 case CTRL_SHUTDOWN_EVENT:
983 {
984 ASMAtomicWriteBool(&g_fKeepRunning, false);
985 com::NativeEventQueue *pQ = com::NativeEventQueue::getMainEventQueue();
986 pQ->interruptEventQueueProcessing();
987 fEventHandled = TRUE;
988 break;
989 }
990 default:
991 break;
992 }
993 return fEventHandled;
994}
995#else
996/**
997 * Signal handler for cleanly terminating the event loop.
998 */
999static void websrvSignalHandler(int iSignal)
1000{
1001 NOREF(iSignal);
1002 ASMAtomicWriteBool(&g_fKeepRunning, false);
1003 com::NativeEventQueue *pQ = com::NativeEventQueue::getMainEventQueue();
1004 pQ->interruptEventQueueProcessing();
1005}
1006#endif
1007
1008
1009/**
1010 * Start up the webservice server. This keeps running and waits
1011 * for incoming SOAP connections; for each request that comes in,
1012 * it calls method implementation code, most of it in the generated
1013 * code in methodmaps.cpp.
1014 *
1015 * @param argc
1016 * @param argv[]
1017 * @return
1018 */
1019int main(int argc, char *argv[])
1020{
1021 // initialize runtime
1022 int rc = RTR3InitExe(argc, &argv, 0);
1023 if (RT_FAILURE(rc))
1024 return RTMsgInitFailure(rc);
1025
1026 // store a log prefix for this thread
1027 g_mapThreads[RTThreadSelf()] = "[M ]";
1028
1029 RTStrmPrintf(g_pStdErr, VBOX_PRODUCT " web service Version " VBOX_VERSION_STRING "\n"
1030 "(C) 2007-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
1031 "All rights reserved.\n");
1032
1033 int c;
1034 const char *pszLogFile = NULL;
1035 const char *pszPidFile = NULL;
1036 RTGETOPTUNION ValueUnion;
1037 RTGETOPTSTATE GetState;
1038 RTGetOptInit(&GetState, argc, argv, g_aOptions, RT_ELEMENTS(g_aOptions), 1, 0 /*fFlags*/);
1039 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1040 {
1041 switch (c)
1042 {
1043 case 'H':
1044 if (!ValueUnion.psz || !*ValueUnion.psz)
1045 {
1046 /* Normalize NULL/empty string to NULL, which will be
1047 * interpreted as "localhost" below. */
1048 g_pcszBindToHost = NULL;
1049 }
1050 else
1051 g_pcszBindToHost = ValueUnion.psz;
1052 break;
1053
1054 case 'p':
1055 g_uBindToPort = ValueUnion.u32;
1056 break;
1057
1058#ifdef WITH_OPENSSL
1059 case 's':
1060 g_fSSL = true;
1061 break;
1062
1063 case 'K':
1064 g_pcszKeyFile = ValueUnion.psz;
1065 break;
1066
1067 case 'a':
1068 if (ValueUnion.psz[0] == '\0')
1069 g_pcszPassword = NULL;
1070 else
1071 {
1072 PRTSTREAM StrmIn;
1073 if (!strcmp(ValueUnion.psz, "-"))
1074 StrmIn = g_pStdIn;
1075 else
1076 {
1077 int vrc = RTStrmOpen(ValueUnion.psz, "r", &StrmIn);
1078 if (RT_FAILURE(vrc))
1079 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open password file (%s, %Rrc)", ValueUnion.psz, vrc);
1080 }
1081 char szPasswd[512];
1082 int vrc = RTStrmGetLine(StrmIn, szPasswd, sizeof(szPasswd));
1083 if (RT_FAILURE(vrc))
1084 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to read password (%s, %Rrc)", ValueUnion.psz, vrc);
1085 g_pcszPassword = RTStrDup(szPasswd);
1086 memset(szPasswd, '\0', sizeof(szPasswd));
1087 if (StrmIn != g_pStdIn)
1088 RTStrmClose(StrmIn);
1089 }
1090 break;
1091
1092 case 'c':
1093 g_pcszCACert = ValueUnion.psz;
1094 break;
1095
1096 case 'C':
1097 g_pcszCAPath = ValueUnion.psz;
1098 break;
1099
1100 case 'D':
1101 g_pcszDHFile = ValueUnion.psz;
1102 break;
1103
1104 case 'r':
1105 g_pcszRandFile = ValueUnion.psz;
1106 break;
1107#endif /* WITH_OPENSSL */
1108
1109 case 't':
1110 g_iWatchdogTimeoutSecs = ValueUnion.u32;
1111 break;
1112
1113 case 'i':
1114 g_iWatchdogCheckInterval = ValueUnion.u32;
1115 break;
1116
1117 case 'F':
1118 pszLogFile = ValueUnion.psz;
1119 break;
1120
1121 case 'R':
1122 g_cHistory = ValueUnion.u32;
1123 break;
1124
1125 case 'S':
1126 g_uHistoryFileSize = ValueUnion.u64;
1127 break;
1128
1129 case 'I':
1130 g_uHistoryFileTime = ValueUnion.u32;
1131 break;
1132
1133 case 'P':
1134 pszPidFile = ValueUnion.psz;
1135 break;
1136
1137 case 'T':
1138 g_cMaxWorkerThreads = ValueUnion.u32;
1139 break;
1140
1141 case 'k':
1142 g_cMaxKeepAlive = ValueUnion.u32;
1143 break;
1144
1145 case 'A':
1146 g_pcszAuthentication = ValueUnion.psz;
1147 break;
1148
1149 case 'h':
1150 DisplayHelp();
1151 return 0;
1152
1153 case 'v':
1154 g_fVerbose = true;
1155 break;
1156
1157#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1158 case 'b':
1159 g_fDaemonize = true;
1160 break;
1161#endif
1162 case 'V':
1163 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
1164 return 0;
1165
1166 default:
1167 rc = RTGetOptPrintError(c, &ValueUnion);
1168 return rc;
1169 }
1170 }
1171
1172 /* create release logger, to stdout */
1173 char szError[RTPATH_MAX + 128];
1174 rc = com::VBoxLogRelCreate("web service", g_fDaemonize ? NULL : pszLogFile,
1175 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
1176 "all", "VBOXWEBSRV_RELEASE_LOG",
1177 RTLOGDEST_STDOUT, UINT32_MAX /* cMaxEntriesPerGroup */,
1178 g_cHistory, g_uHistoryFileTime, g_uHistoryFileSize,
1179 szError, sizeof(szError));
1180 if (RT_FAILURE(rc))
1181 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, rc);
1182
1183#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1184 if (g_fDaemonize)
1185 {
1186 /* prepare release logging */
1187 char szLogFile[RTPATH_MAX];
1188
1189 if (!pszLogFile || !*pszLogFile)
1190 {
1191 rc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
1192 if (RT_FAILURE(rc))
1193 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not get base directory for logging: %Rrc", rc);
1194 rc = RTPathAppend(szLogFile, sizeof(szLogFile), "vboxwebsrv.log");
1195 if (RT_FAILURE(rc))
1196 return RTMsgErrorExit(RTEXITCODE_FAILURE, "could not construct logging path: %Rrc", rc);
1197 pszLogFile = szLogFile;
1198 }
1199
1200 rc = RTProcDaemonizeUsingFork(false /* fNoChDir */, false /* fNoClose */, pszPidFile);
1201 if (RT_FAILURE(rc))
1202 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to daemonize, rc=%Rrc. exiting.", rc);
1203
1204 /* create release logger, to file */
1205 rc = com::VBoxLogRelCreate("web service", pszLogFile,
1206 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
1207 "all", "VBOXWEBSRV_RELEASE_LOG",
1208 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
1209 g_cHistory, g_uHistoryFileTime, g_uHistoryFileSize,
1210 szError, sizeof(szError));
1211 if (RT_FAILURE(rc))
1212 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, rc);
1213 }
1214#endif
1215
1216 // initialize SOAP SSL support if enabled
1217#ifdef WITH_OPENSSL
1218 if (g_fSSL)
1219 soap_ssl_init();
1220#endif /* WITH_OPENSSL */
1221
1222 // initialize COM/XPCOM
1223 HRESULT hrc = com::Initialize();
1224#ifdef VBOX_WITH_XPCOM
1225 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
1226 {
1227 char szHome[RTPATH_MAX] = "";
1228 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
1229 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1230 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
1231 }
1232#endif
1233 if (FAILED(hrc))
1234 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to initialize COM! hrc=%Rhrc\n", hrc);
1235
1236 hrc = g_pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
1237 if (FAILED(hrc))
1238 {
1239 RTMsgError("failed to create the VirtualBoxClient object!");
1240 com::ErrorInfo info;
1241 if (!info.isFullAvailable() && !info.isBasicAvailable())
1242 {
1243 com::GluePrintRCMessage(hrc);
1244 RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
1245 }
1246 else
1247 com::GluePrintErrorInfo(info);
1248 return RTEXITCODE_FAILURE;
1249 }
1250
1251 hrc = g_pVirtualBoxClient->COMGETTER(VirtualBox)(g_pVirtualBox.asOutParam());
1252 if (FAILED(hrc))
1253 {
1254 RTMsgError("Failed to get VirtualBox object (rc=%Rhrc)!", hrc);
1255 return RTEXITCODE_FAILURE;
1256 }
1257
1258 // set the authentication method if requested
1259 if (g_pVirtualBox && g_pcszAuthentication && g_pcszAuthentication[0])
1260 {
1261 ComPtr<ISystemProperties> pSystemProperties;
1262 g_pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
1263 if (pSystemProperties)
1264 pSystemProperties->COMSETTER(WebServiceAuthLibrary)(com::Bstr(g_pcszAuthentication).raw());
1265 }
1266
1267 /* VirtualBoxClient events registration. */
1268 ComPtr<IEventListener> vboxClientListener;
1269 {
1270 ComPtr<IEventSource> pES;
1271 CHECK_ERROR(g_pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1272 ComObjPtr<VirtualBoxClientEventListenerImpl> clientListener;
1273 clientListener.createObject();
1274 clientListener->init(new VirtualBoxClientEventListener());
1275 vboxClientListener = clientListener;
1276 com::SafeArray<VBoxEventType_T> eventTypes;
1277 eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
1278 CHECK_ERROR(pES, RegisterListener(vboxClientListener, ComSafeArrayAsInParam(eventTypes), true));
1279 }
1280
1281 // create the global mutexes
1282 g_pAuthLibLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
1283 g_pVirtualBoxLockHandle = new util::RWLockHandle(util::LOCKCLASS_WEBSERVICE);
1284 g_pWebsessionsLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
1285 g_pThreadsLockHandle = new util::RWLockHandle(util::LOCKCLASS_OBJECTSTATE);
1286
1287 // SOAP queue pumper thread
1288 RTTHREAD threadQPumper;
1289 rc = RTThreadCreate(&threadQPumper,
1290 fntQPumper,
1291 NULL, // pvUser
1292 0, // cbStack (default)
1293 RTTHREADTYPE_MAIN_WORKER,
1294 RTTHREADFLAGS_WAITABLE,
1295 "SQPmp");
1296 if (RT_FAILURE(rc))
1297 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot start SOAP queue pumper thread: %Rrc", rc);
1298
1299 // watchdog thread
1300 RTTHREAD threadWatchdog = NIL_RTTHREAD;
1301 if (g_iWatchdogTimeoutSecs > 0)
1302 {
1303 // start our watchdog thread
1304 rc = RTThreadCreate(&threadWatchdog,
1305 fntWatchdog,
1306 NULL,
1307 0,
1308 RTTHREADTYPE_MAIN_WORKER,
1309 RTTHREADFLAGS_WAITABLE,
1310 "Watchdog");
1311 if (RT_FAILURE(rc))
1312 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot start watchdog thread: %Rrc", rc);
1313 }
1314
1315#ifdef RT_OS_WINDOWS
1316 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)websrvSignalHandler, TRUE /* Add handler */))
1317 {
1318 rc = RTErrConvertFromWin32(GetLastError());
1319 RTMsgError("Unable to install console control handler, rc=%Rrc\n", rc);
1320 }
1321#else
1322 signal(SIGINT, websrvSignalHandler);
1323# ifdef SIGBREAK
1324 signal(SIGBREAK, websrvSignalHandler);
1325# endif
1326#endif
1327
1328 com::NativeEventQueue *pQ = com::NativeEventQueue::getMainEventQueue();
1329 while (g_fKeepRunning)
1330 {
1331 // we have to process main event queue
1332 WEBDEBUG(("Pumping COM event queue\n"));
1333 rc = pQ->processEventQueue(RT_INDEFINITE_WAIT);
1334 if (RT_FAILURE(rc))
1335 RTMsgError("processEventQueue -> %Rrc", rc);
1336 }
1337
1338 LogRel(("requested termination, cleaning up\n"));
1339
1340#ifdef RT_OS_WINDOWS
1341 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)websrvSignalHandler, FALSE /* Remove handler */))
1342 {
1343 rc = RTErrConvertFromWin32(GetLastError());
1344 RTMsgError("Unable to remove console control handler, rc=%Rrc\n", rc);
1345 }
1346#else
1347 signal(SIGINT, SIG_DFL);
1348# ifdef SIGBREAK
1349 signal(SIGBREAK, SIG_DFL);
1350# endif
1351#endif
1352
1353 RTThreadWait(threadQPumper, 30000, NULL);
1354 if (threadWatchdog != NIL_RTTHREAD)
1355 RTThreadWait(threadWatchdog, g_iWatchdogCheckInterval * 1000 + 10000, NULL);
1356
1357 /* VirtualBoxClient events unregistration. */
1358 if (vboxClientListener)
1359 {
1360 ComPtr<IEventSource> pES;
1361 CHECK_ERROR(g_pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
1362 if (!pES.isNull())
1363 CHECK_ERROR(pES, UnregisterListener(vboxClientListener));
1364 vboxClientListener.setNull();
1365 }
1366
1367 {
1368 util::AutoWriteLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
1369 g_pVirtualBox.setNull();
1370 }
1371 {
1372 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1373 WebsessionsMapIterator it = g_mapWebsessions.begin(),
1374 itEnd = g_mapWebsessions.end();
1375 while (it != itEnd)
1376 {
1377 WebServiceSession *pWebsession = it->second;
1378 WEBDEBUG(("SVC unavailable: websession %#llx stale, deleting\n", pWebsession->getID()));
1379 delete pWebsession;
1380 it = g_mapWebsessions.begin();
1381 }
1382 }
1383 g_pVirtualBoxClient.setNull();
1384
1385 com::Shutdown();
1386
1387 return 0;
1388}
1389
1390/****************************************************************************
1391 *
1392 * Watchdog thread
1393 *
1394 ****************************************************************************/
1395
1396/**
1397 * Watchdog thread, runs in the background while the webservice is alive.
1398 *
1399 * This gets started by main() and runs in the background to check all websessions
1400 * for whether they have been no requests in a configurable timeout period. In
1401 * that case, the websession is automatically logged off.
1402 */
1403static DECLCALLBACK(int) fntWatchdog(RTTHREAD ThreadSelf, void *pvUser)
1404{
1405 // store a log prefix for this thread
1406 util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
1407 g_mapThreads[RTThreadSelf()] = "[W ]";
1408 thrLock.release();
1409
1410 WEBDEBUG(("Watchdog thread started\n"));
1411
1412 while (g_fKeepRunning)
1413 {
1414 WEBDEBUG(("Watchdog: sleeping %d seconds\n", g_iWatchdogCheckInterval));
1415 RTThreadSleep(g_iWatchdogCheckInterval * 1000);
1416
1417 time_t tNow;
1418 time(&tNow);
1419
1420 // we're messing with websessions, so lock them
1421 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
1422 WEBDEBUG(("Watchdog: checking %d websessions\n", g_mapWebsessions.size()));
1423
1424 WebsessionsMapIterator it = g_mapWebsessions.begin(),
1425 itEnd = g_mapWebsessions.end();
1426 while (it != itEnd)
1427 {
1428 WebServiceSession *pWebsession = it->second;
1429 WEBDEBUG(("Watchdog: tNow: %d, websession timestamp: %d\n", tNow, pWebsession->getLastObjectLookup()));
1430 if (tNow > pWebsession->getLastObjectLookup() + g_iWatchdogTimeoutSecs)
1431 {
1432 WEBDEBUG(("Watchdog: websession %#llx timed out, deleting\n", pWebsession->getID()));
1433 delete pWebsession;
1434 it = g_mapWebsessions.begin();
1435 }
1436 else
1437 ++it;
1438 }
1439
1440 // re-set the authentication method in case it has been changed
1441 if (g_pVirtualBox && g_pcszAuthentication && g_pcszAuthentication[0])
1442 {
1443 ComPtr<ISystemProperties> pSystemProperties;
1444 g_pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
1445 if (pSystemProperties)
1446 pSystemProperties->COMSETTER(WebServiceAuthLibrary)(com::Bstr(g_pcszAuthentication).raw());
1447 }
1448 }
1449
1450 thrLock.acquire();
1451 g_mapThreads.erase(RTThreadSelf());
1452
1453 LogRel(("ending Watchdog thread\n"));
1454 return 0;
1455}
1456
1457/****************************************************************************
1458 *
1459 * SOAP exceptions
1460 *
1461 ****************************************************************************/
1462
1463/**
1464 * Helper function to raise a SOAP fault. Called by the other helper
1465 * functions, which raise specific SOAP faults.
1466 *
1467 * @param soap
1468 * @param str
1469 * @param extype
1470 * @param ex
1471 */
1472static void RaiseSoapFault(struct soap *soap,
1473 const char *pcsz,
1474 int extype,
1475 void *ex)
1476{
1477 // raise the fault
1478 soap_sender_fault(soap, pcsz, NULL);
1479
1480 struct SOAP_ENV__Detail *pDetail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
1481
1482 // without the following, gSOAP crashes miserably when sending out the
1483 // data because it will try to serialize all fields (stupid documentation)
1484 memset(pDetail, 0, sizeof(struct SOAP_ENV__Detail));
1485
1486 // fill extended info depending on SOAP version
1487 if (soap->version == 2) // SOAP 1.2 is used
1488 {
1489 soap->fault->SOAP_ENV__Detail = pDetail;
1490 soap->fault->SOAP_ENV__Detail->__type = extype;
1491 soap->fault->SOAP_ENV__Detail->fault = ex;
1492 soap->fault->SOAP_ENV__Detail->__any = NULL; // no other XML data
1493 }
1494 else
1495 {
1496 soap->fault->detail = pDetail;
1497 soap->fault->detail->__type = extype;
1498 soap->fault->detail->fault = ex;
1499 soap->fault->detail->__any = NULL; // no other XML data
1500 }
1501}
1502
1503/**
1504 * Raises a SOAP fault that signals that an invalid object was passed.
1505 *
1506 * @param soap
1507 * @param obj
1508 */
1509void RaiseSoapInvalidObjectFault(struct soap *soap,
1510 WSDLT_ID obj)
1511{
1512 _vbox__InvalidObjectFault *ex = soap_new__vbox__InvalidObjectFault(soap, 1);
1513 ex->badObjectID = obj;
1514
1515 std::string str("VirtualBox error: ");
1516 str += "Invalid managed object reference \"" + obj + "\"";
1517
1518 RaiseSoapFault(soap,
1519 str.c_str(),
1520 SOAP_TYPE__vbox__InvalidObjectFault,
1521 ex);
1522}
1523
1524/**
1525 * Return a safe C++ string from the given COM string,
1526 * without crashing if the COM string is empty.
1527 * @param bstr
1528 * @return
1529 */
1530std::string ConvertComString(const com::Bstr &bstr)
1531{
1532 com::Utf8Str ustr(bstr);
1533 return ustr.c_str(); // @todo r=dj since the length is known, we can probably use a better std::string allocator
1534}
1535
1536/**
1537 * Return a safe C++ string from the given COM UUID,
1538 * without crashing if the UUID is empty.
1539 * @param bstr
1540 * @return
1541 */
1542std::string ConvertComString(const com::Guid &uuid)
1543{
1544 com::Utf8Str ustr(uuid.toString());
1545 return ustr.c_str(); // @todo r=dj since the length is known, we can probably use a better std::string allocator
1546}
1547
1548/** Code to handle string <-> byte arrays base64 conversion. */
1549std::string Base64EncodeByteArray(ComSafeArrayIn(BYTE, aData))
1550{
1551
1552 com::SafeArray<BYTE> sfaData(ComSafeArrayInArg(aData));
1553 ssize_t cbData = sfaData.size();
1554
1555 if (cbData == 0)
1556 return "";
1557
1558 ssize_t cchOut = RTBase64EncodedLength(cbData);
1559
1560 RTCString aStr;
1561
1562 aStr.reserve(cchOut+1);
1563 int rc = RTBase64Encode(sfaData.raw(), cbData,
1564 aStr.mutableRaw(), aStr.capacity(),
1565 NULL);
1566 AssertRC(rc);
1567 aStr.jolt();
1568
1569 return aStr.c_str();
1570}
1571
1572#define DECODE_STR_MAX _1M
1573void Base64DecodeByteArray(struct soap *soap, const std::string& aStr, ComSafeArrayOut(BYTE, aData), const WSDLT_ID &idThis, const char *pszMethodName, IUnknown *pObj, const com::Guid &iid)
1574{
1575 const char* pszStr = aStr.c_str();
1576 ssize_t cbOut = RTBase64DecodedSize(pszStr, NULL);
1577
1578 if (cbOut > DECODE_STR_MAX)
1579 {
1580 LogRel(("Decode string too long.\n"));
1581 RaiseSoapRuntimeFault(soap, idThis, pszMethodName, E_INVALIDARG, pObj, iid);
1582 }
1583
1584 com::SafeArray<BYTE> result(cbOut);
1585 int rc = RTBase64Decode(pszStr, result.raw(), cbOut, NULL, NULL);
1586 if (FAILED(rc))
1587 {
1588 LogRel(("String Decoding Failed. Error code: %Rrc\n", rc));
1589 RaiseSoapRuntimeFault(soap, idThis, pszMethodName, E_INVALIDARG, pObj, iid);
1590 }
1591
1592 result.detachTo(ComSafeArrayOutArg(aData));
1593}
1594
1595/**
1596 * Raises a SOAP runtime fault.
1597 *
1598 * @param soap
1599 * @param idThis
1600 * @param pcszMethodName
1601 * @param apirc
1602 * @param pObj
1603 * @param iid
1604 */
1605void RaiseSoapRuntimeFault(struct soap *soap,
1606 const WSDLT_ID &idThis,
1607 const char *pcszMethodName,
1608 HRESULT apirc,
1609 IUnknown *pObj,
1610 const com::Guid &iid)
1611{
1612 com::ErrorInfo info(pObj, iid.ref());
1613
1614 WEBDEBUG((" error, raising SOAP exception\n"));
1615
1616 LogRel(("API method name: %s\n", pcszMethodName));
1617 LogRel(("API return code: %#10lx (%Rhrc)\n", apirc, apirc));
1618 if (info.isFullAvailable() || info.isBasicAvailable())
1619 {
1620 const com::ErrorInfo *pInfo = &info;
1621 do
1622 {
1623 LogRel(("COM error info result code: %#10lx (%Rhrc)\n", pInfo->getResultCode(), pInfo->getResultCode()));
1624 LogRel(("COM error info text: %ls\n", pInfo->getText().raw()));
1625
1626 pInfo = pInfo->getNext();
1627 }
1628 while (pInfo);
1629 }
1630
1631 // compose descriptive message
1632 com::Utf8Str str = com::Utf8StrFmt("VirtualBox error: rc=%#lx", apirc);
1633 if (info.isFullAvailable() || info.isBasicAvailable())
1634 {
1635 const com::ErrorInfo *pInfo = &info;
1636 do
1637 {
1638 str += com::Utf8StrFmt(" %ls (%#lx)", pInfo->getText().raw(), pInfo->getResultCode());
1639 pInfo = pInfo->getNext();
1640 }
1641 while (pInfo);
1642 }
1643
1644 // allocate our own soap fault struct
1645 _vbox__RuntimeFault *ex = soap_new__vbox__RuntimeFault(soap, 1);
1646 ComPtr<IVirtualBoxErrorInfo> pVirtualBoxErrorInfo;
1647 info.getVirtualBoxErrorInfo(pVirtualBoxErrorInfo);
1648 ex->resultCode = apirc;
1649 ex->returnval = createOrFindRefFromComPtr(idThis, g_pcszIVirtualBoxErrorInfo, pVirtualBoxErrorInfo);
1650
1651 RaiseSoapFault(soap,
1652 str.c_str(),
1653 SOAP_TYPE__vbox__RuntimeFault,
1654 ex);
1655}
1656
1657/****************************************************************************
1658 *
1659 * splitting and merging of object IDs
1660 *
1661 ****************************************************************************/
1662
1663/**
1664 * Splits a managed object reference (in string form, as passed in from a SOAP
1665 * method call) into two integers for websession and object IDs, respectively.
1666 *
1667 * @param id
1668 * @param pWebsessId
1669 * @param pObjId
1670 * @return
1671 */
1672static bool SplitManagedObjectRef(const WSDLT_ID &id,
1673 uint64_t *pWebsessId,
1674 uint64_t *pObjId)
1675{
1676 // 64-bit numbers in hex have 16 digits; hence
1677 // the object-ref string must have 16 + "-" + 16 characters
1678 if ( id.length() == 33
1679 && id[16] == '-'
1680 )
1681 {
1682 char psz[34];
1683 memcpy(psz, id.c_str(), 34);
1684 psz[16] = '\0';
1685 if (pWebsessId)
1686 RTStrToUInt64Full(psz, 16, pWebsessId);
1687 if (pObjId)
1688 RTStrToUInt64Full(psz + 17, 16, pObjId);
1689 return true;
1690 }
1691
1692 return false;
1693}
1694
1695/**
1696 * Creates a managed object reference (in string form) from
1697 * two integers representing a websession and object ID, respectively.
1698 *
1699 * @param sz Buffer with at least 34 bytes space to receive MOR string.
1700 * @param websessId
1701 * @param objId
1702 * @return
1703 */
1704static void MakeManagedObjectRef(char *sz,
1705 uint64_t websessId,
1706 uint64_t objId)
1707{
1708 RTStrFormatNumber(sz, websessId, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
1709 sz[16] = '-';
1710 RTStrFormatNumber(sz + 17, objId, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
1711}
1712
1713/****************************************************************************
1714 *
1715 * class WebServiceSession
1716 *
1717 ****************************************************************************/
1718
1719class WebServiceSessionPrivate
1720{
1721 public:
1722 ManagedObjectsMapById _mapManagedObjectsById;
1723 ManagedObjectsMapByPtr _mapManagedObjectsByPtr;
1724};
1725
1726/**
1727 * Constructor for the websession object.
1728 *
1729 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
1730 *
1731 * @param username
1732 * @param password
1733 */
1734WebServiceSession::WebServiceSession()
1735 : _uNextObjectID(1), // avoid 0 for no real reason
1736 _fDestructing(false),
1737 _tLastObjectLookup(0)
1738{
1739 _pp = new WebServiceSessionPrivate;
1740 _uWebsessionID = RTRandU64();
1741
1742 // register this websession globally
1743 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1744 g_mapWebsessions[_uWebsessionID] = this;
1745}
1746
1747/**
1748 * Destructor. Cleans up and destroys all contained managed object references on the way.
1749 *
1750 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
1751 */
1752WebServiceSession::~WebServiceSession()
1753{
1754 // delete us from global map first so we can't be found
1755 // any more while we're cleaning up
1756 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1757 g_mapWebsessions.erase(_uWebsessionID);
1758
1759 // notify ManagedObjectRef destructor so it won't
1760 // remove itself from the maps; this avoids rebalancing
1761 // the map's tree on every delete as well
1762 _fDestructing = true;
1763
1764 ManagedObjectsIteratorById it,
1765 end = _pp->_mapManagedObjectsById.end();
1766 for (it = _pp->_mapManagedObjectsById.begin();
1767 it != end;
1768 ++it)
1769 {
1770 ManagedObjectRef *pRef = it->second;
1771 delete pRef; // this frees the contained ComPtr as well
1772 }
1773
1774 delete _pp;
1775}
1776
1777/**
1778 * Authenticate the username and password against an authentication authority.
1779 *
1780 * @return 0 if the user was successfully authenticated, or an error code
1781 * otherwise.
1782 */
1783int WebServiceSession::authenticate(const char *pcszUsername,
1784 const char *pcszPassword,
1785 IVirtualBox **ppVirtualBox)
1786{
1787 int rc = VERR_WEB_NOT_AUTHENTICATED;
1788 ComPtr<IVirtualBox> pVirtualBox;
1789 {
1790 util::AutoReadLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
1791 pVirtualBox = g_pVirtualBox;
1792 }
1793 if (pVirtualBox.isNull())
1794 return rc;
1795 pVirtualBox.queryInterfaceTo(ppVirtualBox);
1796
1797 util::AutoReadLock lock(g_pAuthLibLockHandle COMMA_LOCKVAL_SRC_POS);
1798
1799 static bool fAuthLibLoaded = false;
1800 static PAUTHENTRY pfnAuthEntry = NULL;
1801 static PAUTHENTRY2 pfnAuthEntry2 = NULL;
1802 static PAUTHENTRY3 pfnAuthEntry3 = NULL;
1803
1804 if (!fAuthLibLoaded)
1805 {
1806 // retrieve authentication library from system properties
1807 ComPtr<ISystemProperties> systemProperties;
1808 pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
1809
1810 com::Bstr authLibrary;
1811 systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
1812 com::Utf8Str filename = authLibrary;
1813
1814 LogRel(("External authentication library is '%ls'\n", authLibrary.raw()));
1815
1816 if (filename == "null")
1817 // authentication disabled, let everyone in:
1818 fAuthLibLoaded = true;
1819 else
1820 {
1821 RTLDRMOD hlibAuth = 0;
1822 do
1823 {
1824 if (RTPathHavePath(filename.c_str()))
1825 rc = RTLdrLoad(filename.c_str(), &hlibAuth);
1826 else
1827 rc = RTLdrLoadAppPriv(filename.c_str(), &hlibAuth);
1828
1829 if (RT_FAILURE(rc))
1830 {
1831 WEBDEBUG(("%s() Failed to load external authentication library '%s'. Error code: %Rrc\n",
1832 __FUNCTION__, filename.c_str(), rc));
1833 break;
1834 }
1835
1836 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY3_NAME, (void**)&pfnAuthEntry3)))
1837 {
1838 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1839 __FUNCTION__, AUTHENTRY3_NAME, rc));
1840
1841 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY2_NAME, (void**)&pfnAuthEntry2)))
1842 {
1843 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1844 __FUNCTION__, AUTHENTRY2_NAME, rc));
1845
1846 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY_NAME, (void**)&pfnAuthEntry)))
1847 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1848 __FUNCTION__, AUTHENTRY_NAME, rc));
1849 }
1850 }
1851
1852 if (pfnAuthEntry || pfnAuthEntry2 || pfnAuthEntry3)
1853 fAuthLibLoaded = true;
1854
1855 } while (0);
1856 }
1857 }
1858
1859 if (pfnAuthEntry3 || pfnAuthEntry2 || pfnAuthEntry)
1860 {
1861 const char *pszFn;
1862 AuthResult result;
1863 if (pfnAuthEntry3)
1864 {
1865 result = pfnAuthEntry3("webservice", NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1866 pszFn = AUTHENTRY3_NAME;
1867 }
1868 else if (pfnAuthEntry2)
1869 {
1870 result = pfnAuthEntry2(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1871 pszFn = AUTHENTRY2_NAME;
1872 }
1873 else
1874 {
1875 result = pfnAuthEntry(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
1876 pszFn = AUTHENTRY_NAME;
1877 }
1878 WEBDEBUG(("%s(): result of %s('%s', [%d]): %d (%s)\n",
1879 __FUNCTION__, pszFn, pcszUsername, strlen(pcszPassword), result, decodeAuthResult(result)));
1880 if (result == AuthResultAccessGranted)
1881 {
1882 LogRel(("Access for user '%s' granted\n", pcszUsername));
1883 rc = VINF_SUCCESS;
1884 }
1885 else
1886 {
1887 if (result == AuthResultAccessDenied)
1888 LogRel(("Access for user '%s' denied\n", pcszUsername));
1889 rc = VERR_WEB_NOT_AUTHENTICATED;
1890 }
1891 }
1892 else if (fAuthLibLoaded)
1893 {
1894 // fAuthLibLoaded = true but all pointers are NULL:
1895 // The authlib was "null" and auth was disabled
1896 rc = VINF_SUCCESS;
1897 }
1898 else
1899 {
1900 WEBDEBUG(("Could not resolve AuthEntry, VRDPAuth2 or VRDPAuth entry point"));
1901 rc = VERR_WEB_NOT_AUTHENTICATED;
1902 }
1903
1904 lock.release();
1905
1906 return rc;
1907}
1908
1909/**
1910 * Look up, in this websession, whether a ManagedObjectRef has already been
1911 * created for the given COM pointer.
1912 *
1913 * Note how we require that a ComPtr<IUnknown> is passed, which causes a
1914 * queryInterface call when the caller passes in a different type, since
1915 * a ComPtr<IUnknown> will point to something different than a
1916 * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
1917 * our private hash table, we must search for one too.
1918 *
1919 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
1920 *
1921 * @param pcu pointer to a COM object.
1922 * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
1923 */
1924ManagedObjectRef* WebServiceSession::findRefFromPtr(const IUnknown *pObject)
1925{
1926 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1927
1928 uintptr_t ulp = (uintptr_t)pObject;
1929 // WEBDEBUG((" %s: looking up %#lx\n", __FUNCTION__, ulp));
1930 ManagedObjectsIteratorByPtr it = _pp->_mapManagedObjectsByPtr.find(ulp);
1931 if (it != _pp->_mapManagedObjectsByPtr.end())
1932 {
1933 ManagedObjectRef *pRef = it->second;
1934 WEBDEBUG((" %s: found existing ref %s (%s) for COM obj %#lx\n", __FUNCTION__, pRef->getWSDLID().c_str(), pRef->getInterfaceName(), ulp));
1935 return pRef;
1936 }
1937
1938 return NULL;
1939}
1940
1941/**
1942 * Static method which attempts to find the websession for which the given
1943 * managed object reference was created, by splitting the reference into the
1944 * websession and object IDs and then looking up the websession object.
1945 *
1946 * Preconditions: Caller must have locked g_pWebsessionsLockHandle in read mode.
1947 *
1948 * @param id Managed object reference (with combined websession and object IDs).
1949 * @return
1950 */
1951WebServiceSession *WebServiceSession::findWebsessionFromRef(const WSDLT_ID &id)
1952{
1953 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1954
1955 WebServiceSession *pWebsession = NULL;
1956 uint64_t websessId;
1957 if (SplitManagedObjectRef(id,
1958 &websessId,
1959 NULL))
1960 {
1961 WebsessionsMapIterator it = g_mapWebsessions.find(websessId);
1962 if (it != g_mapWebsessions.end())
1963 pWebsession = it->second;
1964 }
1965 return pWebsession;
1966}
1967
1968/**
1969 * Touches the websession to prevent it from timing out.
1970 *
1971 * Each websession has an internal timestamp that records the last request made
1972 * to it from the client that started it. If no request was made within a
1973 * configurable timeframe, then the client is logged off automatically,
1974 * by calling IWebsessionManager::logoff()
1975 */
1976void WebServiceSession::touch()
1977{
1978 time(&_tLastObjectLookup);
1979}
1980
1981
1982/****************************************************************************
1983 *
1984 * class ManagedObjectRef
1985 *
1986 ****************************************************************************/
1987
1988/**
1989 * Constructor, which assigns a unique ID to this managed object
1990 * reference and stores it in two hashes (living in the associated
1991 * WebServiceSession object):
1992 *
1993 * a) _mapManagedObjectsById, which maps ManagedObjectID's to
1994 * instances of this class; this hash is then used by the
1995 * findObjectFromRef() template function in vboxweb.h
1996 * to quickly retrieve the COM object from its managed
1997 * object ID (mostly in the context of the method mappers
1998 * in methodmaps.cpp, when a web service client passes in
1999 * a managed object ID);
2000 *
2001 * b) _mapManagedObjectsByPtr, which maps COM pointers to
2002 * instances of this class; this hash is used by
2003 * createRefFromObject() to quickly figure out whether an
2004 * instance already exists for a given COM pointer.
2005 *
2006 * This constructor calls AddRef() on the given COM object, and
2007 * the destructor will call Release(). We require two input pointers
2008 * for that COM object, one generic IUnknown* pointer which is used
2009 * as the map key, and a specific interface pointer (e.g. IMachine*)
2010 * which must support the interface given in guidInterface. All
2011 * three values are returned by getPtr(), which gives future callers
2012 * a chance to reuse the specific interface pointer without having
2013 * to call QueryInterface, which can be expensive.
2014 *
2015 * This does _not_ check whether another instance already
2016 * exists in the hash. This gets called only from the
2017 * createOrFindRefFromComPtr() template function in vboxweb.h, which
2018 * does perform that check.
2019 *
2020 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2021 *
2022 * @param websession Websession to which the MOR will be added.
2023 * @param pobjUnknown Pointer to IUnknown* interface for the COM object; this will be used in the hashes.
2024 * @param pobjInterface Pointer to a specific interface for the COM object, described by guidInterface.
2025 * @param guidInterface Interface which pobjInterface points to.
2026 * @param pcszInterface String representation of that interface (e.g. "IMachine") for readability and logging.
2027 */
2028ManagedObjectRef::ManagedObjectRef(WebServiceSession &websession,
2029 IUnknown *pobjUnknown,
2030 void *pobjInterface,
2031 const com::Guid &guidInterface,
2032 const char *pcszInterface)
2033 : _websession(websession),
2034 _pobjUnknown(pobjUnknown),
2035 _pobjInterface(pobjInterface),
2036 _guidInterface(guidInterface),
2037 _pcszInterface(pcszInterface)
2038{
2039 Assert(pobjUnknown);
2040 Assert(pobjInterface);
2041
2042 // keep both stubs alive while this MOR exists (matching Release() calls are in destructor)
2043 uint32_t cRefs1 = pobjUnknown->AddRef();
2044 uint32_t cRefs2 = ((IUnknown*)pobjInterface)->AddRef();
2045 _ulp = (uintptr_t)pobjUnknown;
2046
2047 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2048 _id = websession.createObjectID();
2049 // and count globally
2050 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
2051
2052 char sz[34];
2053 MakeManagedObjectRef(sz, websession._uWebsessionID, _id);
2054 _strID = sz;
2055
2056 websession._pp->_mapManagedObjectsById[_id] = this;
2057 websession._pp->_mapManagedObjectsByPtr[_ulp] = this;
2058
2059 websession.touch();
2060
2061 WEBDEBUG((" * %s: MOR created for %s*=%#p (IUnknown*=%#p; COM refcount now %RI32/%RI32), new ID is %#llx; now %lld objects total\n",
2062 __FUNCTION__,
2063 pcszInterface,
2064 pobjInterface,
2065 pobjUnknown,
2066 cRefs1,
2067 cRefs2,
2068 _id,
2069 cTotal));
2070}
2071
2072/**
2073 * Destructor; removes the instance from the global hash of
2074 * managed objects. Calls Release() on the contained COM object.
2075 *
2076 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2077 */
2078ManagedObjectRef::~ManagedObjectRef()
2079{
2080 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2081 ULONG64 cTotal = --g_cManagedObjects;
2082
2083 Assert(_pobjUnknown);
2084 Assert(_pobjInterface);
2085
2086 // we called AddRef() on both interfaces, so call Release() on
2087 // both as well, but in reverse order
2088 uint32_t cRefs2 = ((IUnknown*)_pobjInterface)->Release();
2089 uint32_t cRefs1 = _pobjUnknown->Release();
2090 WEBDEBUG((" * %s: deleting MOR for ID %#llx (%s; COM refcount now %RI32/%RI32); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cRefs1, cRefs2, cTotal));
2091
2092 // if we're being destroyed from the websession's destructor,
2093 // then that destructor is iterating over the maps, so
2094 // don't remove us there! (data integrity + speed)
2095 if (!_websession._fDestructing)
2096 {
2097 WEBDEBUG((" * %s: removing from websession maps\n", __FUNCTION__));
2098 _websession._pp->_mapManagedObjectsById.erase(_id);
2099 if (_websession._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
2100 WEBDEBUG((" WARNING: could not find %#llx in _mapManagedObjectsByPtr\n", _ulp));
2101 }
2102}
2103
2104/**
2105 * Static helper method for findObjectFromRef() template that actually
2106 * looks up the object from a given integer ID.
2107 *
2108 * This has been extracted into this non-template function to reduce
2109 * code bloat as we have the actual STL map lookup only in this function.
2110 *
2111 * This also "touches" the timestamp in the websession whose ID is encoded
2112 * in the given integer ID, in order to prevent the websession from timing
2113 * out.
2114 *
2115 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2116 *
2117 * @param strId
2118 * @param iter
2119 * @return
2120 */
2121int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
2122 ManagedObjectRef **pRef,
2123 bool fNullAllowed)
2124{
2125 int rc = 0;
2126
2127 do
2128 {
2129 // allow NULL (== empty string) input reference, which should return a NULL pointer
2130 if (!id.length() && fNullAllowed)
2131 {
2132 *pRef = NULL;
2133 return 0;
2134 }
2135
2136 uint64_t websessId;
2137 uint64_t objId;
2138 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
2139 if (!SplitManagedObjectRef(id,
2140 &websessId,
2141 &objId))
2142 {
2143 rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
2144 break;
2145 }
2146
2147 WebsessionsMapIterator it = g_mapWebsessions.find(websessId);
2148 if (it == g_mapWebsessions.end())
2149 {
2150 WEBDEBUG((" %s: cannot find websession for objref %s\n", __FUNCTION__, id.c_str()));
2151 rc = VERR_WEB_INVALID_SESSION_ID;
2152 break;
2153 }
2154
2155 WebServiceSession *pWebsession = it->second;
2156 // "touch" websession to prevent it from timing out
2157 pWebsession->touch();
2158
2159 ManagedObjectsIteratorById iter = pWebsession->_pp->_mapManagedObjectsById.find(objId);
2160 if (iter == pWebsession->_pp->_mapManagedObjectsById.end())
2161 {
2162 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
2163 rc = VERR_WEB_INVALID_OBJECT_ID;
2164 break;
2165 }
2166
2167 *pRef = iter->second;
2168
2169 } while (0);
2170
2171 return rc;
2172}
2173
2174/****************************************************************************
2175 *
2176 * interface IManagedObjectRef
2177 *
2178 ****************************************************************************/
2179
2180/**
2181 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
2182 * that our WSDL promises to our web service clients. This method returns a
2183 * string describing the interface that this managed object reference
2184 * supports, e.g. "IMachine".
2185 *
2186 * @param soap
2187 * @param req
2188 * @param resp
2189 * @return
2190 */
2191int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
2192 struct soap *soap,
2193 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
2194 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
2195{
2196 HRESULT rc = S_OK;
2197 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2198
2199 do
2200 {
2201 // findRefFromId require the lock
2202 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2203
2204 ManagedObjectRef *pRef;
2205 if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false))
2206 resp->returnval = pRef->getInterfaceName();
2207
2208 } while (0);
2209
2210 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2211 if (FAILED(rc))
2212 return SOAP_FAULT;
2213 return SOAP_OK;
2214}
2215
2216/**
2217 * This is the hard-coded implementation for the IManagedObjectRef::release()
2218 * that our WSDL promises to our web service clients. This method releases
2219 * a managed object reference and removes it from our stacks.
2220 *
2221 * @param soap
2222 * @param req
2223 * @param resp
2224 * @return
2225 */
2226int __vbox__IManagedObjectRef_USCORErelease(
2227 struct soap *soap,
2228 _vbox__IManagedObjectRef_USCORErelease *req,
2229 _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
2230{
2231 HRESULT rc = S_OK;
2232 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2233
2234 do
2235 {
2236 // findRefFromId and the delete call below require the lock
2237 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2238
2239 ManagedObjectRef *pRef;
2240 if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false)))
2241 {
2242 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
2243 break;
2244 }
2245
2246 WEBDEBUG((" found reference; deleting!\n"));
2247 // this removes the object from all stacks; since
2248 // there's a ComPtr<> hidden inside the reference,
2249 // this should also invoke Release() on the COM
2250 // object
2251 delete pRef;
2252 } while (0);
2253
2254 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2255 if (FAILED(rc))
2256 return SOAP_FAULT;
2257 return SOAP_OK;
2258}
2259
2260/****************************************************************************
2261 *
2262 * interface IWebsessionManager
2263 *
2264 ****************************************************************************/
2265
2266/**
2267 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
2268 * COM API, this is the first method that a webservice client must call before the
2269 * webservice will do anything useful.
2270 *
2271 * This returns a managed object reference to the global IVirtualBox object; into this
2272 * reference a websession ID is encoded which remains constant with all managed object
2273 * references returned by other methods.
2274 *
2275 * When the webservice client is done, it should call IWebsessionManager::logoff. This
2276 * will clean up internally (destroy all remaining managed object references and
2277 * related COM objects used internally).
2278 *
2279 * After logon, an internal timeout ensures that if the webservice client does not
2280 * call any methods, after a configurable number of seconds, the webservice will log
2281 * off the client automatically. This is to ensure that the webservice does not
2282 * drown in managed object references and eventually deny service. Still, it is
2283 * a much better solution, both for performance and cleanliness, for the webservice
2284 * client to clean up itself.
2285 *
2286 * @param
2287 * @param vbox__IWebsessionManager_USCORElogon
2288 * @param vbox__IWebsessionManager_USCORElogonResponse
2289 * @return
2290 */
2291int __vbox__IWebsessionManager_USCORElogon(
2292 struct soap *soap,
2293 _vbox__IWebsessionManager_USCORElogon *req,
2294 _vbox__IWebsessionManager_USCORElogonResponse *resp)
2295{
2296 HRESULT rc = S_OK;
2297 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2298
2299 do
2300 {
2301 // WebServiceSession constructor tinkers with global MOR map and requires a write lock
2302 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2303
2304 // create new websession; the constructor stores the new websession
2305 // in the global map automatically
2306 WebServiceSession *pWebsession = new WebServiceSession();
2307 ComPtr<IVirtualBox> pVirtualBox;
2308
2309 // authenticate the user
2310 if (!(pWebsession->authenticate(req->username.c_str(),
2311 req->password.c_str(),
2312 pVirtualBox.asOutParam())))
2313 {
2314 // fake up a "root" MOR for this websession
2315 char sz[34];
2316 MakeManagedObjectRef(sz, pWebsession->getID(), 0ULL);
2317 WSDLT_ID id = sz;
2318
2319 // in the new websession, create a managed object reference (MOR) for the
2320 // global VirtualBox object; this encodes the websession ID in the MOR so
2321 // that it will be implicitly be included in all future requests of this
2322 // webservice client
2323 resp->returnval = createOrFindRefFromComPtr(id, g_pcszIVirtualBox, pVirtualBox);
2324 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
2325 }
2326 else
2327 rc = E_FAIL;
2328 } while (0);
2329
2330 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2331 if (FAILED(rc))
2332 return SOAP_FAULT;
2333 return SOAP_OK;
2334}
2335
2336/**
2337 * Returns a new ISession object every time.
2338 *
2339 * No longer connected in any way to logons, one websession can easily
2340 * handle multiple sessions.
2341 */
2342int __vbox__IWebsessionManager_USCOREgetSessionObject(
2343 struct soap*,
2344 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
2345 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
2346{
2347 HRESULT rc = S_OK;
2348 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2349
2350 do
2351 {
2352 // create a new ISession object
2353 ComPtr<ISession> pSession;
2354 rc = g_pVirtualBoxClient->COMGETTER(Session)(pSession.asOutParam());
2355 if (FAILED(rc))
2356 {
2357 WEBDEBUG(("ERROR: cannot create session object!"));
2358 break;
2359 }
2360
2361 // return its MOR
2362 resp->returnval = createOrFindRefFromComPtr(req->refIVirtualBox, g_pcszISession, pSession);
2363 WEBDEBUG(("Session object ref is %s\n", resp->returnval.c_str()));
2364 } while (0);
2365
2366 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2367 if (FAILED(rc))
2368 return SOAP_FAULT;
2369 return SOAP_OK;
2370}
2371
2372/**
2373 * hard-coded implementation for IWebsessionManager::logoff.
2374 *
2375 * @param
2376 * @param vbox__IWebsessionManager_USCORElogon
2377 * @param vbox__IWebsessionManager_USCORElogonResponse
2378 * @return
2379 */
2380int __vbox__IWebsessionManager_USCORElogoff(
2381 struct soap*,
2382 _vbox__IWebsessionManager_USCORElogoff *req,
2383 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
2384{
2385 HRESULT rc = S_OK;
2386 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2387
2388 do
2389 {
2390 // findWebsessionFromRef and the websession destructor require the lock
2391 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2392
2393 WebServiceSession* pWebsession;
2394 if ((pWebsession = WebServiceSession::findWebsessionFromRef(req->refIVirtualBox)))
2395 {
2396 WEBDEBUG(("websession logoff, deleting websession %#llx\n", pWebsession->getID()));
2397 delete pWebsession;
2398 // destructor cleans up
2399
2400 WEBDEBUG(("websession destroyed, %d websessions left open\n", g_mapWebsessions.size()));
2401 }
2402 } while (0);
2403
2404 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2405 if (FAILED(rc))
2406 return SOAP_FAULT;
2407 return SOAP_OK;
2408}
Note: See TracBrowser for help on using the repository browser.

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