VirtualBox

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

Last change on this file since 99739 was 99739, checked in by vboxsync, 13 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

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

© 2023 Oracle
ContactPrivacy policyTerms of Use