VirtualBox

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

Last change on this file since 75737 was 75737, checked in by vboxsync, 6 years ago

HGCM: Replace C++-style inline members on VBOXHGCMSVCPARM with simple functions.
bugref:9172: Shared folder performance tuning
Changes in bugref:9172 caused a build regression on Ubuntu 18.10 due to the
use of RT_ZERO on a structure containing an embedded VBOXHGCMSVCPARM, as
VBOXHGCMSVCPARM had member functions and was therefore not a simple plain-
old-data structure. Rather than just doing the sensible thing and zeroing
it in a different way, I converted the inline member getters and setters to
standard inline C functions, including fixing callers. Actually I had planned
this for some time, as the member function use seemed a bit gratuitous in
hindsight.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 57.3 KB
Line 
1/* $Id: service.cpp 75737 2018-11-26 15:44:41Z vboxsync $ */
2/** @file
3 * Guest Property Service: Host service entry points.
4 */
5
6/*
7 * Copyright (C) 2008-2017 Oracle Corporation
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
18/** @page pg_svc_guest_properties Guest Property HGCM Service
19 *
20 * This HGCM service allows the guest to set and query values in a property
21 * store on the host. The service proxies the guest requests to the service
22 * owner on the host using a request callback provided by the owner, and is
23 * notified of changes to properties made by the host. It forwards these
24 * notifications to clients in the guest which have expressed interest and
25 * are waiting for notification.
26 *
27 * The service currently consists of two threads. One of these is the main
28 * HGCM service thread which deals with requests from the guest and from the
29 * host. The second thread sends the host asynchronous notifications of
30 * changes made by the guest and deals with notification timeouts.
31 *
32 * Guest requests to wait for notification are added to a list of open
33 * notification requests and completed when a corresponding guest property
34 * is changed or when the request times out.
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#define LOG_GROUP LOG_GROUP_HGCM
42#include <VBox/HostServices/GuestPropertySvc.h>
43
44#include <VBox/log.h>
45#include <iprt/asm.h>
46#include <iprt/assert.h>
47#include <iprt/cpp/autores.h>
48#include <iprt/cpp/utils.h>
49#include <iprt/err.h>
50#include <iprt/mem.h>
51#include <iprt/req.h>
52#include <iprt/string.h>
53#include <iprt/thread.h>
54#include <iprt/time.h>
55#include <VBox/vmm/dbgf.h>
56
57#include <string>
58#include <list>
59
60/** @todo Delete the old !ASYNC_HOST_NOTIFY code and remove this define. */
61#define ASYNC_HOST_NOTIFY
62
63namespace guestProp {
64
65/**
66 * Structure for holding a property
67 */
68struct Property
69{
70 /** The string space core record. */
71 RTSTRSPACECORE mStrCore;
72 /** The name of the property */
73 std::string mName;
74 /** The property value */
75 std::string mValue;
76 /** The timestamp of the property */
77 uint64_t mTimestamp;
78 /** The property flags */
79 uint32_t mFlags;
80
81 /** Default constructor */
82 Property() : mTimestamp(0), mFlags(GUEST_PROP_F_NILFLAG)
83 {
84 RT_ZERO(mStrCore);
85 }
86 /** Constructor with const char * */
87 Property(const char *pcszName, const char *pcszValue,
88 uint64_t u64Timestamp, uint32_t u32Flags)
89 : mName(pcszName), mValue(pcszValue), mTimestamp(u64Timestamp),
90 mFlags(u32Flags)
91 {
92 RT_ZERO(mStrCore);
93 mStrCore.pszString = mName.c_str();
94 }
95 /** Constructor with std::string */
96 Property(std::string name, std::string value, uint64_t u64Timestamp,
97 uint32_t u32Flags)
98 : mName(name), mValue(value), mTimestamp(u64Timestamp),
99 mFlags(u32Flags) {}
100
101 /** Does the property name match one of a set of patterns? */
102 bool Matches(const char *pszPatterns) const
103 {
104 return ( pszPatterns[0] == '\0' /* match all */
105 || RTStrSimplePatternMultiMatch(pszPatterns, RTSTR_MAX,
106 mName.c_str(), RTSTR_MAX,
107 NULL)
108 );
109 }
110
111 /** Are two properties equal? */
112 bool operator==(const Property &prop)
113 {
114 if (mTimestamp != prop.mTimestamp)
115 return false;
116 if (mFlags != prop.mFlags)
117 return false;
118 if (mName != prop.mName)
119 return false;
120 if (mValue != prop.mValue)
121 return false;
122 return true;
123 }
124
125 /* Is the property nil? */
126 bool isNull()
127 {
128 return mName.empty();
129 }
130};
131/** The properties list type */
132typedef std::list <Property> PropertyList;
133
134/**
135 * Structure for holding an uncompleted guest call
136 */
137struct GuestCall
138{
139 uint32_t u32ClientId;
140 /** The call handle */
141 VBOXHGCMCALLHANDLE mHandle;
142 /** The function that was requested */
143 uint32_t mFunction;
144 /** Number of call parameters. */
145 uint32_t mParmsCnt;
146 /** The call parameters */
147 VBOXHGCMSVCPARM *mParms;
148 /** The default return value, used for passing warnings */
149 int mRc;
150
151 /** The standard constructor */
152 GuestCall(void) : u32ClientId(0), mFunction(0), mParmsCnt(0) {}
153 /** The normal constructor */
154 GuestCall(uint32_t aClientId, VBOXHGCMCALLHANDLE aHandle, uint32_t aFunction,
155 uint32_t aParmsCnt, VBOXHGCMSVCPARM aParms[], int aRc)
156 : u32ClientId(aClientId), mHandle(aHandle), mFunction(aFunction),
157 mParmsCnt(aParmsCnt), mParms(aParms), mRc(aRc) {}
158};
159/** The guest call list type */
160typedef std::list <GuestCall> CallList;
161
162/**
163 * Class containing the shared information service functionality.
164 */
165class Service : public RTCNonCopyable
166{
167private:
168 /** Type definition for use in callback functions */
169 typedef Service SELF;
170 /** HGCM helper functions. */
171 PVBOXHGCMSVCHELPERS mpHelpers;
172 /** Global flags for the service */
173 uint32_t mfGlobalFlags;
174 /** The property string space handle. */
175 RTSTRSPACE mhProperties;
176 /** The number of properties. */
177 unsigned mcProperties;
178 /** The list of property changes for guest notifications;
179 * only used for timestamp tracking in notifications at the moment */
180 PropertyList mGuestNotifications;
181 /** The list of outstanding guest notification calls */
182 CallList mGuestWaiters;
183 /** @todo we should have classes for thread and request handler thread */
184 /** Callback function supplied by the host for notification of updates
185 * to properties */
186 PFNHGCMSVCEXT mpfnHostCallback;
187 /** User data pointer to be supplied to the host callback function */
188 void *mpvHostData;
189 /** The previous timestamp.
190 * This is used by getCurrentTimestamp() to decrease the chance of
191 * generating duplicate timestamps. */
192 uint64_t mPrevTimestamp;
193 /** The number of consecutive timestamp adjustments that we've made.
194 * Together with mPrevTimestamp, this defines a set of obsolete timestamp
195 * values: {(mPrevTimestamp - mcTimestampAdjustments), ..., mPrevTimestamp} */
196 uint64_t mcTimestampAdjustments;
197
198 /**
199 * Get the next property change notification from the queue of saved
200 * notification based on the timestamp of the last notification seen.
201 * Notifications will only be reported if the property name matches the
202 * pattern given.
203 *
204 * @returns iprt status value
205 * @returns VWRN_NOT_FOUND if the last notification was not found in the queue
206 * @param pszPatterns the patterns to match the property name against
207 * @param u64Timestamp the timestamp of the last notification
208 * @param pProp where to return the property found. If none is
209 * found this will be set to nil.
210 * @thread HGCM
211 */
212 int getOldNotification(const char *pszPatterns, uint64_t u64Timestamp,
213 Property *pProp)
214 {
215 AssertPtrReturn(pszPatterns, VERR_INVALID_POINTER);
216 /* Zero means wait for a new notification. */
217 AssertReturn(u64Timestamp != 0, VERR_INVALID_PARAMETER);
218 AssertPtrReturn(pProp, VERR_INVALID_POINTER);
219 int rc = getOldNotificationInternal(pszPatterns, u64Timestamp, pProp);
220#ifdef VBOX_STRICT
221 /*
222 * ENSURE that pProp is the first event in the notification queue that:
223 * - Appears later than u64Timestamp
224 * - Matches the pszPatterns
225 */
226 /** @todo r=bird: This incorrectly ASSUMES that mTimestamp is unique.
227 * The timestamp resolution can be very coarse on windows for instance. */
228 PropertyList::const_iterator it = mGuestNotifications.begin();
229 for (; it != mGuestNotifications.end()
230 && it->mTimestamp != u64Timestamp; ++it)
231 {}
232 if (it == mGuestNotifications.end()) /* Not found */
233 it = mGuestNotifications.begin();
234 else
235 ++it; /* Next event */
236 for (; it != mGuestNotifications.end()
237 && it->mTimestamp != pProp->mTimestamp; ++it)
238 Assert(!it->Matches(pszPatterns));
239 if (pProp->mTimestamp != 0)
240 {
241 Assert(*pProp == *it);
242 Assert(pProp->Matches(pszPatterns));
243 }
244#endif /* VBOX_STRICT */
245 return rc;
246 }
247
248 /**
249 * Check whether we have permission to change a property.
250 *
251 * @returns Strict VBox status code.
252 * @retval VINF_SUCCESS if we do.
253 * @retval VERR_PERMISSION_DENIED if the value is read-only for the requesting
254 * side.
255 * @retval VINF_PERMISSION_DENIED if the side is globally marked read-only.
256 *
257 * @param fFlags the flags on the property in question
258 * @param isGuest is the guest or the host trying to make the change?
259 */
260 int checkPermission(uint32_t fFlags, bool isGuest)
261 {
262 if (fFlags & (isGuest ? GUEST_PROP_F_RDONLYGUEST : GUEST_PROP_F_RDONLYHOST))
263 return VERR_PERMISSION_DENIED;
264 if (isGuest && (mfGlobalFlags & GUEST_PROP_F_RDONLYGUEST))
265 return VINF_PERMISSION_DENIED;
266 return VINF_SUCCESS;
267 }
268
269 /**
270 * Check whether the property name is reserved for host changes only.
271 *
272 * @returns Boolean true (host reserved) or false (available to guest).
273 *
274 * @param pszName The property name to check.
275 */
276 bool checkHostReserved(const char *pszName)
277 {
278 if (RTStrStartsWith(pszName, "/VirtualBox/GuestAdd/VBoxService/"))
279 return true;
280 if (RTStrStartsWith(pszName, "/VirtualBox/GuestAdd/PAM/"))
281 return true;
282 if (RTStrStartsWith(pszName, "/VirtualBox/GuestAdd/Greeter/"))
283 return true;
284 if (RTStrStartsWith(pszName, "/VirtualBox/GuestAdd/SharedFolders/"))
285 return true;
286 if (RTStrStartsWith(pszName, "/VirtualBox/HostInfo/"))
287 return true;
288 return false;
289 }
290
291 /**
292 * Gets a property.
293 *
294 * @returns Pointer to the property if found, NULL if not.
295 *
296 * @param pszName The name of the property to get.
297 */
298 Property *getPropertyInternal(const char *pszName)
299 {
300 return (Property *)RTStrSpaceGet(&mhProperties, pszName);
301 }
302
303public:
304 explicit Service(PVBOXHGCMSVCHELPERS pHelpers)
305 : mpHelpers(pHelpers)
306 , mfGlobalFlags(GUEST_PROP_F_NILFLAG)
307 , mhProperties(NULL)
308 , mcProperties(0)
309 , mpfnHostCallback(NULL)
310 , mpvHostData(NULL)
311 , mPrevTimestamp(0)
312 , mcTimestampAdjustments(0)
313#ifdef ASYNC_HOST_NOTIFY
314 , mhThreadNotifyHost(NIL_RTTHREAD)
315 , mhReqQNotifyHost(NIL_RTREQQUEUE)
316#endif
317 { }
318
319 /**
320 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnUnload}
321 * Simply deletes the service object
322 */
323 static DECLCALLBACK(int) svcUnload(void *pvService)
324 {
325 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
326 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
327 int rc = pSelf->uninit();
328 AssertRC(rc);
329 if (RT_SUCCESS(rc))
330 delete pSelf;
331 return rc;
332 }
333
334 /**
335 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnConnect}
336 * Stub implementation of pfnConnect and pfnDisconnect.
337 */
338 static DECLCALLBACK(int) svcConnectDisconnect(void * /* pvService */,
339 uint32_t /* u32ClientID */,
340 void * /* pvClient */)
341 {
342 return VINF_SUCCESS;
343 }
344
345 /**
346 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnCall}
347 * Wraps to the call member function
348 */
349 static DECLCALLBACK(void) svcCall(void * pvService,
350 VBOXHGCMCALLHANDLE callHandle,
351 uint32_t u32ClientID,
352 void *pvClient,
353 uint32_t u32Function,
354 uint32_t cParms,
355 VBOXHGCMSVCPARM paParms[],
356 uint64_t tsArrival)
357 {
358 AssertLogRelReturnVoid(VALID_PTR(pvService));
359 LogFlowFunc(("pvService=%p, callHandle=%p, u32ClientID=%u, pvClient=%p, u32Function=%u, cParms=%u, paParms=%p\n", pvService, callHandle, u32ClientID, pvClient, u32Function, cParms, paParms));
360 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
361 pSelf->call(callHandle, u32ClientID, pvClient, u32Function, cParms, paParms);
362 LogFlowFunc(("returning\n"));
363 RT_NOREF_PV(tsArrival);
364 }
365
366 /**
367 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnHostCall}
368 * Wraps to the hostCall member function
369 */
370 static DECLCALLBACK(int) svcHostCall(void *pvService,
371 uint32_t u32Function,
372 uint32_t cParms,
373 VBOXHGCMSVCPARM paParms[])
374 {
375 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
376 LogFlowFunc(("pvService=%p, u32Function=%u, cParms=%u, paParms=%p\n", pvService, u32Function, cParms, paParms));
377 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
378 int rc = pSelf->hostCall(u32Function, cParms, paParms);
379 LogFlowFunc(("rc=%Rrc\n", rc));
380 return rc;
381 }
382
383 /**
384 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnRegisterExtension}
385 * Installs a host callback for notifications of property changes.
386 */
387 static DECLCALLBACK(int) svcRegisterExtension(void *pvService,
388 PFNHGCMSVCEXT pfnExtension,
389 void *pvExtension)
390 {
391 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
392 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
393 pSelf->mpfnHostCallback = pfnExtension;
394 pSelf->mpvHostData = pvExtension;
395 return VINF_SUCCESS;
396 }
397
398 int initialize();
399
400private:
401 static DECLCALLBACK(int) reqThreadFn(RTTHREAD ThreadSelf, void *pvUser);
402 uint64_t getCurrentTimestamp(void);
403 int validateName(const char *pszName, uint32_t cbName);
404 int validateValue(const char *pszValue, uint32_t cbValue);
405 int setPropertyBlock(uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
406 int getProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
407 int setProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool isGuest);
408 int delProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool isGuest);
409 int enumProps(uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
410 int getNotification(uint32_t u32ClientId, VBOXHGCMCALLHANDLE callHandle, uint32_t cParms,
411 VBOXHGCMSVCPARM paParms[]);
412 int getOldNotificationInternal(const char *pszPattern,
413 uint64_t u64Timestamp, Property *pProp);
414 int getNotificationWriteOut(uint32_t cParms, VBOXHGCMSVCPARM paParms[], Property prop);
415 int doNotifications(const char *pszProperty, uint64_t u64Timestamp);
416 int notifyHost(const char *pszName, const char *pszValue,
417 uint64_t u64Timestamp, const char *pszFlags);
418
419 void call(VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID,
420 void *pvClient, uint32_t eFunction, uint32_t cParms,
421 VBOXHGCMSVCPARM paParms[]);
422 int hostCall(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
423 int uninit();
424 static DECLCALLBACK(void) dbgInfo(void *pvUser, PCDBGFINFOHLP pHlp, const char *pszArgs);
425
426#ifdef ASYNC_HOST_NOTIFY
427 /* Thread for handling host notifications. */
428 RTTHREAD mhThreadNotifyHost;
429 /* Queue for handling requests for notifications. */
430 RTREQQUEUE mhReqQNotifyHost;
431 static DECLCALLBACK(int) threadNotifyHost(RTTHREAD self, void *pvUser);
432#endif
433
434 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(Service);
435};
436
437
438/**
439 * Gets the current timestamp.
440 *
441 * Since the RTTimeNow resolution can be very coarse, this method takes some
442 * simple steps to try avoid returning the same timestamp for two consecutive
443 * calls. Code like getOldNotification() more or less assumes unique
444 * timestamps.
445 *
446 * @returns Nanosecond timestamp.
447 */
448uint64_t Service::getCurrentTimestamp(void)
449{
450 RTTIMESPEC time;
451 uint64_t u64NanoTS = RTTimeSpecGetNano(RTTimeNow(&time));
452 if (mPrevTimestamp - u64NanoTS > mcTimestampAdjustments)
453 mcTimestampAdjustments = 0;
454 else
455 {
456 mcTimestampAdjustments++;
457 u64NanoTS = mPrevTimestamp + 1;
458 }
459 this->mPrevTimestamp = u64NanoTS;
460 return u64NanoTS;
461}
462
463/**
464 * Check that a string fits our criteria for a property name.
465 *
466 * @returns IPRT status code
467 * @param pszName the string to check, must be valid Utf8
468 * @param cbName the number of bytes @a pszName points to, including the
469 * terminating '\0'
470 * @thread HGCM
471 */
472int Service::validateName(const char *pszName, uint32_t cbName)
473{
474 LogFlowFunc(("cbName=%d\n", cbName));
475 int rc = VINF_SUCCESS;
476 if (RT_SUCCESS(rc) && (cbName < 2))
477 rc = VERR_INVALID_PARAMETER;
478 for (unsigned i = 0; RT_SUCCESS(rc) && i < cbName; ++i)
479 if (pszName[i] == '*' || pszName[i] == '?' || pszName[i] == '|')
480 rc = VERR_INVALID_PARAMETER;
481 LogFlowFunc(("returning %Rrc\n", rc));
482 return rc;
483}
484
485
486/**
487 * Check a string fits our criteria for the value of a guest property.
488 *
489 * @returns IPRT status code
490 * @param pszValue the string to check, must be valid Utf8
491 * @param cbValue the length in bytes of @a pszValue, including the
492 * terminator
493 * @thread HGCM
494 */
495int Service::validateValue(const char *pszValue, uint32_t cbValue)
496{
497 LogFlowFunc(("cbValue=%d\n", cbValue)); RT_NOREF1(pszValue);
498
499 int rc = VINF_SUCCESS;
500 if (RT_SUCCESS(rc) && cbValue == 0)
501 rc = VERR_INVALID_PARAMETER;
502 if (RT_SUCCESS(rc))
503 LogFlow((" pszValue=%s\n", cbValue > 0 ? pszValue : NULL));
504 LogFlowFunc(("returning %Rrc\n", rc));
505 return rc;
506}
507
508/**
509 * Set a block of properties in the property registry, checking the validity
510 * of the arguments passed.
511 *
512 * @returns iprt status value
513 * @param cParms the number of HGCM parameters supplied
514 * @param paParms the array of HGCM parameters
515 * @thread HGCM
516 */
517int Service::setPropertyBlock(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
518{
519 const char **papszNames;
520 const char **papszValues;
521 const char **papszFlags;
522 uint64_t *pau64Timestamps;
523 uint32_t cbDummy;
524 int rc = VINF_SUCCESS;
525
526 /*
527 * Get and validate the parameters
528 */
529 if ( cParms != 4
530 || RT_FAILURE(HGCMSvcGetPv(&paParms[0], (void **)&papszNames, &cbDummy))
531 || RT_FAILURE(HGCMSvcGetPv(&paParms[1], (void **)&papszValues, &cbDummy))
532 || RT_FAILURE(HGCMSvcGetPv(&paParms[2], (void **)&pau64Timestamps, &cbDummy))
533 || RT_FAILURE(HGCMSvcGetPv(&paParms[3], (void **)&papszFlags, &cbDummy))
534 )
535 rc = VERR_INVALID_PARAMETER;
536 /** @todo validate the array sizes... */
537 else
538 {
539 for (unsigned i = 0; RT_SUCCESS(rc) && papszNames[i] != NULL; ++i)
540 {
541 if ( !RT_VALID_PTR(papszNames[i])
542 || !RT_VALID_PTR(papszValues[i])
543 || !RT_VALID_PTR(papszFlags[i])
544 )
545 rc = VERR_INVALID_POINTER;
546 else
547 {
548 uint32_t fFlagsIgn;
549 rc = GuestPropValidateFlags(papszFlags[i], &fFlagsIgn);
550 }
551 }
552 if (RT_SUCCESS(rc))
553 {
554 /*
555 * Add the properties. No way to roll back here.
556 */
557 for (unsigned i = 0; papszNames[i] != NULL; ++i)
558 {
559 uint32_t fFlags;
560 rc = GuestPropValidateFlags(papszFlags[i], &fFlags);
561 AssertRCBreak(rc);
562 /*
563 * Handle names which are read-only for the guest.
564 */
565 if (checkHostReserved(papszNames[i]))
566 fFlags |= GUEST_PROP_F_RDONLYGUEST;
567
568 Property *pProp = getPropertyInternal(papszNames[i]);
569 if (pProp)
570 {
571 /* Update existing property. */
572 pProp->mValue = papszValues[i];
573 pProp->mTimestamp = pau64Timestamps[i];
574 pProp->mFlags = fFlags;
575 }
576 else
577 {
578 /* Create a new property */
579 pProp = new Property(papszNames[i], papszValues[i], pau64Timestamps[i], fFlags);
580 if (!pProp)
581 {
582 rc = VERR_NO_MEMORY;
583 break;
584 }
585 if (RTStrSpaceInsert(&mhProperties, &pProp->mStrCore))
586 mcProperties++;
587 else
588 {
589 delete pProp;
590 rc = VERR_INTERNAL_ERROR_3;
591 AssertFailedBreak();
592 }
593 }
594 }
595 }
596 }
597
598 return rc;
599}
600
601/**
602 * Retrieve a value from the property registry by name, checking the validity
603 * of the arguments passed. If the guest has not allocated enough buffer
604 * space for the value then we return VERR_OVERFLOW and set the size of the
605 * buffer needed in the "size" HGCM parameter. If the name was not found at
606 * all, we return VERR_NOT_FOUND.
607 *
608 * @returns iprt status value
609 * @param cParms the number of HGCM parameters supplied
610 * @param paParms the array of HGCM parameters
611 * @thread HGCM
612 */
613int Service::getProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
614{
615 int rc;
616 const char *pcszName = NULL; /* shut up gcc */
617 char *pchBuf = NULL; /* shut up MSC */
618 uint32_t cbName;
619 uint32_t cbBuf = 0; /* shut up MSC */
620
621 /*
622 * Get and validate the parameters
623 */
624 LogFlowThisFunc(("\n"));
625 if ( cParms != 4 /* Hardcoded value as the next lines depend on it. */
626 || RT_FAILURE(HGCMSvcGetCStr(&paParms[0], &pcszName, &cbName)) /* name */
627 || RT_FAILURE(HGCMSvcGetBuf(&paParms[1], (void **)&pchBuf, &cbBuf)) /* buffer */
628 )
629 rc = VERR_INVALID_PARAMETER;
630 else
631 rc = validateName(pcszName, cbName);
632 if (RT_FAILURE(rc))
633 {
634 LogFlowThisFunc(("rc = %Rrc\n", rc));
635 return rc;
636 }
637
638 /*
639 * Read and set the values we will return
640 */
641
642 /* Get the property. */
643 Property *pProp = getPropertyInternal(pcszName);
644 if (pProp)
645 {
646 char szFlags[GUEST_PROP_MAX_FLAGS_LEN];
647 rc = GuestPropWriteFlags(pProp->mFlags, szFlags);
648 if (RT_SUCCESS(rc))
649 {
650 /* Check that the buffer is big enough */
651 size_t const cbFlags = strlen(szFlags) + 1;
652 size_t const cbValue = pProp->mValue.size() + 1;
653 size_t const cbNeeded = cbValue + cbFlags;
654 HGCMSvcSetU32(&paParms[3], (uint32_t)cbNeeded);
655 if (cbBuf >= cbNeeded)
656 {
657 /* Write the value, flags and timestamp */
658 memcpy(pchBuf, pProp->mValue.c_str(), cbValue);
659 memcpy(pchBuf + cbValue, szFlags, cbFlags);
660
661 HGCMSvcSetU64(&paParms[2], pProp->mTimestamp);
662
663 /*
664 * Done! Do exit logging and return.
665 */
666 Log2(("Queried string %s, value=%s, timestamp=%lld, flags=%s\n",
667 pcszName, pProp->mValue.c_str(), pProp->mTimestamp, szFlags));
668 }
669 else
670 rc = VERR_BUFFER_OVERFLOW;
671 }
672 }
673 else
674 rc = VERR_NOT_FOUND;
675
676 LogFlowThisFunc(("rc = %Rrc (%s)\n", rc, pcszName));
677 return rc;
678}
679
680/**
681 * Set a value in the property registry by name, checking the validity
682 * of the arguments passed.
683 *
684 * @returns iprt status value
685 * @param cParms the number of HGCM parameters supplied
686 * @param paParms the array of HGCM parameters
687 * @param isGuest is this call coming from the guest (or the host)?
688 * @throws std::bad_alloc if an out of memory condition occurs
689 * @thread HGCM
690 */
691int Service::setProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool isGuest)
692{
693 int rc = VINF_SUCCESS;
694 const char *pcszName = NULL; /* shut up gcc */
695 const char *pcszValue = NULL; /* ditto */
696 const char *pcszFlags = NULL;
697 uint32_t cchName = 0; /* ditto */
698 uint32_t cchValue = 0; /* ditto */
699 uint32_t cchFlags = 0;
700 uint32_t fFlags = GUEST_PROP_F_NILFLAG;
701 uint64_t u64TimeNano = getCurrentTimestamp();
702
703 LogFlowThisFunc(("\n"));
704
705 /*
706 * General parameter correctness checking.
707 */
708 if ( RT_SUCCESS(rc)
709 && ( (cParms < 2) || (cParms > 3) /* Hardcoded value as the next lines depend on it. */
710 || RT_FAILURE(HGCMSvcGetCStr(&paParms[0], &pcszName, &cchName)) /* name */
711 || RT_FAILURE(HGCMSvcGetCStr(&paParms[1], &pcszValue, &cchValue)) /* value */
712 || ( (3 == cParms)
713 && RT_FAILURE(HGCMSvcGetCStr(&paParms[2], &pcszFlags, &cchFlags)) /* flags */
714 )
715 )
716 )
717 rc = VERR_INVALID_PARAMETER;
718
719 /*
720 * Check the values passed in the parameters for correctness.
721 */
722 if (RT_SUCCESS(rc))
723 rc = validateName(pcszName, cchName);
724 if (RT_SUCCESS(rc))
725 rc = validateValue(pcszValue, cchValue);
726 if ((3 == cParms) && RT_SUCCESS(rc))
727 rc = RTStrValidateEncodingEx(pcszFlags, cchFlags,
728 RTSTR_VALIDATE_ENCODING_ZERO_TERMINATED);
729 if ((3 == cParms) && RT_SUCCESS(rc))
730 rc = GuestPropValidateFlags(pcszFlags, &fFlags);
731 if (RT_FAILURE(rc))
732 {
733 LogFlowThisFunc(("rc = %Rrc\n", rc));
734 return rc;
735 }
736
737 /*
738 * If the property already exists, check its flags to see if we are allowed
739 * to change it.
740 */
741 Property *pProp = getPropertyInternal(pcszName);
742 rc = checkPermission(pProp ? pProp->mFlags : GUEST_PROP_F_NILFLAG, isGuest);
743 /*
744 * Handle names which are read-only for the guest.
745 */
746 if (rc == VINF_SUCCESS && checkHostReserved(pcszName))
747 {
748 if (isGuest)
749 rc = VERR_PERMISSION_DENIED;
750 else
751 fFlags |= GUEST_PROP_F_RDONLYGUEST;
752 }
753 if (rc == VINF_SUCCESS)
754 {
755 /*
756 * Set the actual value
757 */
758 if (pProp)
759 {
760 pProp->mValue = pcszValue;
761 pProp->mTimestamp = u64TimeNano;
762 pProp->mFlags = fFlags;
763 }
764 else if (mcProperties < GUEST_PROP_MAX_PROPS)
765 {
766 try
767 {
768 /* Create a new string space record. */
769 pProp = new Property(pcszName, pcszValue, u64TimeNano, fFlags);
770 AssertPtr(pProp);
771
772 if (RTStrSpaceInsert(&mhProperties, &pProp->mStrCore))
773 mcProperties++;
774 else
775 {
776 AssertFailed();
777 delete pProp;
778
779 rc = VERR_ALREADY_EXISTS;
780 }
781 }
782 catch (std::bad_alloc &)
783 {
784 rc = VERR_NO_MEMORY;
785 }
786 }
787 else
788 rc = VERR_TOO_MUCH_DATA;
789
790 /*
791 * Send a notification to the guest and host and return.
792 */
793 // if (isGuest) /* Notify the host even for properties that the host
794 // * changed. Less efficient, but ensures consistency. */
795 int rc2 = doNotifications(pcszName, u64TimeNano);
796 if (RT_SUCCESS(rc))
797 rc = rc2;
798 }
799
800 LogFlowThisFunc(("%s=%s, rc=%Rrc\n", pcszName, pcszValue, rc));
801 return rc;
802}
803
804
805/**
806 * Remove a value in the property registry by name, checking the validity
807 * of the arguments passed.
808 *
809 * @returns iprt status value
810 * @param cParms the number of HGCM parameters supplied
811 * @param paParms the array of HGCM parameters
812 * @param isGuest is this call coming from the guest (or the host)?
813 * @thread HGCM
814 */
815int Service::delProperty(uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool isGuest)
816{
817 int rc;
818 const char *pcszName = NULL; /* shut up gcc */
819 uint32_t cbName;
820
821 LogFlowThisFunc(("\n"));
822
823 /*
824 * Check the user-supplied parameters.
825 */
826 if ( (cParms == 1) /* Hardcoded value as the next lines depend on it. */
827 && RT_SUCCESS(HGCMSvcGetCStr(&paParms[0], &pcszName, &cbName)) /* name */
828 )
829 rc = validateName(pcszName, cbName);
830 else
831 rc = VERR_INVALID_PARAMETER;
832 if (RT_FAILURE(rc))
833 {
834 LogFlowThisFunc(("rc=%Rrc\n", rc));
835 return rc;
836 }
837
838 /*
839 * If the property exists, check its flags to see if we are allowed
840 * to change it.
841 */
842 Property *pProp = getPropertyInternal(pcszName);
843 if (pProp)
844 rc = checkPermission(pProp->mFlags, isGuest);
845
846 /*
847 * And delete the property if all is well.
848 */
849 if (rc == VINF_SUCCESS && pProp)
850 {
851 uint64_t u64Timestamp = getCurrentTimestamp();
852 PRTSTRSPACECORE pStrCore = RTStrSpaceRemove(&mhProperties, pProp->mStrCore.pszString);
853 AssertPtr(pStrCore); NOREF(pStrCore);
854 mcProperties--;
855 delete pProp;
856 // if (isGuest) /* Notify the host even for properties that the host
857 // * changed. Less efficient, but ensures consistency. */
858 int rc2 = doNotifications(pcszName, u64Timestamp);
859 if (RT_SUCCESS(rc))
860 rc = rc2;
861 }
862
863 LogFlowThisFunc(("%s: rc=%Rrc\n", pcszName, rc));
864 return rc;
865}
866
867/**
868 * Enumeration data shared between enumPropsCallback and Service::enumProps.
869 */
870typedef struct ENUMDATA
871{
872 const char *pszPattern; /**< The pattern to match properties against. */
873 char *pchCur; /**< The current buffer postion. */
874 size_t cbLeft; /**< The amount of available buffer space. */
875 size_t cbNeeded; /**< The amount of needed buffer space. */
876} ENUMDATA;
877
878/**
879 * @callback_method_impl{FNRTSTRSPACECALLBACK}
880 */
881static DECLCALLBACK(int) enumPropsCallback(PRTSTRSPACECORE pStr, void *pvUser)
882{
883 Property *pProp = (Property *)pStr;
884 ENUMDATA *pEnum = (ENUMDATA *)pvUser;
885
886 /* Included in the enumeration? */
887 if (!pProp->Matches(pEnum->pszPattern))
888 return 0;
889
890 /* Convert the non-string members into strings. */
891 char szTimestamp[256];
892 size_t const cbTimestamp = RTStrFormatNumber(szTimestamp, pProp->mTimestamp, 10, 0, 0, 0) + 1;
893
894 char szFlags[GUEST_PROP_MAX_FLAGS_LEN];
895 int rc = GuestPropWriteFlags(pProp->mFlags, szFlags);
896 if (RT_FAILURE(rc))
897 return rc;
898 size_t const cbFlags = strlen(szFlags) + 1;
899
900 /* Calculate the buffer space requirements. */
901 size_t const cbName = pProp->mName.length() + 1;
902 size_t const cbValue = pProp->mValue.length() + 1;
903 size_t const cbRequired = cbName + cbValue + cbTimestamp + cbFlags;
904 pEnum->cbNeeded += cbRequired;
905
906 /* Sufficient buffer space? */
907 if (cbRequired > pEnum->cbLeft)
908 {
909 pEnum->cbLeft = 0;
910 return 0; /* don't quit */
911 }
912 pEnum->cbLeft -= cbRequired;
913
914 /* Append the property to the buffer. */
915 char *pchCur = pEnum->pchCur;
916 pEnum->pchCur += cbRequired;
917
918 memcpy(pchCur, pProp->mName.c_str(), cbName);
919 pchCur += cbName;
920
921 memcpy(pchCur, pProp->mValue.c_str(), cbValue);
922 pchCur += cbValue;
923
924 memcpy(pchCur, szTimestamp, cbTimestamp);
925 pchCur += cbTimestamp;
926
927 memcpy(pchCur, szFlags, cbFlags);
928 pchCur += cbFlags;
929
930 Assert(pchCur == pEnum->pchCur);
931 return 0;
932}
933
934/**
935 * Enumerate guest properties by mask, checking the validity
936 * of the arguments passed.
937 *
938 * @returns iprt status value
939 * @param cParms the number of HGCM parameters supplied
940 * @param paParms the array of HGCM parameters
941 * @thread HGCM
942 */
943int Service::enumProps(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
944{
945 int rc = VINF_SUCCESS;
946
947 /*
948 * Get the HGCM function arguments.
949 */
950 char const *pchPatterns = NULL;
951 char *pchBuf = NULL;
952 uint32_t cbPatterns = 0;
953 uint32_t cbBuf = 0;
954 LogFlowThisFunc(("\n"));
955 if ( (cParms != 3) /* Hardcoded value as the next lines depend on it. */
956 || RT_FAILURE(HGCMSvcGetCStr(&paParms[0], &pchPatterns, &cbPatterns)) /* patterns */
957 || RT_FAILURE(HGCMSvcGetBuf(&paParms[1], (void **)&pchBuf, &cbBuf)) /* return buffer */
958 )
959 rc = VERR_INVALID_PARAMETER;
960 if (RT_SUCCESS(rc) && cbPatterns > GUEST_PROP_MAX_PATTERN_LEN)
961 rc = VERR_TOO_MUCH_DATA;
962
963 /*
964 * First repack the patterns into the format expected by RTStrSimplePatternMatch()
965 */
966 char szPatterns[GUEST_PROP_MAX_PATTERN_LEN];
967 if (RT_SUCCESS(rc))
968 {
969 for (unsigned i = 0; i < cbPatterns - 1; ++i)
970 if (pchPatterns[i] != '\0')
971 szPatterns[i] = pchPatterns[i];
972 else
973 szPatterns[i] = '|';
974 szPatterns[cbPatterns - 1] = '\0';
975 }
976
977 /*
978 * Next enumerate into the buffer.
979 */
980 if (RT_SUCCESS(rc))
981 {
982 ENUMDATA EnumData;
983 EnumData.pszPattern = szPatterns;
984 EnumData.pchCur = pchBuf;
985 EnumData.cbLeft = cbBuf;
986 EnumData.cbNeeded = 0;
987 rc = RTStrSpaceEnumerate(&mhProperties, enumPropsCallback, &EnumData);
988 AssertRCSuccess(rc);
989 if (RT_SUCCESS(rc))
990 {
991 HGCMSvcSetU32(&paParms[2], (uint32_t)(EnumData.cbNeeded + 4));
992 if (EnumData.cbLeft >= 4)
993 {
994 /* The final terminators. */
995 EnumData.pchCur[0] = '\0';
996 EnumData.pchCur[1] = '\0';
997 EnumData.pchCur[2] = '\0';
998 EnumData.pchCur[3] = '\0';
999 }
1000 else
1001 rc = VERR_BUFFER_OVERFLOW;
1002 }
1003 }
1004
1005 return rc;
1006}
1007
1008
1009/** Helper query used by getOldNotification */
1010int Service::getOldNotificationInternal(const char *pszPatterns,
1011 uint64_t u64Timestamp,
1012 Property *pProp)
1013{
1014 /* We count backwards, as the guest should normally be querying the
1015 * most recent events. */
1016 int rc = VWRN_NOT_FOUND;
1017 PropertyList::reverse_iterator it = mGuestNotifications.rbegin();
1018 for (; it != mGuestNotifications.rend(); ++it)
1019 if (it->mTimestamp == u64Timestamp)
1020 {
1021 rc = VINF_SUCCESS;
1022 break;
1023 }
1024
1025 /* Now look for an event matching the patterns supplied. The base()
1026 * member conveniently points to the following element. */
1027 PropertyList::iterator base = it.base();
1028 for (; base != mGuestNotifications.end(); ++base)
1029 if (base->Matches(pszPatterns))
1030 {
1031 *pProp = *base;
1032 return rc;
1033 }
1034 *pProp = Property();
1035 return rc;
1036}
1037
1038
1039/** Helper query used by getNotification */
1040int Service::getNotificationWriteOut(uint32_t cParms, VBOXHGCMSVCPARM paParms[], Property prop)
1041{
1042 AssertReturn(cParms == 4, VERR_INVALID_PARAMETER); /* Basic sanity checking. */
1043
1044 /* Format the data to write to the buffer. */
1045 std::string buffer;
1046 uint64_t u64Timestamp;
1047 char *pchBuf;
1048 uint32_t cbBuf;
1049
1050 int rc = HGCMSvcGetBuf(&paParms[2], (void **)&pchBuf, &cbBuf);
1051 if (RT_SUCCESS(rc))
1052 {
1053 char szFlags[GUEST_PROP_MAX_FLAGS_LEN];
1054 rc = GuestPropWriteFlags(prop.mFlags, szFlags);
1055 if (RT_SUCCESS(rc))
1056 {
1057 buffer += prop.mName;
1058 buffer += '\0';
1059 buffer += prop.mValue;
1060 buffer += '\0';
1061 buffer += szFlags;
1062 buffer += '\0';
1063 u64Timestamp = prop.mTimestamp;
1064
1065 /* Write out the data. */
1066 if (RT_SUCCESS(rc))
1067 {
1068 HGCMSvcSetU64(&paParms[1], u64Timestamp);
1069 HGCMSvcSetU32(&paParms[3], (uint32_t)buffer.size());
1070 if (buffer.size() <= cbBuf)
1071 buffer.copy(pchBuf, cbBuf);
1072 else
1073 rc = VERR_BUFFER_OVERFLOW;
1074 }
1075 }
1076 }
1077 return rc;
1078}
1079
1080
1081/**
1082 * Get the next guest notification.
1083 *
1084 * @returns iprt status value
1085 * @param u32ClientId the client ID
1086 * @param callHandle handle
1087 * @param cParms the number of HGCM parameters supplied
1088 * @param paParms the array of HGCM parameters
1089 * @thread HGCM
1090 * @throws can throw std::bad_alloc
1091 */
1092int Service::getNotification(uint32_t u32ClientId, VBOXHGCMCALLHANDLE callHandle,
1093 uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1094{
1095 int rc = VINF_SUCCESS;
1096 char *pszPatterns = NULL; /* shut up gcc */
1097 char *pchBuf;
1098 uint32_t cchPatterns = 0;
1099 uint32_t cbBuf = 0;
1100 uint64_t u64Timestamp;
1101
1102 /*
1103 * Get the HGCM function arguments and perform basic verification.
1104 */
1105 LogFlowThisFunc(("\n"));
1106 if ( cParms != 4 /* Hardcoded value as the next lines depend on it. */
1107 || RT_FAILURE(HGCMSvcGetStr(&paParms[0], &pszPatterns, &cchPatterns)) /* patterns */
1108 || RT_FAILURE(HGCMSvcGetU64(&paParms[1], &u64Timestamp)) /* timestamp */
1109 || RT_FAILURE(HGCMSvcGetBuf(&paParms[2], (void **)&pchBuf, &cbBuf)) /* return buffer */
1110 )
1111 rc = VERR_INVALID_PARAMETER;
1112 else
1113 {
1114 LogFlow(("pszPatterns=%s, u64Timestamp=%llu\n", pszPatterns, u64Timestamp));
1115
1116 /*
1117 * If no timestamp was supplied or no notification was found in the queue
1118 * of old notifications, enqueue the request in the waiting queue.
1119 */
1120 Property prop;
1121 if (RT_SUCCESS(rc) && u64Timestamp != 0)
1122 rc = getOldNotification(pszPatterns, u64Timestamp, &prop);
1123 if (RT_SUCCESS(rc))
1124 {
1125 if (prop.isNull())
1126 {
1127 /*
1128 * Check if the client already had the same request.
1129 * Complete the old request with an error in this case.
1130 * Protection against clients, which cancel and resubmits requests.
1131 */
1132 CallList::iterator it = mGuestWaiters.begin();
1133 while (it != mGuestWaiters.end())
1134 {
1135 const char *pszPatternsExisting;
1136 uint32_t cchPatternsExisting;
1137 int rc3 = HGCMSvcGetCStr(&it->mParms[0], &pszPatternsExisting, &cchPatternsExisting);
1138
1139 if ( RT_SUCCESS(rc3)
1140 && u32ClientId == it->u32ClientId
1141 && RTStrCmp(pszPatterns, pszPatternsExisting) == 0)
1142 {
1143 /* Complete the old request. */
1144 mpHelpers->pfnCallComplete(it->mHandle, VERR_INTERRUPTED);
1145 it = mGuestWaiters.erase(it);
1146 }
1147 else
1148 ++it;
1149 }
1150
1151 mGuestWaiters.push_back(GuestCall(u32ClientId, callHandle, GUEST_PROP_FN_GET_NOTIFICATION,
1152 cParms, paParms, rc));
1153 rc = VINF_HGCM_ASYNC_EXECUTE;
1154 }
1155 /*
1156 * Otherwise reply at once with the enqueued notification we found.
1157 */
1158 else
1159 {
1160 int rc2 = getNotificationWriteOut(cParms, paParms, prop);
1161 if (RT_FAILURE(rc2))
1162 rc = rc2;
1163 }
1164 }
1165 }
1166
1167 LogFlowThisFunc(("returning rc=%Rrc\n", rc));
1168 return rc;
1169}
1170
1171
1172/**
1173 * Notify the service owner and the guest that a property has been
1174 * added/deleted/changed
1175 * @param pszProperty the name of the property which has changed
1176 * @param u64Timestamp the time at which the change took place
1177 *
1178 * @thread HGCM service
1179 */
1180int Service::doNotifications(const char *pszProperty, uint64_t u64Timestamp)
1181{
1182 AssertPtrReturn(pszProperty, VERR_INVALID_POINTER);
1183 LogFlowThisFunc(("pszProperty=%s, u64Timestamp=%llu\n", pszProperty, u64Timestamp));
1184 /* Ensure that our timestamp is different to the last one. */
1185 if ( !mGuestNotifications.empty()
1186 && u64Timestamp == mGuestNotifications.back().mTimestamp)
1187 ++u64Timestamp;
1188
1189 /*
1190 * Try to find the property. Create a change event if we find it and a
1191 * delete event if we do not.
1192 */
1193 Property prop;
1194 prop.mName = pszProperty;
1195 prop.mTimestamp = u64Timestamp;
1196 /* prop is currently a delete event for pszProperty */
1197 Property const * const pProp = getPropertyInternal(pszProperty);
1198 if (pProp)
1199 {
1200 /* Make prop into a change event. */
1201 prop.mValue = pProp->mValue;
1202 prop.mFlags = pProp->mFlags;
1203 }
1204
1205 /* Release guest waiters if applicable and add the event
1206 * to the queue for guest notifications */
1207 int rc = VINF_SUCCESS;
1208 try
1209 {
1210 CallList::iterator it = mGuestWaiters.begin();
1211 while (it != mGuestWaiters.end())
1212 {
1213 const char *pszPatterns;
1214 uint32_t cchPatterns;
1215 HGCMSvcGetCStr(&it->mParms[0], &pszPatterns, &cchPatterns);
1216 if (prop.Matches(pszPatterns))
1217 {
1218 GuestCall curCall = *it;
1219 int rc2 = getNotificationWriteOut(curCall.mParmsCnt, curCall.mParms, prop);
1220 if (RT_SUCCESS(rc2))
1221 rc2 = curCall.mRc;
1222 mpHelpers->pfnCallComplete(curCall.mHandle, rc2);
1223 it = mGuestWaiters.erase(it);
1224 }
1225 else
1226 ++it;
1227 }
1228
1229 mGuestNotifications.push_back(prop);
1230
1231 /** @todo r=andy This list does not have a purpose but for tracking
1232 * the timestamps ... */
1233 if (mGuestNotifications.size() > GUEST_PROP_MAX_GUEST_NOTIFICATIONS)
1234 mGuestNotifications.pop_front();
1235 }
1236 catch (std::bad_alloc &)
1237 {
1238 rc = VERR_NO_MEMORY;
1239 }
1240
1241 if ( RT_SUCCESS(rc)
1242 && mpfnHostCallback)
1243 {
1244 /*
1245 * Host notifications - first case: if the property exists then send its
1246 * current value
1247 */
1248 if (pProp)
1249 {
1250 char szFlags[GUEST_PROP_MAX_FLAGS_LEN];
1251 /* Send out a host notification */
1252 const char *pszValue = prop.mValue.c_str();
1253 rc = GuestPropWriteFlags(prop.mFlags, szFlags);
1254 if (RT_SUCCESS(rc))
1255 rc = notifyHost(pszProperty, pszValue, u64Timestamp, szFlags);
1256 }
1257 /*
1258 * Host notifications - second case: if the property does not exist then
1259 * send the host an empty value
1260 */
1261 else
1262 {
1263 /* Send out a host notification */
1264 rc = notifyHost(pszProperty, "", u64Timestamp, "");
1265 }
1266 }
1267
1268 LogFlowThisFunc(("returning rc=%Rrc\n", rc));
1269 return rc;
1270}
1271
1272#ifdef ASYNC_HOST_NOTIFY
1273static DECLCALLBACK(void) notifyHostAsyncWorker(PFNHGCMSVCEXT pfnHostCallback,
1274 void *pvHostData,
1275 PGUESTPROPHOSTCALLBACKDATA pHostCallbackData)
1276{
1277 pfnHostCallback(pvHostData, 0 /*u32Function*/,
1278 (void *)pHostCallbackData,
1279 sizeof(GUESTPROPHOSTCALLBACKDATA));
1280 RTMemFree(pHostCallbackData);
1281}
1282#endif
1283
1284/**
1285 * Notify the service owner that a property has been added/deleted/changed.
1286 * @returns IPRT status value
1287 * @param pszName the property name
1288 * @param pszValue the new value, or NULL if the property was deleted
1289 * @param u64Timestamp the time of the change
1290 * @param pszFlags the new flags string
1291 */
1292int Service::notifyHost(const char *pszName, const char *pszValue,
1293 uint64_t u64Timestamp, const char *pszFlags)
1294{
1295 LogFlowFunc(("pszName=%s, pszValue=%s, u64Timestamp=%llu, pszFlags=%s\n",
1296 pszName, pszValue, u64Timestamp, pszFlags));
1297#ifdef ASYNC_HOST_NOTIFY
1298 int rc = VINF_SUCCESS;
1299
1300 /* Allocate buffer for the callback data and strings. */
1301 size_t cbName = pszName? strlen(pszName): 0;
1302 size_t cbValue = pszValue? strlen(pszValue): 0;
1303 size_t cbFlags = pszFlags? strlen(pszFlags): 0;
1304 size_t cbAlloc = sizeof(GUESTPROPHOSTCALLBACKDATA) + cbName + cbValue + cbFlags + 3;
1305 PGUESTPROPHOSTCALLBACKDATA pHostCallbackData = (PGUESTPROPHOSTCALLBACKDATA)RTMemAlloc(cbAlloc);
1306 if (pHostCallbackData)
1307 {
1308 uint8_t *pu8 = (uint8_t *)pHostCallbackData;
1309 pu8 += sizeof(GUESTPROPHOSTCALLBACKDATA);
1310
1311 pHostCallbackData->u32Magic = GUESTPROPHOSTCALLBACKDATA_MAGIC;
1312
1313 pHostCallbackData->pcszName = (const char *)pu8;
1314 memcpy(pu8, pszName, cbName);
1315 pu8 += cbName;
1316 *pu8++ = 0;
1317
1318 pHostCallbackData->pcszValue = (const char *)pu8;
1319 memcpy(pu8, pszValue, cbValue);
1320 pu8 += cbValue;
1321 *pu8++ = 0;
1322
1323 pHostCallbackData->u64Timestamp = u64Timestamp;
1324
1325 pHostCallbackData->pcszFlags = (const char *)pu8;
1326 memcpy(pu8, pszFlags, cbFlags);
1327 pu8 += cbFlags;
1328 *pu8++ = 0;
1329
1330 rc = RTReqQueueCallEx(mhReqQNotifyHost, NULL, 0, RTREQFLAGS_VOID | RTREQFLAGS_NO_WAIT,
1331 (PFNRT)notifyHostAsyncWorker, 3,
1332 mpfnHostCallback, mpvHostData, pHostCallbackData);
1333 if (RT_FAILURE(rc))
1334 {
1335 RTMemFree(pHostCallbackData);
1336 }
1337 }
1338 else
1339 {
1340 rc = VERR_NO_MEMORY;
1341 }
1342#else
1343 GUESTPROPHOSTCALLBACKDATA HostCallbackData;
1344 HostCallbackData.u32Magic = GUESTPROPHOSTCALLBACKDATA_MAGIC;
1345 HostCallbackData.pcszName = pszName;
1346 HostCallbackData.pcszValue = pszValue;
1347 HostCallbackData.u64Timestamp = u64Timestamp;
1348 HostCallbackData.pcszFlags = pszFlags;
1349 int rc = mpfnHostCallback(mpvHostData, 0 /*u32Function*/,
1350 (void *)(&HostCallbackData),
1351 sizeof(HostCallbackData));
1352#endif
1353 LogFlowFunc(("returning rc=%Rrc\n", rc));
1354 return rc;
1355}
1356
1357
1358/**
1359 * Handle an HGCM service call.
1360 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnCall}
1361 * @note All functions which do not involve an unreasonable delay will be
1362 * handled synchronously. If needed, we will add a request handler
1363 * thread in future for those which do.
1364 *
1365 * @thread HGCM
1366 */
1367void Service::call (VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID,
1368 void * /* pvClient */, uint32_t eFunction, uint32_t cParms,
1369 VBOXHGCMSVCPARM paParms[])
1370{
1371 int rc = VINF_SUCCESS;
1372 LogFlowFunc(("u32ClientID = %d, fn = %d, cParms = %d, pparms = %p\n",
1373 u32ClientID, eFunction, cParms, paParms));
1374
1375 try
1376 {
1377 switch (eFunction)
1378 {
1379 /* The guest wishes to read a property */
1380 case GUEST_PROP_FN_GET_PROP:
1381 LogFlowFunc(("GET_PROP\n"));
1382 rc = getProperty(cParms, paParms);
1383 break;
1384
1385 /* The guest wishes to set a property */
1386 case GUEST_PROP_FN_SET_PROP:
1387 LogFlowFunc(("SET_PROP\n"));
1388 rc = setProperty(cParms, paParms, true);
1389 break;
1390
1391 /* The guest wishes to set a property value */
1392 case GUEST_PROP_FN_SET_PROP_VALUE:
1393 LogFlowFunc(("SET_PROP_VALUE\n"));
1394 rc = setProperty(cParms, paParms, true);
1395 break;
1396
1397 /* The guest wishes to remove a configuration value */
1398 case GUEST_PROP_FN_DEL_PROP:
1399 LogFlowFunc(("DEL_PROP\n"));
1400 rc = delProperty(cParms, paParms, true);
1401 break;
1402
1403 /* The guest wishes to enumerate all properties */
1404 case GUEST_PROP_FN_ENUM_PROPS:
1405 LogFlowFunc(("ENUM_PROPS\n"));
1406 rc = enumProps(cParms, paParms);
1407 break;
1408
1409 /* The guest wishes to get the next property notification */
1410 case GUEST_PROP_FN_GET_NOTIFICATION:
1411 LogFlowFunc(("GET_NOTIFICATION\n"));
1412 rc = getNotification(u32ClientID, callHandle, cParms, paParms);
1413 break;
1414
1415 default:
1416 rc = VERR_NOT_IMPLEMENTED;
1417 }
1418 }
1419 catch (std::bad_alloc &)
1420 {
1421 rc = VERR_NO_MEMORY;
1422 }
1423 LogFlowFunc(("rc = %Rrc\n", rc));
1424 if (rc != VINF_HGCM_ASYNC_EXECUTE)
1425 {
1426 mpHelpers->pfnCallComplete (callHandle, rc);
1427 }
1428}
1429
1430/**
1431 * Enumeration data shared between dbgInfoCallback and Service::dbgInfoShow.
1432 */
1433typedef struct ENUMDBGINFO
1434{
1435 PCDBGFINFOHLP pHlp;
1436} ENUMDBGINFO;
1437
1438static DECLCALLBACK(int) dbgInfoCallback(PRTSTRSPACECORE pStr, void *pvUser)
1439{
1440 Property *pProp = (Property *)pStr;
1441 PCDBGFINFOHLP pHlp = ((ENUMDBGINFO *)pvUser)->pHlp;
1442
1443 char szFlags[GUEST_PROP_MAX_FLAGS_LEN];
1444 int rc = GuestPropWriteFlags(pProp->mFlags, szFlags);
1445 if (RT_FAILURE(rc))
1446 RTStrPrintf(szFlags, sizeof(szFlags), "???");
1447
1448 pHlp->pfnPrintf(pHlp, "%s: '%s', %RU64", pProp->mName.c_str(), pProp->mValue.c_str(), pProp->mTimestamp);
1449 if (strlen(szFlags))
1450 pHlp->pfnPrintf(pHlp, " (%s)", szFlags);
1451 pHlp->pfnPrintf(pHlp, "\n");
1452 return 0;
1453}
1454
1455
1456/**
1457 * Handler for debug info.
1458 *
1459 * @param pvUser user pointer.
1460 * @param pHlp The info helper functions.
1461 * @param pszArgs Arguments, ignored.
1462 */
1463DECLCALLBACK(void) Service::dbgInfo(void *pvUser, PCDBGFINFOHLP pHlp, const char *pszArgs)
1464{
1465 RT_NOREF1(pszArgs);
1466 SELF *pSelf = reinterpret_cast<SELF *>(pvUser);
1467
1468 ENUMDBGINFO EnumData = { pHlp };
1469 RTStrSpaceEnumerate(&pSelf->mhProperties, dbgInfoCallback, &EnumData);
1470}
1471
1472
1473/**
1474 * Service call handler for the host.
1475 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnHostCall}
1476 * @thread hgcm
1477 */
1478int Service::hostCall (uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1479{
1480 int rc = VINF_SUCCESS;
1481
1482 LogFlowFunc(("fn = %d, cParms = %d, pparms = %p\n",
1483 eFunction, cParms, paParms));
1484
1485 try
1486 {
1487 switch (eFunction)
1488 {
1489 /* The host wishes to set a block of properties */
1490 case GUEST_PROP_FN_HOST_SET_PROPS:
1491 LogFlowFunc(("SET_PROPS_HOST\n"));
1492 rc = setPropertyBlock(cParms, paParms);
1493 break;
1494
1495 /* The host wishes to read a configuration value */
1496 case GUEST_PROP_FN_HOST_GET_PROP:
1497 LogFlowFunc(("GET_PROP_HOST\n"));
1498 rc = getProperty(cParms, paParms);
1499 break;
1500
1501 /* The host wishes to set a configuration value */
1502 case GUEST_PROP_FN_HOST_SET_PROP:
1503 LogFlowFunc(("SET_PROP_HOST\n"));
1504 rc = setProperty(cParms, paParms, false);
1505 break;
1506
1507 /* The host wishes to set a configuration value */
1508 case GUEST_PROP_FN_HOST_SET_PROP_VALUE:
1509 LogFlowFunc(("SET_PROP_VALUE_HOST\n"));
1510 rc = setProperty(cParms, paParms, false);
1511 break;
1512
1513 /* The host wishes to remove a configuration value */
1514 case GUEST_PROP_FN_HOST_DEL_PROP:
1515 LogFlowFunc(("DEL_PROP_HOST\n"));
1516 rc = delProperty(cParms, paParms, false);
1517 break;
1518
1519 /* The host wishes to enumerate all properties */
1520 case GUEST_PROP_FN_HOST_ENUM_PROPS:
1521 LogFlowFunc(("ENUM_PROPS\n"));
1522 rc = enumProps(cParms, paParms);
1523 break;
1524
1525 /* The host wishes to set global flags for the service */
1526 case GUEST_PROP_FN_HOST_SET_GLOBAL_FLAGS:
1527 LogFlowFunc(("SET_GLOBAL_FLAGS_HOST\n"));
1528 if (cParms == 1)
1529 {
1530 uint32_t fFlags;
1531 rc = HGCMSvcGetU32(&paParms[0], &fFlags);
1532 if (RT_SUCCESS(rc))
1533 mfGlobalFlags = fFlags;
1534 }
1535 else
1536 rc = VERR_INVALID_PARAMETER;
1537 break;
1538
1539 default:
1540 rc = VERR_NOT_SUPPORTED;
1541 break;
1542 }
1543 }
1544 catch (std::bad_alloc &)
1545 {
1546 rc = VERR_NO_MEMORY;
1547 }
1548
1549 LogFlowFunc(("rc = %Rrc\n", rc));
1550 return rc;
1551}
1552
1553#ifdef ASYNC_HOST_NOTIFY
1554
1555/* static */
1556DECLCALLBACK(int) Service::threadNotifyHost(RTTHREAD hThreadSelf, void *pvUser)
1557{
1558 RT_NOREF1(hThreadSelf);
1559 Service *pThis = (Service *)pvUser;
1560 int rc = VINF_SUCCESS;
1561
1562 LogFlowFunc(("ENTER: %p\n", pThis));
1563
1564 for (;;)
1565 {
1566 rc = RTReqQueueProcess(pThis->mhReqQNotifyHost, RT_INDEFINITE_WAIT);
1567
1568 AssertMsg(rc == VWRN_STATE_CHANGED,
1569 ("Left RTReqProcess and error code is not VWRN_STATE_CHANGED rc=%Rrc\n",
1570 rc));
1571 if (rc == VWRN_STATE_CHANGED)
1572 {
1573 break;
1574 }
1575 }
1576
1577 LogFlowFunc(("LEAVE: %Rrc\n", rc));
1578 return rc;
1579}
1580
1581static DECLCALLBACK(int) wakeupNotifyHost(void)
1582{
1583 /* Returning a VWRN_* will cause RTReqQueueProcess return. */
1584 return VWRN_STATE_CHANGED;
1585}
1586
1587#endif /* ASYNC_HOST_NOTIFY */
1588
1589int Service::initialize()
1590{
1591#ifdef ASYNC_HOST_NOTIFY
1592 /* The host notification thread and queue. */
1593 int rc = RTReqQueueCreate(&mhReqQNotifyHost);
1594 if (RT_SUCCESS(rc))
1595 {
1596 rc = RTThreadCreate(&mhThreadNotifyHost,
1597 threadNotifyHost,
1598 this,
1599 0 /* default stack size */,
1600 RTTHREADTYPE_DEFAULT,
1601 RTTHREADFLAGS_WAITABLE,
1602 "GSTPROPNTFY");
1603 }
1604
1605 if (RT_FAILURE(rc))
1606 {
1607 if (mhReqQNotifyHost != NIL_RTREQQUEUE)
1608 {
1609 RTReqQueueDestroy(mhReqQNotifyHost);
1610 mhReqQNotifyHost = NIL_RTREQQUEUE;
1611 }
1612 }
1613#else /* !ASYNC_HOST_NOTIFY */
1614 int rc = VINF_SUCCESS;
1615#endif /* !ASYNC_HOST_NOTIFY */
1616
1617 /* Finally debug stuff (ignore failures): */
1618 if (RT_SUCCESS(rc))
1619 HGCMSvcHlpInfoRegister(mpHelpers, "guestprops", "Display the guest properties", Service::dbgInfo, this);
1620
1621 return rc;
1622}
1623
1624#ifdef ASYNC_HOST_NOTIFY
1625/**
1626 * @callback_method_impl{FNRTSTRSPACECALLBACK, Destroys Property.}
1627 */
1628static DECLCALLBACK(int) destroyProperty(PRTSTRSPACECORE pStr, void *pvUser)
1629{
1630 RT_NOREF(pvUser);
1631 Property *pProp = RT_FROM_CPP_MEMBER(pStr, struct Property, mStrCore); /* clang objects to offsetof on non-POD.*/
1632 delete pProp;
1633 return 0;
1634}
1635
1636#endif
1637
1638int Service::uninit()
1639{
1640 if (mpHelpers)
1641 HGCMSvcHlpInfoDeregister(mpHelpers, "guestprops");
1642
1643#ifdef ASYNC_HOST_NOTIFY
1644 if (mhReqQNotifyHost != NIL_RTREQQUEUE)
1645 {
1646 /* Stop the thread */
1647 PRTREQ pReq;
1648 int rc = RTReqQueueCall(mhReqQNotifyHost, &pReq, 10000, (PFNRT)wakeupNotifyHost, 0);
1649 if (RT_SUCCESS(rc))
1650 RTReqRelease(pReq);
1651 rc = RTThreadWait(mhThreadNotifyHost, 10000, NULL);
1652 AssertRC(rc);
1653 rc = RTReqQueueDestroy(mhReqQNotifyHost);
1654 AssertRC(rc);
1655 mhReqQNotifyHost = NIL_RTREQQUEUE;
1656 mhThreadNotifyHost = NIL_RTTHREAD;
1657 RTStrSpaceDestroy(&mhProperties, destroyProperty, NULL);
1658 mhProperties = NULL;
1659 }
1660#endif
1661 return VINF_SUCCESS;
1662}
1663
1664} /* namespace guestProp */
1665
1666using guestProp::Service;
1667
1668/**
1669 * @copydoc VBOXHGCMSVCLOAD
1670 */
1671extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *ptable)
1672{
1673 int rc = VERR_IPE_UNINITIALIZED_STATUS;
1674
1675 LogFlowFunc(("ptable = %p\n", ptable));
1676
1677 if (!RT_VALID_PTR(ptable))
1678 rc = VERR_INVALID_PARAMETER;
1679 else
1680 {
1681 LogFlowFunc(("ptable->cbSize = %d, ptable->u32Version = 0x%08X\n", ptable->cbSize, ptable->u32Version));
1682
1683 if ( ptable->cbSize != sizeof(VBOXHGCMSVCFNTABLE)
1684 || ptable->u32Version != VBOX_HGCM_SVC_VERSION)
1685 rc = VERR_VERSION_MISMATCH;
1686 else
1687 {
1688 Service *pService = NULL;
1689 /* No exceptions may propagate outside. */
1690 try
1691 {
1692 pService = new Service(ptable->pHelpers);
1693 rc = VINF_SUCCESS;
1694 }
1695 catch (int rcThrown)
1696 {
1697 rc = rcThrown;
1698 }
1699 catch (...)
1700 {
1701 rc = VERR_UNEXPECTED_EXCEPTION;
1702 }
1703
1704 if (RT_SUCCESS(rc))
1705 {
1706 /* We do not maintain connections, so no client data is needed. */
1707 ptable->cbClient = 0;
1708
1709 ptable->pfnUnload = Service::svcUnload;
1710 ptable->pfnConnect = Service::svcConnectDisconnect;
1711 ptable->pfnDisconnect = Service::svcConnectDisconnect;
1712 ptable->pfnCall = Service::svcCall;
1713 ptable->pfnHostCall = Service::svcHostCall;
1714 ptable->pfnSaveState = NULL; /* The service is stateless, so the normal */
1715 ptable->pfnLoadState = NULL; /* construction done before restoring suffices */
1716 ptable->pfnRegisterExtension = Service::svcRegisterExtension;
1717 ptable->pvService = pService;
1718
1719 /* Service specific initialization. */
1720 rc = pService->initialize();
1721 if (RT_FAILURE(rc))
1722 {
1723 delete pService;
1724 pService = NULL;
1725 }
1726 }
1727 else
1728 Assert(!pService);
1729 }
1730 }
1731
1732 LogFlowFunc(("returning %Rrc\n", rc));
1733 return rc;
1734}
1735
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