VirtualBox

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

Last change on this file since 63861 was 63861, checked in by vboxsync, 8 years ago

Main/webservice: back out previous change, it causes trouble on Windows and after looking at the gsoap source again the original check was right

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

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