VirtualBox

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

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

scm --update-copyright-year

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