VirtualBox

source: vbox/trunk/src/VBox/HostServices/GuestProperties/service.cpp@ 28417

Last change on this file since 28417 was 27954, checked in by vboxsync, 15 years ago

HostServices/GuestProperties: do not send an update notification if the value and flags of a property have not changed

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 42.9 KB
Line 
1/* $Id: service.cpp 27954 2010-04-01 21:09:23Z vboxsync $ */
2/** @file
3 * Guest Property Service: Host service entry points.
4 */
5
6/*
7 * Copyright (C) 2008 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22/** @page pg_svc_guest_properties Guest Property HGCM Service
23 *
24 * This HGCM service allows the guest to set and query values in a property
25 * store on the host. The service proxies the guest requests to the service
26 * owner on the host using a request callback provided by the owner, and is
27 * notified of changes to properties made by the host. It forwards these
28 * notifications to clients in the guest which have expressed interest and
29 * are waiting for notification.
30 *
31 * The service currently consists of two threads. One of these is the main
32 * HGCM service thread which deals with requests from the guest and from the
33 * host. The second thread sends the host asynchronous notifications of
34 * changes made by the guest and deals with notification timeouts.
35 *
36 * Guest requests to wait for notification are added to a list of open
37 * notification requests and completed when a corresponding guest property
38 * is changed or when the request times out.
39 */
40
41/*******************************************************************************
42* Header Files *
43*******************************************************************************/
44#define LOG_GROUP LOG_GROUP_HGCM
45#include <VBox/HostServices/GuestPropertySvc.h>
46
47#include <VBox/log.h>
48#include <iprt/asm.h>
49#include <iprt/assert.h>
50#include <iprt/cpp/autores.h>
51#include <iprt/cpp/utils.h>
52#include <iprt/err.h>
53#include <iprt/mem.h>
54#include <iprt/req.h>
55#include <iprt/string.h>
56#include <iprt/thread.h>
57#include <iprt/time.h>
58
59#include <memory> /* for auto_ptr */
60#include <string>
61#include <list>
62
63namespace guestProp {
64
65/**
66 * Structure for holding a property
67 */
68struct Property
69{
70 /** The name of the property */
71 std::string mName;
72 /** The property value */
73 std::string mValue;
74 /** The timestamp of the property */
75 uint64_t mTimestamp;
76 /** The property flags */
77 uint32_t mFlags;
78
79 /** Default constructor */
80 Property() : mTimestamp(0), mFlags(NILFLAG) {}
81 /** Constructor with const char * */
82 Property(const char *pcszName, const char *pcszValue,
83 uint64_t u64Timestamp, uint32_t u32Flags)
84 : mName(pcszName), mValue(pcszValue), mTimestamp(u64Timestamp),
85 mFlags(u32Flags) {}
86 /** Constructor with std::string */
87 Property(std::string name, std::string value, uint64_t u64Timestamp,
88 uint32_t u32Flags)
89 : mName(name), mValue(value), mTimestamp(u64Timestamp),
90 mFlags(u32Flags) {}
91
92 /** Does the property name match one of a set of patterns? */
93 bool Matches(const char *pszPatterns) const
94 {
95 return ( pszPatterns[0] == '\0' /* match all */
96 || RTStrSimplePatternMultiMatch(pszPatterns, RTSTR_MAX,
97 mName.c_str(), RTSTR_MAX,
98 NULL)
99 );
100 }
101
102 /** Are two properties equal? */
103 bool operator== (const Property &prop)
104 {
105 return ( mName == prop.mName
106 && mValue == prop.mValue
107 && mTimestamp == prop.mTimestamp
108 && mFlags == prop.mFlags
109 );
110 }
111
112 /* Is the property nil? */
113 bool isNull()
114 {
115 return mName.empty();
116 }
117};
118/** The properties list type */
119typedef std::list <Property> PropertyList;
120
121/**
122 * Structure for holding an uncompleted guest call
123 */
124struct GuestCall
125{
126 /** The call handle */
127 VBOXHGCMCALLHANDLE mHandle;
128 /** The function that was requested */
129 uint32_t mFunction;
130 /** The call parameters */
131 VBOXHGCMSVCPARM *mParms;
132 /** The default return value, used for passing warnings */
133 int mRc;
134
135 /** The standard constructor */
136 GuestCall() : mFunction(0) {}
137 /** The normal contructor */
138 GuestCall(VBOXHGCMCALLHANDLE aHandle, uint32_t aFunction,
139 VBOXHGCMSVCPARM aParms[], int aRc)
140 : mHandle(aHandle), mFunction(aFunction), mParms(aParms),
141 mRc(aRc) {}
142};
143/** The guest call list type */
144typedef std::list <GuestCall> CallList;
145
146/**
147 * Class containing the shared information service functionality.
148 */
149class Service : public stdx::non_copyable
150{
151private:
152 /** Type definition for use in callback functions */
153 typedef Service SELF;
154 /** HGCM helper functions. */
155 PVBOXHGCMSVCHELPERS mpHelpers;
156 /** Global flags for the service */
157 ePropFlags meGlobalFlags;
158 /** The property list */
159 PropertyList mProperties;
160 /** The list of property changes for guest notifications */
161 PropertyList mGuestNotifications;
162 /** The list of outstanding guest notification calls */
163 CallList mGuestWaiters;
164 /** @todo we should have classes for thread and request handler thread */
165 /** Callback function supplied by the host for notification of updates
166 * to properties */
167 PFNHGCMSVCEXT mpfnHostCallback;
168 /** User data pointer to be supplied to the host callback function */
169 void *mpvHostData;
170
171 /**
172 * Get the next property change notification from the queue of saved
173 * notification based on the timestamp of the last notification seen.
174 * Notifications will only be reported if the property name matches the
175 * pattern given.
176 *
177 * @returns iprt status value
178 * @returns VWRN_NOT_FOUND if the last notification was not found in the queue
179 * @param pszPatterns the patterns to match the property name against
180 * @param u64Timestamp the timestamp of the last notification
181 * @param pProp where to return the property found. If none is
182 * found this will be set to nil.
183 * @thread HGCM
184 */
185 int getOldNotification(const char *pszPatterns, uint64_t u64Timestamp,
186 Property *pProp)
187 {
188 AssertPtrReturn(pszPatterns, VERR_INVALID_POINTER);
189 /* Zero means wait for a new notification. */
190 AssertReturn(u64Timestamp != 0, VERR_INVALID_PARAMETER);
191 AssertPtrReturn(pProp, VERR_INVALID_POINTER);
192 int rc = getOldNotificationInternal(pszPatterns, u64Timestamp, pProp);
193#ifdef VBOX_STRICT
194 /*
195 * ENSURE that pProp is the first event in the notification queue that:
196 * - Appears later than u64Timestamp
197 * - Matches the pszPatterns
198 */
199 PropertyList::const_iterator it = mGuestNotifications.begin();
200 for (; it != mGuestNotifications.end()
201 && it->mTimestamp != u64Timestamp; ++it) {}
202 if (it == mGuestNotifications.end()) /* Not found */
203 it = mGuestNotifications.begin();
204 else
205 ++it; /* Next event */
206 for (; it != mGuestNotifications.end()
207 && it->mTimestamp != pProp->mTimestamp; ++it)
208 Assert(!it->Matches(pszPatterns));
209 if (pProp->mTimestamp != 0)
210 {
211 Assert(*pProp == *it);
212 Assert(pProp->Matches(pszPatterns));
213 }
214#endif /* VBOX_STRICT */
215 return rc;
216 }
217
218 /**
219 * Check whether we have permission to change a property.
220 *
221 * @returns Strict VBox status code.
222 * @retval VINF_SUCCESS if we do.
223 * @retval VERR_PERMISSION_DENIED if the value is read-only for the requesting
224 * side.
225 * @retval VINF_PERMISSION_DENIED if the side is globally marked read-only.
226 *
227 * @param eFlags the flags on the property in question
228 * @param isGuest is the guest or the host trying to make the change?
229 */
230 int checkPermission(ePropFlags eFlags, bool isGuest)
231 {
232 if (eFlags & (isGuest ? RDONLYGUEST : RDONLYHOST))
233 return VERR_PERMISSION_DENIED;
234 if (isGuest && (meGlobalFlags & RDONLYGUEST))
235 return VINF_PERMISSION_DENIED;
236 return VINF_SUCCESS;
237 }
238
239public:
240 explicit Service(PVBOXHGCMSVCHELPERS pHelpers)
241 : mpHelpers(pHelpers)
242 , meGlobalFlags(NILFLAG)
243 , mpfnHostCallback(NULL)
244 , mpvHostData(NULL)
245 { }
246
247 /**
248 * @copydoc VBOXHGCMSVCHELPERS::pfnUnload
249 * Simply deletes the service object
250 */
251 static DECLCALLBACK(int) svcUnload (void *pvService)
252 {
253 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
254 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
255 int rc = pSelf->uninit();
256 AssertRC(rc);
257 if (RT_SUCCESS(rc))
258 delete pSelf;
259 return rc;
260 }
261
262 /**
263 * @copydoc VBOXHGCMSVCHELPERS::pfnConnect
264 * Stub implementation of pfnConnect and pfnDisconnect.
265 */
266 static DECLCALLBACK(int) svcConnectDisconnect (void * /* pvService */,
267 uint32_t /* u32ClientID */,
268 void * /* pvClient */)
269 {
270 return VINF_SUCCESS;
271 }
272
273 /**
274 * @copydoc VBOXHGCMSVCHELPERS::pfnCall
275 * Wraps to the call member function
276 */
277 static DECLCALLBACK(void) svcCall (void * pvService,
278 VBOXHGCMCALLHANDLE callHandle,
279 uint32_t u32ClientID,
280 void *pvClient,
281 uint32_t u32Function,
282 uint32_t cParms,
283 VBOXHGCMSVCPARM paParms[])
284 {
285 AssertLogRelReturnVoid(VALID_PTR(pvService));
286 LogFlowFunc (("pvService=%p, callHandle=%p, u32ClientID=%u, pvClient=%p, u32Function=%u, cParms=%u, paParms=%p\n", pvService, callHandle, u32ClientID, pvClient, u32Function, cParms, paParms));
287 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
288 pSelf->call(callHandle, u32ClientID, pvClient, u32Function, cParms, paParms);
289 LogFlowFunc (("returning\n"));
290 }
291
292 /**
293 * @copydoc VBOXHGCMSVCHELPERS::pfnHostCall
294 * Wraps to the hostCall member function
295 */
296 static DECLCALLBACK(int) svcHostCall (void *pvService,
297 uint32_t u32Function,
298 uint32_t cParms,
299 VBOXHGCMSVCPARM paParms[])
300 {
301 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
302 LogFlowFunc (("pvService=%p, u32Function=%u, cParms=%u, paParms=%p\n", pvService, u32Function, cParms, paParms));
303 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
304 int rc = pSelf->hostCall(u32Function, cParms, paParms);
305 LogFlowFunc (("rc=%Rrc\n", rc));
306 return rc;
307 }
308
309 /**
310 * @copydoc VBOXHGCMSVCHELPERS::pfnRegisterExtension
311 * Installs a host callback for notifications of property changes.
312 */
313 static DECLCALLBACK(int) svcRegisterExtension (void *pvService,
314 PFNHGCMSVCEXT pfnExtension,
315 void *pvExtension)
316 {
317 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
318 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
319 pSelf->mpfnHostCallback = pfnExtension;
320 pSelf->mpvHostData = pvExtension;
321 return VINF_SUCCESS;
322 }
323private:
324 static DECLCALLBACK(int) reqThreadFn(RTTHREAD ThreadSelf, void *pvUser);
325 int validateName(const char *pszName, uint32_t cbName);
326 int validateValue(const char *pszValue, uint32_t cbValue);
327 int setPropertyBlock(uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
328 int getProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
329 int setProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool isGuest);
330 int delProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool isGuest);
331 int enumProps(uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
332 int getNotification(VBOXHGCMCALLHANDLE callHandle, uint32_t cParms,
333 VBOXHGCMSVCPARM paParms[]);
334 int getOldNotificationInternal(const char *pszPattern,
335 uint64_t u64Timestamp, Property *pProp);
336 int getNotificationWriteOut(VBOXHGCMSVCPARM paParms[], Property prop);
337 void doNotifications(const char *pszProperty, uint64_t u64Timestamp);
338 int notifyHost(const char *pszName, const char *pszValue,
339 uint64_t u64Timestamp, const char *pszFlags);
340
341 void call (VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID,
342 void *pvClient, uint32_t eFunction, uint32_t cParms,
343 VBOXHGCMSVCPARM paParms[]);
344 int hostCall (uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
345 int uninit ();
346};
347
348
349/**
350 * Check that a string fits our criteria for a property name.
351 *
352 * @returns IPRT status code
353 * @param pszName the string to check, must be valid Utf8
354 * @param cbName the number of bytes @a pszName points to, including the
355 * terminating '\0'
356 * @thread HGCM
357 */
358int Service::validateName(const char *pszName, uint32_t cbName)
359{
360 LogFlowFunc(("cbName=%d\n", cbName));
361 int rc = VINF_SUCCESS;
362 if (RT_SUCCESS(rc) && (cbName < 2))
363 rc = VERR_INVALID_PARAMETER;
364 for (unsigned i = 0; RT_SUCCESS(rc) && i < cbName; ++i)
365 if (pszName[i] == '*' || pszName[i] == '?' || pszName[i] == '|')
366 rc = VERR_INVALID_PARAMETER;
367 LogFlowFunc(("returning %Rrc\n", rc));
368 return rc;
369}
370
371
372/**
373 * Check a string fits our criteria for the value of a guest property.
374 *
375 * @returns IPRT status code
376 * @param pszValue the string to check, must be valid Utf8
377 * @param cbValue the length in bytes of @a pszValue, including the
378 * terminator
379 * @thread HGCM
380 */
381int Service::validateValue(const char *pszValue, uint32_t cbValue)
382{
383 LogFlowFunc(("cbValue=%d\n", cbValue));
384
385 int rc = VINF_SUCCESS;
386 if (RT_SUCCESS(rc) && cbValue == 0)
387 rc = VERR_INVALID_PARAMETER;
388 if (RT_SUCCESS(rc))
389 LogFlow((" pszValue=%s\n", cbValue > 0 ? pszValue : NULL));
390 LogFlowFunc(("returning %Rrc\n", rc));
391 return rc;
392}
393
394/**
395 * Set a block of properties in the property registry, checking the validity
396 * of the arguments passed.
397 *
398 * @returns iprt status value
399 * @param cParms the number of HGCM parameters supplied
400 * @param paParms the array of HGCM parameters
401 * @thread HGCM
402 */
403int Service::setPropertyBlock(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
404{
405 char **ppNames, **ppValues, **ppFlags;
406 uint64_t *pTimestamps;
407 uint32_t cbDummy;
408 int rc = VINF_SUCCESS;
409
410 /*
411 * Get and validate the parameters
412 */
413 if ( (cParms != 4)
414 || RT_FAILURE(paParms[0].getPointer ((void **) &ppNames, &cbDummy))
415 || RT_FAILURE(paParms[1].getPointer ((void **) &ppValues, &cbDummy))
416 || RT_FAILURE(paParms[2].getPointer ((void **) &pTimestamps, &cbDummy))
417 || RT_FAILURE(paParms[3].getPointer ((void **) &ppFlags, &cbDummy))
418 )
419 rc = VERR_INVALID_PARAMETER;
420
421 /*
422 * Add the properties to the end of the list. If we succeed then we
423 * will remove duplicates afterwards.
424 */
425 /* Remember the last property before we started adding, for rollback or
426 * cleanup. */
427 PropertyList::iterator itEnd = mProperties.end();
428 if (!mProperties.empty())
429 --itEnd;
430 try
431 {
432 for (unsigned i = 0; RT_SUCCESS(rc) && ppNames[i] != NULL; ++i)
433 {
434 uint32_t fFlags;
435 if ( !VALID_PTR(ppNames[i])
436 || !VALID_PTR(ppValues[i])
437 || !VALID_PTR(ppFlags[i])
438 )
439 rc = VERR_INVALID_POINTER;
440 if (RT_SUCCESS(rc))
441 rc = validateFlags(ppFlags[i], &fFlags);
442 if (RT_SUCCESS(rc))
443 mProperties.push_back(Property(ppNames[i], ppValues[i],
444 pTimestamps[i], fFlags));
445 }
446 }
447 catch (std::bad_alloc)
448 {
449 rc = VERR_NO_MEMORY;
450 }
451
452 /*
453 * If all went well then remove the duplicate elements.
454 */
455 if (RT_SUCCESS(rc) && itEnd != mProperties.end())
456 {
457 ++itEnd;
458 for (unsigned i = 0; ppNames[i] != NULL; ++i)
459 for (PropertyList::iterator it = mProperties.begin(); it != itEnd; ++it)
460 if (it->mName.compare(ppNames[i]) == 0)
461 {
462 mProperties.erase(it);
463 break;
464 }
465 }
466
467 /*
468 * If something went wrong then rollback. This is possible because we
469 * haven't deleted anything yet.
470 */
471 if (RT_FAILURE(rc))
472 {
473 if (itEnd != mProperties.end())
474 ++itEnd;
475 mProperties.erase(itEnd, mProperties.end());
476 }
477 return rc;
478}
479
480/**
481 * Retrieve a value from the property registry by name, checking the validity
482 * of the arguments passed. If the guest has not allocated enough buffer
483 * space for the value then we return VERR_OVERFLOW and set the size of the
484 * buffer needed in the "size" HGCM parameter. If the name was not found at
485 * all, we return VERR_NOT_FOUND.
486 *
487 * @returns iprt status value
488 * @param cParms the number of HGCM parameters supplied
489 * @param paParms the array of HGCM parameters
490 * @thread HGCM
491 */
492int Service::getProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
493{
494 int rc = VINF_SUCCESS;
495 const char *pcszName = NULL; /* shut up gcc */
496 char *pchBuf;
497 uint32_t cchName, cchBuf;
498 char szFlags[MAX_FLAGS_LEN];
499
500 /*
501 * Get and validate the parameters
502 */
503 LogFlowThisFunc(("\n"));
504 if ( cParms != 4 /* Hardcoded value as the next lines depend on it. */
505 || RT_FAILURE (paParms[0].getString(&pcszName, &cchName)) /* name */
506 || RT_FAILURE (paParms[1].getBuffer((void **) &pchBuf, &cchBuf)) /* buffer */
507 )
508 rc = VERR_INVALID_PARAMETER;
509 else
510 rc = validateName(pcszName, cchName);
511
512 /*
513 * Read and set the values we will return
514 */
515
516 /* Get the value size */
517 PropertyList::const_iterator it;
518 if (RT_SUCCESS(rc))
519 {
520 rc = VERR_NOT_FOUND;
521 for (it = mProperties.begin(); it != mProperties.end(); ++it)
522 if (it->mName.compare(pcszName) == 0)
523 {
524 rc = VINF_SUCCESS;
525 break;
526 }
527 }
528 if (RT_SUCCESS(rc))
529 rc = writeFlags(it->mFlags, szFlags);
530 if (RT_SUCCESS(rc))
531 {
532 /* Check that the buffer is big enough */
533 size_t cchBufActual = it->mValue.size() + 1 + strlen(szFlags);
534 paParms[3].setUInt32 ((uint32_t)cchBufActual);
535 if (cchBufActual <= cchBuf)
536 {
537 /* Write the value, flags and timestamp */
538 it->mValue.copy(pchBuf, cchBuf, 0);
539 pchBuf[it->mValue.size()] = '\0'; /* Terminate the value */
540 strcpy(pchBuf + it->mValue.size() + 1, szFlags);
541 paParms[2].setUInt64 (it->mTimestamp);
542
543 /*
544 * Done! Do exit logging and return.
545 */
546 Log2(("Queried string %s, value=%s, timestamp=%lld, flags=%s\n",
547 pcszName, it->mValue.c_str(), it->mTimestamp, szFlags));
548 }
549 else
550 rc = VERR_BUFFER_OVERFLOW;
551 }
552
553 LogFlowThisFunc(("rc = %Rrc\n", rc));
554 return rc;
555}
556
557/**
558 * Set a value in the property registry by name, checking the validity
559 * of the arguments passed.
560 *
561 * @returns iprt status value
562 * @param cParms the number of HGCM parameters supplied
563 * @param paParms the array of HGCM parameters
564 * @param isGuest is this call coming from the guest (or the host)?
565 * @throws std::bad_alloc if an out of memory condition occurs
566 * @thread HGCM
567 */
568int Service::setProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool isGuest)
569{
570 int rc = VINF_SUCCESS;
571 const char *pcszName = NULL; /* shut up gcc */
572 const char *pcszValue = NULL; /* ditto */
573 const char *pcszFlags = NULL;
574 uint32_t cchName = 0; /* ditto */
575 uint32_t cchValue = 0; /* ditto */
576 uint32_t cchFlags = 0;
577 uint32_t fFlags = NILFLAG;
578 RTTIMESPEC time;
579 uint64_t u64TimeNano = RTTimeSpecGetNano(RTTimeNow(&time));
580 bool fNotify = true;
581
582 LogFlowThisFunc(("\n"));
583 /*
584 * First of all, make sure that we won't exceed the maximum number of properties.
585 */
586 if (mProperties.size() >= MAX_PROPS)
587 rc = VERR_TOO_MUCH_DATA;
588
589 /*
590 * General parameter correctness checking.
591 */
592 if ( RT_SUCCESS(rc)
593 && ( (cParms < 2) || (cParms > 3) /* Hardcoded value as the next lines depend on it. */
594 || RT_FAILURE(paParms[0].getString(&pcszName, &cchName)) /* name */
595 || RT_FAILURE(paParms[1].getString(&pcszValue, &cchValue)) /* value */
596 || ( (3 == cParms)
597 && RT_FAILURE(paParms[2].getString(&pcszFlags, &cchFlags)) /* flags */
598 )
599 )
600 )
601 rc = VERR_INVALID_PARAMETER;
602
603 /*
604 * Check the values passed in the parameters for correctness.
605 */
606 if (RT_SUCCESS(rc))
607 rc = validateName(pcszName, cchName);
608 if (RT_SUCCESS(rc))
609 rc = validateValue(pcszValue, cchValue);
610 if ((3 == cParms) && RT_SUCCESS(rc))
611 rc = RTStrValidateEncodingEx(pcszFlags, cchFlags,
612 RTSTR_VALIDATE_ENCODING_ZERO_TERMINATED);
613 if ((3 == cParms) && RT_SUCCESS(rc))
614 rc = validateFlags(pcszFlags, &fFlags);
615 if (RT_SUCCESS(rc))
616 {
617 /*
618 * If the property already exists, check its flags to see if we are allowed
619 * to change it.
620 */
621 PropertyList::iterator it;
622 bool found = false;
623 for (it = mProperties.begin(); it != mProperties.end(); ++it)
624 if (it->mName.compare(pcszName) == 0)
625 {
626 found = true;
627 break;
628 }
629
630 rc = checkPermission(found ? (ePropFlags)it->mFlags : NILFLAG,
631 isGuest);
632 if (rc == VINF_SUCCESS)
633 {
634 /*
635 * Set the actual value
636 */
637 if (found)
638 {
639 if ( !it->mValue.compare(pcszValue)
640 && (it->mFlags == fFlags))
641 fNotify = false;
642 it->mValue = pcszValue;
643 it->mTimestamp = u64TimeNano;
644 it->mFlags = fFlags;
645 }
646 else /* This can throw. No problem as we have nothing to roll back. */
647 mProperties.push_back(Property(pcszName, pcszValue, u64TimeNano, fFlags));
648
649 /*
650 * Send a notification to the host and return.
651 */
652 if (fNotify)
653 doNotifications(pcszName, u64TimeNano);
654 Log2(("Set string %s, rc=%Rrc, value=%s\n", pcszName, rc, pcszValue));
655 }
656 }
657
658 LogFlowThisFunc(("rc = %Rrc\n", rc));
659 return rc;
660}
661
662
663/**
664 * Remove a value in the property registry by name, checking the validity
665 * of the arguments passed.
666 *
667 * @returns iprt status value
668 * @param cParms the number of HGCM parameters supplied
669 * @param paParms the array of HGCM parameters
670 * @param isGuest is this call coming from the guest (or the host)?
671 * @thread HGCM
672 */
673int Service::delProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool isGuest)
674{
675 int rc = VINF_SUCCESS;
676 const char *pcszName = NULL; /* shut up gcc */
677 uint32_t cbName;
678
679 LogFlowThisFunc(("\n"));
680
681 /*
682 * Check the user-supplied parameters.
683 */
684 if ( (cParms == 1) /* Hardcoded value as the next lines depend on it. */
685 && RT_SUCCESS(paParms[0].getString(&pcszName, &cbName)) /* name */
686 )
687 rc = validateName(pcszName, cbName);
688 else
689 rc = VERR_INVALID_PARAMETER;
690 if (RT_SUCCESS(rc))
691 {
692 /*
693 * If the property exists, check its flags to see if we are allowed
694 * to change it.
695 */
696 PropertyList::iterator it;
697 bool found = false;
698 for (it = mProperties.begin(); it != mProperties.end(); ++it)
699 if (it->mName.compare(pcszName) == 0)
700 {
701 found = true;
702 rc = checkPermission((ePropFlags)it->mFlags, isGuest);
703 break;
704 }
705
706 /*
707 * And delete the property if all is well.
708 */
709 if (rc == VINF_SUCCESS && found)
710 {
711 RTTIMESPEC time;
712 uint64_t u64Timestamp = RTTimeSpecGetNano(RTTimeNow(&time));
713 mProperties.erase(it);
714 // if (isGuest) /* Notify the host even for properties that the host
715 // * changed. Less efficient, but ensures consistency. */
716 doNotifications(pcszName, u64Timestamp);
717 }
718 }
719
720 LogFlowThisFunc(("rc = %Rrc\n", rc));
721 return rc;
722}
723
724/**
725 * Enumerate guest properties by mask, checking the validity
726 * of the arguments passed.
727 *
728 * @returns iprt status value
729 * @param cParms the number of HGCM parameters supplied
730 * @param paParms the array of HGCM parameters
731 * @thread HGCM
732 */
733int Service::enumProps(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
734{
735 int rc = VINF_SUCCESS;
736
737 /*
738 * Get the HGCM function arguments.
739 */
740 char *pcchPatterns = NULL, *pchBuf = NULL;
741 uint32_t cchPatterns = 0, cchBuf = 0;
742 LogFlowThisFunc(("\n"));
743 if ( (cParms != 3) /* Hardcoded value as the next lines depend on it. */
744 || RT_FAILURE(paParms[0].getString(&pcchPatterns, &cchPatterns)) /* patterns */
745 || RT_FAILURE(paParms[1].getBuffer((void **) &pchBuf, &cchBuf)) /* return buffer */
746 )
747 rc = VERR_INVALID_PARAMETER;
748 if (RT_SUCCESS(rc) && cchPatterns > MAX_PATTERN_LEN)
749 rc = VERR_TOO_MUCH_DATA;
750
751 /*
752 * First repack the patterns into the format expected by RTStrSimplePatternMatch()
753 */
754 char pszPatterns[MAX_PATTERN_LEN];
755 if (RT_SUCCESS(rc))
756 {
757 for (unsigned i = 0; i < cchPatterns - 1; ++i)
758 if (pcchPatterns[i] != '\0')
759 pszPatterns[i] = pcchPatterns[i];
760 else
761 pszPatterns[i] = '|';
762 pszPatterns[cchPatterns - 1] = '\0';
763 }
764
765 /*
766 * Next enumerate into a temporary buffer. This can throw, but this is
767 * not a problem as we have nothing to roll back.
768 */
769 std::string buffer;
770 for (PropertyList::const_iterator it = mProperties.begin();
771 RT_SUCCESS(rc) && (it != mProperties.end()); ++it)
772 {
773 if (it->Matches(pszPatterns))
774 {
775 char szFlags[MAX_FLAGS_LEN];
776 char szTimestamp[256];
777 uint32_t cchTimestamp;
778 buffer += it->mName;
779 buffer += '\0';
780 buffer += it->mValue;
781 buffer += '\0';
782 cchTimestamp = RTStrFormatNumber(szTimestamp, it->mTimestamp,
783 10, 0, 0, 0);
784 buffer.append(szTimestamp, cchTimestamp);
785 buffer += '\0';
786 rc = writeFlags(it->mFlags, szFlags);
787 if (RT_SUCCESS(rc))
788 buffer += szFlags;
789 buffer += '\0';
790 }
791 }
792 if (RT_SUCCESS(rc))
793 buffer.append(4, '\0'); /* The final terminators */
794
795 /*
796 * Finally write out the temporary buffer to the real one if it is not too
797 * small.
798 */
799 if (RT_SUCCESS(rc))
800 {
801 paParms[2].setUInt32 ((uint32_t)buffer.size());
802 /* Copy the memory if it fits into the guest buffer */
803 if (buffer.size() <= cchBuf)
804 buffer.copy(pchBuf, cchBuf);
805 else
806 rc = VERR_BUFFER_OVERFLOW;
807 }
808 return rc;
809}
810
811
812/** Helper query used by getOldNotification */
813int Service::getOldNotificationInternal(const char *pszPatterns,
814 uint64_t u64Timestamp,
815 Property *pProp)
816{
817 int rc = VINF_SUCCESS;
818 bool warn = false;
819
820 /* We count backwards, as the guest should normally be querying the
821 * most recent events. */
822 PropertyList::reverse_iterator it = mGuestNotifications.rbegin();
823 for (; it->mTimestamp != u64Timestamp && it != mGuestNotifications.rend();
824 ++it) {}
825 /* Warn if the timestamp was not found. */
826 if (it->mTimestamp != u64Timestamp)
827 warn = true;
828 /* Now look for an event matching the patterns supplied. The base()
829 * member conveniently points to the following element. */
830 PropertyList::iterator base = it.base();
831 for (; !base->Matches(pszPatterns) && base != mGuestNotifications.end();
832 ++base) {}
833 if (RT_SUCCESS(rc) && base != mGuestNotifications.end())
834 *pProp = *base;
835 else if (RT_SUCCESS(rc))
836 *pProp = Property();
837 if (warn)
838 rc = VWRN_NOT_FOUND;
839 return rc;
840}
841
842
843/** Helper query used by getNotification */
844int Service::getNotificationWriteOut(VBOXHGCMSVCPARM paParms[], Property prop)
845{
846 int rc = VINF_SUCCESS;
847 /* Format the data to write to the buffer. */
848 std::string buffer;
849 uint64_t u64Timestamp;
850 char *pchBuf;
851 uint32_t cchBuf;
852 rc = paParms[2].getBuffer((void **) &pchBuf, &cchBuf);
853 if (RT_SUCCESS(rc))
854 {
855 char szFlags[MAX_FLAGS_LEN];
856 rc = writeFlags(prop.mFlags, szFlags);
857 if (RT_SUCCESS(rc))
858 {
859 buffer += prop.mName;
860 buffer += '\0';
861 buffer += prop.mValue;
862 buffer += '\0';
863 buffer += szFlags;
864 buffer += '\0';
865 u64Timestamp = prop.mTimestamp;
866 }
867 }
868 /* Write out the data. */
869 if (RT_SUCCESS(rc))
870 {
871 paParms[1].setUInt64(u64Timestamp);
872 paParms[3].setUInt32((uint32_t)buffer.size());
873 if (buffer.size() <= cchBuf)
874 buffer.copy(pchBuf, cchBuf);
875 else
876 rc = VERR_BUFFER_OVERFLOW;
877 }
878 return rc;
879}
880
881
882/**
883 * Get the next guest notification.
884 *
885 * @returns iprt status value
886 * @param cParms the number of HGCM parameters supplied
887 * @param paParms the array of HGCM parameters
888 * @thread HGCM
889 * @throws can throw std::bad_alloc
890 */
891int Service::getNotification(VBOXHGCMCALLHANDLE callHandle, uint32_t cParms,
892 VBOXHGCMSVCPARM paParms[])
893{
894 int rc = VINF_SUCCESS;
895 char *pszPatterns = NULL; /* shut up gcc */
896 char *pchBuf;
897 uint32_t cchPatterns = 0;
898 uint32_t cchBuf = 0;
899 uint64_t u64Timestamp;
900
901 /*
902 * Get the HGCM function arguments and perform basic verification.
903 */
904 LogFlowThisFunc(("\n"));
905 if ( (cParms != 4) /* Hardcoded value as the next lines depend on it. */
906 || RT_FAILURE(paParms[0].getString(&pszPatterns, &cchPatterns)) /* patterns */
907 || RT_FAILURE(paParms[1].getUInt64(&u64Timestamp)) /* timestamp */
908 || RT_FAILURE(paParms[2].getBuffer((void **) &pchBuf, &cchBuf)) /* return buffer */
909 )
910 rc = VERR_INVALID_PARAMETER;
911 if (RT_SUCCESS(rc))
912 LogFlow((" pszPatterns=%s, u64Timestamp=%llu\n", pszPatterns,
913 u64Timestamp));
914
915 /*
916 * If no timestamp was supplied or no notification was found in the queue
917 * of old notifications, enqueue the request in the waiting queue.
918 */
919 Property prop;
920 if (RT_SUCCESS(rc) && u64Timestamp != 0)
921 rc = getOldNotification(pszPatterns, u64Timestamp, &prop);
922 if (RT_SUCCESS(rc) && prop.isNull())
923 {
924 mGuestWaiters.push_back(GuestCall(callHandle, GET_NOTIFICATION,
925 paParms, rc));
926 rc = VINF_HGCM_ASYNC_EXECUTE;
927 }
928 /*
929 * Otherwise reply at once with the enqueued notification we found.
930 */
931 else
932 {
933 int rc2 = getNotificationWriteOut(paParms, prop);
934 if (RT_FAILURE(rc2))
935 rc = rc2;
936 }
937 return rc;
938}
939
940
941/**
942 * Notify the service owner and the guest that a property has been
943 * added/deleted/changed
944 * @param pszProperty the name of the property which has changed
945 * @param u64Timestamp the time at which the change took place
946 *
947 * @thread HGCM service
948 */
949void Service::doNotifications(const char *pszProperty, uint64_t u64Timestamp)
950{
951 int rc = VINF_SUCCESS;
952
953 AssertPtrReturnVoid(pszProperty);
954 LogFlowThisFunc (("pszProperty=%s, u64Timestamp=%llu\n", pszProperty, u64Timestamp));
955 /* Ensure that our timestamp is different to the last one. */
956 if ( !mGuestNotifications.empty()
957 && u64Timestamp == mGuestNotifications.back().mTimestamp)
958 ++u64Timestamp;
959
960 /*
961 * Try to find the property. Create a change event if we find it and a
962 * delete event if we do not.
963 */
964 Property prop;
965 prop.mName = pszProperty;
966 prop.mTimestamp = u64Timestamp;
967 /* prop is currently a delete event for pszProperty */
968 bool found = false;
969 if (RT_SUCCESS(rc))
970 for (PropertyList::const_iterator it = mProperties.begin();
971 !found && it != mProperties.end(); ++it)
972 if (it->mName.compare(pszProperty) == 0)
973 {
974 found = true;
975 /* Make prop into a change event. */
976 prop.mValue = it->mValue;
977 prop.mFlags = it->mFlags;
978 }
979
980
981 /* Release waiters if applicable and add the event to the queue for
982 * guest notifications */
983 if (RT_SUCCESS(rc))
984 {
985 try
986 {
987 CallList::iterator it = mGuestWaiters.begin();
988 while (it != mGuestWaiters.end())
989 {
990 const char *pszPatterns;
991 uint32_t cchPatterns;
992 it->mParms[0].getString(&pszPatterns, &cchPatterns);
993 if (prop.Matches(pszPatterns))
994 {
995 GuestCall curCall = *it;
996 int rc2 = getNotificationWriteOut(curCall.mParms, prop);
997 if (RT_SUCCESS(rc2))
998 rc2 = curCall.mRc;
999 mpHelpers->pfnCallComplete(curCall.mHandle, rc2);
1000 it = mGuestWaiters.erase(it);
1001 }
1002 else
1003 ++it;
1004 }
1005 mGuestNotifications.push_back(prop);
1006 }
1007 catch (std::bad_alloc)
1008 {
1009 rc = VERR_NO_MEMORY;
1010 }
1011 }
1012 if (mGuestNotifications.size() > MAX_GUEST_NOTIFICATIONS)
1013 mGuestNotifications.pop_front();
1014
1015 /*
1016 * Host notifications - first case: if the property exists then send its
1017 * current value
1018 */
1019 if (found && mpfnHostCallback != NULL)
1020 {
1021 char szFlags[MAX_FLAGS_LEN];
1022 /* Send out a host notification */
1023 const char *pszValue = prop.mValue.c_str();
1024 if (RT_SUCCESS(rc))
1025 rc = writeFlags(prop.mFlags, szFlags);
1026 if (RT_SUCCESS(rc))
1027 rc = notifyHost(pszProperty, pszValue, u64Timestamp, szFlags);
1028 }
1029
1030 /*
1031 * Host notifications - second case: if the property does not exist then
1032 * send the host an empty value
1033 */
1034 if (!found && mpfnHostCallback != NULL)
1035 {
1036 /* Send out a host notification */
1037 if (RT_SUCCESS(rc))
1038 rc = notifyHost(pszProperty, NULL, u64Timestamp, NULL);
1039 }
1040 LogFlowThisFunc (("returning\n"));
1041}
1042
1043/**
1044 * Notify the service owner that a property has been added/deleted/changed.
1045 * @returns IPRT status value
1046 * @param pszName the property name
1047 * @param pszValue the new value, or NULL if the property was deleted
1048 * @param u64Timestamp the time of the change
1049 * @param pszFlags the new flags string
1050 */
1051int Service::notifyHost(const char *pszName, const char *pszValue,
1052 uint64_t u64Timestamp, const char *pszFlags)
1053{
1054 LogFlowFunc (("pszName=%s, pszValue=%s, u64Timestamp=%llu, pszFlags=%s\n",
1055 pszName, pszValue, u64Timestamp, pszFlags));
1056 HOSTCALLBACKDATA HostCallbackData;
1057 HostCallbackData.u32Magic = HOSTCALLBACKMAGIC;
1058 HostCallbackData.pcszName = pszName;
1059 HostCallbackData.pcszValue = pszValue;
1060 HostCallbackData.u64Timestamp = u64Timestamp;
1061 HostCallbackData.pcszFlags = pszFlags;
1062 int rc = mpfnHostCallback (mpvHostData, 0 /*u32Function*/,
1063 (void *)(&HostCallbackData),
1064 sizeof(HostCallbackData));
1065 LogFlowFunc (("returning %Rrc\n", rc));
1066 return rc;
1067}
1068
1069
1070/**
1071 * Handle an HGCM service call.
1072 * @copydoc VBOXHGCMSVCFNTABLE::pfnCall
1073 * @note All functions which do not involve an unreasonable delay will be
1074 * handled synchronously. If needed, we will add a request handler
1075 * thread in future for those which do.
1076 *
1077 * @thread HGCM
1078 */
1079void Service::call (VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID,
1080 void * /* pvClient */, uint32_t eFunction, uint32_t cParms,
1081 VBOXHGCMSVCPARM paParms[])
1082{
1083 int rc = VINF_SUCCESS;
1084 LogFlowFunc(("u32ClientID = %d, fn = %d, cParms = %d, pparms = %d\n",
1085 u32ClientID, eFunction, cParms, paParms));
1086
1087 try
1088 {
1089 switch (eFunction)
1090 {
1091 /* The guest wishes to read a property */
1092 case GET_PROP:
1093 LogFlowFunc(("GET_PROP\n"));
1094 rc = getProperty(cParms, paParms);
1095 break;
1096
1097 /* The guest wishes to set a property */
1098 case SET_PROP:
1099 LogFlowFunc(("SET_PROP\n"));
1100 rc = setProperty(cParms, paParms, true);
1101 break;
1102
1103 /* The guest wishes to set a property value */
1104 case SET_PROP_VALUE:
1105 LogFlowFunc(("SET_PROP_VALUE\n"));
1106 rc = setProperty(cParms, paParms, true);
1107 break;
1108
1109 /* The guest wishes to remove a configuration value */
1110 case DEL_PROP:
1111 LogFlowFunc(("DEL_PROP\n"));
1112 rc = delProperty(cParms, paParms, true);
1113 break;
1114
1115 /* The guest wishes to enumerate all properties */
1116 case ENUM_PROPS:
1117 LogFlowFunc(("ENUM_PROPS\n"));
1118 rc = enumProps(cParms, paParms);
1119 break;
1120
1121 /* The guest wishes to get the next property notification */
1122 case GET_NOTIFICATION:
1123 LogFlowFunc(("GET_NOTIFICATION\n"));
1124 rc = getNotification(callHandle, cParms, paParms);
1125 break;
1126
1127 default:
1128 rc = VERR_NOT_IMPLEMENTED;
1129 }
1130 }
1131 catch (std::bad_alloc)
1132 {
1133 rc = VERR_NO_MEMORY;
1134 }
1135 LogFlowFunc(("rc = %Rrc\n", rc));
1136 if (rc != VINF_HGCM_ASYNC_EXECUTE)
1137 {
1138 mpHelpers->pfnCallComplete (callHandle, rc);
1139 }
1140}
1141
1142
1143/**
1144 * Service call handler for the host.
1145 * @copydoc VBOXHGCMSVCFNTABLE::pfnHostCall
1146 * @thread hgcm
1147 */
1148int Service::hostCall (uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1149{
1150 int rc = VINF_SUCCESS;
1151
1152 LogFlowFunc(("fn = %d, cParms = %d, pparms = %d\n",
1153 eFunction, cParms, paParms));
1154
1155 try
1156 {
1157 switch (eFunction)
1158 {
1159 /* The host wishes to set a block of properties */
1160 case SET_PROPS_HOST:
1161 LogFlowFunc(("SET_PROPS_HOST\n"));
1162 rc = setPropertyBlock(cParms, paParms);
1163 break;
1164
1165 /* The host wishes to read a configuration value */
1166 case GET_PROP_HOST:
1167 LogFlowFunc(("GET_PROP_HOST\n"));
1168 rc = getProperty(cParms, paParms);
1169 break;
1170
1171 /* The host wishes to set a configuration value */
1172 case SET_PROP_HOST:
1173 LogFlowFunc(("SET_PROP_HOST\n"));
1174 rc = setProperty(cParms, paParms, false);
1175 break;
1176
1177 /* The host wishes to set a configuration value */
1178 case SET_PROP_VALUE_HOST:
1179 LogFlowFunc(("SET_PROP_VALUE_HOST\n"));
1180 rc = setProperty(cParms, paParms, false);
1181 break;
1182
1183 /* The host wishes to remove a configuration value */
1184 case DEL_PROP_HOST:
1185 LogFlowFunc(("DEL_PROP_HOST\n"));
1186 rc = delProperty(cParms, paParms, false);
1187 break;
1188
1189 /* The host wishes to enumerate all properties */
1190 case ENUM_PROPS_HOST:
1191 LogFlowFunc(("ENUM_PROPS\n"));
1192 rc = enumProps(cParms, paParms);
1193 break;
1194
1195 /* The host wishes to set global flags for the service */
1196 case SET_GLOBAL_FLAGS_HOST:
1197 LogFlowFunc(("SET_GLOBAL_FLAGS_HOST\n"));
1198 if (cParms == 1)
1199 {
1200 uint32_t eFlags;
1201 rc = paParms[0].getUInt32(&eFlags);
1202 if (RT_SUCCESS(rc))
1203 meGlobalFlags = (ePropFlags)eFlags;
1204 }
1205 else
1206 rc = VERR_INVALID_PARAMETER;
1207 break;
1208
1209 default:
1210 rc = VERR_NOT_SUPPORTED;
1211 break;
1212 }
1213 }
1214 catch (std::bad_alloc)
1215 {
1216 rc = VERR_NO_MEMORY;
1217 }
1218
1219 LogFlowFunc(("rc = %Rrc\n", rc));
1220 return rc;
1221}
1222
1223int Service::uninit()
1224{
1225 return VINF_SUCCESS;
1226}
1227
1228} /* namespace guestProp */
1229
1230using guestProp::Service;
1231
1232/**
1233 * @copydoc VBOXHGCMSVCLOAD
1234 */
1235extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad (VBOXHGCMSVCFNTABLE *ptable)
1236{
1237 int rc = VINF_SUCCESS;
1238
1239 LogFlowFunc(("ptable = %p\n", ptable));
1240
1241 if (!VALID_PTR(ptable))
1242 {
1243 rc = VERR_INVALID_PARAMETER;
1244 }
1245 else
1246 {
1247 LogFlowFunc(("ptable->cbSize = %d, ptable->u32Version = 0x%08X\n", ptable->cbSize, ptable->u32Version));
1248
1249 if ( ptable->cbSize != sizeof (VBOXHGCMSVCFNTABLE)
1250 || ptable->u32Version != VBOX_HGCM_SVC_VERSION)
1251 {
1252 rc = VERR_VERSION_MISMATCH;
1253 }
1254 else
1255 {
1256 std::auto_ptr<Service> apService;
1257 /* No exceptions may propogate outside. */
1258 try {
1259 apService = std::auto_ptr<Service>(new Service(ptable->pHelpers));
1260 } catch (int rcThrown) {
1261 rc = rcThrown;
1262 } catch (...) {
1263 rc = VERR_UNRESOLVED_ERROR;
1264 }
1265
1266 if (RT_SUCCESS(rc))
1267 {
1268 /* We do not maintain connections, so no client data is needed. */
1269 ptable->cbClient = 0;
1270
1271 ptable->pfnUnload = Service::svcUnload;
1272 ptable->pfnConnect = Service::svcConnectDisconnect;
1273 ptable->pfnDisconnect = Service::svcConnectDisconnect;
1274 ptable->pfnCall = Service::svcCall;
1275 ptable->pfnHostCall = Service::svcHostCall;
1276 ptable->pfnSaveState = NULL; /* The service is stateless, so the normal */
1277 ptable->pfnLoadState = NULL; /* construction done before restoring suffices */
1278 ptable->pfnRegisterExtension = Service::svcRegisterExtension;
1279
1280 /* Service specific initialization. */
1281 ptable->pvService = apService.release();
1282 }
1283 }
1284 }
1285
1286 LogFlowFunc(("returning %Rrc\n", rc));
1287 return rc;
1288}
1289
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