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