VirtualBox

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

Last change on this file since 39312 was 39312, checked in by vboxsync, 13 years ago

HostServices/GuestCtrl: Fixed cancellation of buffered (unassigned) host commands or assigned commands on client disconnect, logging adjustments.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 37.4 KB
Line 
1/* $Id: service.cpp 39312 2011-11-15 14:40:49Z vboxsync $ */
2/** @file
3 * Guest Control Service: Controlling the guest.
4 */
5
6/*
7 * Copyright (C) 2011 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
54/*******************************************************************************
55* Header Files *
56*******************************************************************************/
57#define LOG_GROUP LOG_GROUP_HGCM
58#include <VBox/HostServices/GuestControlSvc.h>
59
60#include <VBox/log.h>
61#include <iprt/asm.h> /* For ASMBreakpoint(). */
62#include <iprt/assert.h>
63#include <iprt/cpp/autores.h>
64#include <iprt/cpp/utils.h>
65#include <iprt/err.h>
66#include <iprt/mem.h>
67#include <iprt/req.h>
68#include <iprt/string.h>
69#include <iprt/thread.h>
70#include <iprt/time.h>
71
72#include <memory> /* for auto_ptr */
73#include <string>
74#include <list>
75
76#include "gctrl.h"
77
78namespace guestControl {
79
80/**
81 * Structure for holding all clients with their
82 * generated host contexts. This is necessary for
83 * maintaining the relationship between a client and its context IDs.
84 */
85struct ClientContexts
86{
87 /** This client ID. */
88 uint32_t mClientID;
89 /** The list of contexts a client is assigned to. */
90 std::list< uint32_t > mContextList;
91
92 /** The normal constructor. */
93 ClientContexts(uint32_t aClientID)
94 : mClientID(aClientID) {}
95};
96/** The client list + iterator type */
97typedef std::list< ClientContexts > ClientContextsList;
98typedef std::list< ClientContexts >::iterator ClientContextsListIter;
99typedef std::list< ClientContexts >::const_iterator ClientContextsListIterConst;
100
101/**
102 * Structure for holding an uncompleted guest call.
103 */
104struct ClientWaiter
105{
106 /** Client ID; a client can have multiple handles! */
107 uint32_t mClientID;
108 /** The call handle */
109 VBOXHGCMCALLHANDLE mHandle;
110 /** The call parameters */
111 VBOXHGCMSVCPARM *mParms;
112 /** Number of parameters */
113 uint32_t mNumParms;
114
115 /** The standard constructor. */
116 ClientWaiter() : mClientID(0), mHandle(0), mParms(NULL), mNumParms(0) {}
117 /** The normal constructor. */
118 ClientWaiter(uint32_t aClientID, VBOXHGCMCALLHANDLE aHandle,
119 VBOXHGCMSVCPARM aParms[], uint32_t cParms)
120 : mClientID(aClientID), mHandle(aHandle), mParms(aParms), mNumParms(cParms) {}
121};
122/** The guest call list type */
123typedef std::list< ClientWaiter > ClientWaiterList;
124typedef std::list< ClientWaiter >::iterator CallListIter;
125typedef std::list< ClientWaiter >::const_iterator CallListIterConst;
126
127/**
128 * Structure for holding a buffered host command.
129 */
130struct HostCmd
131{
132 /** The context ID this command belongs to. Will be extracted
133 * from the HGCM parameters. */
134 uint32_t mContextID;
135 /** How many times the host service has tried to deliver this
136 * command to the guest. */
137 uint32_t mTries;
138 /** Dynamic structure for holding the HGCM parms */
139 VBOXGUESTCTRPARAMBUFFER mParmBuf;
140
141 /** The standard constructor. */
142 HostCmd() : mContextID(0), mTries(0) {}
143};
144/** The host cmd list + iterator type */
145typedef std::list< HostCmd > HostCmdList;
146typedef std::list< HostCmd >::iterator HostCmdListIter;
147typedef std::list< HostCmd >::const_iterator HostCmdListIterConst;
148
149/**
150 * Class containing the shared information service functionality.
151 */
152class Service : public RTCNonCopyable
153{
154private:
155 /** Type definition for use in callback functions. */
156 typedef Service SELF;
157 /** HGCM helper functions. */
158 PVBOXHGCMSVCHELPERS mpHelpers;
159 /*
160 * Callback function supplied by the host for notification of updates
161 * to properties.
162 */
163 PFNHGCMSVCEXT mpfnHostCallback;
164 /** User data pointer to be supplied to the host callback function. */
165 void *mpvHostData;
166 /** The deferred calls list. */
167 ClientWaiterList mClientWaiterList;
168 /** The host command list. */
169 HostCmdList mHostCmds;
170 /** Client contexts list. */
171 ClientContextsList mClientContextsList;
172 /** Number of connected clients. */
173 uint32_t mNumClients;
174public:
175 explicit Service(PVBOXHGCMSVCHELPERS pHelpers)
176 : mpHelpers(pHelpers)
177 , mpfnHostCallback(NULL)
178 , mpvHostData(NULL)
179 , mNumClients(0)
180 {
181 }
182
183 /**
184 * @copydoc VBOXHGCMSVCHELPERS::pfnUnload
185 * Simply deletes the service object
186 */
187 static DECLCALLBACK(int) svcUnload (void *pvService)
188 {
189 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
190 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
191 int rc = pSelf->uninit();
192 AssertRC(rc);
193 if (RT_SUCCESS(rc))
194 delete pSelf;
195 return rc;
196 }
197
198 /**
199 * @copydoc VBOXHGCMSVCHELPERS::pfnConnect
200 * Stub implementation of pfnConnect and pfnDisconnect.
201 */
202 static DECLCALLBACK(int) svcConnect (void *pvService,
203 uint32_t u32ClientID,
204 void *pvClient)
205 {
206 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
207 LogFlowFunc (("pvService=%p, u32ClientID=%u, pvClient=%p\n", pvService, u32ClientID, pvClient));
208 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
209 int rc = pSelf->clientConnect(u32ClientID, pvClient);
210 LogFlowFunc (("rc=%Rrc\n", rc));
211 return rc;
212 }
213
214 /**
215 * @copydoc VBOXHGCMSVCHELPERS::pfnConnect
216 * Stub implementation of pfnConnect and pfnDisconnect.
217 */
218 static DECLCALLBACK(int) svcDisconnect (void *pvService,
219 uint32_t u32ClientID,
220 void *pvClient)
221 {
222 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
223 LogFlowFunc (("pvService=%p, u32ClientID=%u, pvClient=%p\n", pvService, u32ClientID, pvClient));
224 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
225 int rc = pSelf->clientDisconnect(u32ClientID, pvClient);
226 LogFlowFunc (("rc=%Rrc\n", rc));
227 return rc;
228 }
229
230 /**
231 * @copydoc VBOXHGCMSVCHELPERS::pfnCall
232 * Wraps to the call member function
233 */
234 static DECLCALLBACK(void) svcCall (void * pvService,
235 VBOXHGCMCALLHANDLE callHandle,
236 uint32_t u32ClientID,
237 void *pvClient,
238 uint32_t u32Function,
239 uint32_t cParms,
240 VBOXHGCMSVCPARM paParms[])
241 {
242 AssertLogRelReturnVoid(VALID_PTR(pvService));
243 LogFlowFunc (("pvService=%p, callHandle=%p, u32ClientID=%u, pvClient=%p, u32Function=%u, cParms=%u, paParms=%p\n", pvService, callHandle, u32ClientID, pvClient, u32Function, cParms, paParms));
244 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
245 pSelf->call(callHandle, u32ClientID, pvClient, u32Function, cParms, paParms);
246 LogFlowFunc (("returning\n"));
247 }
248
249 /**
250 * @copydoc VBOXHGCMSVCHELPERS::pfnHostCall
251 * Wraps to the hostCall member function
252 */
253 static DECLCALLBACK(int) svcHostCall (void *pvService,
254 uint32_t u32Function,
255 uint32_t cParms,
256 VBOXHGCMSVCPARM paParms[])
257 {
258 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
259 LogFlowFunc (("pvService=%p, u32Function=%u, cParms=%u, paParms=%p\n", pvService, u32Function, cParms, paParms));
260 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
261 int rc = pSelf->hostCall(u32Function, cParms, paParms);
262 LogFlowFunc (("rc=%Rrc\n", rc));
263 return rc;
264 }
265
266 /**
267 * @copydoc VBOXHGCMSVCHELPERS::pfnRegisterExtension
268 * Installs a host callback for notifications of property changes.
269 */
270 static DECLCALLBACK(int) svcRegisterExtension (void *pvService,
271 PFNHGCMSVCEXT pfnExtension,
272 void *pvExtension)
273 {
274 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
275 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
276 pSelf->mpfnHostCallback = pfnExtension;
277 pSelf->mpvHostData = pvExtension;
278 return VINF_SUCCESS;
279 }
280private:
281 int paramBufferAllocate(PVBOXGUESTCTRPARAMBUFFER pBuf, uint32_t uMsg, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
282 void paramBufferFree(PVBOXGUESTCTRPARAMBUFFER pBuf);
283 int paramBufferAssign(PVBOXGUESTCTRPARAMBUFFER pBuf, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
284 int prepareExecute(uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
285 int clientConnect(uint32_t u32ClientID, void *pvClient);
286 int clientDisconnect(uint32_t u32ClientID, void *pvClient);
287 int assignHostCmdToGuest(HostCmd *pCmd, VBOXHGCMCALLHANDLE callHandle, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
288 int retrieveNextHostCmd(uint32_t u32ClientID, VBOXHGCMCALLHANDLE callHandle, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
289 int cancelHostCmd(uint32_t u32ContextID);
290 int cancelPendingWaits(uint32_t u32ClientID);
291 int notifyHost(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
292 int processHostCmd(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
293 void call(VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID,
294 void *pvClient, uint32_t eFunction, uint32_t cParms,
295 VBOXHGCMSVCPARM paParms[]);
296 int hostCall(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
297 int uninit();
298};
299
300
301/**
302 * Stores a HGCM request in an internal buffer. Needs to be free'd using paramBufferFree().
303 *
304 * @return IPRT status code.
305 * @param pBuf Buffer to store the HGCM request into.
306 * @param uMsg Message type.
307 * @param cParms Number of parameters of HGCM request.
308 * @param paParms Array of parameters of HGCM request.
309 */
310int Service::paramBufferAllocate(PVBOXGUESTCTRPARAMBUFFER pBuf, uint32_t uMsg, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
311{
312 AssertPtrReturn(pBuf, VERR_INVALID_POINTER);
313 if (cParms)
314 AssertPtrReturn(paParms, VERR_INVALID_POINTER);
315
316 /* Paranoia. */
317 if (cParms > 256)
318 cParms = 256;
319
320 int rc = VINF_SUCCESS;
321
322 /*
323 * Don't verify anything here (yet), because this function only buffers
324 * the HGCM data into an internal structure and reaches it back to the guest (client)
325 * in an unmodified state.
326 */
327 pBuf->uMsg = uMsg;
328 pBuf->uParmCount = cParms;
329 if (pBuf->uParmCount)
330 {
331 pBuf->pParms = (VBOXHGCMSVCPARM*)RTMemAlloc(sizeof(VBOXHGCMSVCPARM) * pBuf->uParmCount);
332 if (NULL == pBuf->pParms)
333 rc = VERR_NO_MEMORY;
334 }
335
336 if (RT_SUCCESS(rc))
337 {
338 for (uint32_t i = 0; i < pBuf->uParmCount; i++)
339 {
340 pBuf->pParms[i].type = paParms[i].type;
341 switch (paParms[i].type)
342 {
343 case VBOX_HGCM_SVC_PARM_32BIT:
344 pBuf->pParms[i].u.uint32 = paParms[i].u.uint32;
345 break;
346
347 case VBOX_HGCM_SVC_PARM_64BIT:
348 /* Not supported yet. */
349 break;
350
351 case VBOX_HGCM_SVC_PARM_PTR:
352 pBuf->pParms[i].u.pointer.size = paParms[i].u.pointer.size;
353 if (pBuf->pParms[i].u.pointer.size > 0)
354 {
355 pBuf->pParms[i].u.pointer.addr = RTMemAlloc(pBuf->pParms[i].u.pointer.size);
356 if (NULL == pBuf->pParms[i].u.pointer.addr)
357 {
358 rc = VERR_NO_MEMORY;
359 break;
360 }
361 else
362 memcpy(pBuf->pParms[i].u.pointer.addr,
363 paParms[i].u.pointer.addr,
364 pBuf->pParms[i].u.pointer.size);
365 }
366 else
367 {
368 /* Size is 0 -- make sure we don't have any pointer. */
369 pBuf->pParms[i].u.pointer.addr = NULL;
370 }
371 break;
372
373 default:
374 break;
375 }
376 if (RT_FAILURE(rc))
377 break;
378 }
379 }
380 return rc;
381}
382
383/**
384 * Frees a buffered HGCM request.
385 *
386 * @return IPRT status code.
387 * @param pBuf Parameter buffer to free.
388 */
389void Service::paramBufferFree(PVBOXGUESTCTRPARAMBUFFER pBuf)
390{
391 AssertPtr(pBuf);
392 for (uint32_t i = 0; i < pBuf->uParmCount; i++)
393 {
394 switch (pBuf->pParms[i].type)
395 {
396 case VBOX_HGCM_SVC_PARM_PTR:
397 if (pBuf->pParms[i].u.pointer.size > 0)
398 RTMemFree(pBuf->pParms[i].u.pointer.addr);
399 break;
400 }
401 }
402 if (pBuf->uParmCount)
403 {
404 RTMemFree(pBuf->pParms);
405 pBuf->uParmCount = 0;
406 }
407}
408
409/**
410 * Assigns data from a buffered HGCM request to the current HGCM request.
411 *
412 * @return IPRT status code.
413 * @param pBuf Parameter buffer to assign.
414 * @param cParms Number of parameters the HGCM request can handle.
415 * @param paParms Array of parameters of HGCM request to fill the data into.
416 */
417int Service::paramBufferAssign(PVBOXGUESTCTRPARAMBUFFER pBuf, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
418{
419 AssertPtr(pBuf);
420 int rc = VINF_SUCCESS;
421 if (cParms != pBuf->uParmCount)
422 {
423 LogFlowFunc(("Parameter count does not match: %u (host) vs. %u (guest)\n",
424 pBuf->uParmCount, cParms));
425 rc = VERR_INVALID_PARAMETER;
426 }
427 else
428 {
429 /** @todo Add check to verify if the HGCM request is the same *type* as the buffered one! */
430 for (uint32_t i = 0; i < pBuf->uParmCount; i++)
431 {
432 paParms[i].type = pBuf->pParms[i].type;
433 switch (paParms[i].type)
434 {
435 case VBOX_HGCM_SVC_PARM_32BIT:
436 paParms[i].u.uint32 = pBuf->pParms[i].u.uint32;
437 break;
438
439 case VBOX_HGCM_SVC_PARM_64BIT:
440 /* Not supported yet. */
441 break;
442
443 case VBOX_HGCM_SVC_PARM_PTR:
444 if (paParms[i].u.pointer.size >= pBuf->pParms[i].u.pointer.size)
445 {
446 /* Only copy buffer if there actually is something to copy. */
447 if (pBuf->pParms[i].u.pointer.size)
448 {
449 AssertPtr(pBuf->pParms[i].u.pointer.addr);
450 memcpy(paParms[i].u.pointer.addr,
451 pBuf->pParms[i].u.pointer.addr,
452 pBuf->pParms[i].u.pointer.size);
453 }
454 }
455 else
456 rc = VERR_BUFFER_OVERFLOW;
457 break;
458
459 default:
460 break;
461 }
462 }
463 }
464 return rc;
465}
466
467/**
468 * Handles a client which just connected.
469 *
470 * @return IPRT status code.
471 * @param u32ClientID
472 * @param pvClient
473 */
474int Service::clientConnect(uint32_t u32ClientID, void *pvClient)
475{
476 LogFlowFunc(("New client (%ld) connected\n", u32ClientID));
477 if (mNumClients < UINT32_MAX)
478 mNumClients++;
479 else
480 AssertMsgFailed(("Max. number of clients reached\n"));
481 return VINF_SUCCESS;
482}
483
484/**
485 * Handles a client which disconnected. This functiond does some
486 * internal cleanup as well as sends notifications to the host so
487 * that the host can do the same (if required).
488 *
489 * @return IPRT status code.
490 * @param u32ClientID The client's ID of which disconnected.
491 * @param pvClient User data, not used at the moment.
492 */
493int Service::clientDisconnect(uint32_t u32ClientID, void *pvClient)
494{
495 LogFlowFunc(("Client (ID=%u, %u clients total) disconnected\n",
496 u32ClientID, mNumClients));
497 Assert(mNumClients > 0);
498 mNumClients--;
499
500 /* If this was the last connected (guest) client we need to
501 * unblock all eventually queued up (waiting) host calls. */
502 bool fAllClientsDisconnected = mNumClients == 0;
503 if (fAllClientsDisconnected)
504 LogFlowFunc(("No connected clients left, notifying all queued up callbacks\n"));
505
506 /*
507 * Throw out all stale clients.
508 */
509 int rc = VINF_SUCCESS;
510
511 CallListIter itCall = mClientWaiterList.begin();
512 while (itCall != mClientWaiterList.end())
513 {
514 if (itCall->mClientID == u32ClientID)
515 {
516 itCall = mClientWaiterList.erase(itCall);
517 }
518 else
519 itCall++;
520 }
521
522 ClientContextsListIter it = mClientContextsList.begin();
523 while ( it != mClientContextsList.end()
524 && RT_SUCCESS(rc))
525 {
526 /*
527 * Unblock/call back all queued items of the specified client
528 * or for all items in case there is no waiting client around
529 * anymore.
530 */
531 if ( it->mClientID == u32ClientID
532 || fAllClientsDisconnected)
533 {
534 std::list< uint32_t >::iterator itContext = it->mContextList.begin();
535 while (itContext != it->mContextList.end())
536 {
537 uint32_t uContextID = (*itContext);
538
539 /*
540 * Notify the host that clients with u32ClientID are no longer
541 * around and need to be cleaned up (canceling waits etc).
542 */
543 LogFlowFunc(("Notifying CID=%u of disconnect ...\n", uContextID));
544 rc = cancelHostCmd(uContextID);
545 if (RT_FAILURE(rc))
546 {
547 LogFlowFunc(("Cancelling of CID=%u failed with rc=%Rrc\n",
548 uContextID, rc));
549 /* Keep going. */
550 }
551
552 itContext++;
553 }
554 it = mClientContextsList.erase(it);
555 }
556 else
557 it++;
558 }
559
560 if (fAllClientsDisconnected)
561 {
562 /*
563 * If all clients disconnected we also need to make sure that all buffered
564 * host commands need to be notified, because Main is waiting a notification
565 * via a (multi stage) progress object.
566 */
567 HostCmdListIter it;
568 for (it = mHostCmds.begin(); it != mHostCmds.end(); it++)
569 {
570 rc = cancelHostCmd(it->mContextID);
571 if (RT_FAILURE(rc))
572 {
573 LogFlowFunc(("Cancelling of buffered CID=%u failed with rc=%Rrc\n",
574 it->mContextID, rc));
575 /* Keep going. */
576 }
577
578 paramBufferFree(&it->mParmBuf);
579 }
580
581 mHostCmds.clear();
582 }
583
584 return rc;
585}
586
587/**
588 * Assigns a specified host command to a client.
589 *
590 * @return IPRT status code.
591 * @param pCmd Host comamnd to send.
592 * @param callHandle Call handle of the client to send the command to.
593 * @param cParms Number of parameters.
594 * @param paParms Array of parameters.
595 */
596int Service::assignHostCmdToGuest(HostCmd *pCmd, VBOXHGCMCALLHANDLE callHandle, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
597{
598 AssertPtrReturn(pCmd, VERR_INVALID_POINTER);
599 int rc;
600
601 /* Does the current host command need more parameter space which
602 * the client does not provide yet? */
603 if (pCmd->mParmBuf.uParmCount > cParms)
604 {
605 paParms[0].setUInt32(pCmd->mParmBuf.uMsg); /* Message ID */
606 paParms[1].setUInt32(pCmd->mParmBuf.uParmCount); /* Required parameters for message */
607
608 /*
609 * So this call apparently failed because the guest wanted to peek
610 * how much parameters it has to supply in order to successfully retrieve
611 * this command. Let's tell him so!
612 */
613 rc = VERR_TOO_MUCH_DATA;
614 }
615 else
616 {
617 rc = paramBufferAssign(&pCmd->mParmBuf, cParms, paParms);
618 }
619
620 LogFlowFunc(("Returned with rc=%Rrc\n", rc));
621 return rc;
622}
623
624/**
625 * Either fills in parameters from a pending host command into our guest context or
626 * defer the guest call until we have something from the host.
627 *
628 * @return IPRT status code.
629 * @param u32ClientID The client's ID.
630 * @param callHandle The client's call handle.
631 * @param cParms Number of parameters.
632 * @param paParms Array of parameters.
633 */
634int Service::retrieveNextHostCmd(uint32_t u32ClientID, VBOXHGCMCALLHANDLE callHandle,
635 uint32_t cParms, VBOXHGCMSVCPARM paParms[])
636{
637 int rc = VINF_SUCCESS;
638
639 /*
640 * Lookup client in our list so that we can assign the context ID of
641 * a command to that client.
642 */
643 std::list< ClientContexts >::reverse_iterator it = mClientContextsList.rbegin();
644 while (it != mClientContextsList.rend())
645 {
646 if (it->mClientID == u32ClientID)
647 break;
648 it++;
649 }
650
651 /* Not found? Add client to list. */
652 if (it == mClientContextsList.rend())
653 {
654 mClientContextsList.push_back(ClientContexts(u32ClientID));
655 it = mClientContextsList.rbegin();
656 }
657 Assert(it != mClientContextsList.rend());
658
659 /*
660 * If host command list is empty (nothing to do right now) just
661 * defer the call until we got something to do (makes the client
662 * wait, depending on the flags set).
663 */
664 if (mHostCmds.empty()) /* If command list is empty, defer ... */
665 {
666 mClientWaiterList.push_back(ClientWaiter(u32ClientID, callHandle, paParms, cParms));
667 rc = VINF_HGCM_ASYNC_EXECUTE;
668 }
669 else
670 {
671 /*
672 * Get the next unassigned host command in the list.
673 */
674 HostCmd curCmd = mHostCmds.front();
675 rc = assignHostCmdToGuest(&curCmd, callHandle, cParms, paParms);
676 if (RT_SUCCESS(rc))
677 {
678 /* Remember which client processes which context (for
679 * later reference & cleanup). */
680 Assert(curCmd.mContextID > 0);
681 /// @todo r=bird: check if already in the list.
682 it->mContextList.push_back(curCmd.mContextID);
683
684 /* Only if the guest really got and understood the message remove it from the list. */
685 paramBufferFree(&curCmd.mParmBuf);
686 mHostCmds.pop_front();
687 }
688 else if (rc == VERR_BUFFER_OVERFLOW)
689 {
690 /* If the client understood the message but supplied too little buffer space
691 * don't send this message again and drop it after 3 unsuccessful attempts.
692 * The host then should take care of next actions (maybe retry it with a smaller buffer). */
693 if (++curCmd.mTries >= 3)
694 {
695 paramBufferFree(&curCmd.mParmBuf);
696 mHostCmds.pop_front();
697 }
698 }
699 else
700 {
701 /* Client did not understand the message or something else weird happened. Try again one
702 * more time and drop it if it didn't get handled then. */
703 if (++curCmd.mTries > 1)
704 {
705 paramBufferFree(&curCmd.mParmBuf);
706 mHostCmds.pop_front();
707 }
708 }
709 }
710 return rc;
711}
712
713/**
714 * Cancels a buffered host command to unblock waits on Main side
715 * (via (multi stage) progress objects.
716 *
717 * @return IPRT status code.
718 * @param u32ContextID Context ID of host command to cancel.
719 */
720int Service::cancelHostCmd(uint32_t u32ContextID)
721{
722 AssertReturn(u32ContextID, VERR_INVALID_PARAMETER);
723 Assert(mpfnHostCallback);
724
725 LogFlowFunc(("Cancelling CID=%u ...\n", u32ContextID));
726
727 CALLBACKDATACLIENTDISCONNECTED data;
728 data.hdr.u32Magic = CALLBACKDATAMAGIC_CLIENT_DISCONNECTED;
729 data.hdr.u32ContextID = u32ContextID;
730
731 AssertPtr(mpfnHostCallback);
732 AssertPtr(mpvHostData);
733
734 return mpfnHostCallback(mpvHostData, GUEST_DISCONNECTED, (void *)(&data), sizeof(data));
735}
736
737/**
738 * Client asks itself (in another thread) to cancel all pending waits which are blocking the client
739 * from shutting down / doing something else.
740 *
741 * @return IPRT status code.
742 * @param u32ClientID The client's ID.
743 */
744int Service::cancelPendingWaits(uint32_t u32ClientID)
745{
746 int rc = VINF_SUCCESS;
747 CallListIter it = mClientWaiterList.begin();
748 while (it != mClientWaiterList.end())
749 {
750 if (it->mClientID == u32ClientID)
751 {
752 if (it->mNumParms >= 2)
753 {
754 it->mParms[0].setUInt32(HOST_CANCEL_PENDING_WAITS); /* Message ID. */
755 it->mParms[1].setUInt32(0); /* Required parameters for message. */
756 }
757 if (mpHelpers)
758 mpHelpers->pfnCallComplete(it->mHandle, rc);
759 it = mClientWaiterList.erase(it);
760 }
761 else
762 it++;
763 }
764 return rc;
765}
766
767/**
768 * Notifies the host (using low-level HGCM callbacks) about an event
769 * which was sent from the client.
770 *
771 * @return IPRT status code.
772 * @param eFunction Function (event) that occured.
773 * @param cParms Number of parameters.
774 * @param paParms Array of parameters.
775 */
776int Service::notifyHost(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
777{
778 LogFlowFunc(("eFunction=%ld, cParms=%ld, paParms=%p\n",
779 eFunction, cParms, paParms));
780 int rc = VINF_SUCCESS;
781 if ( eFunction == GUEST_EXEC_SEND_STATUS
782 && cParms == 5)
783 {
784 CALLBACKDATAEXECSTATUS data;
785 data.hdr.u32Magic = CALLBACKDATAMAGIC_EXEC_STATUS;
786 paParms[0].getUInt32(&data.hdr.u32ContextID);
787
788 paParms[1].getUInt32(&data.u32PID);
789 paParms[2].getUInt32(&data.u32Status);
790 paParms[3].getUInt32(&data.u32Flags);
791 paParms[4].getPointer(&data.pvData, &data.cbData);
792
793 if (mpfnHostCallback)
794 rc = mpfnHostCallback(mpvHostData, eFunction,
795 (void *)(&data), sizeof(data));
796 }
797 else if ( eFunction == GUEST_EXEC_SEND_OUTPUT
798 && cParms == 5)
799 {
800 CALLBACKDATAEXECOUT data;
801 data.hdr.u32Magic = CALLBACKDATAMAGIC_EXEC_OUT;
802 paParms[0].getUInt32(&data.hdr.u32ContextID);
803
804 paParms[1].getUInt32(&data.u32PID);
805 paParms[2].getUInt32(&data.u32HandleId);
806 paParms[3].getUInt32(&data.u32Flags);
807 paParms[4].getPointer(&data.pvData, &data.cbData);
808
809 if (mpfnHostCallback)
810 rc = mpfnHostCallback(mpvHostData, eFunction,
811 (void *)(&data), sizeof(data));
812 }
813 else if ( eFunction == GUEST_EXEC_SEND_INPUT_STATUS
814 && cParms == 5)
815 {
816 CALLBACKDATAEXECINSTATUS data;
817 data.hdr.u32Magic = CALLBACKDATAMAGIC_EXEC_IN_STATUS;
818 paParms[0].getUInt32(&data.hdr.u32ContextID);
819
820 paParms[1].getUInt32(&data.u32PID);
821 paParms[2].getUInt32(&data.u32Status);
822 paParms[3].getUInt32(&data.u32Flags);
823 paParms[4].getUInt32(&data.cbProcessed);
824
825 if (mpfnHostCallback)
826 rc = mpfnHostCallback(mpvHostData, eFunction,
827 (void *)(&data), sizeof(data));
828 }
829 else
830 rc = VERR_NOT_SUPPORTED;
831 LogFlowFunc(("returning %Rrc\n", rc));
832 return rc;
833}
834
835/**
836 * Processes a command receiveed from the host side and re-routes it to
837 * a connect client on the guest.
838 *
839 * @return IPRT status code.
840 * @param eFunction Function code to process.
841 * @param cParms Number of parameters.
842 * @param paParms Array of parameters.
843 */
844int Service::processHostCmd(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
845{
846 /*
847 * If no client is connected at all we don't buffer any host commands
848 * and immediately return an error to the host. This avoids the host
849 * waiting for a response from the guest side in case VBoxService on
850 * the guest is not running/system is messed up somehow.
851 */
852 if (mNumClients == 0)
853 return VERR_NOT_FOUND;
854 HostCmd newCmd;
855 int rc = paramBufferAllocate(&newCmd.mParmBuf, eFunction, cParms, paParms);
856 if ( RT_SUCCESS(rc)
857 && cParms) /* Make sure we at least get one parameter (that is, the context ID). */
858 {
859 /*
860 * Assume that the context ID *always* is the first parameter,
861 * assign the context ID to the command.
862 */
863 newCmd.mParmBuf.pParms[0].getUInt32(&newCmd.mContextID);
864 Assert(newCmd.mContextID > 0);
865 }
866 else if (!cParms)
867 rc = VERR_INVALID_PARAMETER;
868
869 if (RT_SUCCESS(rc))
870 {
871 LogFlowFunc(("Handling host command CID = %u\n",
872 newCmd.mContextID));
873
874 bool fProcessed = false;
875
876 /* Can we wake up a waiting client on guest? */
877 if (!mClientWaiterList.empty())
878 {
879 ClientWaiter guest = mClientWaiterList.front();
880 rc = assignHostCmdToGuest(&newCmd,
881 guest.mHandle, guest.mNumParms, guest.mParms);
882
883 /* In any case the client did something, so wake up and remove from list. */
884 AssertPtr(mpHelpers);
885 mpHelpers->pfnCallComplete(guest.mHandle, rc);
886 mClientWaiterList.pop_front();
887
888 /*
889 * If we got back an error (like VERR_TOO_MUCH_DATA or VERR_BUFFER_OVERFLOW)
890 * we buffer the host command in the next block and return success to the host.
891 */
892 if (RT_FAILURE(rc))
893 {
894 rc = VINF_SUCCESS;
895 }
896 else /* If command was understood by the client, free and remove from host commands list. */
897 {
898 LogFlowFunc(("Host command CID = %u processed with rc=%Rrc\n",
899 newCmd.mContextID, rc));
900
901 paramBufferFree(&newCmd.mParmBuf);
902 }
903 }
904
905 if (!fProcessed)
906 {
907 LogFlowFunc(("Buffering host command CID = %u (rc=%Rrc)\n",
908 newCmd.mContextID, rc));
909
910 mHostCmds.push_back(newCmd);
911 }
912 }
913
914 LogFlowFunc(("Returned with rc=%Rrc\n", rc));
915 return rc;
916}
917
918/**
919 * Handle an HGCM service call.
920 * @copydoc VBOXHGCMSVCFNTABLE::pfnCall
921 * @note All functions which do not involve an unreasonable delay will be
922 * handled synchronously. If needed, we will add a request handler
923 * thread in future for those which do.
924 *
925 * @thread HGCM
926 */
927void Service::call(VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID,
928 void * /* pvClient */, uint32_t eFunction, uint32_t cParms,
929 VBOXHGCMSVCPARM paParms[])
930{
931 int rc = VINF_SUCCESS;
932 LogFlowFunc(("u32ClientID = %u, fn = %u, cParms = %u, paParms = 0x%p\n",
933 u32ClientID, eFunction, cParms, paParms));
934 try
935 {
936 switch (eFunction)
937 {
938 /*
939 * The guest asks the host for the next message to process.
940 */
941 case GUEST_GET_HOST_MSG:
942 LogFlowFunc(("GUEST_GET_HOST_MSG\n"));
943 rc = retrieveNextHostCmd(u32ClientID, callHandle, cParms, paParms);
944 break;
945
946 /*
947 * The guest wants to shut down and asks us (this service) to cancel
948 * all blocking pending waits (VINF_HGCM_ASYNC_EXECUTE) so that the
949 * guest can gracefully shut down.
950 */
951 case GUEST_CANCEL_PENDING_WAITS:
952 LogFlowFunc(("GUEST_CANCEL_PENDING_WAITS\n"));
953 rc = cancelPendingWaits(u32ClientID);
954 break;
955
956 /*
957 * For all other regular commands we call our notifyHost
958 * function. If the current command does not support notifications
959 * notifyHost will return VERR_NOT_SUPPORTED.
960 */
961 default:
962 rc = notifyHost(eFunction, cParms, paParms);
963 break;
964 }
965 if (rc != VINF_HGCM_ASYNC_EXECUTE)
966 {
967 /* Tell the client that the call is complete (unblocks waiting). */
968 AssertPtr(mpHelpers);
969 mpHelpers->pfnCallComplete(callHandle, rc);
970 }
971 }
972 catch (std::bad_alloc)
973 {
974 rc = VERR_NO_MEMORY;
975 }
976 LogFlowFunc(("rc = %Rrc\n", rc));
977}
978
979/**
980 * Service call handler for the host.
981 * @copydoc VBOXHGCMSVCFNTABLE::pfnHostCall
982 * @thread hgcm
983 */
984int Service::hostCall(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
985{
986 int rc = VERR_NOT_SUPPORTED;
987 LogFlowFunc(("fn = %u, cParms = %u, paParms = 0x%p\n",
988 eFunction, cParms, paParms));
989 try
990 {
991 rc = processHostCmd(eFunction, cParms, paParms);
992 }
993 catch (std::bad_alloc)
994 {
995 rc = VERR_NO_MEMORY;
996 }
997
998 LogFlowFunc(("rc = %Rrc\n", rc));
999 return rc;
1000}
1001
1002int Service::uninit()
1003{
1004 Assert(mHostCmds.empty());
1005
1006 return VINF_SUCCESS;
1007}
1008
1009} /* namespace guestControl */
1010
1011using guestControl::Service;
1012
1013/**
1014 * @copydoc VBOXHGCMSVCLOAD
1015 */
1016extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *ptable)
1017{
1018 int rc = VINF_SUCCESS;
1019
1020 LogFlowFunc(("ptable = %p\n", ptable));
1021
1022 if (!VALID_PTR(ptable))
1023 {
1024 rc = VERR_INVALID_PARAMETER;
1025 }
1026 else
1027 {
1028 LogFlowFunc(("ptable->cbSize = %d, ptable->u32Version = 0x%08X\n", ptable->cbSize, ptable->u32Version));
1029
1030 if ( ptable->cbSize != sizeof (VBOXHGCMSVCFNTABLE)
1031 || ptable->u32Version != VBOX_HGCM_SVC_VERSION)
1032 {
1033 rc = VERR_VERSION_MISMATCH;
1034 }
1035 else
1036 {
1037 std::auto_ptr<Service> apService;
1038 /* No exceptions may propagate outside. */
1039 try {
1040 apService = std::auto_ptr<Service>(new Service(ptable->pHelpers));
1041 } catch (int rcThrown) {
1042 rc = rcThrown;
1043 } catch (...) {
1044 rc = VERR_UNRESOLVED_ERROR;
1045 }
1046
1047 if (RT_SUCCESS(rc))
1048 {
1049 /*
1050 * We don't need an additional client data area on the host,
1051 * because we're a class which can have members for that :-).
1052 */
1053 ptable->cbClient = 0;
1054
1055 /* Register functions. */
1056 ptable->pfnUnload = Service::svcUnload;
1057 ptable->pfnConnect = Service::svcConnect;
1058 ptable->pfnDisconnect = Service::svcDisconnect;
1059 ptable->pfnCall = Service::svcCall;
1060 ptable->pfnHostCall = Service::svcHostCall;
1061 ptable->pfnSaveState = NULL; /* The service is stateless, so the normal */
1062 ptable->pfnLoadState = NULL; /* construction done before restoring suffices */
1063 ptable->pfnRegisterExtension = Service::svcRegisterExtension;
1064
1065 /* Service specific initialization. */
1066 ptable->pvService = apService.release();
1067 }
1068 }
1069 }
1070
1071 LogFlowFunc(("returning %Rrc\n", rc));
1072 return rc;
1073}
1074
Note: See TracBrowser for help on using the repository browser.

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