VirtualBox

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

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

Never use static instances of CComModule as it messes up the log filename by using VBoxRT.dll before it's initialized.

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