VirtualBox

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

Last change on this file since 69111 was 66105, checked in by vboxsync, 8 years ago

Main: trailing spaces and a wrong indent

  • Property filesplitter.c set to Makefile.kmk
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 82.7 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 pcsz
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 uuid
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 */
1801WebServiceSession::WebServiceSession()
1802 : _uNextObjectID(1), // avoid 0 for no real reason
1803 _fDestructing(false),
1804 _tLastObjectLookup(0)
1805{
1806 _pp = new WebServiceSessionPrivate;
1807 _uWebsessionID = RTRandU64();
1808
1809 // register this websession globally
1810 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1811 g_mapWebsessions[_uWebsessionID] = this;
1812}
1813
1814/**
1815 * Destructor. Cleans up and destroys all contained managed object references on the way.
1816 *
1817 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
1818 */
1819WebServiceSession::~WebServiceSession()
1820{
1821 // delete us from global map first so we can't be found
1822 // any more while we're cleaning up
1823 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1824 g_mapWebsessions.erase(_uWebsessionID);
1825
1826 // notify ManagedObjectRef destructor so it won't
1827 // remove itself from the maps; this avoids rebalancing
1828 // the map's tree on every delete as well
1829 _fDestructing = true;
1830
1831 ManagedObjectsIteratorById it,
1832 end = _pp->_mapManagedObjectsById.end();
1833 for (it = _pp->_mapManagedObjectsById.begin();
1834 it != end;
1835 ++it)
1836 {
1837 ManagedObjectRef *pRef = it->second;
1838 delete pRef; // this frees the contained ComPtr as well
1839 }
1840
1841 delete _pp;
1842}
1843
1844/**
1845 * Authenticate the username and password against an authentication authority.
1846 *
1847 * @return 0 if the user was successfully authenticated, or an error code
1848 * otherwise.
1849 */
1850int WebServiceSession::authenticate(const char *pcszUsername,
1851 const char *pcszPassword,
1852 IVirtualBox **ppVirtualBox)
1853{
1854 int rc = VERR_WEB_NOT_AUTHENTICATED;
1855 ComPtr<IVirtualBox> pVirtualBox;
1856 {
1857 util::AutoReadLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
1858 pVirtualBox = g_pVirtualBox;
1859 }
1860 if (pVirtualBox.isNull())
1861 return rc;
1862 pVirtualBox.queryInterfaceTo(ppVirtualBox);
1863
1864 util::AutoReadLock lock(g_pAuthLibLockHandle COMMA_LOCKVAL_SRC_POS);
1865
1866 static bool fAuthLibLoaded = false;
1867 static PAUTHENTRY pfnAuthEntry = NULL;
1868 static PAUTHENTRY2 pfnAuthEntry2 = NULL;
1869 static PAUTHENTRY3 pfnAuthEntry3 = NULL;
1870
1871 if (!fAuthLibLoaded)
1872 {
1873 // retrieve authentication library from system properties
1874 ComPtr<ISystemProperties> systemProperties;
1875 pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
1876
1877 com::Bstr authLibrary;
1878 systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
1879 com::Utf8Str filename = authLibrary;
1880
1881 LogRel(("External authentication library is '%ls'\n", authLibrary.raw()));
1882
1883 if (filename == "null")
1884 // authentication disabled, let everyone in:
1885 fAuthLibLoaded = true;
1886 else
1887 {
1888 RTLDRMOD hlibAuth = 0;
1889 do
1890 {
1891 if (RTPathHavePath(filename.c_str()))
1892 rc = RTLdrLoad(filename.c_str(), &hlibAuth);
1893 else
1894 rc = RTLdrLoadAppPriv(filename.c_str(), &hlibAuth);
1895
1896 if (RT_FAILURE(rc))
1897 {
1898 WEBDEBUG(("%s() Failed to load external authentication library '%s'. Error code: %Rrc\n",
1899 __FUNCTION__, filename.c_str(), rc));
1900 break;
1901 }
1902
1903 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY3_NAME, (void**)&pfnAuthEntry3)))
1904 {
1905 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1906 __FUNCTION__, AUTHENTRY3_NAME, rc));
1907
1908 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY2_NAME, (void**)&pfnAuthEntry2)))
1909 {
1910 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1911 __FUNCTION__, AUTHENTRY2_NAME, rc));
1912
1913 if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY_NAME, (void**)&pfnAuthEntry)))
1914 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1915 __FUNCTION__, AUTHENTRY_NAME, rc));
1916 }
1917 }
1918
1919 if (pfnAuthEntry || pfnAuthEntry2 || pfnAuthEntry3)
1920 fAuthLibLoaded = true;
1921
1922 } while (0);
1923 }
1924 }
1925
1926 if (pfnAuthEntry3 || pfnAuthEntry2 || pfnAuthEntry)
1927 {
1928 const char *pszFn;
1929 AuthResult result;
1930 if (pfnAuthEntry3)
1931 {
1932 result = pfnAuthEntry3("webservice", NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1933 pszFn = AUTHENTRY3_NAME;
1934 }
1935 else if (pfnAuthEntry2)
1936 {
1937 result = pfnAuthEntry2(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1938 pszFn = AUTHENTRY2_NAME;
1939 }
1940 else
1941 {
1942 result = pfnAuthEntry(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
1943 pszFn = AUTHENTRY_NAME;
1944 }
1945 WEBDEBUG(("%s(): result of %s('%s', [%d]): %d (%s)\n",
1946 __FUNCTION__, pszFn, pcszUsername, strlen(pcszPassword), result, decodeAuthResult(result)));
1947 if (result == AuthResultAccessGranted)
1948 {
1949 LogRel(("Access for user '%s' granted\n", pcszUsername));
1950 rc = VINF_SUCCESS;
1951 }
1952 else
1953 {
1954 if (result == AuthResultAccessDenied)
1955 LogRel(("Access for user '%s' denied\n", pcszUsername));
1956 rc = VERR_WEB_NOT_AUTHENTICATED;
1957 }
1958 }
1959 else if (fAuthLibLoaded)
1960 {
1961 // fAuthLibLoaded = true but all pointers are NULL:
1962 // The authlib was "null" and auth was disabled
1963 rc = VINF_SUCCESS;
1964 }
1965 else
1966 {
1967 WEBDEBUG(("Could not resolve AuthEntry, VRDPAuth2 or VRDPAuth entry point"));
1968 rc = VERR_WEB_NOT_AUTHENTICATED;
1969 }
1970
1971 lock.release();
1972
1973 return rc;
1974}
1975
1976/**
1977 * Look up, in this websession, whether a ManagedObjectRef has already been
1978 * created for the given COM pointer.
1979 *
1980 * Note how we require that a ComPtr<IUnknown> is passed, which causes a
1981 * queryInterface call when the caller passes in a different type, since
1982 * a ComPtr<IUnknown> will point to something different than a
1983 * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
1984 * our private hash table, we must search for one too.
1985 *
1986 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
1987 *
1988 * @param pObject pointer to a COM object.
1989 * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
1990 */
1991ManagedObjectRef* WebServiceSession::findRefFromPtr(const IUnknown *pObject)
1992{
1993 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1994
1995 uintptr_t ulp = (uintptr_t)pObject;
1996 // WEBDEBUG((" %s: looking up %#lx\n", __FUNCTION__, ulp));
1997 ManagedObjectsIteratorByPtr it = _pp->_mapManagedObjectsByPtr.find(ulp);
1998 if (it != _pp->_mapManagedObjectsByPtr.end())
1999 {
2000 ManagedObjectRef *pRef = it->second;
2001 WEBDEBUG((" %s: found existing ref %s (%s) for COM obj %#lx\n", __FUNCTION__, pRef->getWSDLID().c_str(), pRef->getInterfaceName(), ulp));
2002 return pRef;
2003 }
2004
2005 return NULL;
2006}
2007
2008/**
2009 * Static method which attempts to find the websession for which the given
2010 * managed object reference was created, by splitting the reference into the
2011 * websession and object IDs and then looking up the websession object.
2012 *
2013 * Preconditions: Caller must have locked g_pWebsessionsLockHandle in read mode.
2014 *
2015 * @param id Managed object reference (with combined websession and object IDs).
2016 * @return
2017 */
2018WebServiceSession *WebServiceSession::findWebsessionFromRef(const WSDLT_ID &id)
2019{
2020 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2021
2022 WebServiceSession *pWebsession = NULL;
2023 uint64_t websessId;
2024 if (SplitManagedObjectRef(id,
2025 &websessId,
2026 NULL))
2027 {
2028 WebsessionsMapIterator it = g_mapWebsessions.find(websessId);
2029 if (it != g_mapWebsessions.end())
2030 pWebsession = it->second;
2031 }
2032 return pWebsession;
2033}
2034
2035/**
2036 * Touches the websession to prevent it from timing out.
2037 *
2038 * Each websession has an internal timestamp that records the last request made
2039 * to it from the client that started it. If no request was made within a
2040 * configurable timeframe, then the client is logged off automatically,
2041 * by calling IWebsessionManager::logoff()
2042 */
2043void WebServiceSession::touch()
2044{
2045 _tLastObjectLookup = RTTimeProgramSecTS();
2046}
2047
2048/**
2049 * Counts the number of managed object references in this websession.
2050 */
2051size_t WebServiceSession::CountRefs()
2052{
2053 return _pp->_mapManagedObjectsById.size();
2054}
2055
2056
2057/****************************************************************************
2058 *
2059 * class ManagedObjectRef
2060 *
2061 ****************************************************************************/
2062
2063/**
2064 * Constructor, which assigns a unique ID to this managed object
2065 * reference and stores it in two hashes (living in the associated
2066 * WebServiceSession object):
2067 *
2068 * a) _mapManagedObjectsById, which maps ManagedObjectID's to
2069 * instances of this class; this hash is then used by the
2070 * findObjectFromRef() template function in vboxweb.h
2071 * to quickly retrieve the COM object from its managed
2072 * object ID (mostly in the context of the method mappers
2073 * in methodmaps.cpp, when a web service client passes in
2074 * a managed object ID);
2075 *
2076 * b) _mapManagedObjectsByPtr, which maps COM pointers to
2077 * instances of this class; this hash is used by
2078 * createRefFromObject() to quickly figure out whether an
2079 * instance already exists for a given COM pointer.
2080 *
2081 * This constructor calls AddRef() on the given COM object, and
2082 * the destructor will call Release(). We require two input pointers
2083 * for that COM object, one generic IUnknown* pointer which is used
2084 * as the map key, and a specific interface pointer (e.g. IMachine*)
2085 * which must support the interface given in guidInterface. All
2086 * three values are returned by getPtr(), which gives future callers
2087 * a chance to reuse the specific interface pointer without having
2088 * to call QueryInterface, which can be expensive.
2089 *
2090 * This does _not_ check whether another instance already
2091 * exists in the hash. This gets called only from the
2092 * createOrFindRefFromComPtr() template function in vboxweb.h, which
2093 * does perform that check.
2094 *
2095 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2096 *
2097 * @param websession Websession to which the MOR will be added.
2098 * @param pobjUnknown Pointer to IUnknown* interface for the COM object; this will be used in the hashes.
2099 * @param pobjInterface Pointer to a specific interface for the COM object, described by guidInterface.
2100 * @param guidInterface Interface which pobjInterface points to.
2101 * @param pcszInterface String representation of that interface (e.g. "IMachine") for readability and logging.
2102 */
2103ManagedObjectRef::ManagedObjectRef(WebServiceSession &websession,
2104 IUnknown *pobjUnknown,
2105 void *pobjInterface,
2106 const com::Guid &guidInterface,
2107 const char *pcszInterface)
2108 : _websession(websession),
2109 _pobjUnknown(pobjUnknown),
2110 _pobjInterface(pobjInterface),
2111 _guidInterface(guidInterface),
2112 _pcszInterface(pcszInterface)
2113{
2114 Assert(pobjUnknown);
2115 Assert(pobjInterface);
2116
2117 // keep both stubs alive while this MOR exists (matching Release() calls are in destructor)
2118 uint32_t cRefs1 = pobjUnknown->AddRef();
2119 uint32_t cRefs2 = ((IUnknown*)pobjInterface)->AddRef();
2120 _ulp = (uintptr_t)pobjUnknown;
2121
2122 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2123 _id = websession.createObjectID();
2124 // and count globally
2125 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
2126
2127 char sz[34];
2128 MakeManagedObjectRef(sz, websession._uWebsessionID, _id);
2129 _strID = sz;
2130
2131 websession._pp->_mapManagedObjectsById[_id] = this;
2132 websession._pp->_mapManagedObjectsByPtr[_ulp] = this;
2133
2134 websession.touch();
2135
2136 WEBDEBUG((" * %s: MOR created for %s*=%#p (IUnknown*=%#p; COM refcount now %RI32/%RI32), new ID is %#llx; now %lld objects total\n",
2137 __FUNCTION__,
2138 pcszInterface,
2139 pobjInterface,
2140 pobjUnknown,
2141 cRefs1,
2142 cRefs2,
2143 _id,
2144 cTotal));
2145}
2146
2147/**
2148 * Destructor; removes the instance from the global hash of
2149 * managed objects. Calls Release() on the contained COM object.
2150 *
2151 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2152 */
2153ManagedObjectRef::~ManagedObjectRef()
2154{
2155 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2156 ULONG64 cTotal = --g_cManagedObjects;
2157
2158 Assert(_pobjUnknown);
2159 Assert(_pobjInterface);
2160
2161 // we called AddRef() on both interfaces, so call Release() on
2162 // both as well, but in reverse order
2163 uint32_t cRefs2 = ((IUnknown*)_pobjInterface)->Release();
2164 uint32_t cRefs1 = _pobjUnknown->Release();
2165 WEBDEBUG((" * %s: deleting MOR for ID %#llx (%s; COM refcount now %RI32/%RI32); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cRefs1, cRefs2, cTotal));
2166
2167 // if we're being destroyed from the websession's destructor,
2168 // then that destructor is iterating over the maps, so
2169 // don't remove us there! (data integrity + speed)
2170 if (!_websession._fDestructing)
2171 {
2172 WEBDEBUG((" * %s: removing from websession maps\n", __FUNCTION__));
2173 _websession._pp->_mapManagedObjectsById.erase(_id);
2174 if (_websession._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
2175 WEBDEBUG((" WARNING: could not find %#llx in _mapManagedObjectsByPtr\n", _ulp));
2176 }
2177}
2178
2179/**
2180 * Static helper method for findObjectFromRef() template that actually
2181 * looks up the object from a given integer ID.
2182 *
2183 * This has been extracted into this non-template function to reduce
2184 * code bloat as we have the actual STL map lookup only in this function.
2185 *
2186 * This also "touches" the timestamp in the websession whose ID is encoded
2187 * in the given integer ID, in order to prevent the websession from timing
2188 * out.
2189 *
2190 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2191 *
2192 * @param id
2193 * @param pRef
2194 * @param fNullAllowed
2195 * @return
2196 */
2197int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
2198 ManagedObjectRef **pRef,
2199 bool fNullAllowed)
2200{
2201 int rc = 0;
2202
2203 do
2204 {
2205 // allow NULL (== empty string) input reference, which should return a NULL pointer
2206 if (!id.length() && fNullAllowed)
2207 {
2208 *pRef = NULL;
2209 return 0;
2210 }
2211
2212 uint64_t websessId;
2213 uint64_t objId;
2214 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
2215 if (!SplitManagedObjectRef(id,
2216 &websessId,
2217 &objId))
2218 {
2219 rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
2220 break;
2221 }
2222
2223 WebsessionsMapIterator it = g_mapWebsessions.find(websessId);
2224 if (it == g_mapWebsessions.end())
2225 {
2226 WEBDEBUG((" %s: cannot find websession for objref %s\n", __FUNCTION__, id.c_str()));
2227 rc = VERR_WEB_INVALID_SESSION_ID;
2228 break;
2229 }
2230
2231 WebServiceSession *pWebsession = it->second;
2232 // "touch" websession to prevent it from timing out
2233 pWebsession->touch();
2234
2235 ManagedObjectsIteratorById iter = pWebsession->_pp->_mapManagedObjectsById.find(objId);
2236 if (iter == pWebsession->_pp->_mapManagedObjectsById.end())
2237 {
2238 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
2239 rc = VERR_WEB_INVALID_OBJECT_ID;
2240 break;
2241 }
2242
2243 *pRef = iter->second;
2244
2245 } while (0);
2246
2247 return rc;
2248}
2249
2250/****************************************************************************
2251 *
2252 * interface IManagedObjectRef
2253 *
2254 ****************************************************************************/
2255
2256/**
2257 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
2258 * that our WSDL promises to our web service clients. This method returns a
2259 * string describing the interface that this managed object reference
2260 * supports, e.g. "IMachine".
2261 *
2262 * @param soap
2263 * @param req
2264 * @param resp
2265 * @return
2266 */
2267int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
2268 struct soap *soap,
2269 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
2270 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
2271{
2272 RT_NOREF(soap);
2273 HRESULT rc = S_OK;
2274 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2275
2276 do
2277 {
2278 // findRefFromId require the lock
2279 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2280
2281 ManagedObjectRef *pRef;
2282 if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false))
2283 resp->returnval = pRef->getInterfaceName();
2284
2285 } while (0);
2286
2287 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2288 if (FAILED(rc))
2289 return SOAP_FAULT;
2290 return SOAP_OK;
2291}
2292
2293/**
2294 * This is the hard-coded implementation for the IManagedObjectRef::release()
2295 * that our WSDL promises to our web service clients. This method releases
2296 * a managed object reference and removes it from our stacks.
2297 *
2298 * @param soap
2299 * @param req
2300 * @param resp
2301 * @return
2302 */
2303int __vbox__IManagedObjectRef_USCORErelease(
2304 struct soap *soap,
2305 _vbox__IManagedObjectRef_USCORErelease *req,
2306 _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
2307{
2308 RT_NOREF(resp);
2309 HRESULT rc = S_OK;
2310 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2311
2312 do
2313 {
2314 // findRefFromId and the delete call below require the lock
2315 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2316
2317 ManagedObjectRef *pRef;
2318 if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false)))
2319 {
2320 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
2321 break;
2322 }
2323
2324 WEBDEBUG((" found reference; deleting!\n"));
2325 // this removes the object from all stacks; since
2326 // there's a ComPtr<> hidden inside the reference,
2327 // this should also invoke Release() on the COM
2328 // object
2329 delete pRef;
2330 } while (0);
2331
2332 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2333 if (FAILED(rc))
2334 return SOAP_FAULT;
2335 return SOAP_OK;
2336}
2337
2338/****************************************************************************
2339 *
2340 * interface IWebsessionManager
2341 *
2342 ****************************************************************************/
2343
2344/**
2345 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
2346 * COM API, this is the first method that a webservice client must call before the
2347 * webservice will do anything useful.
2348 *
2349 * This returns a managed object reference to the global IVirtualBox object; into this
2350 * reference a websession ID is encoded which remains constant with all managed object
2351 * references returned by other methods.
2352 *
2353 * When the webservice client is done, it should call IWebsessionManager::logoff. This
2354 * will clean up internally (destroy all remaining managed object references and
2355 * related COM objects used internally).
2356 *
2357 * After logon, an internal timeout ensures that if the webservice client does not
2358 * call any methods, after a configurable number of seconds, the webservice will log
2359 * off the client automatically. This is to ensure that the webservice does not
2360 * drown in managed object references and eventually deny service. Still, it is
2361 * a much better solution, both for performance and cleanliness, for the webservice
2362 * client to clean up itself.
2363 *
2364 * @param soap
2365 * @param req
2366 * @param resp
2367 * @return
2368 */
2369int __vbox__IWebsessionManager_USCORElogon(
2370 struct soap *soap,
2371 _vbox__IWebsessionManager_USCORElogon *req,
2372 _vbox__IWebsessionManager_USCORElogonResponse *resp)
2373{
2374 RT_NOREF(soap);
2375 HRESULT rc = S_OK;
2376 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2377
2378 do
2379 {
2380 // WebServiceSession constructor tinkers with global MOR map and requires a write lock
2381 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2382
2383 // create new websession; the constructor stores the new websession
2384 // in the global map automatically
2385 WebServiceSession *pWebsession = new WebServiceSession();
2386 ComPtr<IVirtualBox> pVirtualBox;
2387
2388 // authenticate the user
2389 if (!(pWebsession->authenticate(req->username.c_str(),
2390 req->password.c_str(),
2391 pVirtualBox.asOutParam())))
2392 {
2393 // fake up a "root" MOR for this websession
2394 char sz[34];
2395 MakeManagedObjectRef(sz, pWebsession->getID(), 0ULL);
2396 WSDLT_ID id = sz;
2397
2398 // in the new websession, create a managed object reference (MOR) for the
2399 // global VirtualBox object; this encodes the websession ID in the MOR so
2400 // that it will be implicitly be included in all future requests of this
2401 // webservice client
2402 resp->returnval = createOrFindRefFromComPtr(id, g_pcszIVirtualBox, pVirtualBox);
2403 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
2404 }
2405 else
2406 rc = E_FAIL;
2407 } while (0);
2408
2409 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2410 if (FAILED(rc))
2411 return SOAP_FAULT;
2412 return SOAP_OK;
2413}
2414
2415/**
2416 * Returns a new ISession object every time.
2417 *
2418 * No longer connected in any way to logons, one websession can easily
2419 * handle multiple sessions.
2420 */
2421int __vbox__IWebsessionManager_USCOREgetSessionObject(
2422 struct soap*,
2423 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
2424 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
2425{
2426 HRESULT rc = S_OK;
2427 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2428
2429 do
2430 {
2431 // create a new ISession object
2432 ComPtr<ISession> pSession;
2433 rc = g_pVirtualBoxClient->COMGETTER(Session)(pSession.asOutParam());
2434 if (FAILED(rc))
2435 {
2436 WEBDEBUG(("ERROR: cannot create session object!"));
2437 break;
2438 }
2439
2440 // return its MOR
2441 resp->returnval = createOrFindRefFromComPtr(req->refIVirtualBox, g_pcszISession, pSession);
2442 WEBDEBUG(("Session object ref is %s\n", resp->returnval.c_str()));
2443 } while (0);
2444
2445 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2446 if (FAILED(rc))
2447 return SOAP_FAULT;
2448 return SOAP_OK;
2449}
2450
2451/**
2452 * hard-coded implementation for IWebsessionManager::logoff.
2453 *
2454 * @param req
2455 * @param resp
2456 * @return
2457 */
2458int __vbox__IWebsessionManager_USCORElogoff(
2459 struct soap*,
2460 _vbox__IWebsessionManager_USCORElogoff *req,
2461 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
2462{
2463 RT_NOREF(resp);
2464 HRESULT rc = S_OK;
2465 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2466
2467 {
2468 // findWebsessionFromRef and the websession destructor require the lock
2469 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2470
2471 WebServiceSession *pWebsession = WebServiceSession::findWebsessionFromRef(req->refIVirtualBox);
2472 if (pWebsession)
2473 {
2474 WEBDEBUG(("websession logoff, deleting websession %#llx\n", pWebsession->getID()));
2475 delete pWebsession;
2476 // destructor cleans up
2477
2478 WEBDEBUG(("websession destroyed, %d websessions left open\n", g_mapWebsessions.size()));
2479 }
2480 }
2481
2482 WEBDEBUG(("-- leaving %s, rc: %#lx\n", __FUNCTION__, rc));
2483 if (FAILED(rc))
2484 return SOAP_FAULT;
2485 return SOAP_OK;
2486}
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