VirtualBox

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

Last change on this file since 96399 was 96399, checked in by vboxsync, 3 years ago

/Config.kmk and many other places: Change VBOX_VENDOR to the official copyright holder text, needs follow-up changes and equivalent adjustments elsewhere.

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

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