VirtualBox

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

Last change on this file since 34575 was 34253, checked in by vboxsync, 14 years ago

HostServices/GuestControl: Added guest clients reference counting for non-blocking responses without timeout, documentation.

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