1 | /**
|
---|
2 | * vboxweb.cpp:
|
---|
3 | * hand-coded parts of the webservice server. This is linked with the
|
---|
4 | * generated code in out/.../src/VBox/Main/webservice/methodmaps.cpp
|
---|
5 | * (plus static gSOAP server code) to implement the actual webservice
|
---|
6 | * server, to which clients can connect.
|
---|
7 | *
|
---|
8 | * Copyright (C) 2006-2011 Oracle Corporation
|
---|
9 | *
|
---|
10 | * This file is part of VirtualBox Open Source Edition (OSE), as
|
---|
11 | * available from http://www.virtualbox.org. This file is free software;
|
---|
12 | * you can redistribute it and/or modify it under the terms of the GNU
|
---|
13 | * General Public License (GPL) as published by the Free Software
|
---|
14 | * Foundation, in version 2 as it comes in the "COPYING" file of the
|
---|
15 | * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
|
---|
16 | * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
|
---|
17 | */
|
---|
18 |
|
---|
19 | // shared webservice header
|
---|
20 | #include "vboxweb.h"
|
---|
21 |
|
---|
22 | // vbox headers
|
---|
23 | #include <VBox/com/com.h>
|
---|
24 | #include <VBox/com/array.h>
|
---|
25 | #include <VBox/com/ErrorInfo.h>
|
---|
26 | #include <VBox/com/errorprint.h>
|
---|
27 | #include <VBox/com/EventQueue.h>
|
---|
28 | #include <VBox/com/listeners.h>
|
---|
29 | #include <VBox/VBoxAuth.h>
|
---|
30 | #include <VBox/version.h>
|
---|
31 |
|
---|
32 | #include <iprt/buildconfig.h>
|
---|
33 | #include <iprt/ctype.h>
|
---|
34 | #include <iprt/getopt.h>
|
---|
35 | #include <iprt/initterm.h>
|
---|
36 | #include <iprt/ldr.h>
|
---|
37 | #include <iprt/message.h>
|
---|
38 | #include <iprt/process.h>
|
---|
39 | #include <iprt/rand.h>
|
---|
40 | #include <iprt/semaphore.h>
|
---|
41 | #include <iprt/string.h>
|
---|
42 | #include <iprt/thread.h>
|
---|
43 | #include <iprt/time.h>
|
---|
44 |
|
---|
45 | // workaround for compile problems on gcc 4.1
|
---|
46 | #ifdef __GNUC__
|
---|
47 | #pragma GCC visibility push(default)
|
---|
48 | #endif
|
---|
49 |
|
---|
50 | // gSOAP headers (must come after vbox includes because it checks for conflicting defs)
|
---|
51 | #include "soapH.h"
|
---|
52 |
|
---|
53 | // standard headers
|
---|
54 | #include <map>
|
---|
55 | #include <list>
|
---|
56 |
|
---|
57 | #ifdef __GNUC__
|
---|
58 | #pragma GCC visibility pop
|
---|
59 | #endif
|
---|
60 |
|
---|
61 | // include generated namespaces table
|
---|
62 | #include "vboxwebsrv.nsmap"
|
---|
63 |
|
---|
64 | /****************************************************************************
|
---|
65 | *
|
---|
66 | * private typedefs
|
---|
67 | *
|
---|
68 | ****************************************************************************/
|
---|
69 |
|
---|
70 | typedef std::map<uint64_t, ManagedObjectRef*>
|
---|
71 | ManagedObjectsMapById;
|
---|
72 | typedef std::map<uint64_t, ManagedObjectRef*>::iterator
|
---|
73 | ManagedObjectsIteratorById;
|
---|
74 | typedef std::map<uintptr_t, ManagedObjectRef*>
|
---|
75 | ManagedObjectsMapByPtr;
|
---|
76 |
|
---|
77 | typedef std::map<uint64_t, WebServiceSession*>
|
---|
78 | SessionsMap;
|
---|
79 | typedef std::map<uint64_t, WebServiceSession*>::iterator
|
---|
80 | SessionsMapIterator;
|
---|
81 |
|
---|
82 | int fntWatchdog(RTTHREAD ThreadSelf, void *pvUser);
|
---|
83 |
|
---|
84 | /****************************************************************************
|
---|
85 | *
|
---|
86 | * Read-only global variables
|
---|
87 | *
|
---|
88 | ****************************************************************************/
|
---|
89 |
|
---|
90 | static ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
|
---|
91 |
|
---|
92 | // generated strings in methodmaps.cpp
|
---|
93 | extern const char *g_pcszISession,
|
---|
94 | *g_pcszIVirtualBox;
|
---|
95 |
|
---|
96 | // globals for vboxweb command-line arguments
|
---|
97 | #define DEFAULT_TIMEOUT_SECS 300
|
---|
98 | #define DEFAULT_TIMEOUT_SECS_STRING "300"
|
---|
99 | int g_iWatchdogTimeoutSecs = DEFAULT_TIMEOUT_SECS;
|
---|
100 | int g_iWatchdogCheckInterval = 5;
|
---|
101 |
|
---|
102 | const char *g_pcszBindToHost = NULL; // host; NULL = localhost
|
---|
103 | unsigned int g_uBindToPort = 18083; // port
|
---|
104 | unsigned int g_uBacklog = 100; // backlog = max queue size for requests
|
---|
105 | unsigned int g_cMaxWorkerThreads = 100; // max. no. of worker threads
|
---|
106 | unsigned int g_cMaxKeepAlive = 100; // maximum number of soap requests in one connection
|
---|
107 |
|
---|
108 | bool g_fVerbose = false; // be verbose
|
---|
109 | PRTSTREAM g_pStrmLog = NULL;
|
---|
110 |
|
---|
111 | #if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
|
---|
112 | bool g_fDaemonize = false; // run in background.
|
---|
113 | #endif
|
---|
114 |
|
---|
115 | const WSDLT_ID g_EmptyWSDLID; // for NULL MORs
|
---|
116 |
|
---|
117 | /****************************************************************************
|
---|
118 | *
|
---|
119 | * Writeable global variables
|
---|
120 | *
|
---|
121 | ****************************************************************************/
|
---|
122 |
|
---|
123 | // The one global SOAP queue created by main().
|
---|
124 | class SoapQ;
|
---|
125 | SoapQ *g_pSoapQ = NULL;
|
---|
126 |
|
---|
127 | // this mutex protects the auth lib and authentication
|
---|
128 | util::WriteLockHandle *g_pAuthLibLockHandle;
|
---|
129 |
|
---|
130 | // this mutex protects the global VirtualBox reference below
|
---|
131 | static util::RWLockHandle *g_pVirtualBoxLockHandle;
|
---|
132 |
|
---|
133 | static ComPtr<IVirtualBox> g_pVirtualBox = NULL;
|
---|
134 |
|
---|
135 | // this mutex protects all of the below
|
---|
136 | util::WriteLockHandle *g_pSessionsLockHandle;
|
---|
137 |
|
---|
138 | SessionsMap g_mapSessions;
|
---|
139 | ULONG64 g_iMaxManagedObjectID = 0;
|
---|
140 | ULONG64 g_cManagedObjects = 0;
|
---|
141 |
|
---|
142 | // this mutex protects g_mapThreads
|
---|
143 | util::RWLockHandle *g_pThreadsLockHandle;
|
---|
144 |
|
---|
145 | // this mutex synchronizes logging
|
---|
146 | util::WriteLockHandle *g_pWebLogLockHandle;
|
---|
147 |
|
---|
148 | // Threads map, so we can quickly map an RTTHREAD struct to a logger prefix
|
---|
149 | typedef std::map<RTTHREAD, com::Utf8Str> ThreadsMap;
|
---|
150 | ThreadsMap g_mapThreads;
|
---|
151 |
|
---|
152 | /****************************************************************************
|
---|
153 | *
|
---|
154 | * Command line help
|
---|
155 | *
|
---|
156 | ****************************************************************************/
|
---|
157 |
|
---|
158 | static const RTGETOPTDEF g_aOptions[]
|
---|
159 | = {
|
---|
160 | { "--help", 'h', RTGETOPT_REQ_NOTHING }, /* for DisplayHelp() */
|
---|
161 | #if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
|
---|
162 | { "--background", 'b', RTGETOPT_REQ_NOTHING },
|
---|
163 | #endif
|
---|
164 | { "--host", 'H', RTGETOPT_REQ_STRING },
|
---|
165 | { "--port", 'p', RTGETOPT_REQ_UINT32 },
|
---|
166 | { "--timeout", 't', RTGETOPT_REQ_UINT32 },
|
---|
167 | { "--check-interval", 'i', RTGETOPT_REQ_UINT32 },
|
---|
168 | { "--threads", 'T', RTGETOPT_REQ_UINT32 },
|
---|
169 | { "--keepalive", 'k', RTGETOPT_REQ_UINT32 },
|
---|
170 | { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
|
---|
171 | { "--pidfile", 'P', RTGETOPT_REQ_STRING },
|
---|
172 | { "--logfile", 'F', RTGETOPT_REQ_STRING },
|
---|
173 | };
|
---|
174 |
|
---|
175 | void DisplayHelp()
|
---|
176 | {
|
---|
177 | RTStrmPrintf(g_pStdErr, "\nUsage: vboxwebsrv [options]\n\nSupported options (default values in brackets):\n");
|
---|
178 | for (unsigned i = 0;
|
---|
179 | i < RT_ELEMENTS(g_aOptions);
|
---|
180 | ++i)
|
---|
181 | {
|
---|
182 | std::string str(g_aOptions[i].pszLong);
|
---|
183 | str += ", -";
|
---|
184 | str += g_aOptions[i].iShort;
|
---|
185 | str += ":";
|
---|
186 |
|
---|
187 | const char *pcszDescr = "";
|
---|
188 |
|
---|
189 | switch (g_aOptions[i].iShort)
|
---|
190 | {
|
---|
191 | case 'h':
|
---|
192 | pcszDescr = "Print this help message and exit.";
|
---|
193 | break;
|
---|
194 |
|
---|
195 | #if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
|
---|
196 | case 'b':
|
---|
197 | pcszDescr = "Run in background (daemon mode).";
|
---|
198 | break;
|
---|
199 | #endif
|
---|
200 |
|
---|
201 | case 'H':
|
---|
202 | pcszDescr = "The host to bind to (localhost).";
|
---|
203 | break;
|
---|
204 |
|
---|
205 | case 'p':
|
---|
206 | pcszDescr = "The port to bind to (18083).";
|
---|
207 | break;
|
---|
208 |
|
---|
209 | case 't':
|
---|
210 | pcszDescr = "Session timeout in seconds; 0 = disable timeouts (" DEFAULT_TIMEOUT_SECS_STRING ").";
|
---|
211 | break;
|
---|
212 |
|
---|
213 | case 'T':
|
---|
214 | pcszDescr = "Maximum number of worker threads to run in parallel (100).";
|
---|
215 | break;
|
---|
216 |
|
---|
217 | case 'k':
|
---|
218 | pcszDescr = "Maximum number of requests before a socket will be closed (100).";
|
---|
219 | break;
|
---|
220 |
|
---|
221 | case 'i':
|
---|
222 | pcszDescr = "Frequency of timeout checks in seconds (5).";
|
---|
223 | break;
|
---|
224 |
|
---|
225 | case 'v':
|
---|
226 | pcszDescr = "Be verbose.";
|
---|
227 | break;
|
---|
228 |
|
---|
229 | case 'P':
|
---|
230 | pcszDescr = "Name of the PID file which is created when the daemon was started.";
|
---|
231 | break;
|
---|
232 |
|
---|
233 | case 'F':
|
---|
234 | pcszDescr = "Name of file to write log to (no file).";
|
---|
235 | break;
|
---|
236 | }
|
---|
237 |
|
---|
238 | RTStrmPrintf(g_pStdErr, "%-23s%s\n", str.c_str(), pcszDescr);
|
---|
239 | }
|
---|
240 | }
|
---|
241 |
|
---|
242 | /****************************************************************************
|
---|
243 | *
|
---|
244 | * SoapQ, SoapThread (multithreading)
|
---|
245 | *
|
---|
246 | ****************************************************************************/
|
---|
247 |
|
---|
248 | class SoapQ;
|
---|
249 |
|
---|
250 | class SoapThread
|
---|
251 | {
|
---|
252 | public:
|
---|
253 | /**
|
---|
254 | * Constructor. Creates the new thread and makes it call process() for processing the queue.
|
---|
255 | * @param u Thread number. (So we can count from 1 and be readable.)
|
---|
256 | * @param q SoapQ instance which has the queue to process.
|
---|
257 | * @param soap struct soap instance from main() which we copy here.
|
---|
258 | */
|
---|
259 | SoapThread(size_t u,
|
---|
260 | SoapQ &q,
|
---|
261 | const struct soap *soap)
|
---|
262 | : m_u(u),
|
---|
263 | m_strThread(com::Utf8StrFmt("SoapQWrk%02d", m_u)),
|
---|
264 | m_pQ(&q)
|
---|
265 | {
|
---|
266 | // make a copy of the soap struct for the new thread
|
---|
267 | m_soap = soap_copy(soap);
|
---|
268 |
|
---|
269 | /* The soap.max_keep_alive value can be set to the maximum keep-alive calls allowed,
|
---|
270 | * which is important to avoid a client from holding a thread indefinitely.
|
---|
271 | * http://www.cs.fsu.edu/~engelen/soapdoc2.html#sec:keepalive
|
---|
272 | *
|
---|
273 | * Strings with 8-bit content can hold ASCII (default) or UTF8. The latter is
|
---|
274 | * possible by enabling the SOAP_C_UTFSTRING flag.
|
---|
275 | */
|
---|
276 | soap_set_omode(m_soap, SOAP_IO_KEEPALIVE | SOAP_C_UTFSTRING);
|
---|
277 | soap_set_imode(m_soap, SOAP_IO_KEEPALIVE | SOAP_C_UTFSTRING);
|
---|
278 | m_soap->max_keep_alive = g_cMaxKeepAlive;
|
---|
279 |
|
---|
280 | int rc = RTThreadCreate(&m_pThread,
|
---|
281 | fntWrapper,
|
---|
282 | this, // pvUser
|
---|
283 | 0, // cbStack,
|
---|
284 | RTTHREADTYPE_MAIN_HEAVY_WORKER,
|
---|
285 | 0,
|
---|
286 | m_strThread.c_str());
|
---|
287 | if (RT_FAILURE(rc))
|
---|
288 | {
|
---|
289 | RTMsgError("Cannot start worker thread %d: %Rrc\n", u, rc);
|
---|
290 | exit(1);
|
---|
291 | }
|
---|
292 | }
|
---|
293 |
|
---|
294 | void process();
|
---|
295 |
|
---|
296 | /**
|
---|
297 | * Static function that can be passed to RTThreadCreate and that calls
|
---|
298 | * process() on the SoapThread instance passed as the thread parameter.
|
---|
299 | * @param pThread
|
---|
300 | * @param pvThread
|
---|
301 | * @return
|
---|
302 | */
|
---|
303 | static int fntWrapper(RTTHREAD pThread, void *pvThread)
|
---|
304 | {
|
---|
305 | SoapThread *pst = (SoapThread*)pvThread;
|
---|
306 | pst->process(); // this never returns really
|
---|
307 | return 0;
|
---|
308 | }
|
---|
309 |
|
---|
310 | size_t m_u; // thread number
|
---|
311 | com::Utf8Str m_strThread; // thread name ("SoapQWrkXX")
|
---|
312 | SoapQ *m_pQ; // the single SOAP queue that all the threads service
|
---|
313 | struct soap *m_soap; // copy of the soap structure for this thread (from soap_copy())
|
---|
314 | RTTHREAD m_pThread; // IPRT thread struct for this thread
|
---|
315 | };
|
---|
316 |
|
---|
317 | /**
|
---|
318 | * SOAP queue encapsulation. There is only one instance of this, to
|
---|
319 | * which add() adds a queue item (called on the main thread),
|
---|
320 | * and from which get() fetch items, called from each queue thread.
|
---|
321 | */
|
---|
322 | class SoapQ
|
---|
323 | {
|
---|
324 | public:
|
---|
325 |
|
---|
326 | /**
|
---|
327 | * Constructor. Creates the soap queue.
|
---|
328 | * @param pSoap
|
---|
329 | */
|
---|
330 | SoapQ(const struct soap *pSoap)
|
---|
331 | : m_soap(pSoap),
|
---|
332 | m_mutex(util::LOCKCLASS_OBJECTSTATE), // lowest lock order, no other may be held while this is held
|
---|
333 | m_cIdleThreads(0)
|
---|
334 | {
|
---|
335 | RTSemEventMultiCreate(&m_event);
|
---|
336 | }
|
---|
337 |
|
---|
338 | ~SoapQ()
|
---|
339 | {
|
---|
340 | RTSemEventMultiDestroy(m_event);
|
---|
341 | }
|
---|
342 |
|
---|
343 | /**
|
---|
344 | * Adds the given socket to the SOAP queue and posts the
|
---|
345 | * member event sem to wake up the workers. Called on the main thread
|
---|
346 | * whenever a socket has work to do. Creates a new SOAP thread on the
|
---|
347 | * first call or when all existing threads are busy.
|
---|
348 | * @param s Socket from soap_accept() which has work to do.
|
---|
349 | */
|
---|
350 | uint32_t add(int s)
|
---|
351 | {
|
---|
352 | uint32_t cItems;
|
---|
353 | util::AutoWriteLock qlock(m_mutex COMMA_LOCKVAL_SRC_POS);
|
---|
354 |
|
---|
355 | // if no threads have yet been created, or if all threads are busy,
|
---|
356 | // create a new SOAP thread
|
---|
357 | if ( !m_cIdleThreads
|
---|
358 | // but only if we're not exceeding the global maximum (default is 100)
|
---|
359 | && (m_llAllThreads.size() < g_cMaxWorkerThreads)
|
---|
360 | )
|
---|
361 | {
|
---|
362 | SoapThread *pst = new SoapThread(m_llAllThreads.size() + 1,
|
---|
363 | *this,
|
---|
364 | m_soap);
|
---|
365 | m_llAllThreads.push_back(pst);
|
---|
366 | util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
367 | g_mapThreads[pst->m_pThread] = com::Utf8StrFmt("[%3u]", pst->m_u);
|
---|
368 | ++m_cIdleThreads;
|
---|
369 | }
|
---|
370 |
|
---|
371 | // enqueue the socket of this connection and post eventsem so that
|
---|
372 | // one of the threads (possibly the one just created) can pick it up
|
---|
373 | m_llSocketsQ.push_back(s);
|
---|
374 | cItems = m_llSocketsQ.size();
|
---|
375 | qlock.release();
|
---|
376 |
|
---|
377 | // unblock one of the worker threads
|
---|
378 | RTSemEventMultiSignal(m_event);
|
---|
379 |
|
---|
380 | return cItems;
|
---|
381 | }
|
---|
382 |
|
---|
383 | /**
|
---|
384 | * Blocks the current thread until work comes in; then returns
|
---|
385 | * the SOAP socket which has work to do. This reduces m_cIdleThreads
|
---|
386 | * by one, and the caller MUST call done() when it's done processing.
|
---|
387 | * Called from the worker threads.
|
---|
388 | * @param cIdleThreads out: no. of threads which are currently idle (not counting the caller)
|
---|
389 | * @param cThreads out: total no. of SOAP threads running
|
---|
390 | * @return
|
---|
391 | */
|
---|
392 | int get(size_t &cIdleThreads, size_t &cThreads)
|
---|
393 | {
|
---|
394 | while (1)
|
---|
395 | {
|
---|
396 | // wait for something to happen
|
---|
397 | RTSemEventMultiWait(m_event, RT_INDEFINITE_WAIT);
|
---|
398 |
|
---|
399 | util::AutoWriteLock qlock(m_mutex COMMA_LOCKVAL_SRC_POS);
|
---|
400 | if (m_llSocketsQ.size())
|
---|
401 | {
|
---|
402 | int socket = m_llSocketsQ.front();
|
---|
403 | m_llSocketsQ.pop_front();
|
---|
404 | cIdleThreads = --m_cIdleThreads;
|
---|
405 | cThreads = m_llAllThreads.size();
|
---|
406 |
|
---|
407 | // reset the multi event only if the queue is now empty; otherwise
|
---|
408 | // another thread will also wake up when we release the mutex and
|
---|
409 | // process another one
|
---|
410 | if (m_llSocketsQ.size() == 0)
|
---|
411 | RTSemEventMultiReset(m_event);
|
---|
412 |
|
---|
413 | qlock.release();
|
---|
414 |
|
---|
415 | return socket;
|
---|
416 | }
|
---|
417 |
|
---|
418 | // nothing to do: keep looping
|
---|
419 | }
|
---|
420 | }
|
---|
421 |
|
---|
422 | /**
|
---|
423 | * To be called by a worker thread after fetching an item from the
|
---|
424 | * queue via get() and having finished its lengthy processing.
|
---|
425 | */
|
---|
426 | void done()
|
---|
427 | {
|
---|
428 | util::AutoWriteLock qlock(m_mutex COMMA_LOCKVAL_SRC_POS);
|
---|
429 | ++m_cIdleThreads;
|
---|
430 | }
|
---|
431 |
|
---|
432 | const struct soap *m_soap; // soap structure created by main(), passed to constructor
|
---|
433 |
|
---|
434 | util::WriteLockHandle m_mutex;
|
---|
435 | RTSEMEVENTMULTI m_event; // posted by add(), blocked on by get()
|
---|
436 |
|
---|
437 | std::list<SoapThread*> m_llAllThreads; // all the threads created by the constructor
|
---|
438 | size_t m_cIdleThreads; // threads which are currently idle (statistics)
|
---|
439 |
|
---|
440 | // A std::list abused as a queue; this contains the actual jobs to do,
|
---|
441 | // each int being a socket from soap_accept()
|
---|
442 | std::list<int> m_llSocketsQ;
|
---|
443 | };
|
---|
444 |
|
---|
445 | /**
|
---|
446 | * Thread function for each of the SOAP queue worker threads. This keeps
|
---|
447 | * running, blocks on the event semaphore in SoapThread.SoapQ and picks
|
---|
448 | * up a socket from the queue therein, which has been put there by
|
---|
449 | * beginProcessing().
|
---|
450 | */
|
---|
451 | void SoapThread::process()
|
---|
452 | {
|
---|
453 | WebLog("New SOAP thread started\n");
|
---|
454 |
|
---|
455 | while (1)
|
---|
456 | {
|
---|
457 | // wait for a socket to arrive on the queue
|
---|
458 | size_t cIdleThreads = 0, cThreads = 0;
|
---|
459 | m_soap->socket = m_pQ->get(cIdleThreads, cThreads);
|
---|
460 |
|
---|
461 | WebLog("Processing connection from IP=%lu.%lu.%lu.%lu socket=%d (%d out of %d threads idle)\n",
|
---|
462 | (m_soap->ip >> 24) & 0xFF,
|
---|
463 | (m_soap->ip >> 16) & 0xFF,
|
---|
464 | (m_soap->ip >> 8) & 0xFF,
|
---|
465 | m_soap->ip & 0xFF,
|
---|
466 | m_soap->socket,
|
---|
467 | cIdleThreads,
|
---|
468 | cThreads);
|
---|
469 |
|
---|
470 | // process the request; this goes into the COM code in methodmaps.cpp
|
---|
471 | soap_serve(m_soap);
|
---|
472 |
|
---|
473 | soap_destroy(m_soap); // clean up class instances
|
---|
474 | soap_end(m_soap); // clean up everything and close socket
|
---|
475 |
|
---|
476 | // tell the queue we're idle again
|
---|
477 | m_pQ->done();
|
---|
478 | }
|
---|
479 | }
|
---|
480 |
|
---|
481 | /****************************************************************************
|
---|
482 | *
|
---|
483 | * VirtualBoxClient event listener
|
---|
484 | *
|
---|
485 | ****************************************************************************/
|
---|
486 |
|
---|
487 | class VirtualBoxClientEventListener
|
---|
488 | {
|
---|
489 | public:
|
---|
490 | VirtualBoxClientEventListener()
|
---|
491 | {
|
---|
492 | }
|
---|
493 |
|
---|
494 | virtual ~VirtualBoxClientEventListener()
|
---|
495 | {
|
---|
496 | }
|
---|
497 |
|
---|
498 | STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
|
---|
499 | {
|
---|
500 | switch (aType)
|
---|
501 | {
|
---|
502 | case VBoxEventType_OnVBoxSVCAvailabilityChanged:
|
---|
503 | {
|
---|
504 | ComPtr<IVBoxSVCAvailabilityChangedEvent> pVSACEv = aEvent;
|
---|
505 | Assert(pVSACEv);
|
---|
506 | BOOL fAvailable = FALSE;
|
---|
507 | pVSACEv->COMGETTER(Available)(&fAvailable);
|
---|
508 | if (!fAvailable)
|
---|
509 | {
|
---|
510 | WebLog("VBoxSVC became unavailable\n");
|
---|
511 | {
|
---|
512 | util::AutoWriteLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
513 | g_pVirtualBox = NULL;
|
---|
514 | }
|
---|
515 | {
|
---|
516 | // we're messing with sessions, so lock them
|
---|
517 | util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
518 | WEBDEBUG(("SVC unavailable: deleting %d sessions\n", g_mapSessions.size()));
|
---|
519 |
|
---|
520 | SessionsMap::iterator it = g_mapSessions.begin(),
|
---|
521 | itEnd = g_mapSessions.end();
|
---|
522 | while (it != itEnd)
|
---|
523 | {
|
---|
524 | WebServiceSession *pSession = it->second;
|
---|
525 | WEBDEBUG(("SVC unavailable: Session %llX stale, deleting\n", pSession->getID()));
|
---|
526 | delete pSession;
|
---|
527 | it = g_mapSessions.begin();
|
---|
528 | }
|
---|
529 | }
|
---|
530 | }
|
---|
531 | else
|
---|
532 | {
|
---|
533 | WebLog("VBoxSVC became available\n");
|
---|
534 | util::AutoWriteLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
535 | HRESULT hrc = g_pVirtualBoxClient->COMGETTER(VirtualBox)(g_pVirtualBox.asOutParam());
|
---|
536 | AssertComRC(hrc);
|
---|
537 | }
|
---|
538 | break;
|
---|
539 | }
|
---|
540 | default:
|
---|
541 | AssertFailed();
|
---|
542 | }
|
---|
543 |
|
---|
544 | return S_OK;
|
---|
545 | }
|
---|
546 |
|
---|
547 | private:
|
---|
548 | };
|
---|
549 |
|
---|
550 | typedef ListenerImpl<VirtualBoxClientEventListener> VirtualBoxClientEventListenerImpl;
|
---|
551 |
|
---|
552 | VBOX_LISTENER_DECLARE(VirtualBoxClientEventListenerImpl)
|
---|
553 |
|
---|
554 | /**
|
---|
555 | * Implementation for WEBLOG macro defined in vboxweb.h; this prints a message
|
---|
556 | * to the console and optionally to the file that may have been given to the
|
---|
557 | * vboxwebsrv command line.
|
---|
558 | * @param pszFormat
|
---|
559 | */
|
---|
560 | void WebLog(const char *pszFormat, ...)
|
---|
561 | {
|
---|
562 | va_list args;
|
---|
563 | va_start(args, pszFormat);
|
---|
564 | char *psz = NULL;
|
---|
565 | RTStrAPrintfV(&psz, pszFormat, args);
|
---|
566 | va_end(args);
|
---|
567 |
|
---|
568 | const char *pcszPrefix = "[ ]";
|
---|
569 | util::AutoReadLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
570 | ThreadsMap::iterator it = g_mapThreads.find(RTThreadSelf());
|
---|
571 | if (it != g_mapThreads.end())
|
---|
572 | pcszPrefix = it->second.c_str();
|
---|
573 | thrLock.release();
|
---|
574 |
|
---|
575 | // make a timestamp
|
---|
576 | RTTIMESPEC ts;
|
---|
577 | RTTimeLocalNow(&ts);
|
---|
578 | RTTIME t;
|
---|
579 | RTTimeExplode(&t, &ts);
|
---|
580 |
|
---|
581 | com::Utf8StrFmt strPrefix("%04d-%02d-%02d %02d:%02d:%02d %s",
|
---|
582 | t.i32Year, t.u8Month, t.u8MonthDay,
|
---|
583 | t.u8Hour, t.u8Minute, t.u8Second,
|
---|
584 | pcszPrefix);
|
---|
585 |
|
---|
586 | // synchronize the actual output
|
---|
587 | util::AutoWriteLock logLock(g_pWebLogLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
588 | // terminal
|
---|
589 | RTPrintf("%s %s", strPrefix.c_str(), psz);
|
---|
590 |
|
---|
591 | // log file
|
---|
592 | if (g_pStrmLog)
|
---|
593 | {
|
---|
594 | RTStrmPrintf(g_pStrmLog, "%s %s", strPrefix.c_str(), psz);
|
---|
595 | RTStrmFlush(g_pStrmLog);
|
---|
596 | }
|
---|
597 |
|
---|
598 | #ifdef DEBUG
|
---|
599 | // logger instance
|
---|
600 | RTLogLoggerEx(LOG_INSTANCE, RTLOGGRPFLAGS_DJ, LOG_GROUP, "%s %s", pcszPrefix, psz);
|
---|
601 | #endif
|
---|
602 | logLock.release();
|
---|
603 |
|
---|
604 | RTStrFree(psz);
|
---|
605 | }
|
---|
606 |
|
---|
607 | /**
|
---|
608 | * Helper for printing SOAP error messages.
|
---|
609 | * @param soap
|
---|
610 | */
|
---|
611 | void WebLogSoapError(struct soap *soap)
|
---|
612 | {
|
---|
613 | if (soap_check_state(soap))
|
---|
614 | {
|
---|
615 | WebLog("Error: soap struct not initialized\n");
|
---|
616 | return;
|
---|
617 | }
|
---|
618 |
|
---|
619 | const char *pcszFaultString = *soap_faultstring(soap);
|
---|
620 | const char **ppcszDetail = soap_faultcode(soap);
|
---|
621 | WebLog("#### SOAP FAULT: %s [%s]\n",
|
---|
622 | pcszFaultString ? pcszFaultString : "[no fault string available]",
|
---|
623 | (ppcszDetail && *ppcszDetail) ? *ppcszDetail : "no details available");
|
---|
624 | }
|
---|
625 |
|
---|
626 | /****************************************************************************
|
---|
627 | *
|
---|
628 | * SOAP queue pumper thread
|
---|
629 | *
|
---|
630 | ****************************************************************************/
|
---|
631 |
|
---|
632 | void doQueuesLoop()
|
---|
633 | {
|
---|
634 | // set up gSOAP
|
---|
635 | struct soap soap;
|
---|
636 | soap_init(&soap);
|
---|
637 |
|
---|
638 | soap.bind_flags |= SO_REUSEADDR;
|
---|
639 | // avoid EADDRINUSE on bind()
|
---|
640 |
|
---|
641 | int m, s; // master and slave sockets
|
---|
642 | m = soap_bind(&soap,
|
---|
643 | g_pcszBindToHost ? g_pcszBindToHost : "localhost", // safe default host
|
---|
644 | g_uBindToPort, // port
|
---|
645 | g_uBacklog); // backlog = max queue size for requests
|
---|
646 | if (m < 0)
|
---|
647 | WebLogSoapError(&soap);
|
---|
648 | else
|
---|
649 | {
|
---|
650 | WebLog("Socket connection successful: host = %s, port = %u, master socket = %d\n",
|
---|
651 | (g_pcszBindToHost) ? g_pcszBindToHost : "default (localhost)",
|
---|
652 | g_uBindToPort,
|
---|
653 | m);
|
---|
654 |
|
---|
655 | // initialize thread queue, mutex and eventsem
|
---|
656 | g_pSoapQ = new SoapQ(&soap);
|
---|
657 |
|
---|
658 | for (uint64_t i = 1;
|
---|
659 | ;
|
---|
660 | i++)
|
---|
661 | {
|
---|
662 | // call gSOAP to handle incoming SOAP connection
|
---|
663 | s = soap_accept(&soap);
|
---|
664 | if (s < 0)
|
---|
665 | {
|
---|
666 | WebLogSoapError(&soap);
|
---|
667 | break;
|
---|
668 | }
|
---|
669 |
|
---|
670 | // add the socket to the queue and tell worker threads to
|
---|
671 | // pick up the jobn
|
---|
672 | size_t cItemsOnQ = g_pSoapQ->add(s);
|
---|
673 | WebLog("Request %llu on socket %d queued for processing (%d items on Q)\n", i, s, cItemsOnQ);
|
---|
674 | }
|
---|
675 | }
|
---|
676 | soap_done(&soap); // close master socket and detach environment
|
---|
677 | }
|
---|
678 |
|
---|
679 | /**
|
---|
680 | * Thread function for the "queue pumper" thread started from main(). This implements
|
---|
681 | * the loop that takes SOAP calls from HTTP and serves them by handing sockets to the
|
---|
682 | * SOAP queue worker threads.
|
---|
683 | */
|
---|
684 | int fntQPumper(RTTHREAD ThreadSelf, void *pvUser)
|
---|
685 | {
|
---|
686 | // store a log prefix for this thread
|
---|
687 | util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
688 | g_mapThreads[RTThreadSelf()] = "[ P ]";
|
---|
689 | thrLock.release();
|
---|
690 |
|
---|
691 | doQueuesLoop();
|
---|
692 |
|
---|
693 | return 0;
|
---|
694 | }
|
---|
695 |
|
---|
696 | /**
|
---|
697 | * Start up the webservice server. This keeps running and waits
|
---|
698 | * for incoming SOAP connections; for each request that comes in,
|
---|
699 | * it calls method implementation code, most of it in the generated
|
---|
700 | * code in methodmaps.cpp.
|
---|
701 | *
|
---|
702 | * @param argc
|
---|
703 | * @param argv[]
|
---|
704 | * @return
|
---|
705 | */
|
---|
706 | int main(int argc, char *argv[])
|
---|
707 | {
|
---|
708 | // initialize runtime
|
---|
709 | int rc = RTR3Init();
|
---|
710 | if (RT_FAILURE(rc))
|
---|
711 | return RTMsgInitFailure(rc);
|
---|
712 |
|
---|
713 | // store a log prefix for this thread
|
---|
714 | g_mapThreads[RTThreadSelf()] = "[M ]";
|
---|
715 |
|
---|
716 | RTStrmPrintf(g_pStdErr, VBOX_PRODUCT " web service version " VBOX_VERSION_STRING "\n"
|
---|
717 | "(C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
|
---|
718 | "All rights reserved.\n");
|
---|
719 |
|
---|
720 | int c;
|
---|
721 | const char *pszPidFile = NULL;
|
---|
722 | RTGETOPTUNION ValueUnion;
|
---|
723 | RTGETOPTSTATE GetState;
|
---|
724 | RTGetOptInit(&GetState, argc, argv, g_aOptions, RT_ELEMENTS(g_aOptions), 1, 0 /*fFlags*/);
|
---|
725 | while ((c = RTGetOpt(&GetState, &ValueUnion)))
|
---|
726 | {
|
---|
727 | switch (c)
|
---|
728 | {
|
---|
729 | case 'H':
|
---|
730 | if (!ValueUnion.psz || !*ValueUnion.psz)
|
---|
731 | {
|
---|
732 | /* Normalize NULL/empty string to NULL, which will be
|
---|
733 | * interpreted as "localhost" below. */
|
---|
734 | g_pcszBindToHost = NULL;
|
---|
735 | }
|
---|
736 | else
|
---|
737 | g_pcszBindToHost = ValueUnion.psz;
|
---|
738 | break;
|
---|
739 |
|
---|
740 | case 'p':
|
---|
741 | g_uBindToPort = ValueUnion.u32;
|
---|
742 | break;
|
---|
743 |
|
---|
744 | case 't':
|
---|
745 | g_iWatchdogTimeoutSecs = ValueUnion.u32;
|
---|
746 | break;
|
---|
747 |
|
---|
748 | case 'i':
|
---|
749 | g_iWatchdogCheckInterval = ValueUnion.u32;
|
---|
750 | break;
|
---|
751 |
|
---|
752 | case 'F':
|
---|
753 | {
|
---|
754 | int rc2 = RTStrmOpen(ValueUnion.psz, "a", &g_pStrmLog);
|
---|
755 | if (rc2)
|
---|
756 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot open log file \"%s\" for writing: %Rrc", ValueUnion.psz, rc2);
|
---|
757 |
|
---|
758 | WebLog(VBOX_PRODUCT " Webservice Version %s\n"
|
---|
759 | "Opened log file \"%s\"\n", VBOX_VERSION_STRING, ValueUnion.psz);
|
---|
760 | break;
|
---|
761 | }
|
---|
762 |
|
---|
763 | case 'P':
|
---|
764 | pszPidFile = ValueUnion.psz;
|
---|
765 | break;
|
---|
766 |
|
---|
767 | case 'T':
|
---|
768 | g_cMaxWorkerThreads = ValueUnion.u32;
|
---|
769 | break;
|
---|
770 |
|
---|
771 | case 'k':
|
---|
772 | g_cMaxKeepAlive = ValueUnion.u32;
|
---|
773 | break;
|
---|
774 |
|
---|
775 | case 'h':
|
---|
776 | DisplayHelp();
|
---|
777 | return 0;
|
---|
778 |
|
---|
779 | case 'v':
|
---|
780 | g_fVerbose = true;
|
---|
781 | break;
|
---|
782 |
|
---|
783 | #if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
|
---|
784 | case 'b':
|
---|
785 | g_fDaemonize = true;
|
---|
786 | break;
|
---|
787 | #endif
|
---|
788 | case 'V':
|
---|
789 | RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
|
---|
790 | return 0;
|
---|
791 |
|
---|
792 | default:
|
---|
793 | rc = RTGetOptPrintError(c, &ValueUnion);
|
---|
794 | return rc;
|
---|
795 | }
|
---|
796 | }
|
---|
797 |
|
---|
798 | #if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined (RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
|
---|
799 | if (g_fDaemonize)
|
---|
800 | {
|
---|
801 | rc = RTProcDaemonizeUsingFork(false /* fNoChDir */, false /* fNoClose */, pszPidFile);
|
---|
802 | if (RT_FAILURE(rc))
|
---|
803 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to daemonize, rc=%Rrc. exiting.", rc);
|
---|
804 | }
|
---|
805 | #endif
|
---|
806 |
|
---|
807 | // initialize COM/XPCOM
|
---|
808 | HRESULT hrc = com::Initialize();
|
---|
809 | if (FAILED(hrc))
|
---|
810 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to initialize COM! hrc=%Rhrc\n", hrc);
|
---|
811 |
|
---|
812 | hrc = g_pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
|
---|
813 | if (FAILED(hrc))
|
---|
814 | {
|
---|
815 | RTMsgError("failed to create the VirtualBoxClient object!");
|
---|
816 | com::ErrorInfo info;
|
---|
817 | if (!info.isFullAvailable() && !info.isBasicAvailable())
|
---|
818 | {
|
---|
819 | com::GluePrintRCMessage(hrc);
|
---|
820 | RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
|
---|
821 | }
|
---|
822 | else
|
---|
823 | com::GluePrintErrorInfo(info);
|
---|
824 | return RTEXITCODE_FAILURE;
|
---|
825 | }
|
---|
826 |
|
---|
827 | hrc = g_pVirtualBoxClient->COMGETTER(VirtualBox)(g_pVirtualBox.asOutParam());
|
---|
828 | if (FAILED(hrc))
|
---|
829 | {
|
---|
830 | RTMsgError("Failed to get VirtualBox object (rc=%Rhrc)!", hrc);
|
---|
831 | return RTEXITCODE_FAILURE;
|
---|
832 | }
|
---|
833 |
|
---|
834 | /* VirtualBoxClient events registration. */
|
---|
835 | IEventListener *vboxClientListener = NULL;
|
---|
836 | {
|
---|
837 | ComPtr<IEventSource> pES;
|
---|
838 | CHECK_ERROR(g_pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
|
---|
839 | vboxClientListener = new VirtualBoxClientEventListenerImpl();
|
---|
840 | com::SafeArray<VBoxEventType_T> eventTypes;
|
---|
841 | eventTypes.push_back(VBoxEventType_OnVBoxSVCAvailabilityChanged);
|
---|
842 | CHECK_ERROR(pES, RegisterListener(vboxClientListener, ComSafeArrayAsInParam(eventTypes), true));
|
---|
843 | }
|
---|
844 |
|
---|
845 | // create the global mutexes
|
---|
846 | g_pAuthLibLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
|
---|
847 | g_pVirtualBoxLockHandle = new util::RWLockHandle(util::LOCKCLASS_WEBSERVICE);
|
---|
848 | g_pSessionsLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
|
---|
849 | g_pThreadsLockHandle = new util::RWLockHandle(util::LOCKCLASS_OBJECTSTATE);
|
---|
850 | g_pWebLogLockHandle = new util::WriteLockHandle(util::LOCKCLASS_WEBSERVICE);
|
---|
851 |
|
---|
852 | // SOAP queue pumper thread
|
---|
853 | rc = RTThreadCreate(NULL,
|
---|
854 | fntQPumper,
|
---|
855 | NULL, // pvUser
|
---|
856 | 0, // cbStack (default)
|
---|
857 | RTTHREADTYPE_MAIN_WORKER,
|
---|
858 | 0, // flags
|
---|
859 | "SoapQPumper");
|
---|
860 | if (RT_FAILURE(rc))
|
---|
861 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot start SOAP queue pumper thread: %Rrc", rc);
|
---|
862 |
|
---|
863 | // watchdog thread
|
---|
864 | if (g_iWatchdogTimeoutSecs > 0)
|
---|
865 | {
|
---|
866 | // start our watchdog thread
|
---|
867 | rc = RTThreadCreate(NULL,
|
---|
868 | fntWatchdog,
|
---|
869 | NULL,
|
---|
870 | 0,
|
---|
871 | RTTHREADTYPE_MAIN_WORKER,
|
---|
872 | 0,
|
---|
873 | "Watchdog");
|
---|
874 | if (RT_FAILURE(rc))
|
---|
875 | return RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot start watchdog thread: %Rrc", rc);
|
---|
876 | }
|
---|
877 |
|
---|
878 | com::EventQueue *pQ = com::EventQueue::getMainEventQueue();
|
---|
879 | for (;;)
|
---|
880 | {
|
---|
881 | // we have to process main event queue
|
---|
882 | WEBDEBUG(("Pumping COM event queue\n"));
|
---|
883 | rc = pQ->processEventQueue(RT_INDEFINITE_WAIT);
|
---|
884 | if (RT_FAILURE(rc))
|
---|
885 | RTMsgError("processEventQueue -> %Rrc", rc);
|
---|
886 | }
|
---|
887 |
|
---|
888 | /* VirtualBoxClient events unregistration. */
|
---|
889 | if (vboxClientListener)
|
---|
890 | {
|
---|
891 | ComPtr<IEventSource> pES;
|
---|
892 | CHECK_ERROR(g_pVirtualBoxClient, COMGETTER(EventSource)(pES.asOutParam()));
|
---|
893 | if (!pES.isNull())
|
---|
894 | CHECK_ERROR(pES, UnregisterListener(vboxClientListener));
|
---|
895 | vboxClientListener->Release();
|
---|
896 | }
|
---|
897 |
|
---|
898 | com::Shutdown();
|
---|
899 |
|
---|
900 | return 0;
|
---|
901 | }
|
---|
902 |
|
---|
903 | /****************************************************************************
|
---|
904 | *
|
---|
905 | * Watchdog thread
|
---|
906 | *
|
---|
907 | ****************************************************************************/
|
---|
908 |
|
---|
909 | /**
|
---|
910 | * Watchdog thread, runs in the background while the webservice is alive.
|
---|
911 | *
|
---|
912 | * This gets started by main() and runs in the background to check all sessions
|
---|
913 | * for whether they have been no requests in a configurable timeout period. In
|
---|
914 | * that case, the session is automatically logged off.
|
---|
915 | */
|
---|
916 | int fntWatchdog(RTTHREAD ThreadSelf, void *pvUser)
|
---|
917 | {
|
---|
918 | // store a log prefix for this thread
|
---|
919 | util::AutoWriteLock thrLock(g_pThreadsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
920 | g_mapThreads[RTThreadSelf()] = "[W ]";
|
---|
921 | thrLock.release();
|
---|
922 |
|
---|
923 | WEBDEBUG(("Watchdog thread started\n"));
|
---|
924 |
|
---|
925 | while (1)
|
---|
926 | {
|
---|
927 | WEBDEBUG(("Watchdog: sleeping %d seconds\n", g_iWatchdogCheckInterval));
|
---|
928 | RTThreadSleep(g_iWatchdogCheckInterval * 1000);
|
---|
929 |
|
---|
930 | time_t tNow;
|
---|
931 | time(&tNow);
|
---|
932 |
|
---|
933 | // we're messing with sessions, so lock them
|
---|
934 | util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
935 | WEBDEBUG(("Watchdog: checking %d sessions\n", g_mapSessions.size()));
|
---|
936 |
|
---|
937 | SessionsMap::iterator it = g_mapSessions.begin(),
|
---|
938 | itEnd = g_mapSessions.end();
|
---|
939 | while (it != itEnd)
|
---|
940 | {
|
---|
941 | WebServiceSession *pSession = it->second;
|
---|
942 | WEBDEBUG(("Watchdog: tNow: %d, session timestamp: %d\n", tNow, pSession->getLastObjectLookup()));
|
---|
943 | if ( tNow
|
---|
944 | > pSession->getLastObjectLookup() + g_iWatchdogTimeoutSecs
|
---|
945 | )
|
---|
946 | {
|
---|
947 | WEBDEBUG(("Watchdog: Session %llX timed out, deleting\n", pSession->getID()));
|
---|
948 | delete pSession;
|
---|
949 | it = g_mapSessions.begin();
|
---|
950 | }
|
---|
951 | else
|
---|
952 | ++it;
|
---|
953 | }
|
---|
954 | }
|
---|
955 |
|
---|
956 | WEBDEBUG(("Watchdog thread ending\n"));
|
---|
957 | return 0;
|
---|
958 | }
|
---|
959 |
|
---|
960 | /****************************************************************************
|
---|
961 | *
|
---|
962 | * SOAP exceptions
|
---|
963 | *
|
---|
964 | ****************************************************************************/
|
---|
965 |
|
---|
966 | /**
|
---|
967 | * Helper function to raise a SOAP fault. Called by the other helper
|
---|
968 | * functions, which raise specific SOAP faults.
|
---|
969 | *
|
---|
970 | * @param soap
|
---|
971 | * @param str
|
---|
972 | * @param extype
|
---|
973 | * @param ex
|
---|
974 | */
|
---|
975 | void RaiseSoapFault(struct soap *soap,
|
---|
976 | const char *pcsz,
|
---|
977 | int extype,
|
---|
978 | void *ex)
|
---|
979 | {
|
---|
980 | // raise the fault
|
---|
981 | soap_sender_fault(soap, pcsz, NULL);
|
---|
982 |
|
---|
983 | struct SOAP_ENV__Detail *pDetail = (struct SOAP_ENV__Detail*)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail));
|
---|
984 |
|
---|
985 | // without the following, gSOAP crashes miserably when sending out the
|
---|
986 | // data because it will try to serialize all fields (stupid documentation)
|
---|
987 | memset(pDetail, 0, sizeof(struct SOAP_ENV__Detail));
|
---|
988 |
|
---|
989 | // fill extended info depending on SOAP version
|
---|
990 | if (soap->version == 2) // SOAP 1.2 is used
|
---|
991 | {
|
---|
992 | soap->fault->SOAP_ENV__Detail = pDetail;
|
---|
993 | soap->fault->SOAP_ENV__Detail->__type = extype;
|
---|
994 | soap->fault->SOAP_ENV__Detail->fault = ex;
|
---|
995 | soap->fault->SOAP_ENV__Detail->__any = NULL; // no other XML data
|
---|
996 | }
|
---|
997 | else
|
---|
998 | {
|
---|
999 | soap->fault->detail = pDetail;
|
---|
1000 | soap->fault->detail->__type = extype;
|
---|
1001 | soap->fault->detail->fault = ex;
|
---|
1002 | soap->fault->detail->__any = NULL; // no other XML data
|
---|
1003 | }
|
---|
1004 | }
|
---|
1005 |
|
---|
1006 | /**
|
---|
1007 | * Raises a SOAP fault that signals that an invalid object was passed.
|
---|
1008 | *
|
---|
1009 | * @param soap
|
---|
1010 | * @param obj
|
---|
1011 | */
|
---|
1012 | void RaiseSoapInvalidObjectFault(struct soap *soap,
|
---|
1013 | WSDLT_ID obj)
|
---|
1014 | {
|
---|
1015 | _vbox__InvalidObjectFault *ex = soap_new__vbox__InvalidObjectFault(soap, 1);
|
---|
1016 | ex->badObjectID = obj;
|
---|
1017 |
|
---|
1018 | std::string str("VirtualBox error: ");
|
---|
1019 | str += "Invalid managed object reference \"" + obj + "\"";
|
---|
1020 |
|
---|
1021 | RaiseSoapFault(soap,
|
---|
1022 | str.c_str(),
|
---|
1023 | SOAP_TYPE__vbox__InvalidObjectFault,
|
---|
1024 | ex);
|
---|
1025 | }
|
---|
1026 |
|
---|
1027 | /**
|
---|
1028 | * Return a safe C++ string from the given COM string,
|
---|
1029 | * without crashing if the COM string is empty.
|
---|
1030 | * @param bstr
|
---|
1031 | * @return
|
---|
1032 | */
|
---|
1033 | std::string ConvertComString(const com::Bstr &bstr)
|
---|
1034 | {
|
---|
1035 | com::Utf8Str ustr(bstr);
|
---|
1036 | return ustr.c_str(); // @todo r=dj since the length is known, we can probably use a better std::string allocator
|
---|
1037 | }
|
---|
1038 |
|
---|
1039 | /**
|
---|
1040 | * Return a safe C++ string from the given COM UUID,
|
---|
1041 | * without crashing if the UUID is empty.
|
---|
1042 | * @param bstr
|
---|
1043 | * @return
|
---|
1044 | */
|
---|
1045 | std::string ConvertComString(const com::Guid &uuid)
|
---|
1046 | {
|
---|
1047 | com::Utf8Str ustr(uuid.toString());
|
---|
1048 | return ustr.c_str(); // @todo r=dj since the length is known, we can probably use a better std::string allocator
|
---|
1049 | }
|
---|
1050 |
|
---|
1051 | /**
|
---|
1052 | * Raises a SOAP runtime fault. Implementation for the RaiseSoapRuntimeFault template
|
---|
1053 | * function in vboxweb.h.
|
---|
1054 | *
|
---|
1055 | * @param pObj
|
---|
1056 | */
|
---|
1057 | void RaiseSoapRuntimeFault2(struct soap *soap,
|
---|
1058 | HRESULT apirc,
|
---|
1059 | IUnknown *pObj,
|
---|
1060 | const com::Guid &iid)
|
---|
1061 | {
|
---|
1062 | com::ErrorInfo info(pObj, iid.ref());
|
---|
1063 |
|
---|
1064 | WEBDEBUG((" error, raising SOAP exception\n"));
|
---|
1065 |
|
---|
1066 | RTStrmPrintf(g_pStdErr, "API return code: 0x%08X (%Rhrc)\n", apirc, apirc);
|
---|
1067 | RTStrmPrintf(g_pStdErr, "COM error info result code: 0x%lX\n", info.getResultCode());
|
---|
1068 | RTStrmPrintf(g_pStdErr, "COM error info text: %ls\n", info.getText().raw());
|
---|
1069 |
|
---|
1070 | // allocated our own soap fault struct
|
---|
1071 | _vbox__RuntimeFault *ex = soap_new__vbox__RuntimeFault(soap, 1);
|
---|
1072 | // some old vbox methods return errors without setting an error in the error info,
|
---|
1073 | // so use the error info code if it's set and the HRESULT from the method otherwise
|
---|
1074 | if (S_OK == (ex->resultCode = info.getResultCode()))
|
---|
1075 | ex->resultCode = apirc;
|
---|
1076 | ex->text = ConvertComString(info.getText());
|
---|
1077 | ex->component = ConvertComString(info.getComponent());
|
---|
1078 | ex->interfaceID = ConvertComString(info.getInterfaceID());
|
---|
1079 |
|
---|
1080 | // compose descriptive message
|
---|
1081 | com::Utf8StrFmt str("VirtualBox error: %s (0x%lX)", ex->text.c_str(), ex->resultCode);
|
---|
1082 |
|
---|
1083 | RaiseSoapFault(soap,
|
---|
1084 | str.c_str(),
|
---|
1085 | SOAP_TYPE__vbox__RuntimeFault,
|
---|
1086 | ex);
|
---|
1087 | }
|
---|
1088 |
|
---|
1089 | /****************************************************************************
|
---|
1090 | *
|
---|
1091 | * splitting and merging of object IDs
|
---|
1092 | *
|
---|
1093 | ****************************************************************************/
|
---|
1094 |
|
---|
1095 | uint64_t str2ulonglong(const char *pcsz)
|
---|
1096 | {
|
---|
1097 | uint64_t u = 0;
|
---|
1098 | RTStrToUInt64Full(pcsz, 16, &u);
|
---|
1099 | return u;
|
---|
1100 | }
|
---|
1101 |
|
---|
1102 | /**
|
---|
1103 | * Splits a managed object reference (in string form, as
|
---|
1104 | * passed in from a SOAP method call) into two integers for
|
---|
1105 | * session and object IDs, respectively.
|
---|
1106 | *
|
---|
1107 | * @param id
|
---|
1108 | * @param sessid
|
---|
1109 | * @param objid
|
---|
1110 | * @return
|
---|
1111 | */
|
---|
1112 | bool SplitManagedObjectRef(const WSDLT_ID &id,
|
---|
1113 | uint64_t *pSessid,
|
---|
1114 | uint64_t *pObjid)
|
---|
1115 | {
|
---|
1116 | // 64-bit numbers in hex have 16 digits; hence
|
---|
1117 | // the object-ref string must have 16 + "-" + 16 characters
|
---|
1118 | std::string str;
|
---|
1119 | if ( (id.length() == 33)
|
---|
1120 | && (id[16] == '-')
|
---|
1121 | )
|
---|
1122 | {
|
---|
1123 | char psz[34];
|
---|
1124 | memcpy(psz, id.c_str(), 34);
|
---|
1125 | psz[16] = '\0';
|
---|
1126 | if (pSessid)
|
---|
1127 | *pSessid = str2ulonglong(psz);
|
---|
1128 | if (pObjid)
|
---|
1129 | *pObjid = str2ulonglong(psz + 17);
|
---|
1130 | return true;
|
---|
1131 | }
|
---|
1132 |
|
---|
1133 | return false;
|
---|
1134 | }
|
---|
1135 |
|
---|
1136 | /**
|
---|
1137 | * Creates a managed object reference (in string form) from
|
---|
1138 | * two integers representing a session and object ID, respectively.
|
---|
1139 | *
|
---|
1140 | * @param sz Buffer with at least 34 bytes space to receive MOR string.
|
---|
1141 | * @param sessid
|
---|
1142 | * @param objid
|
---|
1143 | * @return
|
---|
1144 | */
|
---|
1145 | void MakeManagedObjectRef(char *sz,
|
---|
1146 | uint64_t &sessid,
|
---|
1147 | uint64_t &objid)
|
---|
1148 | {
|
---|
1149 | RTStrFormatNumber(sz, sessid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
|
---|
1150 | sz[16] = '-';
|
---|
1151 | RTStrFormatNumber(sz + 17, objid, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
|
---|
1152 | }
|
---|
1153 |
|
---|
1154 | /****************************************************************************
|
---|
1155 | *
|
---|
1156 | * class WebServiceSession
|
---|
1157 | *
|
---|
1158 | ****************************************************************************/
|
---|
1159 |
|
---|
1160 | class WebServiceSessionPrivate
|
---|
1161 | {
|
---|
1162 | public:
|
---|
1163 | ManagedObjectsMapById _mapManagedObjectsById;
|
---|
1164 | ManagedObjectsMapByPtr _mapManagedObjectsByPtr;
|
---|
1165 | };
|
---|
1166 |
|
---|
1167 | /**
|
---|
1168 | * Constructor for the session object.
|
---|
1169 | *
|
---|
1170 | * Preconditions: Caller must have locked g_pSessionsLockHandle.
|
---|
1171 | *
|
---|
1172 | * @param username
|
---|
1173 | * @param password
|
---|
1174 | */
|
---|
1175 | WebServiceSession::WebServiceSession()
|
---|
1176 | : _fDestructing(false),
|
---|
1177 | _pISession(NULL),
|
---|
1178 | _tLastObjectLookup(0)
|
---|
1179 | {
|
---|
1180 | _pp = new WebServiceSessionPrivate;
|
---|
1181 | _uSessionID = RTRandU64();
|
---|
1182 |
|
---|
1183 | // register this session globally
|
---|
1184 | Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
|
---|
1185 | g_mapSessions[_uSessionID] = this;
|
---|
1186 | }
|
---|
1187 |
|
---|
1188 | /**
|
---|
1189 | * Destructor. Cleans up and destroys all contained managed object references on the way.
|
---|
1190 | *
|
---|
1191 | * Preconditions: Caller must have locked g_pSessionsLockHandle.
|
---|
1192 | */
|
---|
1193 | WebServiceSession::~WebServiceSession()
|
---|
1194 | {
|
---|
1195 | // delete us from global map first so we can't be found
|
---|
1196 | // any more while we're cleaning up
|
---|
1197 | Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
|
---|
1198 | g_mapSessions.erase(_uSessionID);
|
---|
1199 |
|
---|
1200 | // notify ManagedObjectRef destructor so it won't
|
---|
1201 | // remove itself from the maps; this avoids rebalancing
|
---|
1202 | // the map's tree on every delete as well
|
---|
1203 | _fDestructing = true;
|
---|
1204 |
|
---|
1205 | // if (_pISession)
|
---|
1206 | // {
|
---|
1207 | // delete _pISession;
|
---|
1208 | // _pISession = NULL;
|
---|
1209 | // }
|
---|
1210 |
|
---|
1211 | ManagedObjectsMapById::iterator it,
|
---|
1212 | end = _pp->_mapManagedObjectsById.end();
|
---|
1213 | for (it = _pp->_mapManagedObjectsById.begin();
|
---|
1214 | it != end;
|
---|
1215 | ++it)
|
---|
1216 | {
|
---|
1217 | ManagedObjectRef *pRef = it->second;
|
---|
1218 | delete pRef; // this frees the contained ComPtr as well
|
---|
1219 | }
|
---|
1220 |
|
---|
1221 | delete _pp;
|
---|
1222 | }
|
---|
1223 |
|
---|
1224 | /**
|
---|
1225 | * Authenticate the username and password against an authentication authority.
|
---|
1226 | *
|
---|
1227 | * @return 0 if the user was successfully authenticated, or an error code
|
---|
1228 | * otherwise.
|
---|
1229 | */
|
---|
1230 |
|
---|
1231 | int WebServiceSession::authenticate(const char *pcszUsername,
|
---|
1232 | const char *pcszPassword,
|
---|
1233 | IVirtualBox **ppVirtualBox)
|
---|
1234 | {
|
---|
1235 | int rc = VERR_WEB_NOT_AUTHENTICATED;
|
---|
1236 | ComPtr<IVirtualBox> pVirtualBox;
|
---|
1237 | {
|
---|
1238 | util::AutoReadLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
1239 | pVirtualBox = g_pVirtualBox;
|
---|
1240 | }
|
---|
1241 | pVirtualBox.queryInterfaceTo(ppVirtualBox);
|
---|
1242 | if (pVirtualBox.isNull())
|
---|
1243 | return rc;
|
---|
1244 |
|
---|
1245 | util::AutoReadLock lock(g_pAuthLibLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
1246 |
|
---|
1247 | static bool fAuthLibLoaded = false;
|
---|
1248 | static PAUTHENTRY pfnAuthEntry = NULL;
|
---|
1249 | static PAUTHENTRY2 pfnAuthEntry2 = NULL;
|
---|
1250 | static PAUTHENTRY3 pfnAuthEntry3 = NULL;
|
---|
1251 |
|
---|
1252 | if (!fAuthLibLoaded)
|
---|
1253 | {
|
---|
1254 | // retrieve authentication library from system properties
|
---|
1255 | ComPtr<ISystemProperties> systemProperties;
|
---|
1256 | pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
|
---|
1257 |
|
---|
1258 | com::Bstr authLibrary;
|
---|
1259 | systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
|
---|
1260 | com::Utf8Str filename = authLibrary;
|
---|
1261 |
|
---|
1262 | WEBDEBUG(("external authentication library is '%ls'\n", authLibrary.raw()));
|
---|
1263 |
|
---|
1264 | if (filename == "null")
|
---|
1265 | // authentication disabled, let everyone in:
|
---|
1266 | fAuthLibLoaded = true;
|
---|
1267 | else
|
---|
1268 | {
|
---|
1269 | RTLDRMOD hlibAuth = 0;
|
---|
1270 | do
|
---|
1271 | {
|
---|
1272 | rc = RTLdrLoad(filename.c_str(), &hlibAuth);
|
---|
1273 | if (RT_FAILURE(rc))
|
---|
1274 | {
|
---|
1275 | WEBDEBUG(("%s() Failed to load external authentication library. Error code: %Rrc\n", __FUNCTION__, rc));
|
---|
1276 | break;
|
---|
1277 | }
|
---|
1278 |
|
---|
1279 | if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY3_NAME, (void**)&pfnAuthEntry3)))
|
---|
1280 | WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY3_NAME, rc));
|
---|
1281 |
|
---|
1282 | if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY2_NAME, (void**)&pfnAuthEntry2)))
|
---|
1283 | WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY2_NAME, rc));
|
---|
1284 |
|
---|
1285 | if (RT_FAILURE(rc = RTLdrGetSymbol(hlibAuth, AUTHENTRY_NAME, (void**)&pfnAuthEntry)))
|
---|
1286 | WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n", __FUNCTION__, AUTHENTRY_NAME, rc));
|
---|
1287 |
|
---|
1288 | if (pfnAuthEntry || pfnAuthEntry2 || pfnAuthEntry3)
|
---|
1289 | fAuthLibLoaded = true;
|
---|
1290 |
|
---|
1291 | } while (0);
|
---|
1292 | }
|
---|
1293 | }
|
---|
1294 |
|
---|
1295 | rc = VERR_WEB_NOT_AUTHENTICATED;
|
---|
1296 | AuthResult result;
|
---|
1297 | if (pfnAuthEntry3)
|
---|
1298 | {
|
---|
1299 | result = pfnAuthEntry3("webservice", NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
|
---|
1300 | WEBDEBUG(("%s(): result of AuthEntry(): %d\n", __FUNCTION__, result));
|
---|
1301 | if (result == AuthResultAccessGranted)
|
---|
1302 | rc = 0;
|
---|
1303 | }
|
---|
1304 | else if (pfnAuthEntry2)
|
---|
1305 | {
|
---|
1306 | result = pfnAuthEntry2(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
|
---|
1307 | WEBDEBUG(("%s(): result of VRDPAuth2(): %d\n", __FUNCTION__, result));
|
---|
1308 | if (result == AuthResultAccessGranted)
|
---|
1309 | rc = 0;
|
---|
1310 | }
|
---|
1311 | else if (pfnAuthEntry)
|
---|
1312 | {
|
---|
1313 | result = pfnAuthEntry(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
|
---|
1314 | WEBDEBUG(("%s(): result of VRDPAuth(%s, [%d]): %d\n", __FUNCTION__, pcszUsername, strlen(pcszPassword), result));
|
---|
1315 | if (result == AuthResultAccessGranted)
|
---|
1316 | rc = 0;
|
---|
1317 | }
|
---|
1318 | else if (fAuthLibLoaded)
|
---|
1319 | // fAuthLibLoaded = true but both pointers are NULL:
|
---|
1320 | // then the authlib was "null" and auth was disabled
|
---|
1321 | rc = 0;
|
---|
1322 | else
|
---|
1323 | {
|
---|
1324 | WEBDEBUG(("Could not resolve AuthEntry, VRDPAuth2 or VRDPAuth entry point"));
|
---|
1325 | }
|
---|
1326 |
|
---|
1327 | lock.release();
|
---|
1328 |
|
---|
1329 | if (!rc)
|
---|
1330 | {
|
---|
1331 | do
|
---|
1332 | {
|
---|
1333 | // now create the ISession object that this webservice session can use
|
---|
1334 | // (and of which IWebsessionManager::getSessionObject returns a managed object reference)
|
---|
1335 | ComPtr<ISession> session;
|
---|
1336 | rc = g_pVirtualBoxClient->COMGETTER(Session)(session.asOutParam());
|
---|
1337 | if (FAILED(rc))
|
---|
1338 | {
|
---|
1339 | WEBDEBUG(("ERROR: cannot create session object!"));
|
---|
1340 | break;
|
---|
1341 | }
|
---|
1342 |
|
---|
1343 | ComPtr<IUnknown> p2 = session;
|
---|
1344 | _pISession = new ManagedObjectRef(*this,
|
---|
1345 | p2, // IUnknown *pobjUnknown
|
---|
1346 | session, // void *pobjInterface
|
---|
1347 | com::Guid(COM_IIDOF(ISession)),
|
---|
1348 | g_pcszISession);
|
---|
1349 |
|
---|
1350 | if (g_fVerbose)
|
---|
1351 | {
|
---|
1352 | ISession *p = session;
|
---|
1353 | WEBDEBUG((" * %s: created session object with comptr 0x%lX, MOR = %s\n", __FUNCTION__, p, _pISession->getWSDLID().c_str()));
|
---|
1354 | }
|
---|
1355 | } while (0);
|
---|
1356 | }
|
---|
1357 |
|
---|
1358 | return rc;
|
---|
1359 | }
|
---|
1360 |
|
---|
1361 | /**
|
---|
1362 | * Look up, in this session, whether a ManagedObjectRef has already been
|
---|
1363 | * created for the given COM pointer.
|
---|
1364 | *
|
---|
1365 | * Note how we require that a ComPtr<IUnknown> is passed, which causes a
|
---|
1366 | * queryInterface call when the caller passes in a different type, since
|
---|
1367 | * a ComPtr<IUnknown> will point to something different than a
|
---|
1368 | * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
|
---|
1369 | * our private hash table, we must search for one too.
|
---|
1370 | *
|
---|
1371 | * Preconditions: Caller must have locked g_pSessionsLockHandle.
|
---|
1372 | *
|
---|
1373 | * @param pcu pointer to a COM object.
|
---|
1374 | * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
|
---|
1375 | */
|
---|
1376 | ManagedObjectRef* WebServiceSession::findRefFromPtr(const IUnknown *pObject)
|
---|
1377 | {
|
---|
1378 | Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
|
---|
1379 |
|
---|
1380 | uintptr_t ulp = (uintptr_t)pObject;
|
---|
1381 | // WEBDEBUG((" %s: looking up 0x%lX\n", __FUNCTION__, ulp));
|
---|
1382 | ManagedObjectsMapByPtr::iterator it = _pp->_mapManagedObjectsByPtr.find(ulp);
|
---|
1383 | if (it != _pp->_mapManagedObjectsByPtr.end())
|
---|
1384 | {
|
---|
1385 | ManagedObjectRef *pRef = it->second;
|
---|
1386 | WEBDEBUG((" %s: found existing ref %s (%s) for COM obj 0x%lX\n", __FUNCTION__, pRef->getWSDLID().c_str(), pRef->getInterfaceName(), ulp));
|
---|
1387 | return pRef;
|
---|
1388 | }
|
---|
1389 |
|
---|
1390 | return NULL;
|
---|
1391 | }
|
---|
1392 |
|
---|
1393 | /**
|
---|
1394 | * Static method which attempts to find the session for which the given managed
|
---|
1395 | * object reference was created, by splitting the reference into the session and
|
---|
1396 | * object IDs and then looking up the session object for that session ID.
|
---|
1397 | *
|
---|
1398 | * Preconditions: Caller must have locked g_pSessionsLockHandle in read mode.
|
---|
1399 | *
|
---|
1400 | * @param id Managed object reference (with combined session and object IDs).
|
---|
1401 | * @return
|
---|
1402 | */
|
---|
1403 | WebServiceSession* WebServiceSession::findSessionFromRef(const WSDLT_ID &id)
|
---|
1404 | {
|
---|
1405 | Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
|
---|
1406 |
|
---|
1407 | WebServiceSession *pSession = NULL;
|
---|
1408 | uint64_t sessid;
|
---|
1409 | if (SplitManagedObjectRef(id,
|
---|
1410 | &sessid,
|
---|
1411 | NULL))
|
---|
1412 | {
|
---|
1413 | SessionsMapIterator it = g_mapSessions.find(sessid);
|
---|
1414 | if (it != g_mapSessions.end())
|
---|
1415 | pSession = it->second;
|
---|
1416 | }
|
---|
1417 | return pSession;
|
---|
1418 | }
|
---|
1419 |
|
---|
1420 | /**
|
---|
1421 | *
|
---|
1422 | */
|
---|
1423 | const WSDLT_ID& WebServiceSession::getSessionWSDLID() const
|
---|
1424 | {
|
---|
1425 | return _pISession->getWSDLID();
|
---|
1426 | }
|
---|
1427 |
|
---|
1428 | /**
|
---|
1429 | * Touches the webservice session to prevent it from timing out.
|
---|
1430 | *
|
---|
1431 | * Each webservice session has an internal timestamp that records
|
---|
1432 | * the last request made to it from the client that started it.
|
---|
1433 | * If no request was made within a configurable timeframe, then
|
---|
1434 | * the client is logged off automatically,
|
---|
1435 | * by calling IWebsessionManager::logoff()
|
---|
1436 | */
|
---|
1437 | void WebServiceSession::touch()
|
---|
1438 | {
|
---|
1439 | time(&_tLastObjectLookup);
|
---|
1440 | }
|
---|
1441 |
|
---|
1442 |
|
---|
1443 | /****************************************************************************
|
---|
1444 | *
|
---|
1445 | * class ManagedObjectRef
|
---|
1446 | *
|
---|
1447 | ****************************************************************************/
|
---|
1448 |
|
---|
1449 | /**
|
---|
1450 | * Constructor, which assigns a unique ID to this managed object
|
---|
1451 | * reference and stores it two global hashes:
|
---|
1452 | *
|
---|
1453 | * a) G_mapManagedObjectsById, which maps ManagedObjectID's to
|
---|
1454 | * instances of this class; this hash is then used by the
|
---|
1455 | * findObjectFromRef() template function in vboxweb.h
|
---|
1456 | * to quickly retrieve the COM object from its managed
|
---|
1457 | * object ID (mostly in the context of the method mappers
|
---|
1458 | * in methodmaps.cpp, when a web service client passes in
|
---|
1459 | * a managed object ID);
|
---|
1460 | *
|
---|
1461 | * b) G_mapManagedObjectsByComPtr, which maps COM pointers to
|
---|
1462 | * instances of this class; this hash is used by
|
---|
1463 | * createRefFromObject() to quickly figure out whether an
|
---|
1464 | * instance already exists for a given COM pointer.
|
---|
1465 | *
|
---|
1466 | * This constructor calls AddRef() on the given COM object, and
|
---|
1467 | * the destructor will call Release(). We require two input pointers
|
---|
1468 | * for that COM object, one generic IUnknown* pointer which is used
|
---|
1469 | * as the map key, and a specific interface pointer (e.g. IMachine*)
|
---|
1470 | * which must support the interface given in guidInterface. All
|
---|
1471 | * three values are returned by getPtr(), which gives future callers
|
---|
1472 | * a chance to reuse the specific interface pointer without having
|
---|
1473 | * to call QueryInterface, which can be expensive.
|
---|
1474 | *
|
---|
1475 | * This does _not_ check whether another instance already
|
---|
1476 | * exists in the hash. This gets called only from the
|
---|
1477 | * createOrFindRefFromComPtr() template function in vboxweb.h, which
|
---|
1478 | * does perform that check.
|
---|
1479 | *
|
---|
1480 | * Preconditions: Caller must have locked g_pSessionsLockHandle.
|
---|
1481 | *
|
---|
1482 | * @param session Session to which the MOR will be added.
|
---|
1483 | * @param pobjUnknown Pointer to IUnknown* interface for the COM object; this will be used in the hashes.
|
---|
1484 | * @param pobjInterface Pointer to a specific interface for the COM object, described by guidInterface.
|
---|
1485 | * @param guidInterface Interface which pobjInterface points to.
|
---|
1486 | * @param pcszInterface String representation of that interface (e.g. "IMachine") for readability and logging.
|
---|
1487 | */
|
---|
1488 | ManagedObjectRef::ManagedObjectRef(WebServiceSession &session,
|
---|
1489 | IUnknown *pobjUnknown,
|
---|
1490 | void *pobjInterface,
|
---|
1491 | const com::Guid &guidInterface,
|
---|
1492 | const char *pcszInterface)
|
---|
1493 | : _session(session),
|
---|
1494 | _pobjUnknown(pobjUnknown),
|
---|
1495 | _pobjInterface(pobjInterface),
|
---|
1496 | _guidInterface(guidInterface),
|
---|
1497 | _pcszInterface(pcszInterface)
|
---|
1498 | {
|
---|
1499 | Assert(pobjUnknown);
|
---|
1500 | Assert(pobjInterface);
|
---|
1501 |
|
---|
1502 | // keep both stubs alive while this MOR exists (matching Release() calls are in destructor)
|
---|
1503 | uint32_t cRefs1 = pobjUnknown->AddRef();
|
---|
1504 | uint32_t cRefs2 = ((IUnknown*)pobjInterface)->AddRef();
|
---|
1505 | _ulp = (uintptr_t)pobjUnknown;
|
---|
1506 |
|
---|
1507 | Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
|
---|
1508 | _id = ++g_iMaxManagedObjectID;
|
---|
1509 | // and count globally
|
---|
1510 | ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
|
---|
1511 |
|
---|
1512 | char sz[34];
|
---|
1513 | MakeManagedObjectRef(sz, session._uSessionID, _id);
|
---|
1514 | _strID = sz;
|
---|
1515 |
|
---|
1516 | session._pp->_mapManagedObjectsById[_id] = this;
|
---|
1517 | session._pp->_mapManagedObjectsByPtr[_ulp] = this;
|
---|
1518 |
|
---|
1519 | session.touch();
|
---|
1520 |
|
---|
1521 | WEBDEBUG((" * %s: MOR created for %s*=0x%lX (IUnknown*=0x%lX; COM refcount now %RI32/%RI32), new ID is %llX; now %lld objects total\n",
|
---|
1522 | __FUNCTION__,
|
---|
1523 | pcszInterface,
|
---|
1524 | pobjInterface,
|
---|
1525 | pobjUnknown,
|
---|
1526 | cRefs1,
|
---|
1527 | cRefs2,
|
---|
1528 | _id,
|
---|
1529 | cTotal));
|
---|
1530 | }
|
---|
1531 |
|
---|
1532 | /**
|
---|
1533 | * Destructor; removes the instance from the global hash of
|
---|
1534 | * managed objects. Calls Release() on the contained COM object.
|
---|
1535 | *
|
---|
1536 | * Preconditions: Caller must have locked g_pSessionsLockHandle.
|
---|
1537 | */
|
---|
1538 | ManagedObjectRef::~ManagedObjectRef()
|
---|
1539 | {
|
---|
1540 | Assert(g_pSessionsLockHandle->isWriteLockOnCurrentThread());
|
---|
1541 | ULONG64 cTotal = --g_cManagedObjects;
|
---|
1542 |
|
---|
1543 | Assert(_pobjUnknown);
|
---|
1544 | Assert(_pobjInterface);
|
---|
1545 |
|
---|
1546 | // we called AddRef() on both interfaces, so call Release() on
|
---|
1547 | // both as well, but in reverse order
|
---|
1548 | uint32_t cRefs2 = ((IUnknown*)_pobjInterface)->Release();
|
---|
1549 | uint32_t cRefs1 = _pobjUnknown->Release();
|
---|
1550 | WEBDEBUG((" * %s: deleting MOR for ID %llX (%s; COM refcount now %RI32/%RI32); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cRefs1, cRefs2, cTotal));
|
---|
1551 |
|
---|
1552 | // if we're being destroyed from the session's destructor,
|
---|
1553 | // then that destructor is iterating over the maps, so
|
---|
1554 | // don't remove us there! (data integrity + speed)
|
---|
1555 | if (!_session._fDestructing)
|
---|
1556 | {
|
---|
1557 | WEBDEBUG((" * %s: removing from session maps\n", __FUNCTION__));
|
---|
1558 | _session._pp->_mapManagedObjectsById.erase(_id);
|
---|
1559 | if (_session._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
|
---|
1560 | WEBDEBUG((" WARNING: could not find %llX in _mapManagedObjectsByPtr\n", _ulp));
|
---|
1561 | }
|
---|
1562 | }
|
---|
1563 |
|
---|
1564 | /**
|
---|
1565 | * Static helper method for findObjectFromRef() template that actually
|
---|
1566 | * looks up the object from a given integer ID.
|
---|
1567 | *
|
---|
1568 | * This has been extracted into this non-template function to reduce
|
---|
1569 | * code bloat as we have the actual STL map lookup only in this function.
|
---|
1570 | *
|
---|
1571 | * This also "touches" the timestamp in the session whose ID is encoded
|
---|
1572 | * in the given integer ID, in order to prevent the session from timing
|
---|
1573 | * out.
|
---|
1574 | *
|
---|
1575 | * Preconditions: Caller must have locked g_mutexSessions.
|
---|
1576 | *
|
---|
1577 | * @param strId
|
---|
1578 | * @param iter
|
---|
1579 | * @return
|
---|
1580 | */
|
---|
1581 | int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
|
---|
1582 | ManagedObjectRef **pRef,
|
---|
1583 | bool fNullAllowed)
|
---|
1584 | {
|
---|
1585 | int rc = 0;
|
---|
1586 |
|
---|
1587 | do
|
---|
1588 | {
|
---|
1589 | // allow NULL (== empty string) input reference, which should return a NULL pointer
|
---|
1590 | if (!id.length() && fNullAllowed)
|
---|
1591 | {
|
---|
1592 | *pRef = NULL;
|
---|
1593 | return 0;
|
---|
1594 | }
|
---|
1595 |
|
---|
1596 | uint64_t sessid;
|
---|
1597 | uint64_t objid;
|
---|
1598 | WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
|
---|
1599 | if (!SplitManagedObjectRef(id,
|
---|
1600 | &sessid,
|
---|
1601 | &objid))
|
---|
1602 | {
|
---|
1603 | rc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
|
---|
1604 | break;
|
---|
1605 | }
|
---|
1606 |
|
---|
1607 | SessionsMapIterator it = g_mapSessions.find(sessid);
|
---|
1608 | if (it == g_mapSessions.end())
|
---|
1609 | {
|
---|
1610 | WEBDEBUG((" %s: cannot find session for objref %s\n", __FUNCTION__, id.c_str()));
|
---|
1611 | rc = VERR_WEB_INVALID_SESSION_ID;
|
---|
1612 | break;
|
---|
1613 | }
|
---|
1614 |
|
---|
1615 | WebServiceSession *pSess = it->second;
|
---|
1616 | // "touch" session to prevent it from timing out
|
---|
1617 | pSess->touch();
|
---|
1618 |
|
---|
1619 | ManagedObjectsIteratorById iter = pSess->_pp->_mapManagedObjectsById.find(objid);
|
---|
1620 | if (iter == pSess->_pp->_mapManagedObjectsById.end())
|
---|
1621 | {
|
---|
1622 | WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
|
---|
1623 | rc = VERR_WEB_INVALID_OBJECT_ID;
|
---|
1624 | break;
|
---|
1625 | }
|
---|
1626 |
|
---|
1627 | *pRef = iter->second;
|
---|
1628 |
|
---|
1629 | } while (0);
|
---|
1630 |
|
---|
1631 | return rc;
|
---|
1632 | }
|
---|
1633 |
|
---|
1634 | /****************************************************************************
|
---|
1635 | *
|
---|
1636 | * interface IManagedObjectRef
|
---|
1637 | *
|
---|
1638 | ****************************************************************************/
|
---|
1639 |
|
---|
1640 | /**
|
---|
1641 | * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
|
---|
1642 | * that our WSDL promises to our web service clients. This method returns a
|
---|
1643 | * string describing the interface that this managed object reference
|
---|
1644 | * supports, e.g. "IMachine".
|
---|
1645 | *
|
---|
1646 | * @param soap
|
---|
1647 | * @param req
|
---|
1648 | * @param resp
|
---|
1649 | * @return
|
---|
1650 | */
|
---|
1651 | int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
|
---|
1652 | struct soap *soap,
|
---|
1653 | _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
|
---|
1654 | _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
|
---|
1655 | {
|
---|
1656 | HRESULT rc = S_OK;
|
---|
1657 | WEBDEBUG(("-- entering %s\n", __FUNCTION__));
|
---|
1658 |
|
---|
1659 | do
|
---|
1660 | {
|
---|
1661 | // findRefFromId require the lock
|
---|
1662 | util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
1663 |
|
---|
1664 | ManagedObjectRef *pRef;
|
---|
1665 | if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false))
|
---|
1666 | resp->returnval = pRef->getInterfaceName();
|
---|
1667 |
|
---|
1668 | } while (0);
|
---|
1669 |
|
---|
1670 | WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
|
---|
1671 | if (FAILED(rc))
|
---|
1672 | return SOAP_FAULT;
|
---|
1673 | return SOAP_OK;
|
---|
1674 | }
|
---|
1675 |
|
---|
1676 | /**
|
---|
1677 | * This is the hard-coded implementation for the IManagedObjectRef::release()
|
---|
1678 | * that our WSDL promises to our web service clients. This method releases
|
---|
1679 | * a managed object reference and removes it from our stacks.
|
---|
1680 | *
|
---|
1681 | * @param soap
|
---|
1682 | * @param req
|
---|
1683 | * @param resp
|
---|
1684 | * @return
|
---|
1685 | */
|
---|
1686 | int __vbox__IManagedObjectRef_USCORErelease(
|
---|
1687 | struct soap *soap,
|
---|
1688 | _vbox__IManagedObjectRef_USCORErelease *req,
|
---|
1689 | _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
|
---|
1690 | {
|
---|
1691 | HRESULT rc = S_OK;
|
---|
1692 | WEBDEBUG(("-- entering %s\n", __FUNCTION__));
|
---|
1693 |
|
---|
1694 | do
|
---|
1695 | {
|
---|
1696 | // findRefFromId and the delete call below require the lock
|
---|
1697 | util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
1698 |
|
---|
1699 | ManagedObjectRef *pRef;
|
---|
1700 | if ((rc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false)))
|
---|
1701 | {
|
---|
1702 | RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
|
---|
1703 | break;
|
---|
1704 | }
|
---|
1705 |
|
---|
1706 | WEBDEBUG((" found reference; deleting!\n"));
|
---|
1707 | // this removes the object from all stacks; since
|
---|
1708 | // there's a ComPtr<> hidden inside the reference,
|
---|
1709 | // this should also invoke Release() on the COM
|
---|
1710 | // object
|
---|
1711 | delete pRef;
|
---|
1712 | } while (0);
|
---|
1713 |
|
---|
1714 | WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
|
---|
1715 | if (FAILED(rc))
|
---|
1716 | return SOAP_FAULT;
|
---|
1717 | return SOAP_OK;
|
---|
1718 | }
|
---|
1719 |
|
---|
1720 | /****************************************************************************
|
---|
1721 | *
|
---|
1722 | * interface IWebsessionManager
|
---|
1723 | *
|
---|
1724 | ****************************************************************************/
|
---|
1725 |
|
---|
1726 | /**
|
---|
1727 | * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
|
---|
1728 | * COM API, this is the first method that a webservice client must call before the
|
---|
1729 | * webservice will do anything useful.
|
---|
1730 | *
|
---|
1731 | * This returns a managed object reference to the global IVirtualBox object; into this
|
---|
1732 | * reference a session ID is encoded which remains constant with all managed object
|
---|
1733 | * references returned by other methods.
|
---|
1734 | *
|
---|
1735 | * This also creates an instance of ISession, which is stored internally with the
|
---|
1736 | * webservice session and can be retrieved with IWebsessionManager::getSessionObject
|
---|
1737 | * (__vbox__IWebsessionManager_USCOREgetSessionObject). In order for the
|
---|
1738 | * VirtualBox web service to do anything useful, one usually needs both a
|
---|
1739 | * VirtualBox and an ISession object, for which these two methods are designed.
|
---|
1740 | *
|
---|
1741 | * When the webservice client is done, it should call IWebsessionManager::logoff. This
|
---|
1742 | * will clean up internally (destroy all remaining managed object references and
|
---|
1743 | * related COM objects used internally).
|
---|
1744 | *
|
---|
1745 | * After logon, an internal timeout ensures that if the webservice client does not
|
---|
1746 | * call any methods, after a configurable number of seconds, the webservice will log
|
---|
1747 | * off the client automatically. This is to ensure that the webservice does not
|
---|
1748 | * drown in managed object references and eventually deny service. Still, it is
|
---|
1749 | * a much better solution, both for performance and cleanliness, for the webservice
|
---|
1750 | * client to clean up itself.
|
---|
1751 | *
|
---|
1752 | * @param
|
---|
1753 | * @param vbox__IWebsessionManager_USCORElogon
|
---|
1754 | * @param vbox__IWebsessionManager_USCORElogonResponse
|
---|
1755 | * @return
|
---|
1756 | */
|
---|
1757 | int __vbox__IWebsessionManager_USCORElogon(
|
---|
1758 | struct soap *soap,
|
---|
1759 | _vbox__IWebsessionManager_USCORElogon *req,
|
---|
1760 | _vbox__IWebsessionManager_USCORElogonResponse *resp)
|
---|
1761 | {
|
---|
1762 | HRESULT rc = S_OK;
|
---|
1763 | WEBDEBUG(("-- entering %s\n", __FUNCTION__));
|
---|
1764 |
|
---|
1765 | do
|
---|
1766 | {
|
---|
1767 | // WebServiceSession constructor tinkers with global MOR map and requires a write lock
|
---|
1768 | util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
1769 |
|
---|
1770 | // create new session; the constructor stores the new session
|
---|
1771 | // in the global map automatically
|
---|
1772 | WebServiceSession *pSession = new WebServiceSession();
|
---|
1773 | ComPtr<IVirtualBox> pVirtualBox;
|
---|
1774 |
|
---|
1775 | // authenticate the user
|
---|
1776 | if (!(pSession->authenticate(req->username.c_str(),
|
---|
1777 | req->password.c_str(),
|
---|
1778 | pVirtualBox.asOutParam())))
|
---|
1779 | {
|
---|
1780 | // in the new session, create a managed object reference (MOR) for the
|
---|
1781 | // global VirtualBox object; this encodes the session ID in the MOR so
|
---|
1782 | // that it will be implicitly be included in all future requests of this
|
---|
1783 | // webservice client
|
---|
1784 | ComPtr<IUnknown> p2 = pVirtualBox;
|
---|
1785 | if (pVirtualBox.isNull() || p2.isNull())
|
---|
1786 | {
|
---|
1787 | rc = E_FAIL;
|
---|
1788 | break;
|
---|
1789 | }
|
---|
1790 | ManagedObjectRef *pRef = new ManagedObjectRef(*pSession,
|
---|
1791 | p2, // IUnknown *pobjUnknown
|
---|
1792 | pVirtualBox, // void *pobjInterface
|
---|
1793 | COM_IIDOF(IVirtualBox),
|
---|
1794 | g_pcszIVirtualBox);
|
---|
1795 | resp->returnval = pRef->getWSDLID();
|
---|
1796 | WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
|
---|
1797 | }
|
---|
1798 | else
|
---|
1799 | rc = E_FAIL;
|
---|
1800 | } while (0);
|
---|
1801 |
|
---|
1802 | WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
|
---|
1803 | if (FAILED(rc))
|
---|
1804 | return SOAP_FAULT;
|
---|
1805 | return SOAP_OK;
|
---|
1806 | }
|
---|
1807 |
|
---|
1808 | /**
|
---|
1809 | * Returns the ISession object that was created for the webservice client
|
---|
1810 | * on logon.
|
---|
1811 | */
|
---|
1812 | int __vbox__IWebsessionManager_USCOREgetSessionObject(
|
---|
1813 | struct soap*,
|
---|
1814 | _vbox__IWebsessionManager_USCOREgetSessionObject *req,
|
---|
1815 | _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
|
---|
1816 | {
|
---|
1817 | HRESULT rc = S_OK;
|
---|
1818 | WEBDEBUG(("-- entering %s\n", __FUNCTION__));
|
---|
1819 |
|
---|
1820 | do
|
---|
1821 | {
|
---|
1822 | // findSessionFromRef needs lock
|
---|
1823 | util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
1824 |
|
---|
1825 | WebServiceSession* pSession;
|
---|
1826 | if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
|
---|
1827 | resp->returnval = pSession->getSessionWSDLID();
|
---|
1828 |
|
---|
1829 | } while (0);
|
---|
1830 |
|
---|
1831 | WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
|
---|
1832 | if (FAILED(rc))
|
---|
1833 | return SOAP_FAULT;
|
---|
1834 | return SOAP_OK;
|
---|
1835 | }
|
---|
1836 |
|
---|
1837 | /**
|
---|
1838 | * hard-coded implementation for IWebsessionManager::logoff.
|
---|
1839 | *
|
---|
1840 | * @param
|
---|
1841 | * @param vbox__IWebsessionManager_USCORElogon
|
---|
1842 | * @param vbox__IWebsessionManager_USCORElogonResponse
|
---|
1843 | * @return
|
---|
1844 | */
|
---|
1845 | int __vbox__IWebsessionManager_USCORElogoff(
|
---|
1846 | struct soap*,
|
---|
1847 | _vbox__IWebsessionManager_USCORElogoff *req,
|
---|
1848 | _vbox__IWebsessionManager_USCORElogoffResponse *resp)
|
---|
1849 | {
|
---|
1850 | HRESULT rc = S_OK;
|
---|
1851 | WEBDEBUG(("-- entering %s\n", __FUNCTION__));
|
---|
1852 |
|
---|
1853 | do
|
---|
1854 | {
|
---|
1855 | // findSessionFromRef and the session destructor require the lock
|
---|
1856 | util::AutoWriteLock lock(g_pSessionsLockHandle COMMA_LOCKVAL_SRC_POS);
|
---|
1857 |
|
---|
1858 | WebServiceSession* pSession;
|
---|
1859 | if ((pSession = WebServiceSession::findSessionFromRef(req->refIVirtualBox)))
|
---|
1860 | {
|
---|
1861 | delete pSession;
|
---|
1862 | // destructor cleans up
|
---|
1863 |
|
---|
1864 | WEBDEBUG(("session destroyed, %d sessions left open\n", g_mapSessions.size()));
|
---|
1865 | }
|
---|
1866 | } while (0);
|
---|
1867 |
|
---|
1868 | WEBDEBUG(("-- leaving %s, rc: 0x%lX\n", __FUNCTION__, rc));
|
---|
1869 | if (FAILED(rc))
|
---|
1870 | return SOAP_FAULT;
|
---|
1871 | return SOAP_OK;
|
---|
1872 | }
|
---|
1873 |
|
---|