VirtualBox

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

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

webservice/vboxweb: be a bit more verbose when logging AuthResult, cosmetical fixes

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