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