VirtualBox

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

Last change on this file since 84347 was 84347, checked in by vboxsync, 5 years ago

Add/WebService: VC++ 19.2 build adjustment. bugref:8489

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