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