VirtualBox

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

Last change on this file since 64664 was 64012, checked in by vboxsync, 8 years ago

Main/webservice: OpenSSL 1.1 adaptions

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

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