VirtualBox

source: vbox/trunk/src/VBox/HostServices/GuestControl/service.cpp@ 75876

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

GuestControl: Some more cleanups. bugref:9313

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 90.4 KB
Line 
1/* $Id: service.cpp 75876 2018-12-02 17:27:34Z vboxsync $ */
2/** @file
3 * Guest Control Service: Controlling the guest.
4 */
5
6/*
7 * Copyright (C) 2011-2018 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_control Guest Control HGCM Service
19 *
20 * This service acts as a proxy for handling and buffering host command requests
21 * and clients on the guest. It tries to be as transparent as possible to let
22 * the guest (client) and host side do their protocol handling as desired.
23 *
24 * The following terms are used:
25 * - Host: A host process (e.g. VBoxManage or another tool utilizing the Main API)
26 * which wants to control something on the guest.
27 * - Client: A client (e.g. VBoxService) running inside the guest OS waiting for
28 * new host commands to perform. There can be multiple clients connected
29 * to this service. A client is represented by its unique HGCM client ID.
30 * - Context ID: An (almost) unique ID automatically generated on the host (Main API)
31 * to not only distinguish clients but individual requests. Because
32 * the host does not know anything about connected clients it needs
33 * an indicator which it can refer to later. This context ID gets
34 * internally bound by the service to a client which actually processes
35 * the command in order to have a relationship between client<->context ID(s).
36 *
37 * The host can trigger commands which get buffered by the service (with full HGCM
38 * parameter info). As soon as a client connects (or is ready to do some new work)
39 * it gets a buffered host command to process it. This command then will be immediately
40 * removed from the command list. If there are ready clients but no new commands to be
41 * processed, these clients will be set into a deferred state (that is being blocked
42 * to return until a new command is available).
43 *
44 * If a client needs to inform the host that something happened, it can send a
45 * message to a low level HGCM callback registered in Main. This callback contains
46 * the actual data as well as the context ID to let the host do the next necessary
47 * steps for this context. This context ID makes it possible to wait for an event
48 * inside the host's Main API function (like starting a process on the guest and
49 * wait for getting its PID returned by the client) as well as cancelling blocking
50 * host calls in order the client terminated/crashed (HGCM detects disconnected
51 * clients and reports it to this service's callback).
52 *
53 * Starting at VBox 4.2 the context ID itself consists of a session ID, an object
54 * ID (for example a process or file ID) and a count. This is necessary to not break
55 * compatibility between older hosts and to manage guest session on the host.
56 */
57
58
59/*********************************************************************************************************************************
60* Header Files *
61*********************************************************************************************************************************/
62#define LOG_GROUP LOG_GROUP_GUEST_CONTROL
63#include <VBox/HostServices/GuestControlSvc.h>
64#include <VBox/GuestHost/GuestControl.h> /** @todo r=bird: Why two headers??? */
65
66#include <VBox/log.h>
67#include <VBox/AssertGuest.h>
68#include <VBox/VMMDev.h>
69#include <VBox/vmm/ssm.h>
70#include <iprt/assert.h>
71#include <iprt/cpp/autores.h>
72#include <iprt/cpp/utils.h>
73#include <iprt/err.h>
74#include <iprt/mem.h>
75#include <iprt/list.h>
76#include <iprt/req.h>
77#include <iprt/string.h>
78#include <iprt/thread.h>
79#include <iprt/time.h>
80
81#include <map>
82#include <new> /* for std::nothrow*/
83
84
85using namespace guestControl;
86
87
88/**
89 * Structure for maintaining a request.
90 */
91typedef struct ClientRequest
92{
93 /** The call handle */
94 VBOXHGCMCALLHANDLE mHandle;
95 /** Number of parameters */
96 uint32_t mNumParms;
97 /** The call parameters */
98 VBOXHGCMSVCPARM *mParms;
99 /** The default constructor. */
100 ClientRequest(void)
101 : mHandle(0), mNumParms(0), mParms(NULL)
102 {}
103} ClientRequest;
104
105/**
106 * Structure for holding a buffered host command which has
107 * not been processed yet.
108 *
109 * @todo r=bird: It would be nice if we could decide on _one_ term for what the
110 * host passes to the guest. We currently have:
111 * - The enum is called eHostFn, implying it's a function
112 * - The guest retrieves messages, if the eGuestFn enum is anything to
113 * go by: GUEST_MSG_GET, GUEST_MSG_CANCEL, GUEST_MSG_XXX
114 * - Here it's called a host command.
115 * - But this HostCommand structure has a mMsgType rather than command
116 * number/enum value, impliying it's a message.
117 */
118typedef struct HostCommand
119{
120 /** Entry on the ClientState::m_HostCmdList list. */
121 RTLISTNODE m_ListEntry;
122 union
123 {
124 /** The top two twomost bits are exploited for message destination.
125 * See VBOX_GUESTCTRL_DST_XXX. */
126 uint64_t m_idContextAndDst;
127 /** The context ID this command belongs to (extracted from the first parameter). */
128 uint32_t m_idContext;
129 };
130 /** Dynamic structure for holding the HGCM parms */
131 uint32_t mMsgType;
132 /** Number of HGCM parameters. */
133 uint32_t mParmCount;
134 /** Array of HGCM parameters. */
135 PVBOXHGCMSVCPARM mpParms;
136
137 HostCommand()
138 : m_idContextAndDst(0)
139 , mMsgType(UINT32_MAX)
140 , mParmCount(0)
141 , mpParms(NULL)
142 {
143 RTListInit(&m_ListEntry);
144 }
145
146 /**
147 * Releases the host command, properly deleting it if no further references.
148 */
149 void Delete(void)
150 {
151 LogFlowThisFunc(("[Cmd %RU32 (%s)] destroying\n", mMsgType, GstCtrlHostFnName((eHostFn)mMsgType)));
152 Assert(m_ListEntry.pNext == NULL);
153 if (mpParms)
154 {
155 for (uint32_t i = 0; i < mParmCount; i++)
156 if (mpParms[i].type == VBOX_HGCM_SVC_PARM_PTR)
157 {
158 RTMemFree(mpParms[i].u.pointer.addr);
159 mpParms[i].u.pointer.addr = NULL;
160 }
161 RTMemFree(mpParms);
162 mpParms = NULL;
163 }
164 mParmCount = 0;
165 delete this;
166 }
167
168
169 /**
170 * Initializes the command.
171 *
172 * The specified parameters are copied and any buffers referenced by it
173 * duplicated as well.
174 *
175 * @returns VBox status code.
176 * @param idFunction The host function (message) number, eHostFn.
177 * @param cParms Number of parameters in the HGCM request.
178 * @param paParms Array of parameters.
179 */
180 int Init(uint32_t idFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
181 {
182 LogFlowThisFunc(("[Cmd %RU32 (%s)] Allocating cParms=%RU32, paParms=%p\n",
183 idFunction, GstCtrlHostFnName((eHostFn)idFunction), cParms, paParms));
184 Assert(mpParms == NULL);
185 Assert(mParmCount == 0);
186 Assert(RTListIsEmpty(&m_ListEntry));
187
188 /*
189 * Fend of bad stuff.
190 */
191 AssertReturn(cParms > 0, VERR_WRONG_PARAMETER_COUNT); /* At least one parameter (context ID) must be present. */
192 AssertReturn(cParms < VMMDEV_MAX_HGCM_PARMS, VERR_WRONG_PARAMETER_COUNT);
193 AssertPtrReturn(paParms, VERR_INVALID_POINTER);
194
195 /*
196 * The first parameter is the context ID and the command destiation mask.
197 */
198 if (paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT)
199 {
200 m_idContextAndDst = paParms[0].u.uint64;
201 AssertReturn(m_idContextAndDst & VBOX_GUESTCTRL_DST_BOTH, VERR_INTERNAL_ERROR_3);
202 }
203 else if (paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT)
204 {
205 AssertMsgFailed(("idFunction=%u %s - caller must set dst!\n", idFunction, GstCtrlHostFnName((eHostFn)idFunction)));
206 m_idContextAndDst = paParms[0].u.uint32 | VBOX_GUESTCTRL_DST_BOTH;
207 }
208 else
209 AssertFailedReturn(VERR_WRONG_PARAMETER_TYPE);
210
211 /*
212 * Just make a copy of the parameters and any buffers.
213 */
214 mMsgType = idFunction;
215 mParmCount = cParms;
216 mpParms = (VBOXHGCMSVCPARM *)RTMemAllocZ(sizeof(VBOXHGCMSVCPARM) * mParmCount);
217 AssertReturn(mpParms, VERR_NO_MEMORY);
218
219 for (uint32_t i = 0; i < cParms; i++)
220 {
221 mpParms[i].type = paParms[i].type;
222 switch (paParms[i].type)
223 {
224 case VBOX_HGCM_SVC_PARM_32BIT:
225 mpParms[i].u.uint32 = paParms[i].u.uint32;
226 break;
227
228 case VBOX_HGCM_SVC_PARM_64BIT:
229 mpParms[i].u.uint64 = paParms[i].u.uint64;
230 break;
231
232 case VBOX_HGCM_SVC_PARM_PTR:
233 mpParms[i].u.pointer.size = paParms[i].u.pointer.size;
234 if (mpParms[i].u.pointer.size > 0)
235 {
236 mpParms[i].u.pointer.addr = RTMemDup(paParms[i].u.pointer.addr, mpParms[i].u.pointer.size);
237 AssertReturn(mpParms[i].u.pointer.addr, VERR_NO_MEMORY);
238 }
239 /* else: structure is zeroed by allocator. */
240 break;
241
242 default:
243 AssertMsgFailedReturn(("idFunction=%u (%s) parameter #%u: type=%u\n",
244 idFunction, GstCtrlHostFnName((eHostFn)idFunction), i, paParms[i].type),
245 VERR_WRONG_PARAMETER_TYPE);
246 }
247 }
248
249 /*
250 * Morph the first parameter back to 32-bit.
251 */
252 mpParms[0].type = VBOX_HGCM_SVC_PARM_32BIT;
253 mpParms[0].u.uint32 = (uint32_t)paParms[0].u.uint64;
254
255 return VINF_SUCCESS;
256 }
257
258
259 /**
260 * Sets the GUEST_MSG_PEEK_WAIT GUEST_MSG_PEEK_NOWAIT return parameters.
261 *
262 * @param paDstParms The peek parameter vector.
263 * @param cDstParms The number of peek parameters (at least two).
264 * @remarks ASSUMES the parameters has been cleared by clientMsgPeek.
265 */
266 inline void setPeekReturn(PVBOXHGCMSVCPARM paDstParms, uint32_t cDstParms)
267 {
268 Assert(cDstParms >= 2);
269 if (paDstParms[0].type == VBOX_HGCM_SVC_PARM_32BIT)
270 paDstParms[0].u.uint32 = mMsgType;
271 else
272 paDstParms[0].u.uint64 = mMsgType;
273 paDstParms[1].u.uint32 = mParmCount;
274
275 uint32_t i = RT_MIN(cDstParms, mParmCount + 2);
276 while (i-- > 2)
277 switch (mpParms[i - 2].type)
278 {
279 case VBOX_HGCM_SVC_PARM_32BIT: paDstParms[i].u.uint32 = ~(uint32_t)sizeof(uint32_t); break;
280 case VBOX_HGCM_SVC_PARM_64BIT: paDstParms[i].u.uint32 = ~(uint32_t)sizeof(uint64_t); break;
281 case VBOX_HGCM_SVC_PARM_PTR: paDstParms[i].u.uint32 = mpParms[i - 2].u.pointer.size; break;
282 }
283 }
284
285
286 /** @name Support for old-style (GUEST_MSG_WAIT) operation.
287 * @{
288 */
289
290 /**
291 * Worker for Assign() that opies data from the buffered HGCM request to the
292 * current HGCM request.
293 *
294 * @returns VBox status code.
295 * @param paDstParms Array of parameters of HGCM request to fill the data into.
296 * @param cDstParms Number of parameters the HGCM request can handle.
297 */
298 int CopyTo(VBOXHGCMSVCPARM paDstParms[], uint32_t cDstParms) const
299 {
300 LogFlowThisFunc(("[Cmd %RU32] mParmCount=%RU32, m_idContext=%RU32 (Session %RU32)\n",
301 mMsgType, mParmCount, m_idContext, VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(m_idContext)));
302
303 int rc = VINF_SUCCESS;
304 if (cDstParms != mParmCount)
305 {
306 LogFlowFunc(("Parameter count does not match (got %RU32, expected %RU32)\n",
307 cDstParms, mParmCount));
308 rc = VERR_INVALID_PARAMETER;
309 }
310
311 if (RT_SUCCESS(rc))
312 {
313 for (uint32_t i = 0; i < mParmCount; i++)
314 {
315 if (paDstParms[i].type != mpParms[i].type)
316 {
317 LogFunc(("Parameter %RU32 type mismatch (got %RU32, expected %RU32)\n", i, paDstParms[i].type, mpParms[i].type));
318 rc = VERR_INVALID_PARAMETER;
319 }
320 else
321 {
322 switch (mpParms[i].type)
323 {
324 case VBOX_HGCM_SVC_PARM_32BIT:
325#ifdef DEBUG_andy
326 LogFlowFunc(("\tmpParms[%RU32] = %RU32 (uint32_t)\n",
327 i, mpParms[i].u.uint32));
328#endif
329 paDstParms[i].u.uint32 = mpParms[i].u.uint32;
330 break;
331
332 case VBOX_HGCM_SVC_PARM_64BIT:
333#ifdef DEBUG_andy
334 LogFlowFunc(("\tmpParms[%RU32] = %RU64 (uint64_t)\n",
335 i, mpParms[i].u.uint64));
336#endif
337 paDstParms[i].u.uint64 = mpParms[i].u.uint64;
338 break;
339
340 case VBOX_HGCM_SVC_PARM_PTR:
341 {
342#ifdef DEBUG_andy
343 LogFlowFunc(("\tmpParms[%RU32] = %p (ptr), size = %RU32\n",
344 i, mpParms[i].u.pointer.addr, mpParms[i].u.pointer.size));
345#endif
346 if (!mpParms[i].u.pointer.size)
347 continue; /* Only copy buffer if there actually is something to copy. */
348
349 if (!paDstParms[i].u.pointer.addr)
350 rc = VERR_INVALID_PARAMETER;
351 else if (paDstParms[i].u.pointer.size < mpParms[i].u.pointer.size)
352 rc = VERR_BUFFER_OVERFLOW;
353 else
354 memcpy(paDstParms[i].u.pointer.addr,
355 mpParms[i].u.pointer.addr,
356 mpParms[i].u.pointer.size);
357 break;
358 }
359
360 default:
361 LogFunc(("Parameter %RU32 of type %RU32 is not supported yet\n", i, mpParms[i].type));
362 rc = VERR_NOT_SUPPORTED;
363 break;
364 }
365 }
366
367 if (RT_FAILURE(rc))
368 {
369 LogFunc(("Parameter %RU32 invalid (%Rrc), refusing\n", i, rc));
370 break;
371 }
372 }
373 }
374
375 LogFlowFunc(("Returned with rc=%Rrc\n", rc));
376 return rc;
377 }
378
379 int Assign(const ClientRequest *pReq)
380 {
381 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
382
383 int rc;
384
385 LogFlowThisFunc(("[Cmd %RU32] mParmCount=%RU32, mpParms=%p\n", mMsgType, mParmCount, mpParms));
386
387 /* Does the current host command need more parameter space which
388 * the client does not provide yet? */
389 if (mParmCount > pReq->mNumParms)
390 {
391 LogFlowThisFunc(("[Cmd %RU32] Requires %RU32 parms, only got %RU32 from client\n",
392 mMsgType, mParmCount, pReq->mNumParms));
393 /*
394 * So this call apparently failed because the guest wanted to peek
395 * how much parameters it has to supply in order to successfully retrieve
396 * this command. Let's tell him so!
397 */
398 rc = VERR_TOO_MUCH_DATA;
399 }
400 else
401 {
402 rc = CopyTo(pReq->mParms, pReq->mNumParms);
403
404 /*
405 * Has there been enough parameter space but the wrong parameter types
406 * were submitted -- maybe the client was just asking for the next upcoming
407 * host message?
408 *
409 * Note: To keep this compatible to older clients we return VERR_TOO_MUCH_DATA
410 * in every case.
411 */
412 if (RT_FAILURE(rc))
413 rc = VERR_TOO_MUCH_DATA;
414 }
415
416 return rc;
417 }
418
419 int Peek(const ClientRequest *pReq)
420 {
421 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
422
423 LogFlowThisFunc(("[Cmd %RU32] mParmCount=%RU32, mpParms=%p\n", mMsgType, mParmCount, mpParms));
424
425 if (pReq->mNumParms >= 2)
426 {
427 HGCMSvcSetU32(&pReq->mParms[0], mMsgType); /* Message ID */
428 HGCMSvcSetU32(&pReq->mParms[1], mParmCount); /* Required parameters for message */
429 }
430 else
431 LogFlowThisFunc(("Warning: Client has not (yet) submitted enough parameters (%RU32, must be at least 2) to at least peak for the next message\n",
432 pReq->mNumParms));
433
434 /*
435 * Always return VERR_TOO_MUCH_DATA data here to
436 * keep it compatible with older clients and to
437 * have correct accounting (mHostRc + mHostCmdTries).
438 */
439 return VERR_TOO_MUCH_DATA;
440 }
441
442 /** @} */
443} HostCommand;
444
445/**
446 * Per-client structure used for book keeping/state tracking a
447 * certain host command.
448 */
449typedef struct ClientContext
450{
451 /* Pointer to list node of this command. */
452 HostCommand *mpHostCmd;
453 /** The standard constructor. */
454 ClientContext(void) : mpHostCmd(NULL) {}
455 /** Internal constrcutor. */
456 ClientContext(HostCommand *pHostCmd) : mpHostCmd(pHostCmd) {}
457} ClientContext;
458typedef std::map< uint32_t, ClientContext > ClientContextMap;
459
460/**
461 * Structure for holding a connected guest client state.
462 */
463typedef struct ClientState
464{
465 PVBOXHGCMSVCHELPERS m_pSvcHelpers;
466 /** Host command list to process (HostCommand). */
467 RTLISTANCHOR m_HostCmdList;
468 /** The HGCM client ID. */
469 uint32_t m_idClient;
470 /** The session ID for this client, UINT32_MAX if not set or master. */
471 uint32_t m_idSession;
472 /** Set if master. */
473 bool m_fIsMaster;
474
475 /** Set if we've got a pending wait cancel. */
476 bool m_fPendingCancel;
477 /** Pending client call (GUEST_MSG_PEEK_WAIT or GUEST_MSG_WAIT), zero if none pending.
478 *
479 * This means the client waits for a new host command to reply and won't return
480 * from the waiting call until a new host command is available. */
481 guestControl::eGuestFn m_enmIsPending;
482 /** Pending peek/wait request details. */
483 ClientRequest m_PendingReq;
484
485
486 ClientState(void)
487 : m_pSvcHelpers(NULL)
488 , m_idClient(0)
489 , m_idSession(UINT32_MAX)
490 , m_fIsMaster(false)
491 , m_fPendingCancel(false)
492 , m_enmIsPending((guestControl::eGuestFn)0)
493 , mHostCmdRc(VINF_SUCCESS)
494 , mHostCmdTries(0)
495 , mPeekCount(0)
496 {
497 RTListInit(&m_HostCmdList);
498 }
499
500 ClientState(PVBOXHGCMSVCHELPERS pSvcHelpers, uint32_t idClient)
501 : m_pSvcHelpers(pSvcHelpers)
502 , m_idClient(idClient)
503 , m_idSession(UINT32_MAX)
504 , m_fIsMaster(false)
505 , m_fPendingCancel(false)
506 , m_enmIsPending((guestControl::eGuestFn)0)
507 , mHostCmdRc(VINF_SUCCESS)
508 , mHostCmdTries(0)
509 , mPeekCount(0)
510 {
511 RTListInit(&m_HostCmdList);
512 }
513
514 /**
515 * Used by for Service::hostProcessCommand().
516 */
517 void EnqueueCommand(HostCommand *pHostCmd)
518 {
519 AssertPtr(pHostCmd);
520 RTListAppend(&m_HostCmdList, &pHostCmd->m_ListEntry);
521 }
522
523 /**
524 * Used by for Service::hostProcessCommand().
525 *
526 * @note This wakes up both GUEST_MSG_WAIT and GUEST_MSG_PEEK_WAIT sleepers.
527 */
528 int Wakeup(void)
529 {
530 int rc = VINF_NO_CHANGE;
531
532 if (m_enmIsPending != 0)
533 {
534 LogFlowFunc(("[Client %RU32] Waking up ...\n", m_idClient));
535
536 rc = VINF_SUCCESS;
537
538 HostCommand *pFirstCmd = RTListGetFirstCpp(&m_HostCmdList, HostCommand, m_ListEntry);
539 if (pFirstCmd)
540 {
541 LogFlowThisFunc(("[Client %RU32] Current host command is %RU32 (CID=%#RX32, cParms=%RU32)\n",
542 m_idClient, pFirstCmd->mMsgType, pFirstCmd->m_idContext, pFirstCmd->mParmCount));
543
544 if (m_enmIsPending == GUEST_MSG_PEEK_WAIT)
545 {
546 pFirstCmd->setPeekReturn(m_PendingReq.mParms, m_PendingReq.mNumParms);
547 rc = m_pSvcHelpers->pfnCallComplete(m_PendingReq.mHandle, VINF_SUCCESS);
548
549 m_PendingReq.mHandle = NULL;
550 m_PendingReq.mParms = NULL;
551 m_PendingReq.mNumParms = 0;
552 m_enmIsPending = (guestControl::eGuestFn)0;
553 }
554 else if (m_enmIsPending == GUEST_MSG_WAIT)
555 rc = OldRun(&m_PendingReq, pFirstCmd);
556 else
557 AssertMsgFailed(("m_enmIsPending=%d\n", m_enmIsPending));
558 }
559 else
560 AssertMsgFailed(("Waking up client ID=%RU32 with no host command in queue is a bad idea\n", m_idClient));
561
562 return rc;
563 }
564
565 return VINF_NO_CHANGE;
566 }
567
568 /**
569 * Used by Service::call() to handle GUEST_MSG_CANCEL.
570 *
571 * @note This cancels both GUEST_MSG_WAIT and GUEST_MSG_PEEK_WAIT sleepers.
572 */
573 int CancelWaiting()
574 {
575 LogFlowFunc(("[Client %RU32] Cancelling waiting thread, isPending=%d, pendingNumParms=%RU32, m_idSession=%x\n",
576 m_idClient, m_enmIsPending, m_PendingReq.mNumParms, m_idSession));
577
578 /*
579 * The PEEK call is simple: At least two parameters, all set to zero before sleeping.
580 */
581 int rcComplete;
582 if (m_enmIsPending == GUEST_MSG_PEEK_WAIT)
583 {
584 HGCMSvcSetU32(&m_PendingReq.mParms[0], HOST_CANCEL_PENDING_WAITS);
585 rcComplete = VINF_TRY_AGAIN;
586 }
587 /*
588 * The GUEST_MSG_WAIT call is complicated, though we're generally here
589 * to wake up someone who is peeking and have two parameters. If there
590 * aren't two parameters, fail the call.
591 */
592 else if (m_enmIsPending != 0)
593 {
594 Assert(m_enmIsPending == GUEST_MSG_WAIT);
595 if (m_PendingReq.mNumParms > 0)
596 HGCMSvcSetU32(&m_PendingReq.mParms[0], HOST_CANCEL_PENDING_WAITS);
597 if (m_PendingReq.mNumParms > 1)
598 HGCMSvcSetU32(&m_PendingReq.mParms[1], 0);
599 rcComplete = m_PendingReq.mNumParms == 2 ? VINF_SUCCESS : VERR_TRY_AGAIN;
600 }
601 /*
602 * If nobody is waiting, flag the next wait call as cancelled.
603 */
604 else
605 {
606 m_fPendingCancel = true;
607 return VINF_SUCCESS;
608 }
609
610 m_pSvcHelpers->pfnCallComplete(m_PendingReq.mHandle, rcComplete);
611
612 m_PendingReq.mHandle = NULL;
613 m_PendingReq.mParms = NULL;
614 m_PendingReq.mNumParms = 0;
615 m_enmIsPending = (guestControl::eGuestFn)0;
616 m_fPendingCancel = false;
617 return VINF_SUCCESS;
618 }
619
620
621 /** @name The GUEST_MSG_WAIT state and helpers.
622 *
623 * @note Don't try understand this, it is certificable!
624 *
625 * @{
626 */
627
628 /** Last (most recent) rc after handling the host command. */
629 int mHostCmdRc;
630 /** How many GUEST_MSG_WAIT calls the client has issued to retrieve one command.
631 *
632 * This is used as a heuristic to remove a message that the client appears not
633 * to be able to successfully retrieve. */
634 uint32_t mHostCmdTries;
635 /** Number of times we've peeked at a pending message.
636 *
637 * This is necessary for being compatible with older Guest Additions. In case
638 * there are commands which only have two (2) parameters and therefore would fit
639 * into the GUEST_MSG_WAIT reply immediately, we now can make sure that the
640 * client first gets back the GUEST_MSG_WAIT results first.
641 */
642 uint32_t mPeekCount;
643
644 /**
645 * Ditches the first host command and crazy GUEST_MSG_WAIT state.
646 *
647 * @note Only used by GUEST_MSG_WAIT scenarios.
648 */
649 void OldDitchFirstHostCmd()
650 {
651 HostCommand *pFirstCmd = RTListGetFirstCpp(&m_HostCmdList, HostCommand, m_ListEntry);
652 Assert(pFirstCmd);
653 RTListNodeRemove(&pFirstCmd->m_ListEntry);
654
655 /* Reset state else. */
656 mHostCmdRc = VINF_SUCCESS;
657 mHostCmdTries = 0;
658 mPeekCount = 0;
659 }
660
661 /**
662 * Used by Wakeup() and OldRunCurrent().
663 *
664 * @note Only used by GUEST_MSG_WAIT scenarios.
665 */
666 int OldRun(ClientRequest const *pReq, HostCommand *pHostCmd)
667 {
668 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
669 AssertPtrReturn(pHostCmd, VERR_INVALID_POINTER);
670 Assert(RTListNodeIsFirst(&m_HostCmdList, &pHostCmd->m_ListEntry));
671
672 LogFlowFunc(("[Client %RU32] pReq=%p, mHostCmdRc=%Rrc, mHostCmdTries=%RU32, mPeekCount=%RU32\n",
673 m_idClient, pReq, mHostCmdRc, mHostCmdTries, mPeekCount));
674
675 int rc = mHostCmdRc = OldSendReply(pReq, pHostCmd);
676
677 LogFlowThisFunc(("[Client %RU32] Processing command %RU32 ended with rc=%Rrc\n", m_idClient, pHostCmd->mMsgType, mHostCmdRc));
678
679 bool fRemove = false;
680 if (RT_FAILURE(rc))
681 {
682 mHostCmdTries++;
683
684 /*
685 * If the client understood the message but supplied too little buffer space
686 * don't send this message again and drop it after 6 unsuccessful attempts.
687 *
688 * Note: Due to legacy reasons this the retry counter has to be even because on
689 * every peek there will be the actual command retrieval from the client side.
690 * To not get the actual command if the client actually only wants to peek for
691 * the next command, there needs to be two rounds per try, e.g. 3 rounds = 6 tries.
692 */
693 /** @todo Fix the mess stated above. GUEST_MSG_WAIT should be become GUEST_MSG_PEEK, *only*
694 * (and every time) returning the next upcoming host command (if any, blocking). Then
695 * it's up to the client what to do next, either peeking again or getting the actual
696 * host command via an own GUEST_ type message.
697 */
698 if ( rc == VERR_TOO_MUCH_DATA
699 || rc == VERR_CANCELLED)
700 {
701 if (mHostCmdTries == 6)
702 fRemove = true;
703 }
704 /* Client did not understand the message or something else weird happened. Try again one
705 * more time and drop it if it didn't get handled then. */
706 else if (mHostCmdTries > 1)
707 fRemove = true;
708 }
709 else
710 fRemove = true; /* Everything went fine, remove it. */
711
712 LogFlowThisFunc(("[Client %RU32] Tried command %RU32 for %RU32 times, (last result=%Rrc, fRemove=%RTbool)\n",
713 m_idClient, pHostCmd->mMsgType, mHostCmdTries, rc, fRemove));
714
715 if (fRemove)
716 {
717 Assert(RTListNodeIsFirst(&m_HostCmdList, &pHostCmd->m_ListEntry));
718 OldDitchFirstHostCmd();
719 }
720
721 LogFlowFunc(("[Client %RU32] Returned with rc=%Rrc\n", m_idClient, rc));
722 return rc;
723 }
724
725 /**
726 * @note Only used by GUEST_MSG_WAIT scenarios.
727 */
728 int OldRunCurrent(const ClientRequest *pReq)
729 {
730 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
731
732 /*
733 * If the host command list is empty, the request must wait for one to be posted.
734 */
735 HostCommand *pFirstCmd = RTListGetFirstCpp(&m_HostCmdList, HostCommand, m_ListEntry);
736 if (!pFirstCmd)
737 {
738 if (!m_fPendingCancel)
739 {
740 /* Go to sleep. */
741 ASSERT_GUEST_RETURN(m_enmIsPending == 0, VERR_WRONG_ORDER);
742 m_PendingReq = *pReq;
743 m_enmIsPending = GUEST_MSG_WAIT;
744 LogFlowFunc(("[Client %RU32] Is now in pending mode\n", m_idClient));
745 return VINF_HGCM_ASYNC_EXECUTE;
746 }
747
748 /* Wait was cancelled. */
749 m_fPendingCancel = false;
750 if (pReq->mNumParms > 0)
751 HGCMSvcSetU32(&pReq->mParms[0], HOST_CANCEL_PENDING_WAITS);
752 if (pReq->mNumParms > 1)
753 HGCMSvcSetU32(&pReq->mParms[1], 0);
754 return pReq->mNumParms == 2 ? VINF_SUCCESS : VERR_TRY_AGAIN;
755 }
756
757 /*
758 * Return first host command.
759 */
760 return OldRun(pReq, pFirstCmd);
761 }
762
763 /**
764 * Internal worker for OldRun().
765 * @note Only used for GUEST_MSG_WAIT.
766 */
767 int OldSendReply(ClientRequest const *pReq,
768 HostCommand *pHostCmd)
769 {
770 AssertPtrReturn(pReq, VERR_INVALID_POINTER);
771 AssertPtrReturn(pHostCmd, VERR_INVALID_POINTER);
772
773 /* In case of VERR_CANCELLED. */
774 uint32_t const cSavedPeeks = mPeekCount;
775
776 int rc;
777 /* If the client is in pending mode, always send back
778 * the peek result first. */
779 if (m_enmIsPending)
780 {
781 Assert(m_enmIsPending == GUEST_MSG_WAIT);
782 rc = pHostCmd->Peek(pReq);
783 mPeekCount++;
784 }
785 else
786 {
787 /* If this is the very first peek, make sure to *always* give back the peeking answer
788 * instead of the actual command, even if this command would fit into the current
789 * connection buffer. */
790 if (!mPeekCount)
791 {
792 rc = pHostCmd->Peek(pReq);
793 mPeekCount++;
794 }
795 else
796 {
797 /* Try assigning the host command to the client and store the
798 * result code for later use. */
799 rc = pHostCmd->Assign(pReq);
800 if (RT_FAILURE(rc)) /* If something failed, let the client peek (again). */
801 {
802 rc = pHostCmd->Peek(pReq);
803 mPeekCount++;
804 }
805 else
806 mPeekCount = 0;
807 }
808 }
809
810 /* Reset pending status. */
811 m_enmIsPending = (guestControl::eGuestFn)0;
812
813 /* In any case the client did something, so complete
814 * the pending call with the result we just got. */
815 AssertPtr(m_pSvcHelpers);
816 int rc2 = m_pSvcHelpers->pfnCallComplete(pReq->mHandle, rc);
817
818 /* Rollback in case the guest cancelled the call. */
819 if (rc2 == VERR_CANCELLED && RT_SUCCESS(rc))
820 {
821 mPeekCount = cSavedPeeks;
822 rc = VERR_CANCELLED;
823 }
824
825 LogFlowThisFunc(("[Client %RU32] Command %RU32 ended with %Rrc (mPeekCount=%RU32, pReq=%p)\n",
826 m_idClient, pHostCmd->mMsgType, rc, mPeekCount, pReq));
827 return rc;
828 }
829
830 /** @} */
831} ClientState;
832typedef std::map< uint32_t, ClientState *> ClientStateMap;
833
834/**
835 * Prepared session (GUEST_SESSION_PREPARE).
836 */
837typedef struct GstCtrlPreparedSession
838{
839 /** List entry. */
840 RTLISTNODE ListEntry;
841 /** The session ID. */
842 uint32_t idSession;
843 /** The key size. */
844 uint32_t cbKey;
845 /** The key bytes. */
846 uint8_t abKey[RT_FLEXIBLE_ARRAY];
847} GstCtrlPreparedSession;
848
849
850/**
851 * Class containing the shared information service functionality.
852 */
853class GstCtrlService : public RTCNonCopyable
854{
855
856private:
857
858 /** Type definition for use in callback functions. */
859 typedef GstCtrlService SELF;
860 /** HGCM helper functions. */
861 PVBOXHGCMSVCHELPERS mpHelpers;
862 /** Callback function supplied by the host for notification of updates to properties. */
863 PFNHGCMSVCEXT mpfnHostCallback;
864 /** User data pointer to be supplied to the host callback function. */
865 void *mpvHostData;
866 /** Map containing all connected clients, key is HGCM client ID. */
867 ClientStateMap mClientStateMap; /**< @todo Use VBOXHGCMSVCFNTABLE::cbClient for this! */
868 /** The current master client, NULL if none. */
869 ClientState *m_pMasterClient;
870 /** The master HGCM client ID, UINT32_MAX if none. */
871 uint32_t m_idMasterClient;
872 /** Set if we're in legacy mode (pre 6.0). */
873 bool m_fLegacyMode;
874 /** Number of prepared sessions. */
875 uint32_t m_cPreparedSessions;
876 /** List of prepared session (GstCtrlPreparedSession). */
877 RTLISTANCHOR m_PreparedSessions;
878
879public:
880 explicit GstCtrlService(PVBOXHGCMSVCHELPERS pHelpers)
881 : mpHelpers(pHelpers)
882 , mpfnHostCallback(NULL)
883 , mpvHostData(NULL)
884 , m_pMasterClient(NULL)
885 , m_idMasterClient(UINT32_MAX)
886 , m_fLegacyMode(true)
887 , m_cPreparedSessions(0)
888 {
889 RTListInit(&m_PreparedSessions);
890 }
891
892 static DECLCALLBACK(int) svcUnload(void *pvService);
893 static DECLCALLBACK(int) svcConnect(void *pvService, uint32_t idClient, void *pvClient,
894 uint32_t fRequestor, bool fRestoring);
895 static DECLCALLBACK(int) svcDisconnect(void *pvService, uint32_t idClient, void *pvClient);
896 static DECLCALLBACK(void) svcCall(void *pvService, VBOXHGCMCALLHANDLE callHandle, uint32_t idClient, void *pvClient,
897 uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM paParms[], uint64_t tsArrival);
898 static DECLCALLBACK(int) svcHostCall(void *pvService, uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
899 static DECLCALLBACK(int) svcSaveState(void *pvService, uint32_t idClient, void *pvClient, PSSMHANDLE pSSM);
900 static DECLCALLBACK(int) svcLoadState(void *pvService, uint32_t idClient, void *pvClient, PSSMHANDLE pSSM, uint32_t uVersion);
901 static DECLCALLBACK(int) svcRegisterExtension(void *pvService, PFNHGCMSVCEXT pfnExtension, void *pvExtension);
902
903private:
904 int clientMakeMeMaster(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms);
905 int clientMsgPeek(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool fWait);
906 int clientMsgGet(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
907 int clientMsgCancel(ClientState *pClient, uint32_t cParms);
908 int clientMsgSkip(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
909 int clientSessionPrepare(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
910 int clientSessionCancelPrepared(ClientState *pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
911 int clientSessionAccept(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
912 int clientSessionCloseOther(ClientState *pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
913 int clientToMain(ClientState *pClient, uint32_t idFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
914
915 int clientMsgOldGet(ClientState *pClient, VBOXHGCMCALLHANDLE callHandle, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
916 int clientMsgOldFilterSet(ClientState *pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
917 int clientMsgOldSkip(ClientState *pClient, uint32_t cParms);
918
919 int hostCallback(uint32_t idFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
920 int hostProcessCommand(uint32_t idFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
921
922 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(GstCtrlService);
923};
924
925
926/**
927 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnUnload,
928 * Simply deletes the GstCtrlService object}
929 */
930/*static*/ DECLCALLBACK(int)
931GstCtrlService::svcUnload(void *pvService)
932{
933 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
934 SELF *pThis = reinterpret_cast<SELF *>(pvService);
935 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
936
937 delete pThis;
938
939 return VINF_SUCCESS;
940}
941
942
943
944/**
945 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnConnect,
946 * Initializes the state for a new client.}
947 */
948/*static*/ DECLCALLBACK(int)
949GstCtrlService::svcConnect(void *pvService, uint32_t idClient, void *pvClient, uint32_t fRequestor, bool fRestoring)
950{
951 LogFlowFunc(("[Client %RU32] Connected\n", idClient));
952
953 RT_NOREF(fRestoring, pvClient);
954 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
955 SELF *pThis = reinterpret_cast<SELF *>(pvService);
956 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
957
958 AssertMsg(pThis->mClientStateMap.find(idClient) == pThis->mClientStateMap.end(),
959 ("Client with ID=%RU32 already connected when it should not\n", idClient));
960
961 /*
962 * Create client state.
963 */
964 ClientState *pClient;
965 //try - can't currently throw anything.
966 {
967 pClient = new (pvClient) ClientState(pThis->mpHelpers, idClient);
968 }
969 //catch (std::bad_alloc &)
970 //{
971 // return VERR_NO_MEMORY;
972 //}
973 try
974 {
975 pThis->mClientStateMap[idClient] = pClient;
976 }
977 catch (std::bad_alloc &)
978 {
979 pClient->~ClientState();
980 return VERR_NO_MEMORY;
981 }
982
983 /*
984 * For legacy compatibility reasons we have to pick a master client at some
985 * point, so if the /dev/vboxguest requirements checks out we pick the first
986 * one through the door.
987 */
988/** @todo make picking the master more dynamic/flexible? */
989 if ( pThis->m_fLegacyMode
990 && pThis->m_idMasterClient == UINT32_MAX)
991 {
992 if ( fRequestor == VMMDEV_REQUESTOR_LEGACY
993 || !(fRequestor & VMMDEV_REQUESTOR_USER_DEVICE))
994 {
995 LogFunc(("Picking %u as master for now.\n", idClient));
996 pThis->m_pMasterClient = pClient;
997 pThis->m_idMasterClient = idClient;
998 pClient->m_fIsMaster = true;
999 }
1000 }
1001
1002 return VINF_SUCCESS;
1003}
1004
1005
1006/**
1007 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnConnect,
1008 * Handles a client which disconnected.}
1009 *
1010 * This functiond does some internal cleanup as well as sends notifications to
1011 * the host so that the host can do the same (if required).
1012 */
1013/*static*/ DECLCALLBACK(int)
1014GstCtrlService::svcDisconnect(void *pvService, uint32_t idClient, void *pvClient)
1015{
1016 SELF *pThis = reinterpret_cast<SELF *>(pvService);
1017 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1018 ClientState *pClient = reinterpret_cast<ClientState *>(pvClient);
1019 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1020 LogFlowFunc(("[Client %RU32] Disconnected (%zu clients total)\n", idClient, pThis->mClientStateMap.size()));
1021
1022 /*
1023 * Cancel all pending host commands, replying with GUEST_DISCONNECTED if final recipient.
1024 */
1025 HostCommand *pCurCmd, *pNextCmd;
1026 RTListForEachSafeCpp(&pClient->m_HostCmdList, pCurCmd, pNextCmd, HostCommand, m_ListEntry)
1027 {
1028 RTListNodeRemove(&pCurCmd->m_ListEntry);
1029
1030 VBOXHGCMSVCPARM Parm;
1031 HGCMSvcSetU32(&Parm, pCurCmd->m_idContext);
1032 int rc2 = pThis->hostCallback(GUEST_DISCONNECTED, 1, &Parm);
1033 LogFlowFunc(("Cancelled host command %u (%s) with idContext=%#x -> %Rrc\n",
1034 pCurCmd->mMsgType, GstCtrlHostFnName((eHostFn)pCurCmd->mMsgType), pCurCmd->m_idContext, rc2));
1035 RT_NOREF(rc2);
1036
1037 pCurCmd->Delete();
1038 }
1039
1040 /*
1041 * Delete the client state.
1042 */
1043 pThis->mClientStateMap.erase(idClient);
1044 pClient->~ClientState();
1045 pClient = NULL;
1046
1047 /*
1048 * If it's the master disconnecting, we need to reset related globals.
1049 */
1050 if (idClient == pThis->m_idMasterClient)
1051 {
1052 pThis->m_pMasterClient = NULL;
1053 pThis->m_idMasterClient = UINT32_MAX;
1054
1055 GstCtrlPreparedSession *pCur, *pNext;
1056 RTListForEachSafe(&pThis->m_PreparedSessions, pCur, pNext, GstCtrlPreparedSession, ListEntry)
1057 {
1058 RTListNodeRemove(&pCur->ListEntry);
1059 RTMemFree(pCur);
1060 }
1061 pThis->m_cPreparedSessions = 0;
1062 }
1063 else
1064 Assert(pClient != pThis->m_pMasterClient);
1065
1066 if (pThis->mClientStateMap.empty())
1067 pThis->m_fLegacyMode = true;
1068
1069 return VINF_SUCCESS;
1070}
1071
1072
1073/**
1074 * A client asks for the next message to process.
1075 *
1076 * This either fills in a pending host command into the client's parameter space
1077 * or defers the guest call until we have something from the host.
1078 *
1079 * @returns VBox status code.
1080 * @param pClient The client state.
1081 * @param hCall The client's call handle.
1082 * @param cParms Number of parameters.
1083 * @param paParms Array of parameters.
1084 */
1085int GstCtrlService::clientMsgOldGet(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1086{
1087 ASSERT_GUEST(pClient->m_idSession != UINT32_MAX || pClient->m_fIsMaster);
1088
1089 /* Use the current (inbound) connection. */
1090 ClientRequest thisCon;
1091 thisCon.mHandle = hCall;
1092 thisCon.mNumParms = cParms;
1093 thisCon.mParms = paParms;
1094
1095 return pClient->OldRunCurrent(&thisCon);
1096}
1097
1098
1099/**
1100 * Implements GUEST_MAKE_ME_MASTER.
1101 *
1102 * @returns VBox status code.
1103 * @retval VINF_HGCM_ASYNC_EXECUTE on success (we complete the message here).
1104 * @retval VERR_ACCESS_DENIED if not using main VBoxGuest device not
1105 * @retval VERR_RESOURCE_BUSY if there is already a master.
1106 * @retval VERR_VERSION_MISMATCH if VBoxGuest didn't supply requestor info.
1107 * @retval VERR_WRONG_PARAMETER_COUNT
1108 *
1109 * @param pClient The client state.
1110 * @param hCall The client's call handle.
1111 * @param cParms Number of parameters.
1112 */
1113int GstCtrlService::clientMakeMeMaster(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms)
1114{
1115 /*
1116 * Validate the request.
1117 */
1118 ASSERT_GUEST_RETURN(cParms == 0, VERR_WRONG_PARAMETER_COUNT);
1119
1120 uint32_t fRequestor = mpHelpers->pfnGetRequestor(hCall);
1121 ASSERT_GUEST_LOGREL_MSG_RETURN(fRequestor != VMMDEV_REQUESTOR_LEGACY,
1122 ("Outdated VBoxGuest w/o requestor support. Please update!\n"),
1123 VERR_VERSION_MISMATCH);
1124 ASSERT_GUEST_LOGREL_MSG_RETURN(!(fRequestor & VMMDEV_REQUESTOR_USER_DEVICE), ("fRequestor=%#x\n", fRequestor),
1125 VERR_ACCESS_DENIED);
1126
1127 /*
1128 * Do the work.
1129 */
1130 ASSERT_GUEST_MSG_RETURN(m_idMasterClient == pClient->m_idClient || m_idMasterClient == UINT32_MAX,
1131 ("Already have master session %RU32, refusing %RU32.\n", m_idMasterClient, pClient->m_idClient),
1132 VERR_RESOURCE_BUSY);
1133 int rc = mpHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
1134 if (RT_SUCCESS(rc))
1135 {
1136 m_pMasterClient = pClient;
1137 m_idMasterClient = pClient->m_idClient;
1138 m_fLegacyMode = false;
1139 pClient->m_fIsMaster = true;
1140 Log(("[Client %RU32] is master.\n", pClient->m_idClient));
1141 }
1142 else
1143 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
1144
1145 return VINF_HGCM_ASYNC_EXECUTE;
1146}
1147
1148/**
1149 * Implements GUEST_MSG_PEEK_WAIT and GUEST_MSG_PEEK_NOWAIT.
1150 *
1151 * @returns VBox status code.
1152 * @retval VINF_SUCCESS if a message was pending and is being returned.
1153 * @retval VERR_TRY_AGAIN if no message pending and not blocking.
1154 * @retval VERR_RESOURCE_BUSY if another read already made a waiting call.
1155 * @retval VINF_HGCM_ASYNC_EXECUTE if message wait is pending.
1156 *
1157 * @param pClient The client state.
1158 * @param hCall The client's call handle.
1159 * @param cParms Number of parameters.
1160 * @param paParms Array of parameters.
1161 * @param fWait Set if we should wait for a message, clear if to return
1162 * immediately.
1163 */
1164int GstCtrlService::clientMsgPeek(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool fWait)
1165{
1166 /*
1167 * Validate the request.
1168 */
1169 ASSERT_GUEST_MSG_RETURN(cParms >= 2, ("cParms=%u!\n", cParms), VERR_WRONG_PARAMETER_COUNT);
1170
1171 uint64_t idRestoreCheck = 0;
1172 uint32_t i = 0;
1173 if (paParms[i].type == VBOX_HGCM_SVC_PARM_64BIT)
1174 {
1175 idRestoreCheck = paParms[0].u.uint64;
1176 paParms[0].u.uint64 = 0;
1177 i++;
1178 }
1179 for (; i < cParms; i++)
1180 {
1181 ASSERT_GUEST_MSG_RETURN(paParms[i].type == VBOX_HGCM_SVC_PARM_32BIT, ("#%u type=%u\n", i, paParms[i].type),
1182 VERR_WRONG_PARAMETER_TYPE);
1183 paParms[i].u.uint32 = 0;
1184 }
1185
1186 /*
1187 * Check restore session ID.
1188 */
1189 if (idRestoreCheck != 0)
1190 {
1191 uint64_t idRestore = mpHelpers->pfnGetVMMDevSessionId(mpHelpers);
1192 if (idRestoreCheck != idRestore)
1193 {
1194 paParms[0].u.uint64 = idRestore;
1195 LogFlowFunc(("[Client %RU32] GUEST_MSG_PEEK_XXXX -> VERR_VM_RESTORED (%#RX64 -> %#RX64)\n",
1196 pClient->m_idClient, idRestoreCheck, idRestore));
1197 return VERR_VM_RESTORED;
1198 }
1199 Assert(!mpHelpers->pfnIsCallRestored(hCall));
1200 }
1201
1202 /*
1203 * Return information about the first command if one is pending in the list.
1204 */
1205 HostCommand *pFirstCmd = RTListGetFirstCpp(&pClient->m_HostCmdList, HostCommand, m_ListEntry);
1206 if (pFirstCmd)
1207 {
1208 pFirstCmd->setPeekReturn(paParms, cParms);
1209 LogFlowFunc(("[Client %RU32] GUEST_MSG_PEEK_XXXX -> VINF_SUCCESS (idMsg=%u (%s), cParms=%u)\n",
1210 pClient->m_idClient, pFirstCmd->mMsgType, GstCtrlHostFnName((eHostFn)pFirstCmd->mMsgType), pFirstCmd->mParmCount));
1211 return VINF_SUCCESS;
1212 }
1213
1214 /*
1215 * If we cannot wait, fail the call.
1216 */
1217 if (!fWait)
1218 {
1219 LogFlowFunc(("[Client %RU32] GUEST_MSG_PEEK_NOWAIT -> VERR_TRY_AGAIN\n", pClient->m_idClient));
1220 return VERR_TRY_AGAIN;
1221 }
1222
1223 /*
1224 * Wait for the host to queue a message for this client.
1225 */
1226 ASSERT_GUEST_MSG_RETURN(pClient->m_enmIsPending == 0, ("Already pending! (idClient=%RU32)\n", pClient->m_idClient),
1227 VERR_RESOURCE_BUSY);
1228 pClient->m_PendingReq.mHandle = hCall;
1229 pClient->m_PendingReq.mNumParms = cParms;
1230 pClient->m_PendingReq.mParms = paParms;
1231 pClient->m_enmIsPending = GUEST_MSG_PEEK_WAIT;
1232 LogFlowFunc(("[Client %RU32] Is now in pending mode...\n", pClient->m_idClient));
1233 return VINF_HGCM_ASYNC_EXECUTE;
1234}
1235
1236/**
1237 * Implements GUEST_MSG_GET.
1238 *
1239 * @returns VBox status code.
1240 * @retval VINF_SUCCESS if message retrieved and removed from the pending queue.
1241 * @retval VERR_TRY_AGAIN if no message pending.
1242 * @retval VERR_BUFFER_OVERFLOW if a parmeter buffer is too small. The buffer
1243 * size was updated to reflect the required size, though this isn't yet
1244 * forwarded to the guest. (The guest is better of using peek with
1245 * parameter count + 2 parameters to get the sizes.)
1246 * @retval VERR_MISMATCH if the incoming message ID does not match the pending.
1247 * @retval VINF_HGCM_ASYNC_EXECUTE if message was completed already.
1248 *
1249 * @param pClient The client state.
1250 * @param hCall The client's call handle.
1251 * @param cParms Number of parameters.
1252 * @param paParms Array of parameters.
1253 */
1254int GstCtrlService::clientMsgGet(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1255{
1256 /*
1257 * Validate the request.
1258 *
1259 * The weird first parameter logic is due to GUEST_MSG_WAIT compatibility
1260 * (don't want to rewrite all the message structures).
1261 */
1262 uint32_t const idMsgExpected = cParms > 0 && paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT ? paParms[0].u.uint32
1263 : cParms > 0 && paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT ? paParms[0].u.uint64
1264 : UINT32_MAX;
1265
1266 /*
1267 * Return information about the first command if one is pending in the list.
1268 */
1269 HostCommand *pFirstCmd = RTListGetFirstCpp(&pClient->m_HostCmdList, HostCommand, m_ListEntry);
1270 if (pFirstCmd)
1271 {
1272
1273 ASSERT_GUEST_MSG_RETURN(pFirstCmd->mMsgType == idMsgExpected || idMsgExpected == UINT32_MAX,
1274 ("idMsg=%u (%s) cParms=%u, caller expected %u (%s) and %u\n",
1275 pFirstCmd->mMsgType, GstCtrlHostFnName((eHostFn)pFirstCmd->mMsgType), pFirstCmd->mParmCount,
1276 idMsgExpected, GstCtrlHostFnName((eHostFn)idMsgExpected), cParms),
1277 VERR_MISMATCH);
1278 ASSERT_GUEST_MSG_RETURN(pFirstCmd->mParmCount == cParms,
1279 ("idMsg=%u (%s) cParms=%u, caller expected %u (%s) and %u\n",
1280 pFirstCmd->mMsgType, GstCtrlHostFnName((eHostFn)pFirstCmd->mMsgType), pFirstCmd->mParmCount,
1281 idMsgExpected, GstCtrlHostFnName((eHostFn)idMsgExpected), cParms),
1282 VERR_WRONG_PARAMETER_COUNT);
1283
1284 /* Check the parameter types. */
1285 for (uint32_t i = 0; i < cParms; i++)
1286 ASSERT_GUEST_MSG_RETURN(pFirstCmd->mpParms[i].type == paParms[i].type,
1287 ("param #%u: type %u, caller expected %u (idMsg=%u %s)\n", i, pFirstCmd->mpParms[i].type,
1288 paParms[i].type, pFirstCmd->mMsgType, GstCtrlHostFnName((eHostFn)pFirstCmd->mMsgType)),
1289 VERR_WRONG_PARAMETER_TYPE);
1290
1291 /*
1292 * Copy out the parameters.
1293 *
1294 * No assertions on buffer overflows, and keep going till the end so we can
1295 * communicate all the required buffer sizes.
1296 */
1297 int rc = VINF_SUCCESS;
1298 for (uint32_t i = 0; i < cParms; i++)
1299 switch (pFirstCmd->mpParms[i].type)
1300 {
1301 case VBOX_HGCM_SVC_PARM_32BIT:
1302 paParms[i].u.uint32 = pFirstCmd->mpParms[i].u.uint32;
1303 break;
1304
1305 case VBOX_HGCM_SVC_PARM_64BIT:
1306 paParms[i].u.uint64 = pFirstCmd->mpParms[i].u.uint64;
1307 break;
1308
1309 case VBOX_HGCM_SVC_PARM_PTR:
1310 {
1311 uint32_t const cbSrc = pFirstCmd->mpParms[i].u.pointer.size;
1312 uint32_t const cbDst = paParms[i].u.pointer.size;
1313 paParms[i].u.pointer.size = cbSrc; /** @todo Check if this is safe in other layers...
1314 * Update: Safe, yes, but VMMDevHGCM doesn't pass it along. */
1315 if (cbSrc <= cbDst)
1316 memcpy(paParms[i].u.pointer.addr, pFirstCmd->mpParms[i].u.pointer.addr, cbSrc);
1317 else
1318 rc = VERR_BUFFER_OVERFLOW;
1319 break;
1320 }
1321
1322 default:
1323 AssertMsgFailed(("#%u: %u\n", i, pFirstCmd->mpParms[i].type));
1324 rc = VERR_INTERNAL_ERROR;
1325 break;
1326 }
1327 if (RT_SUCCESS(rc))
1328 {
1329 /*
1330 * Complete the command and remove the pending message unless the
1331 * guest raced us and cancelled this call in the meantime.
1332 */
1333 AssertPtr(mpHelpers);
1334 rc = mpHelpers->pfnCallComplete(hCall, rc);
1335 if (rc != VERR_CANCELLED)
1336 {
1337 RTListNodeRemove(&pFirstCmd->m_ListEntry);
1338 pFirstCmd->Delete();
1339 }
1340 else
1341 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
1342 return VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
1343 }
1344 return rc;
1345 }
1346
1347 paParms[0].u.uint32 = 0;
1348 paParms[1].u.uint32 = 0;
1349 LogFlowFunc(("[Client %RU32] GUEST_MSG_GET -> VERR_TRY_AGAIN\n", pClient->m_idClient));
1350 return VERR_TRY_AGAIN;
1351}
1352
1353/**
1354 * Implements GUEST_MSG_CANCEL.
1355 *
1356 * @returns VBox status code.
1357 * @retval VINF_SUCCESS if cancelled any calls.
1358 * @retval VWRN_NOT_FOUND if no callers.
1359 * @retval VINF_HGCM_ASYNC_EXECUTE if message wait is pending.
1360 *
1361 * @param pClient The client state.
1362 * @param cParms Number of parameters.
1363 */
1364int GstCtrlService::clientMsgCancel(ClientState *pClient, uint32_t cParms)
1365{
1366 /*
1367 * Validate the request.
1368 */
1369 ASSERT_GUEST_MSG_RETURN(cParms == 0, ("cParms=%u!\n", cParms), VERR_WRONG_PARAMETER_COUNT);
1370
1371 /*
1372 * Execute.
1373 */
1374 if (pClient->m_enmIsPending != 0)
1375 {
1376 pClient->CancelWaiting();
1377 return VINF_SUCCESS;
1378 }
1379 return VWRN_NOT_FOUND;
1380}
1381
1382
1383/**
1384 * Implements GUEST_MSG_SKIP.
1385 *
1386 * @returns VBox status code.
1387 * @retval VINF_HGCM_ASYNC_EXECUTE on success as we complete the message.
1388 * @retval VERR_NOT_FOUND if no message pending.
1389 *
1390 * @param pClient The client state.
1391 * @param hCall The call handle for completing it.
1392 * @param cParms Number of parameters.
1393 * @param paParms The parameters.
1394 */
1395int GstCtrlService::clientMsgSkip(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1396{
1397 /*
1398 * Validate the call.
1399 */
1400 ASSERT_GUEST_RETURN(cParms <= 2, VERR_WRONG_PARAMETER_COUNT);
1401
1402 int32_t rcSkip = VERR_NOT_SUPPORTED;
1403 if (cParms >= 1)
1404 {
1405 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1406 rcSkip = (int32_t)paParms[0].u.uint32;
1407 }
1408
1409 uint32_t idMsg = UINT32_MAX;
1410 if (cParms >= 2)
1411 {
1412 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1413 idMsg = paParms[1].u.uint32;
1414 }
1415
1416 /*
1417 * Do the job.
1418 */
1419 HostCommand *pFirstCmd = RTListGetFirstCpp(&pClient->m_HostCmdList, HostCommand, m_ListEntry);
1420 if (pFirstCmd)
1421 {
1422 if ( pFirstCmd->mMsgType == idMsg
1423 || idMsg == UINT32_MAX)
1424 {
1425 int rc = mpHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
1426 if (RT_SUCCESS(rc))
1427 {
1428 /*
1429 * Remove the command from the queue.
1430 */
1431 Assert(RTListNodeIsFirst(&pClient->m_HostCmdList, &pFirstCmd->m_ListEntry) );
1432 RTListNodeRemove(&pFirstCmd->m_ListEntry);
1433
1434 /*
1435 * Compose a reply to the host service.
1436 */
1437 VBOXHGCMSVCPARM aReplyParams[5];
1438 HGCMSvcSetU32(&aReplyParams[0], pFirstCmd->m_idContext);
1439 switch (pFirstCmd->mMsgType)
1440 {
1441 case HOST_EXEC_CMD:
1442 HGCMSvcSetU32(&aReplyParams[1], 0); /* pid */
1443 HGCMSvcSetU32(&aReplyParams[2], PROC_STS_ERROR); /* status */
1444 HGCMSvcSetU32(&aReplyParams[3], rcSkip); /* flags / whatever */
1445 HGCMSvcSetPv(&aReplyParams[4], NULL, 0); /* data buffer */
1446 hostCallback(GUEST_EXEC_STATUS, 5, aReplyParams);
1447 break;
1448
1449 case HOST_SESSION_CREATE:
1450 HGCMSvcSetU32(&aReplyParams[1], GUEST_SESSION_NOTIFYTYPE_ERROR); /* type */
1451 HGCMSvcSetU32(&aReplyParams[2], rcSkip); /* result */
1452 hostCallback(GUEST_SESSION_NOTIFY, 3, aReplyParams);
1453 break;
1454
1455 case HOST_EXEC_SET_INPUT:
1456 HGCMSvcSetU32(&aReplyParams[1], pFirstCmd->mParmCount >= 2 ? pFirstCmd->mpParms[1].u.uint32 : 0);
1457 HGCMSvcSetU32(&aReplyParams[2], INPUT_STS_ERROR); /* status */
1458 HGCMSvcSetU32(&aReplyParams[3], rcSkip); /* flags / whatever */
1459 HGCMSvcSetU32(&aReplyParams[4], 0); /* bytes consumed */
1460 hostCallback(GUEST_EXEC_INPUT_STATUS, 5, aReplyParams);
1461 break;
1462
1463 case HOST_FILE_OPEN:
1464 HGCMSvcSetU32(&aReplyParams[1], GUEST_FILE_NOTIFYTYPE_OPEN); /* type*/
1465 HGCMSvcSetU32(&aReplyParams[2], rcSkip); /* rc */
1466 HGCMSvcSetU32(&aReplyParams[3], VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pFirstCmd->m_idContext)); /* handle */
1467 hostCallback(GUEST_FILE_NOTIFY, 4, aReplyParams);
1468 break;
1469 case HOST_FILE_CLOSE:
1470 HGCMSvcSetU32(&aReplyParams[1], GUEST_FILE_NOTIFYTYPE_ERROR); /* type*/
1471 HGCMSvcSetU32(&aReplyParams[2], rcSkip); /* rc */
1472 hostCallback(GUEST_FILE_NOTIFY, 3, aReplyParams);
1473 break;
1474 case HOST_FILE_READ:
1475 case HOST_FILE_READ_AT:
1476 HGCMSvcSetU32(&aReplyParams[1], GUEST_FILE_NOTIFYTYPE_READ); /* type */
1477 HGCMSvcSetU32(&aReplyParams[2], rcSkip); /* rc */
1478 HGCMSvcSetPv(&aReplyParams[3], NULL, 0); /* data buffer */
1479 hostCallback(GUEST_FILE_NOTIFY, 4, aReplyParams);
1480 break;
1481 case HOST_FILE_WRITE:
1482 case HOST_FILE_WRITE_AT:
1483 HGCMSvcSetU32(&aReplyParams[1], GUEST_FILE_NOTIFYTYPE_WRITE); /* type */
1484 HGCMSvcSetU32(&aReplyParams[2], rcSkip); /* rc */
1485 HGCMSvcSetU32(&aReplyParams[3], 0); /* bytes written */
1486 hostCallback(GUEST_FILE_NOTIFY, 4, aReplyParams);
1487 break;
1488 case HOST_FILE_SEEK:
1489 HGCMSvcSetU32(&aReplyParams[1], GUEST_FILE_NOTIFYTYPE_SEEK); /* type */
1490 HGCMSvcSetU32(&aReplyParams[2], rcSkip); /* rc */
1491 HGCMSvcSetU64(&aReplyParams[3], 0); /* actual */
1492 hostCallback(GUEST_FILE_NOTIFY, 4, aReplyParams);
1493 break;
1494 case HOST_FILE_TELL:
1495 HGCMSvcSetU32(&aReplyParams[1], GUEST_FILE_NOTIFYTYPE_TELL); /* type */
1496 HGCMSvcSetU32(&aReplyParams[2], rcSkip); /* rc */
1497 HGCMSvcSetU64(&aReplyParams[3], 0); /* actual */
1498 hostCallback(GUEST_FILE_NOTIFY, 4, aReplyParams);
1499 break;
1500
1501 case HOST_EXEC_GET_OUTPUT: /** @todo This can't be right/work. */
1502 case HOST_EXEC_TERMINATE: /** @todo This can't be right/work. */
1503 case HOST_EXEC_WAIT_FOR: /** @todo This can't be right/work. */
1504 case HOST_PATH_USER_DOCUMENTS:
1505 case HOST_PATH_USER_HOME:
1506 case HOST_PATH_RENAME:
1507 case HOST_DIR_REMOVE:
1508 default:
1509 HGCMSvcSetU32(&aReplyParams[1], pFirstCmd->mMsgType);
1510 HGCMSvcSetU32(&aReplyParams[2], (uint32_t)rcSkip);
1511 HGCMSvcSetPv(&aReplyParams[3], NULL, 0);
1512 hostCallback(GUEST_MSG_REPLY, 4, aReplyParams);
1513 break;
1514 }
1515
1516 /*
1517 * Free the command.
1518 */
1519 pFirstCmd->Delete();
1520 }
1521 else
1522 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
1523 return VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
1524 }
1525 LogFunc(("Warning: GUEST_MSG_SKIP mismatch! Found %u, caller expected %u!\n", pFirstCmd->mMsgType, idMsg));
1526 return VERR_MISMATCH;
1527 }
1528 return VERR_NOT_FOUND;
1529}
1530
1531
1532/**
1533 * Implements GUEST_SESSION_PREPARE.
1534 *
1535 * @returns VBox status code.
1536 * @retval VINF_HGCM_ASYNC_EXECUTE on success as we complete the message.
1537 * @retval VERR_OUT_OF_RESOURCES if too many pending sessions hanging around.
1538 * @retval VERR_OUT_OF_RANGE if the session ID outside the allowed range.
1539 * @retval VERR_BUFFER_OVERFLOW if key too large.
1540 * @retval VERR_BUFFER_UNDERFLOW if key too small.
1541 * @retval VERR_ACCESS_DENIED if not master or in legacy mode.
1542 * @retval VERR_DUPLICATE if the session ID has been prepared already.
1543 *
1544 * @param pClient The client state.
1545 * @param hCall The call handle for completing it.
1546 * @param cParms Number of parameters.
1547 * @param paParms The parameters.
1548 */
1549int GstCtrlService::clientSessionPrepare(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1550{
1551 /*
1552 * Validate parameters.
1553 */
1554 ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
1555 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1556 uint32_t const idSession = paParms[0].u.uint32;
1557 ASSERT_GUEST_RETURN(idSession >= 1, VERR_OUT_OF_RANGE);
1558 ASSERT_GUEST_RETURN(idSession <= 0xfff0, VERR_OUT_OF_RANGE);
1559
1560 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE);
1561 uint32_t const cbKey = paParms[1].u.pointer.size;
1562 void const *pvKey = paParms[1].u.pointer.addr;
1563 ASSERT_GUEST_RETURN(cbKey >= 64, VERR_BUFFER_UNDERFLOW);
1564 ASSERT_GUEST_RETURN(cbKey <= _16K, VERR_BUFFER_OVERFLOW);
1565
1566 ASSERT_GUEST_RETURN(pClient->m_fIsMaster, VERR_ACCESS_DENIED);
1567 ASSERT_GUEST_RETURN(!m_fLegacyMode, VERR_ACCESS_DENIED);
1568 Assert(m_idMasterClient == pClient->m_idClient);
1569 Assert(m_pMasterClient == pClient);
1570
1571 /* Now that we know it's the master, we can check for session ID duplicates. */
1572 GstCtrlPreparedSession *pCur;
1573 RTListForEach(&m_PreparedSessions, pCur, GstCtrlPreparedSession, ListEntry)
1574 {
1575 ASSERT_GUEST_RETURN(pCur->idSession != idSession, VERR_DUPLICATE);
1576 }
1577
1578 /*
1579 * Make a copy of the session ID and key.
1580 */
1581 ASSERT_GUEST_RETURN(m_cPreparedSessions < 128, VERR_OUT_OF_RESOURCES);
1582
1583 GstCtrlPreparedSession *pPrepped = (GstCtrlPreparedSession *)RTMemAlloc(RT_UOFFSETOF_DYN(GstCtrlPreparedSession, abKey[cbKey]));
1584 AssertReturn(pPrepped, VERR_NO_MEMORY);
1585 pPrepped->idSession = idSession;
1586 pPrepped->cbKey = cbKey;
1587 memcpy(pPrepped->abKey, pvKey, cbKey);
1588
1589 RTListAppend(&m_PreparedSessions, &pPrepped->ListEntry);
1590 m_cPreparedSessions++;
1591
1592 /*
1593 * Try complete the command.
1594 */
1595 int rc = mpHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
1596 if (RT_SUCCESS(rc))
1597 LogFlow(("Prepared %u with a %#x byte key (%u pending).\n", idSession, cbKey, m_cPreparedSessions));
1598 else
1599 {
1600 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
1601 RTListNodeRemove(&pPrepped->ListEntry);
1602 RTMemFree(pPrepped);
1603 m_cPreparedSessions--;
1604 }
1605 return VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
1606}
1607
1608
1609/**
1610 * Implements GUEST_SESSION_CANCEL_PREPARED.
1611 *
1612 * @returns VBox status code.
1613 * @retval VINF_HGCM_ASYNC_EXECUTE on success as we complete the message.
1614 * @retval VWRN_NOT_FOUND if no session with the specified ID.
1615 * @retval VERR_ACCESS_DENIED if not master or in legacy mode.
1616 *
1617 * @param pClient The client state.
1618 * @param cParms Number of parameters.
1619 * @param paParms The parameters.
1620 */
1621int GstCtrlService::clientSessionCancelPrepared(ClientState *pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1622{
1623 /*
1624 * Validate parameters.
1625 */
1626 ASSERT_GUEST_RETURN(cParms == 1, VERR_WRONG_PARAMETER_COUNT);
1627 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1628 uint32_t const idSession = paParms[0].u.uint32;
1629
1630 ASSERT_GUEST_RETURN(pClient->m_fIsMaster, VERR_ACCESS_DENIED);
1631 ASSERT_GUEST_RETURN(!m_fLegacyMode, VERR_ACCESS_DENIED);
1632 Assert(m_idMasterClient == pClient->m_idClient);
1633 Assert(m_pMasterClient == pClient);
1634
1635 /*
1636 * Do the work.
1637 */
1638 int rc = VWRN_NOT_FOUND;
1639 if (idSession == UINT32_MAX)
1640 {
1641 GstCtrlPreparedSession *pCur, *pNext;
1642 RTListForEachSafe(&m_PreparedSessions, pCur, pNext, GstCtrlPreparedSession, ListEntry)
1643 {
1644 RTListNodeRemove(&pCur->ListEntry);
1645 RTMemFree(pCur);
1646 rc = VINF_SUCCESS;
1647 }
1648 m_cPreparedSessions = 0;
1649 }
1650 else
1651 {
1652 GstCtrlPreparedSession *pCur, *pNext;
1653 RTListForEachSafe(&m_PreparedSessions, pCur, pNext, GstCtrlPreparedSession, ListEntry)
1654 {
1655 if (pCur->idSession == idSession)
1656 {
1657 RTListNodeRemove(&pCur->ListEntry);
1658 RTMemFree(pCur);
1659 m_cPreparedSessions -= 1;
1660 rc = VINF_SUCCESS;
1661 break;
1662 }
1663 }
1664 }
1665 return VINF_SUCCESS;
1666}
1667
1668
1669/**
1670 * Implements GUEST_SESSION_ACCEPT.
1671 *
1672 * @returns VBox status code.
1673 * @retval VINF_HGCM_ASYNC_EXECUTE on success as we complete the message.
1674 * @retval VERR_NOT_FOUND if the specified session ID wasn't found.
1675 * @retval VERR_MISMATCH if the key didn't match.
1676 * @retval VERR_ACCESS_DENIED if we're in legacy mode or is master.
1677 * @retval VERR_RESOURCE_BUSY if the client is already associated with a
1678 * session.
1679 *
1680 * @param pClient The client state.
1681 * @param hCall The call handle for completing it.
1682 * @param cParms Number of parameters.
1683 * @param paParms The parameters.
1684 */
1685int GstCtrlService::clientSessionAccept(ClientState *pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1686{
1687 /*
1688 * Validate parameters.
1689 */
1690 ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
1691 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1692 uint32_t const idSession = paParms[0].u.uint32;
1693 ASSERT_GUEST_RETURN(idSession >= 1, VERR_OUT_OF_RANGE);
1694 ASSERT_GUEST_RETURN(idSession <= 0xfff0, VERR_OUT_OF_RANGE);
1695
1696 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE);
1697 uint32_t const cbKey = paParms[1].u.pointer.size;
1698 void const *pvKey = paParms[1].u.pointer.addr;
1699 ASSERT_GUEST_RETURN(cbKey >= 64, VERR_BUFFER_UNDERFLOW);
1700 ASSERT_GUEST_RETURN(cbKey <= _16K, VERR_BUFFER_OVERFLOW);
1701
1702 ASSERT_GUEST_RETURN(!pClient->m_fIsMaster, VERR_ACCESS_DENIED);
1703 ASSERT_GUEST_RETURN(!m_fLegacyMode, VERR_ACCESS_DENIED);
1704 Assert(m_idMasterClient != pClient->m_idClient);
1705 Assert(m_pMasterClient != pClient);
1706 ASSERT_GUEST_RETURN(pClient->m_idSession == UINT32_MAX, VERR_RESOURCE_BUSY);
1707
1708 /*
1709 * Look for the specified session and match the key to it.
1710 */
1711 GstCtrlPreparedSession *pCur;
1712 RTListForEach(&m_PreparedSessions, pCur, GstCtrlPreparedSession, ListEntry)
1713 {
1714 if (pCur->idSession == idSession)
1715 {
1716 if ( pCur->cbKey == cbKey
1717 && memcmp(pCur->abKey, pvKey, cbKey) == 0)
1718 {
1719 /*
1720 * We've got a match. Try complete the request and
1721 */
1722 int rc = mpHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
1723 if (RT_SUCCESS(rc))
1724 {
1725 pClient->m_idSession = idSession;
1726
1727 RTListNodeRemove(&pCur->ListEntry);
1728 RTMemFree(pCur);
1729 m_cPreparedSessions -= 1;
1730 Log(("[Client %RU32] accepted session id %u.\n", pClient->m_idClient, idSession));
1731 }
1732 else
1733 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
1734 return VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
1735 }
1736 LogFunc(("Key mismatch for %u!\n", pClient->m_idClient));
1737 return VERR_MISMATCH;
1738 }
1739 }
1740
1741 LogFunc(("No client prepared for %u!\n", pClient->m_idClient));
1742 return VERR_NOT_FOUND;
1743}
1744
1745
1746/**
1747 * Client asks another client (guest) session to close.
1748 *
1749 * @returns VBox status code.
1750 * @param pClient The client state.
1751 * @param cParms Number of parameters.
1752 * @param paParms Array of parameters.
1753 */
1754int GstCtrlService::clientSessionCloseOther(ClientState *pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1755{
1756 /*
1757 * Validate input.
1758 */
1759 ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
1760 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1761 uint32_t const idContext = paParms[0].u.uint32;
1762
1763 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1764 uint32_t const fFlags = paParms[1].u.uint32;
1765
1766 ASSERT_GUEST_RETURN(pClient->m_fIsMaster, VERR_ACCESS_DENIED);
1767
1768 /*
1769 * Forward the command to the destiation.
1770 * Since we modify the first parameter, we must make a copy of the parameters.
1771 */
1772 VBOXHGCMSVCPARM aParms[2];
1773 HGCMSvcSetU64(&aParms[0], idContext | VBOX_GUESTCTRL_DST_SESSION);
1774 HGCMSvcSetU32(&aParms[1], fFlags);
1775 int rc = hostProcessCommand(HOST_SESSION_CLOSE, RT_ELEMENTS(aParms), aParms);
1776
1777 LogFlowFunc(("Closing guest context ID=%RU32 (from client ID=%RU32) returned with rc=%Rrc\n", idContext, pClient->m_idClient, rc));
1778 return rc;
1779}
1780
1781
1782/**
1783 * For compatiblity with old additions only - filtering / set session ID.
1784 *
1785 * @return VBox status code.
1786 * @param pClient The client state.
1787 * @param cParms Number of parameters.
1788 * @param paParms Array of parameters.
1789 */
1790int GstCtrlService::clientMsgOldFilterSet(ClientState *pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1791{
1792 /*
1793 * Validate input and access.
1794 */
1795 ASSERT_GUEST_RETURN(cParms == 4, VERR_WRONG_PARAMETER_COUNT);
1796 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1797 uint32_t uValue = paParms[0].u.uint32;
1798 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1799 uint32_t fMaskAdd = paParms[1].u.uint32;
1800 ASSERT_GUEST_RETURN(paParms[2].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1801 uint32_t fMaskRemove = paParms[2].u.uint32;
1802 ASSERT_GUEST_RETURN(paParms[3].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* flags, unused */
1803
1804 /*
1805 * We have a bunch of expectations here:
1806 * - Never called in non-legacy mode.
1807 * - Only called once per session.
1808 * - Never called by the master session.
1809 * - Clients that doesn't wish for any messages passes all zeros.
1810 * - All other calls has a unique session ID.
1811 */
1812 ASSERT_GUEST_LOGREL_RETURN(m_fLegacyMode, VERR_WRONG_ORDER);
1813 ASSERT_GUEST_LOGREL_MSG_RETURN(pClient->m_idSession == UINT32_MAX, ("m_idSession=%#x\n", pClient->m_idSession),
1814 VERR_WRONG_ORDER);
1815 ASSERT_GUEST_LOGREL_RETURN(!pClient->m_fIsMaster, VERR_WRONG_ORDER);
1816
1817 if (uValue == 0)
1818 {
1819 ASSERT_GUEST_LOGREL(fMaskAdd == 0);
1820 ASSERT_GUEST_LOGREL(fMaskRemove == 0);
1821 /* Nothing to do, already muted (UINT32_MAX). */
1822 }
1823 else
1824 {
1825 ASSERT_GUEST_LOGREL(fMaskAdd == UINT32_C(0xf8000000));
1826 ASSERT_GUEST_LOGREL(fMaskRemove == 0);
1827
1828 uint32_t idSession = VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(uValue);
1829 ASSERT_GUEST_LOGREL_MSG_RETURN(idSession > 0, ("idSession=%u (%#x)\n", idSession, uValue), VERR_OUT_OF_RANGE);
1830
1831 for (ClientStateMap::iterator It = mClientStateMap.begin(); It != mClientStateMap.end(); ++It)
1832 ASSERT_GUEST_LOGREL_MSG_RETURN(It->second->m_idSession != idSession,
1833 ("idSession=%u uValue=%#x idClient=%u; conflicting with client %u\n",
1834 idSession, uValue, pClient->m_idClient, It->second->m_idClient),
1835 VERR_DUPLICATE);
1836 /* Commit it. */
1837 pClient->m_idSession = idSession;
1838 }
1839 return VINF_SUCCESS;
1840}
1841
1842
1843/**
1844 * For compatibility with old additions only - skip the current command w/o
1845 * calling main code.
1846 *
1847 * Please note that we don't care if the caller cancelled the request, because
1848 * old additions code didn't give damn about VERR_INTERRUPT.
1849 *
1850 * @return VBox status code.
1851 * @param pClient The client state.
1852 * @param cParms Number of parameters.
1853 */
1854int GstCtrlService::clientMsgOldSkip(ClientState *pClient, uint32_t cParms)
1855{
1856 /*
1857 * Validate input and access.
1858 */
1859 ASSERT_GUEST_RETURN(cParms == 1, VERR_WRONG_PARAMETER_COUNT);
1860
1861 /*
1862 * Execute the request.
1863 */
1864 if (!RTListIsEmpty(&pClient->m_HostCmdList))
1865 pClient->OldDitchFirstHostCmd();
1866
1867 LogFlowFunc(("[Client %RU32] Skipped current message - leagcy function\n", pClient->m_idClient));
1868 return VINF_SUCCESS;
1869}
1870
1871
1872/**
1873 * Forwards client call to the Main API.
1874 *
1875 * This is typically notifications and replys.
1876 *
1877 * @returns VBox status code.
1878 * @param pClient The client state.
1879 * @param idFunction Function (event) that occured.
1880 * @param cParms Number of parameters.
1881 * @param paParms Array of parameters.
1882 */
1883int GstCtrlService::clientToMain(ClientState *pClient, uint32_t idFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1884{
1885 /*
1886 * Do input validation. This class of messages all have a 32-bit context ID as
1887 * the first parameter, so make sure it is there and appropriate for the caller.
1888 */
1889 ASSERT_GUEST_RETURN(cParms >= 1, VERR_WRONG_PARAMETER_COUNT);
1890 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_COUNT);
1891 uint32_t const idContext = paParms[0].u.uint32;
1892 uint32_t const idSession = VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(idContext);
1893
1894 ASSERT_GUEST_MSG_RETURN( pClient->m_idSession == idSession
1895 || pClient->m_fIsMaster
1896 || ( m_fLegacyMode /* (see bugref:9313#c16) */
1897 && pClient->m_idSession == UINT32_MAX
1898 && ( idFunction == GUEST_EXEC_STATUS
1899 || idFunction == GUEST_SESSION_NOTIFY)),
1900 ("idSession=%u (CID=%#x) m_idSession=%u idClient=%u idFunction=%u (%s)\n", idSession, idContext,
1901 pClient->m_idSession, pClient->m_idClient, idFunction, GstCtrlGuestFnName((eGuestFn)idFunction)),
1902 VERR_ACCESS_DENIED);
1903
1904 /*
1905 * It seems okay, so make the call.
1906 */
1907 return hostCallback(idFunction, cParms, paParms);
1908}
1909
1910
1911/**
1912 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnCall}
1913 *
1914 * @note All functions which do not involve an unreasonable delay will be
1915 * handled synchronously. If needed, we will add a request handler
1916 * thread in future for those which do.
1917 * @thread HGCM
1918 */
1919/*static*/ DECLCALLBACK(void)
1920GstCtrlService::svcCall(void *pvService, VBOXHGCMCALLHANDLE hCall, uint32_t idClient, void *pvClient,
1921 uint32_t idFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[], uint64_t tsArrival)
1922{
1923 LogFlowFunc(("[Client %RU32] idFunction=%RU32 (%s), cParms=%RU32, paParms=0x%p\n",
1924 idClient, idFunction, GstCtrlGuestFnName((eGuestFn)idFunction), cParms, paParms));
1925 RT_NOREF(tsArrival, idClient);
1926
1927 /*
1928 * Convert opaque pointers to typed ones.
1929 */
1930 SELF *pThis = reinterpret_cast<SELF *>(pvService);
1931 AssertReturnVoidStmt(pThis, pThis->mpHelpers->pfnCallComplete(hCall, VERR_INTERNAL_ERROR_5));
1932 ClientState *pClient = reinterpret_cast<ClientState *>(pvClient);
1933 AssertReturnVoidStmt(pClient, pThis->mpHelpers->pfnCallComplete(hCall, VERR_INVALID_CLIENT_ID));
1934 Assert(pClient->m_idClient == idClient);
1935
1936 /*
1937 * Do the dispatching.
1938 */
1939 int rc;
1940 switch (idFunction)
1941 {
1942 case GUEST_MAKE_ME_MASTER:
1943 LogFlowFunc(("[Client %RU32] GUEST_MAKE_ME_MASTER\n", idClient));
1944 rc = pThis->clientMakeMeMaster(pClient, hCall, cParms);
1945 break;
1946 case GUEST_MSG_PEEK_NOWAIT:
1947 LogFlowFunc(("[Client %RU32] GUEST_MSG_PEEK_NOWAIT\n", idClient));
1948 rc = pThis->clientMsgPeek(pClient, hCall, cParms, paParms, false /*fWait*/);
1949 break;
1950 case GUEST_MSG_PEEK_WAIT:
1951 LogFlowFunc(("[Client %RU32] GUEST_MSG_PEEK_WAIT\n", idClient));
1952 rc = pThis->clientMsgPeek(pClient, hCall, cParms, paParms, true /*fWait*/);
1953 break;
1954 case GUEST_MSG_GET:
1955 LogFlowFunc(("[Client %RU32] GUEST_MSG_GET\n", idClient));
1956 rc = pThis->clientMsgGet(pClient, hCall, cParms, paParms);
1957 break;
1958 case GUEST_MSG_CANCEL:
1959 LogFlowFunc(("[Client %RU32] GUEST_MSG_CANCEL\n", idClient));
1960 rc = pThis->clientMsgCancel(pClient, cParms);
1961 break;
1962 case GUEST_MSG_SKIP:
1963 LogFlowFunc(("[Client %RU32] GUEST_MSG_SKIP\n", idClient));
1964 rc = pThis->clientMsgSkip(pClient, hCall, cParms, paParms);
1965 break;
1966 case GUEST_SESSION_PREPARE:
1967 LogFlowFunc(("[Client %RU32] GUEST_SESSION_PREPARE\n", idClient));
1968 rc = pThis->clientSessionPrepare(pClient, hCall, cParms, paParms);
1969 break;
1970 case GUEST_SESSION_CANCEL_PREPARED:
1971 LogFlowFunc(("[Client %RU32] GUEST_SESSION_CANCEL_PREPARED\n", idClient));
1972 rc = pThis->clientSessionCancelPrepared(pClient, cParms, paParms);
1973 break;
1974 case GUEST_SESSION_ACCEPT:
1975 LogFlowFunc(("[Client %RU32] GUEST_SESSION_ACCEPT\n", idClient));
1976 rc = pThis->clientSessionAccept(pClient, hCall, cParms, paParms);
1977 break;
1978 case GUEST_SESSION_CLOSE:
1979 LogFlowFunc(("[Client %RU32] GUEST_SESSION_CLOSE\n", idClient));
1980 rc = pThis->clientSessionCloseOther(pClient, cParms, paParms);
1981 break;
1982
1983 /*
1984 * Stuff the goes to various main objects:
1985 */
1986 case GUEST_MSG_REPLY:
1987 case GUEST_MSG_PROGRESS_UPDATE:
1988 case GUEST_SESSION_NOTIFY:
1989 case GUEST_EXEC_OUTPUT:
1990 case GUEST_EXEC_STATUS:
1991 case GUEST_EXEC_INPUT_STATUS:
1992 case GUEST_EXEC_IO_NOTIFY:
1993 case GUEST_DIR_NOTIFY:
1994 case GUEST_FILE_NOTIFY:
1995 LogFlowFunc(("[Client %RU32] %s\n", idClient, GstCtrlGuestFnName((eGuestFn)idFunction)));
1996 rc = pThis->clientToMain(pClient, idFunction, cParms, paParms);
1997 Assert(rc != VINF_HGCM_ASYNC_EXECUTE);
1998 break;
1999
2000 /*
2001 * The remaining commands are here for compatibility with older guest additions:
2002 */
2003 case GUEST_MSG_WAIT:
2004 LogFlowFunc(("[Client %RU32] GUEST_MSG_WAIT\n", idClient));
2005 pThis->clientMsgOldGet(pClient, hCall, cParms, paParms);
2006 rc = VINF_HGCM_ASYNC_EXECUTE;
2007 break;
2008
2009 case GUEST_MSG_SKIP_OLD:
2010 LogFlowFunc(("[Client %RU32] GUEST_MSG_SKIP_OLD\n", idClient));
2011 rc = pThis->clientMsgOldSkip(pClient, cParms);
2012 break;
2013
2014 case GUEST_MSG_FILTER_SET:
2015 LogFlowFunc(("[Client %RU32] GUEST_MSG_FILTER_SET\n", idClient));
2016 rc = pThis->clientMsgOldFilterSet(pClient, cParms, paParms);
2017 break;
2018
2019 case GUEST_MSG_FILTER_UNSET:
2020 LogFlowFunc(("[Client %RU32] GUEST_MSG_FILTER_UNSET\n", idClient));
2021 rc = VERR_NOT_IMPLEMENTED;
2022 break;
2023
2024 /*
2025 * Anything else shall return invalid function.
2026 * Note! We used to return VINF_SUCCESS for these. See bugref:9313
2027 * and Guest::i_notifyCtrlDispatcher().
2028 */
2029 default:
2030 ASSERT_GUEST_MSG_FAILED(("idFunction=%d (%#x)\n", idFunction, idFunction));
2031 rc = VERR_INVALID_FUNCTION;
2032 break;
2033 }
2034
2035 if (rc != VINF_HGCM_ASYNC_EXECUTE)
2036 {
2037 /* Tell the client that the call is complete (unblocks waiting). */
2038 LogFlowFunc(("[Client %RU32] Calling pfnCallComplete w/ rc=%Rrc\n", idClient, rc));
2039 AssertPtr(pThis->mpHelpers);
2040 pThis->mpHelpers->pfnCallComplete(hCall, rc);
2041 }
2042}
2043
2044
2045/**
2046 * Notifies the host (using low-level HGCM callbacks) about an event
2047 * which was sent from the client.
2048 *
2049 * @returns VBox status code.
2050 * @param idFunction Function (event) that occured.
2051 * @param cParms Number of parameters.
2052 * @param paParms Array of parameters.
2053 */
2054int GstCtrlService::hostCallback(uint32_t idFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
2055{
2056 LogFlowFunc(("idFunction=%u (%s), cParms=%ld, paParms=%p\n", idFunction, GstCtrlGuestFnName((eGuestFn)idFunction), cParms, paParms));
2057
2058 int rc;
2059 if (mpfnHostCallback)
2060 {
2061 VBOXGUESTCTRLHOSTCALLBACK data(cParms, paParms);
2062 /** @todo Not sure if this try/catch is necessary, I pushed it down here from
2063 * GstCtrlService::call where it was not needed for anything else that I
2064 * could spot. I know this might be a tough, but I expect someone writing
2065 * this kind of code to know what can throw errors and handle them where it
2066 * is appropriate, rather than grand catch-all-at-the-top crap like this.
2067 * The reason why it is utter crap, is that you have no state cleanup code
2068 * where you might need it, which is why I despise exceptions in general */
2069 try
2070 {
2071 rc = mpfnHostCallback(mpvHostData, idFunction, &data, sizeof(data));
2072 }
2073 catch (std::bad_alloc &)
2074 {
2075 rc = VERR_NO_MEMORY;
2076 }
2077 }
2078 else
2079 rc = VERR_NOT_SUPPORTED;
2080
2081 LogFlowFunc(("Returning rc=%Rrc\n", rc));
2082 return rc;
2083}
2084
2085
2086/**
2087 * Processes a command received from the host side and re-routes it to
2088 * a connect client on the guest.
2089 *
2090 * @returns VBox status code.
2091 * @param idFunction Function code to process.
2092 * @param cParms Number of parameters.
2093 * @param paParms Array of parameters.
2094 */
2095int GstCtrlService::hostProcessCommand(uint32_t idFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
2096{
2097 /*
2098 * If no client is connected at all we don't buffer any host commands
2099 * and immediately return an error to the host. This avoids the host
2100 * waiting for a response from the guest side in case VBoxService on
2101 * the guest is not running/system is messed up somehow.
2102 */
2103 if (mClientStateMap.empty())
2104 {
2105 LogFlow(("GstCtrlService::hostProcessCommand: VERR_NOT_FOUND!\n"));
2106 return VERR_NOT_FOUND;
2107 }
2108
2109 /*
2110 * Create a host command for each destination.
2111 * Note! There is currently only one scenario in which we send a host
2112 * command to two recipients.
2113 */
2114 HostCommand *pHostCmd = new (std::nothrow) HostCommand();
2115 AssertReturn(pHostCmd, VERR_NO_MEMORY);
2116 int rc = pHostCmd->Init(idFunction, cParms, paParms);
2117 if (RT_SUCCESS(rc))
2118 {
2119 uint64_t const fDestinations = pHostCmd->m_idContextAndDst & VBOX_GUESTCTRL_DST_BOTH;
2120 HostCommand *pHostCmd2 = NULL;
2121 if (fDestinations != VBOX_GUESTCTRL_DST_BOTH)
2122 { /* likely */ }
2123 else
2124 {
2125 pHostCmd2 = new (std::nothrow) HostCommand();
2126 if (pHostCmd2)
2127 rc = pHostCmd2->Init(idFunction, cParms, paParms);
2128 else
2129 rc = VERR_NO_MEMORY;
2130 }
2131 if (RT_SUCCESS(rc))
2132 {
2133 LogFlowFunc(("Handling host command m_idContextAndDst=%#RX64, idFunction=%RU32, cParms=%RU32, paParms=%p, cClients=%zu\n",
2134 pHostCmd->m_idContextAndDst, idFunction, cParms, paParms, mClientStateMap.size()));
2135
2136 /*
2137 * Find the message destination and post it to the client. If the
2138 * session ID doesn't match any particular client it goes to the master.
2139 */
2140 AssertMsg(!mClientStateMap.empty(), ("Client state map is empty when it should not be!\n"));
2141
2142 /* Dispatch to the session. */
2143 if (fDestinations & VBOX_GUESTCTRL_DST_SESSION)
2144 {
2145 rc = VWRN_NOT_FOUND;
2146 uint32_t const idSession = VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(pHostCmd->m_idContext);
2147 for (ClientStateMap::iterator It = mClientStateMap.begin(); It != mClientStateMap.end(); ++It)
2148 {
2149 ClientState *pClient = It->second;
2150 if (pClient->m_idSession == idSession)
2151 {
2152 RTListAppend(&pClient->m_HostCmdList, &pHostCmd->m_ListEntry);
2153 pHostCmd = pHostCmd2;
2154 pHostCmd2 = NULL;
2155
2156 int rc2 = pClient->Wakeup();
2157 LogFlowFunc(("Woke up client ID=%RU32 -> rc=%Rrc\n", pClient->m_idClient, rc2));
2158 RT_NOREF(rc2);
2159 rc = VINF_SUCCESS;
2160 break;
2161 }
2162 }
2163 }
2164
2165 /* Does the message go to the root service? */
2166 if ( (fDestinations & VBOX_GUESTCTRL_DST_ROOT_SVC)
2167 && RT_SUCCESS(rc))
2168 {
2169 Assert(pHostCmd);
2170 if (m_pMasterClient)
2171 {
2172 RTListAppend(&m_pMasterClient->m_HostCmdList, &pHostCmd->m_ListEntry);
2173 pHostCmd = NULL;
2174
2175 int rc2 = m_pMasterClient->Wakeup();
2176 LogFlowFunc(("Woke up client ID=%RU32 (master) -> rc=%Rrc\n", m_pMasterClient->m_idClient, rc2));
2177 NOREF(rc2);
2178 }
2179 else
2180 rc = VERR_NOT_FOUND;
2181 }
2182 }
2183
2184 /* Drop unset commands */
2185 if (pHostCmd2)
2186 pHostCmd2->Delete();
2187 }
2188 if (pHostCmd)
2189 pHostCmd->Delete();
2190
2191 if (RT_FAILURE(rc))
2192 LogFunc(("Failed %Rrc (idFunction=%u, cParms=%u)\n", rc, idFunction, cParms));
2193 return rc;
2194}
2195
2196
2197/**
2198 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnHostCall,
2199 * Wraps to the hostProcessCommand() member function.}
2200 */
2201/*static*/ DECLCALLBACK(int)
2202GstCtrlService::svcHostCall(void *pvService, uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
2203{
2204 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
2205 SELF *pThis = reinterpret_cast<SELF *>(pvService);
2206 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2207
2208 LogFlowFunc(("fn=%RU32, cParms=%RU32, paParms=0x%p\n", u32Function, cParms, paParms));
2209 AssertReturn(u32Function != HOST_CANCEL_PENDING_WAITS, VERR_INVALID_FUNCTION);
2210 return pThis->hostProcessCommand(u32Function, cParms, paParms);
2211}
2212
2213
2214
2215
2216/**
2217 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnSaveState}
2218 */
2219/*static*/ DECLCALLBACK(int)
2220GstCtrlService::svcSaveState(void *pvService, uint32_t idClient, void *pvClient, PSSMHANDLE pSSM)
2221{
2222 RT_NOREF(pvClient);
2223 SELF *pThis = reinterpret_cast<SELF *>(pvService);
2224 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2225
2226 /* Note! We don't need to save the idSession here because it's only used
2227 for sessions and the sessions are not persistent across a state
2228 save/restore. The Main objects aren't there. Clients shuts down.
2229 Only the root service survives, so remember who that is and its mode. */
2230
2231 SSMR3PutU32(pSSM, 1);
2232 SSMR3PutBool(pSSM, pThis->m_fLegacyMode);
2233 return SSMR3PutBool(pSSM, idClient == pThis->m_idMasterClient);
2234}
2235
2236
2237/**
2238 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnLoadState}
2239 */
2240/*static*/ DECLCALLBACK(int)
2241GstCtrlService::svcLoadState(void *pvService, uint32_t idClient, void *pvClient, PSSMHANDLE pSSM, uint32_t uVersion)
2242{
2243 SELF *pThis = reinterpret_cast<SELF *>(pvService);
2244 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2245 ClientState *pClient = reinterpret_cast<ClientState *>(pvClient);
2246 AssertReturn(pClient, VERR_INVALID_CLIENT_ID);
2247 Assert(pClient->m_idClient == idClient);
2248
2249 if (uVersion >= HGCM_SAVED_STATE_VERSION)
2250 {
2251 uint32_t uSubVersion;
2252 int rc = SSMR3GetU32(pSSM, &uSubVersion);
2253 AssertRCReturn(rc, rc);
2254 if (uSubVersion != 1)
2255 return SSMR3SetLoadError(pSSM, VERR_SSM_DATA_UNIT_FORMAT_CHANGED, RT_SRC_POS,
2256 "sub version %u, expected 1\n", uSubVersion);
2257 bool fLegacyMode;
2258 rc = SSMR3GetBool(pSSM, &fLegacyMode);
2259 AssertRCReturn(rc, rc);
2260 pThis->m_fLegacyMode = fLegacyMode;
2261
2262 bool fIsMaster;
2263 rc = SSMR3GetBool(pSSM, &fIsMaster);
2264 AssertRCReturn(rc, rc);
2265
2266 pClient->m_fIsMaster = fIsMaster;
2267 if (fIsMaster)
2268 {
2269 pThis->m_pMasterClient = pClient;
2270 pThis->m_idMasterClient = idClient;
2271 }
2272 }
2273 else
2274 {
2275 /*
2276 * For old saved states we have to guess at who should be the master.
2277 * Given how HGCMService::CreateAndConnectClient and associates manage
2278 * and saves the client, the first client connecting will be restored
2279 * first. The only time this might go wrong if the there are zombie
2280 * VBoxService session processes in the restored guest, and I don't
2281 * we need to care too much about that scenario.
2282 *
2283 * Given how HGCM first re-connects the clients before this function
2284 * gets called, there isn't anything we need to do here it turns out. :-)
2285 */
2286 }
2287 return VINF_SUCCESS;
2288}
2289
2290
2291/**
2292 * @interface_method_impl{VBOXHGCMSVCFNTABLE,pfnRegisterExtension,
2293 * Installs a host callback for notifications of property changes.}
2294 */
2295/*static*/ DECLCALLBACK(int) GstCtrlService::svcRegisterExtension(void *pvService, PFNHGCMSVCEXT pfnExtension, void *pvExtension)
2296{
2297 SELF *pThis = reinterpret_cast<SELF *>(pvService);
2298 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2299 AssertPtrNullReturn(pfnExtension, VERR_INVALID_POINTER);
2300
2301 pThis->mpfnHostCallback = pfnExtension;
2302 pThis->mpvHostData = pvExtension;
2303 return VINF_SUCCESS;
2304}
2305
2306
2307/**
2308 * @copydoc VBOXHGCMSVCLOAD
2309 */
2310extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *pTable)
2311{
2312 int rc = VINF_SUCCESS;
2313
2314 LogFlowFunc(("pTable=%p\n", pTable));
2315
2316 if (!VALID_PTR(pTable))
2317 {
2318 rc = VERR_INVALID_PARAMETER;
2319 }
2320 else
2321 {
2322 LogFlowFunc(("pTable->cbSize=%d, pTable->u32Version=0x%08X\n", pTable->cbSize, pTable->u32Version));
2323
2324 if ( pTable->cbSize != sizeof (VBOXHGCMSVCFNTABLE)
2325 || pTable->u32Version != VBOX_HGCM_SVC_VERSION)
2326 {
2327 rc = VERR_VERSION_MISMATCH;
2328 }
2329 else
2330 {
2331 GstCtrlService *pService = NULL;
2332 /* No exceptions may propagate outside. */
2333 try
2334 {
2335 pService = new GstCtrlService(pTable->pHelpers);
2336 }
2337 catch (int rcThrown)
2338 {
2339 rc = rcThrown;
2340 }
2341 catch(std::bad_alloc &)
2342 {
2343 rc = VERR_NO_MEMORY;
2344 }
2345
2346 if (RT_SUCCESS(rc))
2347 {
2348 /*
2349 * We don't need an additional client data area on the host,
2350 * because we're a class which can have members for that :-).
2351 */
2352 pTable->cbClient = sizeof(ClientState);
2353
2354 /* Register functions. */
2355 pTable->pfnUnload = GstCtrlService::svcUnload;
2356 pTable->pfnConnect = GstCtrlService::svcConnect;
2357 pTable->pfnDisconnect = GstCtrlService::svcDisconnect;
2358 pTable->pfnCall = GstCtrlService::svcCall;
2359 pTable->pfnHostCall = GstCtrlService::svcHostCall;
2360 pTable->pfnSaveState = GstCtrlService::svcSaveState;
2361 pTable->pfnLoadState = GstCtrlService::svcLoadState;
2362 pTable->pfnRegisterExtension = GstCtrlService::svcRegisterExtension;
2363
2364 /* Service specific initialization. */
2365 pTable->pvService = pService;
2366 }
2367 else
2368 {
2369 if (pService)
2370 {
2371 delete pService;
2372 pService = NULL;
2373 }
2374 }
2375 }
2376 }
2377
2378 LogFlowFunc(("Returning %Rrc\n", rc));
2379 return rc;
2380}
2381
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