VirtualBox

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

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

iprt::non_copyable -> RTCNonCopyable (now in utils.h), moved and renamed RTMemAutoPtr et al out of iprt/mem.h.

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