VirtualBox

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

Last change on this file since 69749 was 69749, checked in by vboxsync, 7 years ago

Changed RTLogCreateEx[V] to take a RTERRINFO pointer rather than plain char * and size_t. Turned out a several callers didn't actually make use of the error message even.

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