VirtualBox

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

Last change on this file since 102869 was 99739, checked in by vboxsync, 19 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

  • Property filesplitter.c set to Makefile.kmk
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 84.0 KB
Line 
1/* $Id: vboxweb.cpp 99739 2023-05-11 01:01:08Z 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
93RT_C_DECLS_BEGIN
94
95// declarations for the generated WSDL text
96extern const unsigned char g_abVBoxWebWSDL[];
97extern const unsigned g_cbVBoxWebWSDL;
98
99RT_C_DECLS_END
100
101static void WebLogSoapError(struct soap *soap);
102
103/****************************************************************************
104 *
105 * private typedefs
106 *
107 ****************************************************************************/
108
109typedef std::map<uint64_t, ManagedObjectRef*> ManagedObjectsMapById;
110typedef ManagedObjectsMapById::iterator ManagedObjectsIteratorById;
111typedef std::map<uintptr_t, ManagedObjectRef*> ManagedObjectsMapByPtr;
112typedef ManagedObjectsMapByPtr::iterator ManagedObjectsIteratorByPtr;
113
114typedef std::map<uint64_t, WebServiceSession*> WebsessionsMap;
115typedef WebsessionsMap::iterator WebsessionsMapIterator;
116
117typedef std::map<RTTHREAD, com::Utf8Str> ThreadsMap;
118
119static DECLCALLBACK(int) fntWatchdog(RTTHREAD ThreadSelf, void *pvUser);
120
121/****************************************************************************
122 *
123 * Read-only global variables
124 *
125 ****************************************************************************/
126
127static ComPtr<IVirtualBoxClient> g_pVirtualBoxClient = NULL;
128
129// generated strings in methodmaps.cpp
130extern 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"
137static int g_iWatchdogTimeoutSecs = DEFAULT_TIMEOUT_SECS;
138static int g_iWatchdogCheckInterval = 5;
139
140static const char *g_pcszBindToHost = NULL; // host; NULL = localhost
141static unsigned int g_uBindToPort = 18083; // port
142static unsigned int g_uBacklog = 100; // backlog = max queue size for requests
143
144#ifdef WITH_OPENSSL
145static bool g_fSSL = false; // if SSL is enabled
146static const char *g_pcszKeyFile = NULL; // server key file
147static const char *g_pcszPassword = NULL; // password for server key
148static const char *g_pcszCACert = NULL; // file with trusted CA certificates
149static const char *g_pcszCAPath = NULL; // directory with trusted CA certificates
150static const char *g_pcszDHFile = NULL; // DH file name or DH key length in bits, NULL=use RSA
151static const char *g_pcszRandFile = NULL; // file with random data seed
152static const char *g_pcszSID = "vboxwebsrv"; // server ID for SSL session cache
153#endif /* WITH_OPENSSL */
154
155static unsigned int g_cMaxWorkerThreads = 100; // max. no. of worker threads
156static unsigned int g_cMaxKeepAlive = 100; // maximum number of soap requests in one connection
157
158static const char *g_pcszAuthentication = NULL; // web service authentication
159
160static uint32_t g_cHistory = 10; // enable log rotation, 10 files
161static uint32_t g_uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
162static uint64_t g_uHistoryFileSize = 100 * _1M; // max 100MB per file
163bool g_fVerbose = false; // be verbose
164
165static bool g_fDaemonize = false; // run in background.
166static volatile bool g_fKeepRunning = true; // controlling the exit
167
168const 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().
177class SoapQ;
178static SoapQ *g_pSoapQ = NULL;
179
180// this mutex protects the auth lib and authentication
181static util::WriteLockHandle *g_pAuthLibLockHandle;
182
183// this mutex protects the global VirtualBox reference below
184static util::RWLockHandle *g_pVirtualBoxLockHandle;
185
186static ComPtr<IVirtualBox> g_pVirtualBox = NULL;
187
188// this mutex protects all of the below
189util::WriteLockHandle *g_pWebsessionsLockHandle;
190
191static WebsessionsMap g_mapWebsessions;
192static ULONG64 g_cManagedObjects = 0;
193
194// this mutex protects g_mapThreads
195static util::RWLockHandle *g_pThreadsLockHandle;
196
197// Threads map, so we can quickly map an RTTHREAD struct to a logger prefix
198static ThreadsMap g_mapThreads;
199
200/****************************************************************************
201 *
202 * Command line help
203 *
204 ****************************************************************************/
205
206static 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
236static 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
355class SoapQ;
356
357class SoapThread
358{
359public:
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 */
443class SoapQ
444{
445public:
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 */
609void 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
661class VirtualBoxClientEventListener
662{
663public:
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
731private:
732};
733
734typedef ListenerImpl<VirtualBoxClientEventListener> VirtualBoxClientEventListenerImpl;
735
736VBOX_LISTENER_DECLARE(VirtualBoxClientEventListenerImpl)
737
738/**
739 * Helper for printing SOAP error messages.
740 * @param soap
741 */
742/*static*/
743void 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 */
762static 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
781static RTCRITSECT *g_pSSLMutexes = NULL;
782
783struct CRYPTO_dynlock_value
784{
785 RTCRITSECT mutex;
786};
787
788static unsigned long CRYPTO_id_function()
789{
790 return (unsigned long)RTThreadNativeSelf();
791}
792
793static 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
801static 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
813static 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
821static 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
830static 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
861static 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
887static 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 */
1007static 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 */
1027static 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 */
1055static 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 */
1075int 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 */
1470static 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 */
1564static 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 */
1601void 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 */
1622std::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 */
1634std::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. */
1641std::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
1663void 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 */
1695void 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 */
1762static 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 */
1793static void MakeManagedObjectRef(char *sz,
1794 uint64_t websessId,
1795 uint64_t objId)
1796{
1797 RTStrFormatNumber(sz, websessId, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
1798 sz[16] = '-';
1799 RTStrFormatNumber(sz + 17, objId, 16, 16, 0, RTSTR_F_64BIT | RTSTR_F_ZEROPAD);
1800}
1801
1802/****************************************************************************
1803 *
1804 * class WebServiceSession
1805 *
1806 ****************************************************************************/
1807
1808class WebServiceSessionPrivate
1809{
1810 public:
1811 ManagedObjectsMapById _mapManagedObjectsById;
1812 ManagedObjectsMapByPtr _mapManagedObjectsByPtr;
1813};
1814
1815/**
1816 * Constructor for the websession object.
1817 *
1818 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
1819 */
1820WebServiceSession::WebServiceSession()
1821 : _uNextObjectID(1), // avoid 0 for no real reason
1822 _fDestructing(false),
1823 _tLastObjectLookup(0)
1824{
1825 _pp = new WebServiceSessionPrivate;
1826 _uWebsessionID = RTRandU64();
1827
1828 // register this websession globally
1829 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1830 g_mapWebsessions[_uWebsessionID] = this;
1831}
1832
1833/**
1834 * Destructor. Cleans up and destroys all contained managed object references on the way.
1835 *
1836 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
1837 */
1838WebServiceSession::~WebServiceSession()
1839{
1840 // delete us from global map first so we can't be found
1841 // any more while we're cleaning up
1842 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
1843 g_mapWebsessions.erase(_uWebsessionID);
1844
1845 // notify ManagedObjectRef destructor so it won't
1846 // remove itself from the maps; this avoids rebalancing
1847 // the map's tree on every delete as well
1848 _fDestructing = true;
1849
1850 ManagedObjectsIteratorById it,
1851 end = _pp->_mapManagedObjectsById.end();
1852 for (it = _pp->_mapManagedObjectsById.begin();
1853 it != end;
1854 ++it)
1855 {
1856 ManagedObjectRef *pRef = it->second;
1857 delete pRef; // this frees the contained ComPtr as well
1858 }
1859
1860 delete _pp;
1861}
1862
1863/**
1864 * Authenticate the username and password against an authentication authority.
1865 *
1866 * @return 0 if the user was successfully authenticated, or an error code
1867 * otherwise.
1868 */
1869int WebServiceSession::authenticate(const char *pcszUsername,
1870 const char *pcszPassword,
1871 IVirtualBox **ppVirtualBox)
1872{
1873 int vrc = VERR_WEB_NOT_AUTHENTICATED;
1874 ComPtr<IVirtualBox> pVirtualBox;
1875 {
1876 util::AutoReadLock vlock(g_pVirtualBoxLockHandle COMMA_LOCKVAL_SRC_POS);
1877 pVirtualBox = g_pVirtualBox;
1878 }
1879 if (pVirtualBox.isNull())
1880 return vrc;
1881 pVirtualBox.queryInterfaceTo(ppVirtualBox);
1882
1883 util::AutoReadLock lock(g_pAuthLibLockHandle COMMA_LOCKVAL_SRC_POS);
1884
1885 static bool fAuthLibLoaded = false;
1886 static PAUTHENTRY pfnAuthEntry = NULL;
1887 static PAUTHENTRY2 pfnAuthEntry2 = NULL;
1888 static PAUTHENTRY3 pfnAuthEntry3 = NULL;
1889
1890 if (!fAuthLibLoaded)
1891 {
1892 // retrieve authentication library from system properties
1893 ComPtr<ISystemProperties> systemProperties;
1894 pVirtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
1895
1896 com::Bstr authLibrary;
1897 systemProperties->COMGETTER(WebServiceAuthLibrary)(authLibrary.asOutParam());
1898 com::Utf8Str filename = authLibrary;
1899
1900 LogRel(("External authentication library is '%ls'\n", authLibrary.raw()));
1901
1902 if (filename == "null")
1903 // authentication disabled, let everyone in:
1904 fAuthLibLoaded = true;
1905 else
1906 {
1907 RTLDRMOD hlibAuth = 0;
1908 do
1909 {
1910 if (RTPathHavePath(filename.c_str()))
1911 vrc = RTLdrLoad(filename.c_str(), &hlibAuth);
1912 else
1913 vrc = RTLdrLoadAppPriv(filename.c_str(), &hlibAuth);
1914 if (RT_FAILURE(vrc))
1915 {
1916 WEBDEBUG(("%s() Failed to load external authentication library '%s'. Error code: %Rrc\n",
1917 __FUNCTION__, filename.c_str(), vrc));
1918 break;
1919 }
1920
1921 if (RT_FAILURE(vrc = RTLdrGetSymbol(hlibAuth, AUTHENTRY3_NAME, (void**)&pfnAuthEntry3)))
1922 {
1923 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1924 __FUNCTION__, AUTHENTRY3_NAME, vrc));
1925
1926 if (RT_FAILURE(vrc = RTLdrGetSymbol(hlibAuth, AUTHENTRY2_NAME, (void**)&pfnAuthEntry2)))
1927 {
1928 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1929 __FUNCTION__, AUTHENTRY2_NAME, vrc));
1930
1931 if (RT_FAILURE(vrc = RTLdrGetSymbol(hlibAuth, AUTHENTRY_NAME, (void**)&pfnAuthEntry)))
1932 WEBDEBUG(("%s(): Could not resolve import '%s'. Error code: %Rrc\n",
1933 __FUNCTION__, AUTHENTRY_NAME, vrc));
1934 }
1935 }
1936
1937 if (pfnAuthEntry || pfnAuthEntry2 || pfnAuthEntry3)
1938 fAuthLibLoaded = true;
1939
1940 } while (0);
1941 }
1942 }
1943
1944 if (strlen(pcszUsername) >= _1K)
1945 {
1946 LogRel(("Access denied, excessive username length: %zu\n", strlen(pcszUsername)));
1947 vrc = VERR_WEB_NOT_AUTHENTICATED;
1948 }
1949 else if (strlen(pcszPassword) >= _1K)
1950 {
1951 LogRel(("Access denied, excessive password length: %zu\n", strlen(pcszPassword)));
1952 vrc = VERR_WEB_NOT_AUTHENTICATED;
1953 }
1954 else if (pfnAuthEntry3 || pfnAuthEntry2 || pfnAuthEntry)
1955 {
1956 const char *pszFn;
1957 AuthResult result;
1958 if (pfnAuthEntry3)
1959 {
1960 result = pfnAuthEntry3("webservice", NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1961 pszFn = AUTHENTRY3_NAME;
1962 }
1963 else if (pfnAuthEntry2)
1964 {
1965 result = pfnAuthEntry2(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL, true, 0);
1966 pszFn = AUTHENTRY2_NAME;
1967 }
1968 else
1969 {
1970 result = pfnAuthEntry(NULL, AuthGuestNotAsked, pcszUsername, pcszPassword, NULL);
1971 pszFn = AUTHENTRY_NAME;
1972 }
1973 WEBDEBUG(("%s(): result of %s('%s', [%d]): %d (%s)\n",
1974 __FUNCTION__, pszFn, pcszUsername, strlen(pcszPassword), result, decodeAuthResult(result)));
1975 if (result == AuthResultAccessGranted)
1976 {
1977 LogRel(("Access for user '%s' granted\n", pcszUsername));
1978 vrc = VINF_SUCCESS;
1979 }
1980 else
1981 {
1982 if (result == AuthResultAccessDenied)
1983 LogRel(("Access for user '%s' denied\n", pcszUsername));
1984 vrc = VERR_WEB_NOT_AUTHENTICATED;
1985 }
1986 }
1987 else if (fAuthLibLoaded)
1988 {
1989 // fAuthLibLoaded = true but all pointers are NULL:
1990 // The authlib was "null" and auth was disabled
1991 vrc = VINF_SUCCESS;
1992 }
1993 else
1994 {
1995 WEBDEBUG(("Could not resolve AuthEntry, VRDPAuth2 or VRDPAuth entry point"));
1996 vrc = VERR_WEB_NOT_AUTHENTICATED;
1997 }
1998
1999 lock.release();
2000
2001 return vrc;
2002}
2003
2004/**
2005 * Look up, in this websession, whether a ManagedObjectRef has already been
2006 * created for the given COM pointer.
2007 *
2008 * Note how we require that a ComPtr<IUnknown> is passed, which causes a
2009 * queryInterface call when the caller passes in a different type, since
2010 * a ComPtr<IUnknown> will point to something different than a
2011 * ComPtr<IVirtualBox>, for example. As we store the ComPtr<IUnknown> in
2012 * our private hash table, we must search for one too.
2013 *
2014 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2015 *
2016 * @param pObject pointer to a COM object.
2017 * @return The existing ManagedObjectRef that represents the COM object, or NULL if there's none yet.
2018 */
2019ManagedObjectRef* WebServiceSession::findRefFromPtr(const IUnknown *pObject)
2020{
2021 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2022
2023 uintptr_t ulp = (uintptr_t)pObject;
2024 // WEBDEBUG((" %s: looking up %#lx\n", __FUNCTION__, ulp));
2025 ManagedObjectsIteratorByPtr it = _pp->_mapManagedObjectsByPtr.find(ulp);
2026 if (it != _pp->_mapManagedObjectsByPtr.end())
2027 {
2028 ManagedObjectRef *pRef = it->second;
2029 WEBDEBUG((" %s: found existing ref %s (%s) for COM obj %#lx\n", __FUNCTION__, pRef->getWSDLID().c_str(), pRef->getInterfaceName(), ulp));
2030 return pRef;
2031 }
2032
2033 return NULL;
2034}
2035
2036/**
2037 * Static method which attempts to find the websession for which the given
2038 * managed object reference was created, by splitting the reference into the
2039 * websession and object IDs and then looking up the websession object.
2040 *
2041 * Preconditions: Caller must have locked g_pWebsessionsLockHandle in read mode.
2042 *
2043 * @param id Managed object reference (with combined websession and object IDs).
2044 * @return
2045 */
2046WebServiceSession *WebServiceSession::findWebsessionFromRef(const WSDLT_ID &id)
2047{
2048 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2049
2050 WebServiceSession *pWebsession = NULL;
2051 uint64_t websessId;
2052 if (SplitManagedObjectRef(id,
2053 &websessId,
2054 NULL))
2055 {
2056 WebsessionsMapIterator it = g_mapWebsessions.find(websessId);
2057 if (it != g_mapWebsessions.end())
2058 pWebsession = it->second;
2059 }
2060 return pWebsession;
2061}
2062
2063/**
2064 * Touches the websession to prevent it from timing out.
2065 *
2066 * Each websession has an internal timestamp that records the last request made
2067 * to it from the client that started it. If no request was made within a
2068 * configurable timeframe, then the client is logged off automatically,
2069 * by calling IWebsessionManager::logoff()
2070 */
2071void WebServiceSession::touch()
2072{
2073 _tLastObjectLookup = RTTimeProgramSecTS();
2074}
2075
2076/**
2077 * Counts the number of managed object references in this websession.
2078 */
2079size_t WebServiceSession::CountRefs()
2080{
2081 return _pp->_mapManagedObjectsById.size();
2082}
2083
2084
2085/****************************************************************************
2086 *
2087 * class ManagedObjectRef
2088 *
2089 ****************************************************************************/
2090
2091/**
2092 * Constructor, which assigns a unique ID to this managed object
2093 * reference and stores it in two hashes (living in the associated
2094 * WebServiceSession object):
2095 *
2096 * a) _mapManagedObjectsById, which maps ManagedObjectID's to
2097 * instances of this class; this hash is then used by the
2098 * findObjectFromRef() template function in vboxweb.h
2099 * to quickly retrieve the COM object from its managed
2100 * object ID (mostly in the context of the method mappers
2101 * in methodmaps.cpp, when a web service client passes in
2102 * a managed object ID);
2103 *
2104 * b) _mapManagedObjectsByPtr, which maps COM pointers to
2105 * instances of this class; this hash is used by
2106 * createRefFromObject() to quickly figure out whether an
2107 * instance already exists for a given COM pointer.
2108 *
2109 * This constructor calls AddRef() on the given COM object, and
2110 * the destructor will call Release(). We require two input pointers
2111 * for that COM object, one generic IUnknown* pointer which is used
2112 * as the map key, and a specific interface pointer (e.g. IMachine*)
2113 * which must support the interface given in guidInterface. All
2114 * three values are returned by getPtr(), which gives future callers
2115 * a chance to reuse the specific interface pointer without having
2116 * to call QueryInterface, which can be expensive.
2117 *
2118 * This does _not_ check whether another instance already
2119 * exists in the hash. This gets called only from the
2120 * createOrFindRefFromComPtr() template function in vboxweb.h, which
2121 * does perform that check.
2122 *
2123 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2124 *
2125 * @param websession Websession to which the MOR will be added.
2126 * @param pobjUnknown Pointer to IUnknown* interface for the COM object; this will be used in the hashes.
2127 * @param pobjInterface Pointer to a specific interface for the COM object, described by guidInterface.
2128 * @param guidInterface Interface which pobjInterface points to.
2129 * @param pcszInterface String representation of that interface (e.g. "IMachine") for readability and logging.
2130 */
2131ManagedObjectRef::ManagedObjectRef(WebServiceSession &websession,
2132 IUnknown *pobjUnknown,
2133 void *pobjInterface,
2134 const com::Guid &guidInterface,
2135 const char *pcszInterface)
2136 : _websession(websession),
2137 _pobjUnknown(pobjUnknown),
2138 _pobjInterface(pobjInterface),
2139 _guidInterface(guidInterface),
2140 _pcszInterface(pcszInterface)
2141{
2142 Assert(pobjUnknown);
2143 Assert(pobjInterface);
2144
2145 // keep both stubs alive while this MOR exists (matching Release() calls are in destructor)
2146 uint32_t cRefs1 = pobjUnknown->AddRef();
2147 uint32_t cRefs2 = ((IUnknown*)pobjInterface)->AddRef();
2148 _ulp = (uintptr_t)pobjUnknown;
2149
2150 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2151 _id = websession.createObjectID();
2152 // and count globally
2153 ULONG64 cTotal = ++g_cManagedObjects; // raise global count and make a copy for the debug message below
2154
2155 char sz[34];
2156 MakeManagedObjectRef(sz, websession._uWebsessionID, _id);
2157 _strID = sz;
2158
2159 websession._pp->_mapManagedObjectsById[_id] = this;
2160 websession._pp->_mapManagedObjectsByPtr[_ulp] = this;
2161
2162 websession.touch();
2163
2164 WEBDEBUG((" * %s: MOR created for %s*=%#p (IUnknown*=%#p; COM refcount now %RI32/%RI32), new ID is %#llx; now %lld objects total\n",
2165 __FUNCTION__,
2166 pcszInterface,
2167 pobjInterface,
2168 pobjUnknown,
2169 cRefs1,
2170 cRefs2,
2171 _id,
2172 cTotal));
2173}
2174
2175/**
2176 * Destructor; removes the instance from the global hash of
2177 * managed objects. Calls Release() on the contained COM object.
2178 *
2179 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2180 */
2181ManagedObjectRef::~ManagedObjectRef()
2182{
2183 Assert(g_pWebsessionsLockHandle->isWriteLockOnCurrentThread());
2184 ULONG64 cTotal = --g_cManagedObjects;
2185
2186 Assert(_pobjUnknown);
2187 Assert(_pobjInterface);
2188
2189 // we called AddRef() on both interfaces, so call Release() on
2190 // both as well, but in reverse order
2191 uint32_t cRefs2 = ((IUnknown*)_pobjInterface)->Release();
2192 uint32_t cRefs1 = _pobjUnknown->Release();
2193 WEBDEBUG((" * %s: deleting MOR for ID %#llx (%s; COM refcount now %RI32/%RI32); now %lld objects total\n", __FUNCTION__, _id, _pcszInterface, cRefs1, cRefs2, cTotal));
2194
2195 // if we're being destroyed from the websession's destructor,
2196 // then that destructor is iterating over the maps, so
2197 // don't remove us there! (data integrity + speed)
2198 if (!_websession._fDestructing)
2199 {
2200 WEBDEBUG((" * %s: removing from websession maps\n", __FUNCTION__));
2201 _websession._pp->_mapManagedObjectsById.erase(_id);
2202 if (_websession._pp->_mapManagedObjectsByPtr.erase(_ulp) != 1)
2203 WEBDEBUG((" WARNING: could not find %#llx in _mapManagedObjectsByPtr\n", _ulp));
2204 }
2205}
2206
2207/**
2208 * Static helper method for findObjectFromRef() template that actually
2209 * looks up the object from a given integer ID.
2210 *
2211 * This has been extracted into this non-template function to reduce
2212 * code bloat as we have the actual STL map lookup only in this function.
2213 *
2214 * This also "touches" the timestamp in the websession whose ID is encoded
2215 * in the given integer ID, in order to prevent the websession from timing
2216 * out.
2217 *
2218 * Preconditions: Caller must have locked g_pWebsessionsLockHandle.
2219 *
2220 * @param id
2221 * @param pRef
2222 * @param fNullAllowed
2223 * @return
2224 */
2225int ManagedObjectRef::findRefFromId(const WSDLT_ID &id,
2226 ManagedObjectRef **pRef,
2227 bool fNullAllowed)
2228{
2229 int vrc = VINF_SUCCESS;
2230
2231 do
2232 {
2233 // allow NULL (== empty string) input reference, which should return a NULL pointer
2234 if (!id.length() && fNullAllowed)
2235 {
2236 *pRef = NULL;
2237 return 0;
2238 }
2239
2240 uint64_t websessId;
2241 uint64_t objId;
2242 WEBDEBUG((" %s(): looking up objref %s\n", __FUNCTION__, id.c_str()));
2243 if (!SplitManagedObjectRef(id,
2244 &websessId,
2245 &objId))
2246 {
2247 vrc = VERR_WEB_INVALID_MANAGED_OBJECT_REFERENCE;
2248 break;
2249 }
2250
2251 WebsessionsMapIterator it = g_mapWebsessions.find(websessId);
2252 if (it == g_mapWebsessions.end())
2253 {
2254 WEBDEBUG((" %s: cannot find websession for objref %s\n", __FUNCTION__, id.c_str()));
2255 vrc = VERR_WEB_INVALID_SESSION_ID;
2256 break;
2257 }
2258
2259 WebServiceSession *pWebsession = it->second;
2260 // "touch" websession to prevent it from timing out
2261 pWebsession->touch();
2262
2263 ManagedObjectsIteratorById iter = pWebsession->_pp->_mapManagedObjectsById.find(objId);
2264 if (iter == pWebsession->_pp->_mapManagedObjectsById.end())
2265 {
2266 WEBDEBUG((" %s: cannot find comobj for objref %s\n", __FUNCTION__, id.c_str()));
2267 vrc = VERR_WEB_INVALID_OBJECT_ID;
2268 break;
2269 }
2270
2271 *pRef = iter->second;
2272
2273 } while (0);
2274
2275 return vrc;
2276}
2277
2278/****************************************************************************
2279 *
2280 * interface IManagedObjectRef
2281 *
2282 ****************************************************************************/
2283
2284/**
2285 * This is the hard-coded implementation for the IManagedObjectRef::getInterfaceName()
2286 * that our WSDL promises to our web service clients. This method returns a
2287 * string describing the interface that this managed object reference
2288 * supports, e.g. "IMachine".
2289 *
2290 * @param soap
2291 * @param req
2292 * @param resp
2293 * @return
2294 */
2295int __vbox__IManagedObjectRef_USCOREgetInterfaceName(
2296 struct soap *soap,
2297 _vbox__IManagedObjectRef_USCOREgetInterfaceName *req,
2298 _vbox__IManagedObjectRef_USCOREgetInterfaceNameResponse *resp)
2299{
2300 RT_NOREF(soap);
2301 HRESULT hrc = S_OK; /** @todo r=bird: hrc is not set.... */
2302 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2303
2304 do
2305 {
2306 // findRefFromId require the lock
2307 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2308
2309 ManagedObjectRef *pRef;
2310 if (!ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false))
2311 resp->returnval = pRef->getInterfaceName();
2312
2313 } while (0);
2314
2315 WEBDEBUG(("-- leaving %s, hrc: %#lx\n", __FUNCTION__, hrc));
2316 if (FAILED(hrc))
2317 return SOAP_FAULT;
2318 return SOAP_OK;
2319}
2320
2321/**
2322 * This is the hard-coded implementation for the IManagedObjectRef::release()
2323 * that our WSDL promises to our web service clients. This method releases
2324 * a managed object reference and removes it from our stacks.
2325 *
2326 * @param soap
2327 * @param req
2328 * @param resp
2329 * @return
2330 */
2331int __vbox__IManagedObjectRef_USCORErelease(
2332 struct soap *soap,
2333 _vbox__IManagedObjectRef_USCORErelease *req,
2334 _vbox__IManagedObjectRef_USCOREreleaseResponse *resp)
2335{
2336 RT_NOREF(resp);
2337 HRESULT hrc;
2338 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2339
2340 {
2341 // findRefFromId and the delete call below require the lock
2342 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2343
2344 ManagedObjectRef *pRef;
2345 hrc = ManagedObjectRef::findRefFromId(req->_USCOREthis, &pRef, false);
2346 if (hrc == S_OK)
2347 {
2348 WEBDEBUG((" found reference; deleting!\n"));
2349 // this removes the object from all stacks; since
2350 // there's a ComPtr<> hidden inside the reference,
2351 // this should also invoke Release() on the COM
2352 // object
2353 delete pRef;
2354 }
2355 else
2356 RaiseSoapInvalidObjectFault(soap, req->_USCOREthis);
2357 }
2358
2359 WEBDEBUG(("-- leaving %s, hrc: %#lx\n", __FUNCTION__, hrc));
2360 if (FAILED(hrc))
2361 return SOAP_FAULT;
2362 return SOAP_OK;
2363}
2364
2365/****************************************************************************
2366 *
2367 * interface IWebsessionManager
2368 *
2369 ****************************************************************************/
2370
2371/**
2372 * Hard-coded implementation for IWebsessionManager::logon. As opposed to the underlying
2373 * COM API, this is the first method that a webservice client must call before the
2374 * webservice will do anything useful.
2375 *
2376 * This returns a managed object reference to the global IVirtualBox object; into this
2377 * reference a websession ID is encoded which remains constant with all managed object
2378 * references returned by other methods.
2379 *
2380 * When the webservice client is done, it should call IWebsessionManager::logoff. This
2381 * will clean up internally (destroy all remaining managed object references and
2382 * related COM objects used internally).
2383 *
2384 * After logon, an internal timeout ensures that if the webservice client does not
2385 * call any methods, after a configurable number of seconds, the webservice will log
2386 * off the client automatically. This is to ensure that the webservice does not
2387 * drown in managed object references and eventually deny service. Still, it is
2388 * a much better solution, both for performance and cleanliness, for the webservice
2389 * client to clean up itself.
2390 *
2391 * @param soap
2392 * @param req
2393 * @param resp
2394 * @return
2395 */
2396int __vbox__IWebsessionManager_USCORElogon(
2397 struct soap *soap,
2398 _vbox__IWebsessionManager_USCORElogon *req,
2399 _vbox__IWebsessionManager_USCORElogonResponse *resp)
2400{
2401 RT_NOREF(soap);
2402 HRESULT hrc = S_OK;
2403 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2404
2405 do
2406 {
2407 // WebServiceSession constructor tinkers with global MOR map and requires a write lock
2408 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2409
2410 // create new websession; the constructor stores the new websession
2411 // in the global map automatically
2412 WebServiceSession *pWebsession = new WebServiceSession();
2413 ComPtr<IVirtualBox> pVirtualBox;
2414
2415 // authenticate the user
2416 if (!(pWebsession->authenticate(req->username.c_str(),
2417 req->password.c_str(),
2418 pVirtualBox.asOutParam())))
2419 {
2420 // fake up a "root" MOR for this websession
2421 char sz[34];
2422 MakeManagedObjectRef(sz, pWebsession->getID(), 0ULL);
2423 WSDLT_ID id = sz;
2424
2425 // in the new websession, create a managed object reference (MOR) for the
2426 // global VirtualBox object; this encodes the websession ID in the MOR so
2427 // that it will be implicitly be included in all future requests of this
2428 // webservice client
2429 resp->returnval = createOrFindRefFromComPtr(id, g_pcszIVirtualBox, pVirtualBox);
2430 WEBDEBUG(("VirtualBox object ref is %s\n", resp->returnval.c_str()));
2431 }
2432 else
2433 hrc = E_FAIL;
2434 } while (0);
2435
2436 WEBDEBUG(("-- leaving %s, hrc: %#lx\n", __FUNCTION__, hrc));
2437 if (FAILED(hrc))
2438 return SOAP_FAULT;
2439 return SOAP_OK;
2440}
2441
2442/**
2443 * Returns a new ISession object every time.
2444 *
2445 * No longer connected in any way to logons, one websession can easily
2446 * handle multiple sessions.
2447 */
2448int __vbox__IWebsessionManager_USCOREgetSessionObject(
2449 struct soap*,
2450 _vbox__IWebsessionManager_USCOREgetSessionObject *req,
2451 _vbox__IWebsessionManager_USCOREgetSessionObjectResponse *resp)
2452{
2453 HRESULT hrc = S_OK;
2454 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2455
2456 do
2457 {
2458 // create a new ISession object
2459 ComPtr<ISession> pSession;
2460 hrc = g_pVirtualBoxClient->COMGETTER(Session)(pSession.asOutParam());
2461 if (FAILED(hrc))
2462 {
2463 WEBDEBUG(("ERROR: cannot create session object!"));
2464 break;
2465 }
2466
2467 // return its MOR
2468 resp->returnval = createOrFindRefFromComPtr(req->refIVirtualBox, g_pcszISession, pSession);
2469 WEBDEBUG(("Session object ref is %s\n", resp->returnval.c_str()));
2470 } while (0);
2471
2472 WEBDEBUG(("-- leaving %s, hrc: %#lx\n", __FUNCTION__, hrc));
2473 if (FAILED(hrc))
2474 return SOAP_FAULT;
2475 return SOAP_OK;
2476}
2477
2478/**
2479 * hard-coded implementation for IWebsessionManager::logoff.
2480 *
2481 * @param req
2482 * @param resp
2483 * @return
2484 */
2485int __vbox__IWebsessionManager_USCORElogoff(
2486 struct soap*,
2487 _vbox__IWebsessionManager_USCORElogoff *req,
2488 _vbox__IWebsessionManager_USCORElogoffResponse *resp)
2489{
2490 RT_NOREF(resp);
2491 HRESULT hrc = S_OK;
2492 WEBDEBUG(("-- entering %s\n", __FUNCTION__));
2493
2494 {
2495 // findWebsessionFromRef and the websession destructor require the lock
2496 util::AutoWriteLock lock(g_pWebsessionsLockHandle COMMA_LOCKVAL_SRC_POS);
2497
2498 WebServiceSession *pWebsession = WebServiceSession::findWebsessionFromRef(req->refIVirtualBox);
2499 if (pWebsession)
2500 {
2501 WEBDEBUG(("websession logoff, deleting websession %#llx\n", pWebsession->getID()));
2502 delete pWebsession;
2503 // destructor cleans up
2504
2505 WEBDEBUG(("websession destroyed, %d websessions left open\n", g_mapWebsessions.size()));
2506 }
2507 }
2508
2509 WEBDEBUG(("-- leaving %s, hrc: %#lx\n", __FUNCTION__, hrc));
2510 if (FAILED(hrc))
2511 return SOAP_FAULT;
2512 return SOAP_OK;
2513}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette