VirtualBox

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

最後變更 在這個檔案從36743是 36743,由 vboxsync 提交於 14 年 前

HostServices/GuestCtrl: More checks for empty buffers, drop host message if client did not understand it a second time.

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

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