VirtualBox

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

Last change on this file since 45697 was 45697, checked in by vboxsync, 12 years ago

GuestCtrl: Various bugfixes required for test driver to pass.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 53.2 KB
Line 
1/* $Id: service.cpp 45697 2013-04-24 13:30:50Z vboxsync $ */
2/** @file
3 * Guest Control Service: Controlling the guest.
4 */
5
6/*
7 * Copyright (C) 2011-2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @page pg_svc_guest_control Guest Control HGCM Service
19 *
20 * This service acts as a proxy for handling and buffering host command requests
21 * and clients on the guest. It tries to be as transparent as possible to let
22 * the guest (client) and host side do their protocol handling as desired.
23 *
24 * The following terms are used:
25 * - Host: A host process (e.g. VBoxManage or another tool utilizing the Main API)
26 * which wants to control something on the guest.
27 * - Client: A client (e.g. VBoxService) running inside the guest OS waiting for
28 * new host commands to perform. There can be multiple clients connected
29 * to this service. A client is represented by its unique HGCM client ID.
30 * - Context ID: An (almost) unique ID automatically generated on the host (Main API)
31 * to not only distinguish clients but individual requests. Because
32 * the host does not know anything about connected clients it needs
33 * an indicator which it can refer to later. This context ID gets
34 * internally bound by the service to a client which actually processes
35 * the command in order to have a relationship between client<->context ID(s).
36 *
37 * The host can trigger commands which get buffered by the service (with full HGCM
38 * parameter info). As soon as a client connects (or is ready to do some new work)
39 * it gets a buffered host command to process it. This command then will be immediately
40 * removed from the command list. If there are ready clients but no new commands to be
41 * processed, these clients will be set into a deferred state (that is being blocked
42 * to return until a new command is available).
43 *
44 * If a client needs to inform the host that something happened, it can send a
45 * message to a low level HGCM callback registered in Main. This callback contains
46 * the actual data as well as the context ID to let the host do the next necessary
47 * steps for this context. This context ID makes it possible to wait for an event
48 * inside the host's Main API function (like starting a process on the guest and
49 * wait for getting its PID returned by the client) as well as cancelling blocking
50 * host calls in order the client terminated/crashed (HGCM detects disconnected
51 * clients and reports it to this service's callback).
52 *
53 * Starting at VBox 4.2 the context ID itself consists of a session ID, an object
54 * ID (for example a process or file ID) and a count. This is necessary to not break
55 * compatibility between older hosts and to manage guest session on the host.
56 */
57
58/*******************************************************************************
59* Header Files *
60*******************************************************************************/
61#ifdef LOG_GROUP
62 #undef LOG_GROUP
63#endif
64#define LOG_GROUP LOG_GROUP_GUEST_CONTROL
65#include <VBox/HostServices/GuestControlSvc.h>
66
67#include <VBox/log.h>
68#include <iprt/assert.h>
69#include <iprt/cpp/autores.h>
70#include <iprt/cpp/utils.h>
71#include <iprt/err.h>
72#include <iprt/mem.h>
73#include <iprt/list.h>
74#include <iprt/req.h>
75#include <iprt/string.h>
76#include <iprt/thread.h>
77#include <iprt/time.h>
78
79#include <map>
80#include <memory> /* for auto_ptr */
81#include <string>
82#include <list>
83
84#include "gctrl.h"
85
86namespace guestControl {
87
88/** Flag for indicating that the client only is interested in
89 * messages of specific context IDs. */
90#define CLIENTSTATE_FLAG_CONTEXTFILTER RT_BIT(0)
91
92/**
93 * Structure for maintaining a pending (that is, a deferred and not yet completed)
94 * client command.
95 */
96typedef struct ClientConnection
97{
98 /** The call handle */
99 VBOXHGCMCALLHANDLE mHandle;
100 /** Number of parameters */
101 uint32_t mNumParms;
102 /** The call parameters */
103 VBOXHGCMSVCPARM *mParms;
104 /** The standard constructor. */
105 ClientConnection(void)
106 : mHandle(0), mNumParms(0), mParms(NULL) {}
107} ClientConnection;
108
109/**
110 * Structure for holding a buffered host command which has
111 * not been processed yet.
112 */
113typedef struct HostCommand
114{
115 RTLISTNODE Node;
116
117 uint32_t AddRef(void)
118 {
119#ifdef DEBUG_andy
120 LogFlowFunc(("Adding reference pHostCmd=%p, CID=%RU32, new refCount=%RU32\n",
121 this, mContextID, mRefCount + 1));
122#endif
123 return ++mRefCount;
124 }
125
126 uint32_t Release(void)
127 {
128#ifdef DEBUG_andy
129 LogFlowFunc(("Releasing reference pHostCmd=%p, CID=%RU32, new refCount=%RU32\n",
130 this, mContextID, mRefCount - 1));
131#endif
132 /* Release reference for current command. */
133 Assert(mRefCount);
134 if (--mRefCount == 0)
135 Free();
136
137 return mRefCount;
138 }
139
140 /**
141 * Allocates the command with an HGCM request. Needs to be free'd using Free().
142 *
143 * @return IPRT status code.
144 * @param uMsg Message type.
145 * @param cParms Number of parameters of HGCM request.
146 * @param paParms Array of parameters of HGCM request.
147 */
148 int Allocate(uint32_t uMsg, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
149 {
150 LogFlowFunc(("Allocating pHostCmd=%p, uMsg=%RU32, cParms=%RU32, paParms=%p\n",
151 this, uMsg, cParms, paParms));
152
153 if (!cParms) /* At least one parameter (context ID) must be present. */
154 return VERR_INVALID_PARAMETER;
155
156 AssertPtrReturn(paParms, VERR_INVALID_POINTER);
157
158 /* Paranoia. */
159 if (cParms > 256)
160 cParms = 256;
161
162 int rc = VINF_SUCCESS;
163
164 /*
165 * Don't verify anything here (yet), because this function only buffers
166 * the HGCM data into an internal structure and reaches it back to the guest (client)
167 * in an unmodified state.
168 */
169 mMsgType = uMsg;
170 mParmCount = cParms;
171 if (mParmCount)
172 {
173 mpParms = (VBOXHGCMSVCPARM*)RTMemAllocZ(sizeof(VBOXHGCMSVCPARM) * mParmCount);
174 if (NULL == mpParms)
175 rc = VERR_NO_MEMORY;
176 }
177
178 if (RT_SUCCESS(rc))
179 {
180 for (uint32_t i = 0; i < mParmCount; i++)
181 {
182 mpParms[i].type = paParms[i].type;
183 switch (paParms[i].type)
184 {
185 case VBOX_HGCM_SVC_PARM_32BIT:
186 mpParms[i].u.uint32 = paParms[i].u.uint32;
187 break;
188
189 case VBOX_HGCM_SVC_PARM_64BIT:
190 /* Not supported yet. */
191 break;
192
193 case VBOX_HGCM_SVC_PARM_PTR:
194 mpParms[i].u.pointer.size = paParms[i].u.pointer.size;
195 if (mpParms[i].u.pointer.size > 0)
196 {
197 mpParms[i].u.pointer.addr = RTMemAlloc(mpParms[i].u.pointer.size);
198 if (NULL == mpParms[i].u.pointer.addr)
199 {
200 rc = VERR_NO_MEMORY;
201 break;
202 }
203 else
204 memcpy(mpParms[i].u.pointer.addr,
205 paParms[i].u.pointer.addr,
206 mpParms[i].u.pointer.size);
207 }
208 else
209 {
210 /* Size is 0 -- make sure we don't have any pointer. */
211 mpParms[i].u.pointer.addr = NULL;
212 }
213 break;
214
215 default:
216 break;
217 }
218 if (RT_FAILURE(rc))
219 break;
220 }
221 }
222
223 if (RT_SUCCESS(rc))
224 {
225 /*
226 * Assume that the context ID *always* is the first parameter,
227 * assign the context ID to the command.
228 */
229 rc = mpParms[0].getUInt32(&mContextID);
230
231 /* Set timestamp so that clients can distinguish between already
232 * processed commands and new ones. */
233 mTimestamp = RTTimeNanoTS();
234 }
235
236 LogFlowFunc(("Returned with rc=%Rrc\n", rc));
237 return rc;
238 }
239
240 /**
241 * Frees the buffered HGCM request.
242 *
243 * @return IPRT status code.
244 */
245 void Free(void)
246 {
247 AssertMsg(mRefCount == 0, ("pHostCmd=%p, CID=%RU32 still being used by a client (%RU32 refs), cannot free yet\n",
248 this, mContextID, mRefCount));
249
250 LogFlowFunc(("Freeing host command pHostCmd=%p, CID=%RU32, mMsgType=%RU32, mParmCount=%RU32, mpParms=%p\n",
251 this, mContextID, mMsgType, mParmCount, mpParms));
252
253 for (uint32_t i = 0; i < mParmCount; i++)
254 {
255 switch (mpParms[i].type)
256 {
257 case VBOX_HGCM_SVC_PARM_PTR:
258 if (mpParms[i].u.pointer.size > 0)
259 RTMemFree(mpParms[i].u.pointer.addr);
260 break;
261
262 default:
263 break;
264 }
265 }
266
267 if (mpParms)
268 {
269 RTMemFree(mpParms);
270 mpParms = NULL;
271 }
272
273 mParmCount = 0;
274
275 /* Removes the command from its list */
276 RTListNodeRemove(&Node);
277 }
278
279 /**
280 * Copies data from the buffered HGCM request to the current HGCM request.
281 *
282 * @return IPRT status code.
283 * @param paDstParms Array of parameters of HGCM request to fill the data into.
284 * @param cPDstarms Number of parameters the HGCM request can handle.
285 * @param pSrcBuf Parameter buffer to assign.
286 */
287 int CopyTo(VBOXHGCMSVCPARM paDstParms[], uint32_t cDstParms) const
288 {
289 LogFlowFunc(("pHostCmd=%p, mMsgType=%RU32, mParmCount=%RU32, mContextID=%RU32\n",
290 this, mMsgType, mParmCount, mContextID));
291
292 int rc = VINF_SUCCESS;
293 if (cDstParms != mParmCount)
294 {
295 LogFlowFunc(("Parameter count does not match (got %RU32, expected %RU32)\n",
296 cDstParms, mParmCount));
297 rc = VERR_INVALID_PARAMETER;
298 }
299
300 if (RT_SUCCESS(rc))
301 {
302 for (uint32_t i = 0; i < mParmCount; i++)
303 {
304 if (paDstParms[i].type != mpParms[i].type)
305 {
306 LogFlowFunc(("Parameter %RU32 type mismatch (got %RU32, expected %RU32)\n",
307 i, paDstParms[i].type, mpParms[i].type));
308 rc = VERR_INVALID_PARAMETER;
309 }
310 else
311 {
312 switch (mpParms[i].type)
313 {
314 case VBOX_HGCM_SVC_PARM_32BIT:
315#ifdef DEBUG_andy
316 LogFlowFunc(("\tmpParms[%RU32] = %RU32 (uint32_t)\n",
317 i, mpParms[i].u.uint32));
318#endif
319 paDstParms[i].u.uint32 = mpParms[i].u.uint32;
320 break;
321
322 case VBOX_HGCM_SVC_PARM_PTR:
323 {
324#ifdef DEBUG_andy
325 LogFlowFunc(("\tmpParms[%RU32] = %p (ptr), size = %RU32\n",
326 i, mpParms[i].u.pointer.addr, mpParms[i].u.pointer.size));
327#endif
328 if (!mpParms[i].u.pointer.size)
329 continue; /* Only copy buffer if there actually is something to copy. */
330
331 if (!paDstParms[i].u.pointer.addr)
332 rc = VERR_INVALID_PARAMETER;
333
334 if ( RT_SUCCESS(rc)
335 && paDstParms[i].u.pointer.size < mpParms[i].u.pointer.size)
336 rc = VERR_BUFFER_OVERFLOW;
337
338 if (RT_SUCCESS(rc))
339 {
340 memcpy(paDstParms[i].u.pointer.addr,
341 mpParms[i].u.pointer.addr,
342 mpParms[i].u.pointer.size);
343 }
344
345 break;
346 }
347
348 case VBOX_HGCM_SVC_PARM_64BIT:
349 /* Fall through is intentional. */
350 default:
351 LogFlowFunc(("Parameter %RU32 of type %RU32 is not supported yet\n",
352 i, mpParms[i].type));
353 rc = VERR_NOT_SUPPORTED;
354 break;
355 }
356 }
357
358 if (RT_FAILURE(rc))
359 {
360 LogFlowFunc(("Parameter %RU32 invalid (%Rrc), refusing\n",
361 i, rc));
362 break;
363 }
364 }
365 }
366
367 LogFlowFunc(("Returned with rc=%Rrc\n", rc));
368 return rc;
369 }
370
371 int Assign(const ClientConnection *pConnection)
372 {
373 AssertPtrReturn(pConnection, VERR_INVALID_POINTER);
374
375 int rc;
376
377 LogFlowFunc(("pHostCmd=%p, mMsgType=%RU32, mParmCount=%RU32, mpParms=%p\n",
378 this, mMsgType, mParmCount, mpParms));
379
380 /* Does the current host command need more parameter space which
381 * the client does not provide yet? */
382 if (mParmCount > pConnection->mNumParms)
383 {
384 /*
385 * So this call apparently failed because the guest wanted to peek
386 * how much parameters it has to supply in order to successfully retrieve
387 * this command. Let's tell him so!
388 */
389 rc = VERR_TOO_MUCH_DATA;
390 }
391 else
392 {
393 rc = CopyTo(pConnection->mParms, pConnection->mNumParms);
394
395 /*
396 * Has there been enough parameter space but the wrong parameter types
397 * were submitted -- maybe the client was just asking for the next upcoming
398 * host message?
399 *
400 * Note: To keep this compatible to older clients we return VERR_TOO_MUCH_DATA
401 * in every case.
402 */
403 if (RT_FAILURE(rc))
404 rc = VERR_TOO_MUCH_DATA;
405 }
406
407 return rc;
408 }
409
410 int Peek(const ClientConnection *pConnection)
411 {
412 AssertPtrReturn(pConnection, VERR_INVALID_POINTER);
413
414 LogFlowFunc(("pHostCmd=%p, mMsgType=%RU32, mParmCount=%RU32, mpParms=%p\n",
415 this, mMsgType, mParmCount, mpParms));
416
417 if (pConnection->mNumParms >= 2)
418 {
419 pConnection->mParms[0].setUInt32(mMsgType); /* Message ID */
420 pConnection->mParms[1].setUInt32(mParmCount); /* Required parameters for message */
421 }
422 else
423 LogFlowFunc(("Warning: Client has not (yet) submitted enough parameters (%RU32, must be at least 2) to at least peak for the next message\n",
424 pConnection->mNumParms));
425
426 /*
427 * Always return VERR_TOO_MUCH_DATA data here to
428 * keep it compatible with older clients and to
429 * have correct accounting (mHostRc + mHostCmdTries).
430 */
431 return VERR_TOO_MUCH_DATA;
432 }
433
434 /** Reference count for keeping track how many connected
435 * clients still need to process this command until it can
436 * be removed. */
437 uint32_t mRefCount;
438 /** The context ID this command belongs to. Will be extracted
439 * *always* from HGCM parameter [0]. */
440 uint32_t mContextID;
441 /** Dynamic structure for holding the HGCM parms */
442 uint32_t mMsgType;
443 /** Number of HGCM parameters. */
444 uint32_t mParmCount;
445 /** Array of HGCM parameters. */
446 PVBOXHGCMSVCPARM mpParms;
447 /** Incoming timestamp (us). */
448 uint64_t mTimestamp;
449} HostCommand;
450typedef std::list< HostCommand *> HostCmdList;
451typedef std::list< HostCommand *>::iterator HostCmdListIter;
452typedef std::list< HostCommand *>::const_iterator HostCmdListIterConst;
453
454/**
455 * Per-client structure used for book keeping/state tracking a
456 * certain host command.
457 */
458typedef struct ClientContext
459{
460 /* Pointer to list node of this command. */
461 HostCommand *mpHostCmd;
462 /** The standard constructor. */
463 ClientContext(void) : mpHostCmd(NULL) {}
464 /** Internal constrcutor. */
465 ClientContext(HostCommand *pHostCmd) : mpHostCmd(pHostCmd) {}
466} ClientContext;
467typedef std::map< uint32_t, ClientContext > ClientContextMap;
468typedef std::map< uint32_t, ClientContext >::iterator ClientContextMapIter;
469typedef std::map< uint32_t, ClientContext >::const_iterator ClientContextMapIterConst;
470
471/**
472 * Structure for holding a connected guest client
473 * state.
474 */
475typedef struct ClientState
476{
477 ClientState(void)
478 : mSvcHelpers(NULL),
479 mID(0),
480 mFlags(0), mContextFilter(0),
481 mHostCmdRc(VINF_SUCCESS), mHostCmdTries(0),
482 mHostCmdTS(0),
483 mIsPending(false),
484 mPeekCount(0) { }
485
486 ClientState(PVBOXHGCMSVCHELPERS pSvcHelpers, uint32_t uClientID)
487 : mSvcHelpers(pSvcHelpers),
488 mID(uClientID),
489 mFlags(0), mContextFilter(0),
490 mHostCmdRc(VINF_SUCCESS), mHostCmdTries(0),
491 mHostCmdTS(0),
492 mIsPending(false),
493 mPeekCount(0){ }
494
495 void DequeueAll(void)
496 {
497 HostCmdListIter curItem = mHostCmdList.begin();
498 while (curItem != mHostCmdList.end())
499 curItem = Dequeue(curItem);
500 }
501
502 void DequeueCurrent(void)
503 {
504 HostCmdListIter curCmd = mHostCmdList.begin();
505 if (curCmd != mHostCmdList.end())
506 Dequeue(curCmd);
507 }
508
509 HostCmdListIter Dequeue(HostCmdListIter &curItem)
510 {
511 HostCommand *pHostCmd = (*curItem);
512 AssertPtr(pHostCmd);
513
514 if (pHostCmd->Release() == 0)
515 {
516 LogFlowFunc(("[Client %RU32] Destroying pHostCmd=%p\n",
517 mID, (*curItem)));
518
519 delete pHostCmd;
520 pHostCmd = NULL;
521 }
522
523 HostCmdListIter nextItem = mHostCmdList.erase(curItem);
524
525 /* Reset everything else. */
526 mHostCmdRc = VINF_SUCCESS;
527 mHostCmdTries = 0;
528 mPeekCount = 0;
529
530 return nextItem;
531 }
532
533 int EnqueueCommand(HostCommand *pHostCmd)
534 {
535 AssertPtrReturn(pHostCmd, VERR_INVALID_POINTER);
536
537 int rc = VINF_SUCCESS;
538
539 try
540 {
541 mHostCmdList.push_back(pHostCmd);
542 pHostCmd->AddRef();
543 }
544 catch (std::bad_alloc)
545 {
546 rc = VERR_NO_MEMORY;
547 }
548
549 return rc;
550 }
551
552 bool WantsHostCommand(const HostCommand *pHostCmd) const
553 {
554 AssertPtrReturn(pHostCmd, false);
555
556#ifdef DEBUG_andy
557 LogFlowFunc(("mHostCmdTS=%RU64, pHostCmdTS=%RU64\n",
558 mHostCmdTS, pHostCmd->mTimestamp));
559#endif
560
561 /* Only process newer commands. */
562 if (pHostCmd->mTimestamp <= mHostCmdTS)
563 return false;
564
565#ifdef DEBUG_andy
566 LogFlowFunc(("[Client %RU32] mFlags=%x, mContextID=%RU32, mContextFilter=%x, filterRes=%x, sessionID=%RU32\n",
567 mID, mFlags, pHostCmd->mContextID, mContextFilter,
568 pHostCmd->mContextID & mContextFilter, VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(pHostCmd->mContextID)));
569#endif
570 /*
571 * If a sesseion filter is set, only obey those sessions we're interested in.
572 */
573 bool fWant = false;
574 if (mFlags & CLIENTSTATE_FLAG_CONTEXTFILTER)
575 {
576 if ((pHostCmd->mContextID & mContextFilter) == mContextFilter)
577 fWant = true;
578 }
579 else /* Client is interested in all commands. */
580 fWant = true;
581
582 return fWant;
583 }
584
585 int SetPending(const ClientConnection *pConnection)
586 {
587 AssertPtrReturn(pConnection, VERR_INVALID_POINTER);
588
589 if (mIsPending)
590 {
591 LogFlowFunc(("[Client %RU32] Already is in pending mode\n", mID));
592
593 /*
594 * Signal that we don't and can't return yet.
595 */
596 return VINF_HGCM_ASYNC_EXECUTE;
597 }
598
599 if (mHostCmdList.empty())
600 {
601 AssertMsg(mIsPending == false,
602 ("Client ID=%RU32 already is pending but tried to receive a new host command\n", mID));
603
604 mPendingCon.mHandle = pConnection->mHandle;
605 mPendingCon.mNumParms = pConnection->mNumParms;
606 mPendingCon.mParms = pConnection->mParms;
607
608 mIsPending = true;
609
610 LogFlowFunc(("[Client %RU32] Is now in pending mode\n", mID));
611
612 /*
613 * Signal that we don't and can't return yet.
614 */
615 return VINF_HGCM_ASYNC_EXECUTE;
616 }
617
618 /*
619 * Signal that there already is a connection pending.
620 * Shouldn't happen in daily usage.
621 */
622 AssertMsgFailed(("Client already has a connection pending\n"));
623 return VERR_SIGNAL_PENDING;
624 }
625
626 int Run(const ClientConnection *pConnection,
627 HostCommand *pHostCmd)
628 {
629 AssertPtrReturn(pConnection, VERR_INVALID_POINTER);
630 AssertPtrReturn(pHostCmd, VERR_INVALID_POINTER);
631
632 int rc = VINF_SUCCESS;
633
634 LogFlowFunc(("[Client %RU32] pConnection=%p, mHostCmdRc=%Rrc, mHostCmdTries=%RU32, mPeekCount=%RU32\n",
635 mID, pConnection, mHostCmdRc, mHostCmdTries, mPeekCount));
636
637 mHostCmdRc = SendReply(pConnection, pHostCmd);
638 LogFlowFunc(("[Client %RU32] Processing pHostCmd=%p ended with rc=%Rrc\n",
639 mID, pHostCmd, mHostCmdRc));
640
641 bool fRemove = false;
642 if (RT_FAILURE(mHostCmdRc))
643 {
644 mHostCmdTries++;
645
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 6 unsuccessful attempts.
649 *
650 * Note: Due to legacy reasons this the retry counter has to be even because on
651 * every peek there will be the actual command retrieval from the client side.
652 * To not get the actual command if the client actually only wants to peek for
653 * the next command, there needs to be two rounds per try, e.g. 3 rounds = 6 tries.
654 *
655 ** @todo Fix the mess stated above. GUEST_MSG_WAIT should be become GUEST_MSG_PEEK, *only*
656 * (and every time) returning the next upcoming host command (if any, blocking). Then
657 * it's up to the client what to do next, either peeking again or getting the actual
658 * host command via an own GUEST_ type message.
659 */
660 if (mHostCmdRc == VERR_TOO_MUCH_DATA)
661 {
662 if (mHostCmdTries == 6)
663 fRemove = true;
664 }
665 /* Client did not understand the message or something else weird happened. Try again one
666 * more time and drop it if it didn't get handled then. */
667 else if (mHostCmdTries > 1)
668 fRemove = true;
669 }
670 else
671 fRemove = true; /* Everything went fine, remove it. */
672
673 LogFlowFunc(("[Client %RU32] Tried pHostCmd=%p for %RU32 times, (last result=%Rrc, fRemove=%RTbool)\n",
674 mID, pHostCmd, mHostCmdTries, mHostCmdRc, fRemove));
675
676 if (RT_SUCCESS(rc))
677 rc = mHostCmdRc;
678
679 if (fRemove)
680 {
681 /** @todo Fix this (slow) lookup. Too late today. */
682 HostCmdListIter curItem = mHostCmdList.begin();
683 while (curItem != mHostCmdList.end())
684 {
685 if ((*curItem) == pHostCmd)
686 {
687 Dequeue(curItem);
688 break;
689 }
690
691 curItem++;
692 }
693 }
694
695 LogFlowFunc(("[Client %RU32] Returned with rc=%Rrc\n", mID, rc));
696 return rc;
697 }
698
699 int RunCurrent(const ClientConnection *pConnection)
700 {
701 AssertPtrReturn(pConnection, VERR_INVALID_POINTER);
702
703 int rc;
704 if (mHostCmdList.empty())
705 {
706 rc = SetPending(pConnection);
707 }
708 else
709 {
710 AssertMsgReturn(!mIsPending,
711 ("Client ID=%RU32 still is in pending mode; can't use another connection\n", mID), VERR_INVALID_PARAMETER);
712
713 HostCmdListIter curCmd = mHostCmdList.begin();
714 Assert(curCmd != mHostCmdList.end());
715 HostCommand *pHostCmd = (*curCmd);
716 AssertPtrReturn(pHostCmd, VERR_INVALID_POINTER);
717
718 rc = Run(pConnection, pHostCmd);
719 }
720
721 return rc;
722 }
723
724 int Wakeup(void)
725 {
726 int rc = VINF_NO_CHANGE;
727
728 if (mIsPending)
729 {
730 LogFlowFunc(("[Client %RU32] Waking up ...\n", mID));
731
732 rc = VINF_SUCCESS;
733
734 HostCmdListIter curCmd = mHostCmdList.begin();
735 if (curCmd != mHostCmdList.end())
736 {
737 HostCommand *pHostCmd = (*curCmd);
738 AssertPtrReturn(pHostCmd, VERR_INVALID_POINTER);
739
740 LogFlowFunc(("[Client %RU32] Current host command is pHostCmd=%p, CID=%RU32, cmdType=%RU32, cmdParms=%RU32, refCount=%RU32\n",
741 mID, pHostCmd, pHostCmd->mContextID, pHostCmd->mMsgType, pHostCmd->mParmCount, pHostCmd->mRefCount));
742
743 rc = Run(&mPendingCon, pHostCmd);
744 }
745 else
746 AssertMsgFailed(("Waking up client ID=%RU32 with no host command in queue is a bad idea\n", mID));
747
748 return rc;
749 }
750
751 return VINF_NO_CHANGE;
752 }
753
754 int CancelWaiting(int rcPending)
755 {
756 LogFlowFunc(("[Client %RU32] Cancelling waiting with %Rrc, isPending=%RTbool, pendingNumParms=%RU32, flags=%x\n",
757 mID, rcPending, mIsPending, mPendingCon.mNumParms, mFlags));
758
759 if ( mIsPending
760 && mPendingCon.mNumParms >= 2)
761 {
762 mPendingCon.mParms[0].setUInt32(HOST_CANCEL_PENDING_WAITS); /* Message ID. */
763 mPendingCon.mParms[1].setUInt32(0); /* Required parameters for message. */
764
765 AssertPtr(mSvcHelpers);
766 mSvcHelpers->pfnCallComplete(mPendingCon.mHandle, rcPending);
767
768 mIsPending = false;
769 }
770
771 return VINF_SUCCESS;
772 }
773
774 int SendReply(const ClientConnection *pConnection,
775 HostCommand *pHostCmd)
776 {
777 AssertPtrReturn(pConnection, VERR_INVALID_POINTER);
778 AssertPtrReturn(pHostCmd, VERR_INVALID_POINTER);
779
780 int rc;
781 /* If the client is in pending mode, always send back
782 * the peek result first. */
783 if (mIsPending)
784 {
785 rc = pHostCmd->Peek(pConnection);
786 mPeekCount++;
787 }
788 else
789 {
790 /* If this is the very first peek, make sure to *always* give back the peeking answer
791 * instead of the actual command, even if this command would fit into the current
792 * connection buffer. */
793 if (!mPeekCount)
794 {
795 rc = pHostCmd->Peek(pConnection);
796 mPeekCount++;
797 }
798 else
799 {
800 /* Try assigning the host command to the client and store the
801 * result code for later use. */
802 rc = pHostCmd->Assign(pConnection);
803 if (RT_FAILURE(rc)) /* If something failed, let the client peek (again). */
804 {
805 rc = pHostCmd->Peek(pConnection);
806 mPeekCount++;
807 }
808 else
809 mPeekCount = 0;
810 }
811 }
812
813 /* Reset pending status. */
814 mIsPending = false;
815
816 /* In any case the client did something, so complete
817 * the pending call with the result we just got. */
818 AssertPtr(mSvcHelpers);
819 mSvcHelpers->pfnCallComplete(pConnection->mHandle, rc);
820
821 LogFlowFunc(("[Client %RU32] mPeekCount=%RU32, pConnection=%p, pHostCmd=%p, replyRc=%Rrc\n",
822 mID, mPeekCount, pConnection, pHostCmd, rc));
823 return rc;
824 }
825
826 PVBOXHGCMSVCHELPERS mSvcHelpers;
827 /** The client's ID. */
828 uint32_t mID;
829 /** Client flags. @sa CLIENTSTATE_FLAG_ flags. */
830 uint32_t mFlags;
831 /** The context ID filter, based on the flags set. */
832 uint32_t mContextFilter;
833 /** Host command list to process. */
834 HostCmdList mHostCmdList;
835 /** Last (most recent) rc after handling the
836 * host command. */
837 int mHostCmdRc;
838 /** How many times the host service has tried to deliver this
839 * command to the according client. */
840 uint32_t mHostCmdTries;
841 /** Timestamp (us) of last host command processed. */
842 uint64_t mHostCmdTS;
843 /**
844 * Flag indicating whether the client currently is pending.
845 * This means the client waits for a new host command to reply
846 * and won't return from the waiting call until a new host
847 * command is available.
848 */
849 bool mIsPending;
850 /**
851 * This is necessary for being compatible with older
852 * Guest Additions. In case there are commands which only
853 * have two (2) parameters and therefore would fit into the
854 * GUEST_MSG_WAIT reply immediately, we now can make sure
855 * that the client first gets back the GUEST_MSG_WAIT results
856 * first.
857 */
858 uint32_t mPeekCount;
859 /** The client's pending connection. */
860 ClientConnection mPendingCon;
861} ClientState;
862typedef std::map< uint32_t, ClientState > ClientStateMap;
863typedef std::map< uint32_t, ClientState >::iterator ClientStateMapIter;
864typedef std::map< uint32_t, ClientState >::const_iterator ClientStateMapIterConst;
865
866/**
867 * Class containing the shared information service functionality.
868 */
869class Service : public RTCNonCopyable
870{
871
872private:
873
874 /** Type definition for use in callback functions. */
875 typedef Service SELF;
876 /** HGCM helper functions. */
877 PVBOXHGCMSVCHELPERS mpHelpers;
878 /**
879 * Callback function supplied by the host for notification of updates
880 * to properties.
881 */
882 PFNHGCMSVCEXT mpfnHostCallback;
883 /** User data pointer to be supplied to the host callback function. */
884 void *mpvHostData;
885 /** List containing all buffered host commands. */
886 RTLISTANCHOR mHostCmdList;
887 /** Map containing all connected clients. The primary key contains
888 * the HGCM client ID to identify the client. */
889 ClientStateMap mClientStateMap;
890public:
891 explicit Service(PVBOXHGCMSVCHELPERS pHelpers)
892 : mpHelpers(pHelpers)
893 , mpfnHostCallback(NULL)
894 , mpvHostData(NULL)
895 {
896 RTListInit(&mHostCmdList);
897 }
898
899 /**
900 * @copydoc VBOXHGCMSVCHELPERS::pfnUnload
901 * Simply deletes the service object
902 */
903 static DECLCALLBACK(int) svcUnload (void *pvService)
904 {
905 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
906 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
907 int rc = pSelf->uninit();
908 AssertRC(rc);
909 if (RT_SUCCESS(rc))
910 delete pSelf;
911 return rc;
912 }
913
914 /**
915 * @copydoc VBOXHGCMSVCHELPERS::pfnConnect
916 * Stub implementation of pfnConnect and pfnDisconnect.
917 */
918 static DECLCALLBACK(int) svcConnect (void *pvService,
919 uint32_t u32ClientID,
920 void *pvClient)
921 {
922 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
923 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
924 AssertPtrReturn(pSelf, VERR_INVALID_POINTER);
925 return pSelf->clientConnect(u32ClientID, pvClient);
926 }
927
928 /**
929 * @copydoc VBOXHGCMSVCHELPERS::pfnConnect
930 * Stub implementation of pfnConnect and pfnDisconnect.
931 */
932 static DECLCALLBACK(int) svcDisconnect (void *pvService,
933 uint32_t u32ClientID,
934 void *pvClient)
935 {
936 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
937 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
938 AssertPtrReturn(pSelf, VERR_INVALID_POINTER);
939 return pSelf->clientDisconnect(u32ClientID, pvClient);
940 }
941
942 /**
943 * @copydoc VBOXHGCMSVCHELPERS::pfnCall
944 * Wraps to the call member function
945 */
946 static DECLCALLBACK(void) svcCall (void * pvService,
947 VBOXHGCMCALLHANDLE callHandle,
948 uint32_t u32ClientID,
949 void *pvClient,
950 uint32_t u32Function,
951 uint32_t cParms,
952 VBOXHGCMSVCPARM paParms[])
953 {
954 AssertLogRelReturnVoid(VALID_PTR(pvService));
955 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
956 AssertPtrReturnVoid(pSelf);
957 pSelf->call(callHandle, u32ClientID, pvClient, u32Function, cParms, paParms);
958 }
959
960 /**
961 * @copydoc VBOXHGCMSVCHELPERS::pfnHostCall
962 * Wraps to the hostCall member function
963 */
964 static DECLCALLBACK(int) svcHostCall (void *pvService,
965 uint32_t u32Function,
966 uint32_t cParms,
967 VBOXHGCMSVCPARM paParms[])
968 {
969 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
970 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
971 AssertPtrReturn(pSelf, VERR_INVALID_POINTER);
972 return pSelf->hostCall(u32Function, cParms, paParms);
973 }
974
975 /**
976 * @copydoc VBOXHGCMSVCHELPERS::pfnRegisterExtension
977 * Installs a host callback for notifications of property changes.
978 */
979 static DECLCALLBACK(int) svcRegisterExtension (void *pvService,
980 PFNHGCMSVCEXT pfnExtension,
981 void *pvExtension)
982 {
983 AssertLogRelReturn(VALID_PTR(pvService), VERR_INVALID_PARAMETER);
984 SELF *pSelf = reinterpret_cast<SELF *>(pvService);
985 AssertPtrReturn(pSelf, VERR_INVALID_POINTER);
986 pSelf->mpfnHostCallback = pfnExtension;
987 pSelf->mpvHostData = pvExtension;
988 return VINF_SUCCESS;
989 }
990
991private:
992
993 int prepareExecute(uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
994 int clientConnect(uint32_t u32ClientID, void *pvClient);
995 int clientDisconnect(uint32_t u32ClientID, void *pvClient);
996 int clientGetCommand(uint32_t u32ClientID, VBOXHGCMCALLHANDLE callHandle, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
997 int clientSetMsgFilter(uint32_t u32ClientID, VBOXHGCMCALLHANDLE callHandle, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
998 int clientSkipMsg(uint32_t u32ClientID, VBOXHGCMCALLHANDLE callHandle, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
999 int cancelHostCmd(uint32_t u32ContextID);
1000 int cancelPendingWaits(uint32_t u32ClientID, int rcPending);
1001 int hostCallback(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
1002 int hostProcessCommand(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
1003 void call(VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID, void *pvClient, uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
1004 int hostCall(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[]);
1005 int uninit(void);
1006};
1007
1008/**
1009 * Handles a client which just connected.
1010 *
1011 * @return IPRT status code.
1012 * @param u32ClientID
1013 * @param pvClient
1014 */
1015int Service::clientConnect(uint32_t u32ClientID, void *pvClient)
1016{
1017 LogFlowFunc(("[Client %RU32] Connected\n", u32ClientID));
1018#ifdef VBOX_STRICT
1019 ClientStateMapIterConst it = mClientStateMap.find(u32ClientID);
1020 if (it != mClientStateMap.end())
1021 {
1022 AssertMsgFailed(("Client with ID=%RU32 already connected when it should not\n",
1023 u32ClientID));
1024 return VERR_ALREADY_EXISTS;
1025 }
1026#endif
1027 ClientState clientState(mpHelpers, u32ClientID);
1028 mClientStateMap[u32ClientID] = clientState;
1029 /** @todo Exception handling! */
1030 return VINF_SUCCESS;
1031}
1032
1033/**
1034 * Handles a client which disconnected. This functiond does some
1035 * internal cleanup as well as sends notifications to the host so
1036 * that the host can do the same (if required).
1037 *
1038 * @return IPRT status code.
1039 * @param u32ClientID The client's ID of which disconnected.
1040 * @param pvClient User data, not used at the moment.
1041 */
1042int Service::clientDisconnect(uint32_t u32ClientID, void *pvClient)
1043{
1044 LogFlowFunc(("[Client %RU32] Disonnected (%zu clients total)\n",
1045 u32ClientID, mClientStateMap.size()));
1046
1047 AssertMsg(mClientStateMap.size(),
1048 ("No clients in list anymore when there should (client ID=%RU32)\n", u32ClientID));
1049
1050 int rc = VINF_SUCCESS;
1051
1052 ClientStateMapIter itClientState = mClientStateMap.find(u32ClientID);
1053 AssertMsg(itClientState != mClientStateMap.end(),
1054 ("Clients ID=%RU32 not found in client list when it should be there\n", u32ClientID));
1055
1056 if (itClientState != mClientStateMap.end())
1057 {
1058 itClientState->second.DequeueAll();
1059
1060 mClientStateMap.erase(itClientState);
1061 }
1062
1063 bool fAllClientsDisconnected = mClientStateMap.size() == 0;
1064 if (fAllClientsDisconnected)
1065 {
1066 LogFlowFunc(("All clients disconnected, cancelling all host commands ...\n"));
1067
1068 /*
1069 * If all clients disconnected we also need to make sure that all buffered
1070 * host commands need to be notified, because Main is waiting a notification
1071 * via a (multi stage) progress object.
1072 */
1073 HostCommand *pCurCmd = RTListGetFirst(&mHostCmdList, HostCommand, Node);
1074 while (pCurCmd)
1075 {
1076 HostCommand *pNext = RTListNodeGetNext(&pCurCmd->Node, HostCommand, Node);
1077 bool fLast = RTListNodeIsLast(&mHostCmdList, &pCurCmd->Node);
1078
1079 int rc2 = cancelHostCmd(pCurCmd->mContextID);
1080 if (RT_FAILURE(rc2))
1081 {
1082 LogFlowFunc(("Cancelling host command with CID=%u (refCount=%RU32) failed with rc=%Rrc\n",
1083 pCurCmd->mContextID, pCurCmd->mRefCount, rc2));
1084 /* Keep going. */
1085 }
1086
1087 while (pCurCmd->Release());
1088
1089 delete pCurCmd;
1090 pCurCmd = NULL;
1091
1092 if (fLast)
1093 break;
1094
1095 pCurCmd = pNext;
1096 }
1097
1098 Assert(RTListIsEmpty(&mHostCmdList));
1099 }
1100
1101 return rc;
1102}
1103
1104/**
1105 * Either fills in parameters from a pending host command into our guest context or
1106 * defer the guest call until we have something from the host.
1107 *
1108 * @return IPRT status code.
1109 * @param u32ClientID The client's ID.
1110 * @param callHandle The client's call handle.
1111 * @param cParms Number of parameters.
1112 * @param paParms Array of parameters.
1113 */
1114int Service::clientGetCommand(uint32_t u32ClientID, VBOXHGCMCALLHANDLE callHandle,
1115 uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1116{
1117 /*
1118 * Lookup client in our list so that we can assign the context ID of
1119 * a command to that client.
1120 */
1121 ClientStateMapIter itClientState = mClientStateMap.find(u32ClientID);
1122 AssertMsg(itClientState != mClientStateMap.end(), ("Client with ID=%RU32 not found when it should be present\n",
1123 u32ClientID));
1124 if (itClientState == mClientStateMap.end())
1125 return VERR_NOT_FOUND; /* Should never happen. */
1126
1127 ClientState &clientState = itClientState->second;
1128
1129 /* Use the current (inbound) connection. */
1130 ClientConnection thisCon;
1131 thisCon.mHandle = callHandle;
1132 thisCon.mNumParms = cParms;
1133 thisCon.mParms = paParms;
1134
1135 return clientState.RunCurrent(&thisCon);
1136}
1137
1138int Service::clientSetMsgFilter(uint32_t u32ClientID, VBOXHGCMCALLHANDLE callHandle,
1139 uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1140{
1141 /*
1142 * Lookup client in our list so that we can assign the context ID of
1143 * a command to that client.
1144 */
1145 ClientStateMapIter itClientState = mClientStateMap.find(u32ClientID);
1146 AssertMsg(itClientState != mClientStateMap.end(), ("Client with ID=%RU32 not found when it should be present\n",
1147 u32ClientID));
1148 if (itClientState == mClientStateMap.end())
1149 return VERR_NOT_FOUND; /* Should never happen. */
1150
1151 if (cParms != 2)
1152 return VERR_INVALID_PARAMETER;
1153
1154 uint32_t uMaskAdd, uMaskRemove;
1155 int rc = paParms[0].getUInt32(&uMaskAdd);
1156 if (RT_SUCCESS(rc))
1157 rc = paParms[1].getUInt32(&uMaskRemove);
1158 if (RT_SUCCESS(rc))
1159 {
1160 ClientState &clientState = itClientState->second;
1161
1162 clientState.mFlags |= CLIENTSTATE_FLAG_CONTEXTFILTER;
1163 if (uMaskAdd)
1164 clientState.mContextFilter |= uMaskAdd;
1165 if (uMaskRemove)
1166 clientState.mContextFilter &= ~uMaskRemove;
1167
1168 LogFlowFunc(("Client ID=%RU32 now has filter=%x enabled (flags=%x, maskAdd=%x, maskRemove=%x)\n",
1169 u32ClientID, clientState.mContextFilter, clientState.mFlags,
1170 uMaskAdd, uMaskRemove));
1171 }
1172
1173 return rc;
1174}
1175
1176int Service::clientSkipMsg(uint32_t u32ClientID, VBOXHGCMCALLHANDLE callHandle,
1177 uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1178{
1179 /*
1180 * Lookup client in our list so that we can assign the context ID of
1181 * a command to that client.
1182 */
1183 ClientStateMapIter itClientState = mClientStateMap.find(u32ClientID);
1184 AssertMsg(itClientState != mClientStateMap.end(), ("Client ID=%RU32 not found when it should be present\n",
1185 u32ClientID));
1186 if (itClientState == mClientStateMap.end())
1187 return VERR_NOT_FOUND; /* Should never happen. */
1188
1189 if (cParms != 0)
1190 return VERR_INVALID_PARAMETER;
1191
1192 LogFlowFunc(("Client ID=%RU32 skipping message ...\n", u32ClientID));
1193
1194 itClientState->second.DequeueCurrent();
1195
1196 return VINF_SUCCESS;
1197}
1198
1199/**
1200 * Cancels a buffered host command to unblock waiting on Main side
1201 * via callbacks.
1202 *
1203 * @return IPRT status code.
1204 * @param u32ContextID Context ID of host command to cancel.
1205 */
1206int Service::cancelHostCmd(uint32_t u32ContextID)
1207{
1208 Assert(mpfnHostCallback);
1209
1210 LogFlowFunc(("Cancelling CID=%u ...\n", u32ContextID));
1211
1212 uint32_t cParms = 0;
1213 VBOXHGCMSVCPARM arParms[2];
1214 arParms[cParms++].setUInt32(u32ContextID);
1215
1216 return hostCallback(GUEST_DISCONNECTED, cParms, arParms);
1217}
1218
1219/**
1220 * Client asks itself (in another thread) to cancel all pending waits which are blocking the client
1221 * from shutting down / doing something else.
1222 *
1223 * @return IPRT status code.
1224 * @param u32ClientID The client's ID.
1225 * @param rcPending Result code for completing pending operation.
1226 */
1227int Service::cancelPendingWaits(uint32_t u32ClientID, int rcPending)
1228{
1229 ClientStateMapIter itClientState = mClientStateMap.find(u32ClientID);
1230 if (itClientState != mClientStateMap.end())
1231 return itClientState->second.CancelWaiting(rcPending);
1232
1233 return VINF_SUCCESS;
1234}
1235
1236/**
1237 * Notifies the host (using low-level HGCM callbacks) about an event
1238 * which was sent from the client.
1239 *
1240 * @return IPRT status code.
1241 * @param eFunction Function (event) that occured.
1242 * @param cParms Number of parameters.
1243 * @param paParms Array of parameters.
1244 */
1245int Service::hostCallback(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1246{
1247 LogFlowFunc(("eFunction=%ld, cParms=%ld, paParms=%p\n",
1248 eFunction, cParms, paParms));
1249
1250 int rc;
1251 if (mpfnHostCallback)
1252 {
1253 VBOXGUESTCTRLHOSTCALLBACK data(cParms, paParms);
1254 rc = mpfnHostCallback(mpvHostData, eFunction,
1255 (void *)(&data), sizeof(data));
1256 }
1257 else
1258 rc = VERR_NOT_SUPPORTED;
1259
1260 LogFlowFunc(("Returning rc=%Rrc\n", rc));
1261 return rc;
1262}
1263
1264/**
1265 * Processes a command receiveed from the host side and re-routes it to
1266 * a connect client on the guest.
1267 *
1268 * @return IPRT status code.
1269 * @param eFunction Function code to process.
1270 * @param cParms Number of parameters.
1271 * @param paParms Array of parameters.
1272 */
1273int Service::hostProcessCommand(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1274{
1275 /*
1276 * If no client is connected at all we don't buffer any host commands
1277 * and immediately return an error to the host. This avoids the host
1278 * waiting for a response from the guest side in case VBoxService on
1279 * the guest is not running/system is messed up somehow.
1280 */
1281 if (mClientStateMap.size() == 0)
1282 return VERR_NOT_FOUND;
1283
1284 int rc;
1285
1286 HostCommand *pHostCmd = NULL;
1287 try
1288 {
1289 pHostCmd = new HostCommand();
1290 rc = pHostCmd->Allocate(eFunction, cParms, paParms);
1291 if (RT_SUCCESS(rc))
1292 /* rc = */ RTListAppend(&mHostCmdList, &pHostCmd->Node);
1293 }
1294 catch (std::bad_alloc)
1295 {
1296 rc = VERR_NO_MEMORY;
1297 }
1298
1299 if (RT_SUCCESS(rc))
1300 {
1301 LogFlowFunc(("Handling host command CID=%RU32, eFunction=%RU32, cParms=%RU32, paParms=%p, numClients=%zu\n",
1302 pHostCmd->mContextID, eFunction, cParms, paParms, mClientStateMap.size()));
1303
1304 /*
1305 * Wake up all pending clients which are interested in this
1306 * host command.
1307 */
1308#ifdef DEBUG
1309 uint32_t uClientsWokenUp = 0;
1310#endif
1311 ClientStateMapIter itClientState = mClientStateMap.begin();
1312 AssertMsg(itClientState != mClientStateMap.end(), ("Client state map is empty when it should not\n"));
1313 while (itClientState != mClientStateMap.end())
1314 {
1315 ClientState &clientState = itClientState->second;
1316
1317 /* If a client indicates that it it wants the new host command,
1318 * add a reference to not delete it.*/
1319 if (clientState.WantsHostCommand(pHostCmd))
1320 {
1321 clientState.EnqueueCommand(pHostCmd);
1322
1323 int rc2 = clientState.Wakeup();
1324 if (RT_FAILURE(rc2))
1325 LogFlowFunc(("Waking up client ID=%RU32 failed with rc=%Rrc\n",
1326 itClientState->first, rc2));
1327#ifdef DEBUG_andy
1328 uClientsWokenUp++;
1329#endif
1330 }
1331
1332 itClientState++;
1333 }
1334
1335#ifdef DEBUG_andy
1336 LogFlowFunc(("%RU32 clients have been woken up\n", uClientsWokenUp));
1337#endif
1338 }
1339
1340 return rc;
1341}
1342
1343/**
1344 * Handle an HGCM service call.
1345 * @copydoc VBOXHGCMSVCFNTABLE::pfnCall
1346 * @note All functions which do not involve an unreasonable delay will be
1347 * handled synchronously. If needed, we will add a request handler
1348 * thread in future for those which do.
1349 *
1350 * @thread HGCM
1351 */
1352void Service::call(VBOXHGCMCALLHANDLE callHandle, uint32_t u32ClientID,
1353 void * /* pvClient */, uint32_t eFunction, uint32_t cParms,
1354 VBOXHGCMSVCPARM paParms[])
1355{
1356 int rc = VINF_SUCCESS;
1357 LogFlowFunc(("[Client %RU32] eFunction=%RU32, cParms=%RU32, paParms=0x%p\n",
1358 u32ClientID, eFunction, cParms, paParms));
1359 try
1360 {
1361 /*
1362 * The guest asks the host for the next message to process.
1363 */
1364 if (eFunction == GUEST_MSG_WAIT)
1365 {
1366 LogFlowFunc(("[Client %RU32] GUEST_MSG_GET\n", u32ClientID));
1367 rc = clientGetCommand(u32ClientID, callHandle, cParms, paParms);
1368 }
1369 else
1370 {
1371 switch (eFunction)
1372 {
1373 /*
1374 * A client wants to shut down and asks us (this service) to cancel
1375 * all blocking/pending waits (VINF_HGCM_ASYNC_EXECUTE) so that the
1376 * client can gracefully shut down.
1377 */
1378 case GUEST_CANCEL_PENDING_WAITS:
1379 LogFlowFunc(("[Client %RU32] GUEST_CANCEL_PENDING_WAITS\n", u32ClientID));
1380 rc = cancelPendingWaits(u32ClientID, VINF_SUCCESS /* Pending result */);
1381 break;
1382
1383 /*
1384 * The guest only wants certain messages set by the filter mask(s).
1385 * Since VBox 4.3+.
1386 */
1387 case GUEST_MSG_FILTER:
1388 LogFlowFunc(("[Client %RU32] GUEST_MSG_FILTER\n", u32ClientID));
1389 rc = clientSetMsgFilter(u32ClientID, callHandle, cParms, paParms);
1390 break;
1391
1392 /*
1393 * The guest only wants skip the currently assigned messages. Neded
1394 * for dropping its assigned reference of the current assigned host
1395 * command in queue.
1396 * Since VBox 4.3+.
1397 */
1398 case GUEST_MSG_SKIP:
1399 LogFlowFunc(("[Client %RU32] GUEST_MSG_SKIP\n", u32ClientID));
1400 rc = clientSkipMsg(u32ClientID, callHandle, cParms, paParms);
1401 break;
1402
1403 /*
1404 * For all other regular commands we call our hostCallback
1405 * function. If the current command does not support notifications,
1406 * notifyHost will return VERR_NOT_SUPPORTED.
1407 */
1408 default:
1409 rc = hostCallback(eFunction, cParms, paParms);
1410 break;
1411 }
1412
1413 if (rc != VINF_HGCM_ASYNC_EXECUTE)
1414 {
1415 /* Tell the client that the call is complete (unblocks waiting). */
1416 AssertPtr(mpHelpers);
1417 mpHelpers->pfnCallComplete(callHandle, rc);
1418 }
1419 }
1420 }
1421 catch (std::bad_alloc)
1422 {
1423 rc = VERR_NO_MEMORY;
1424 }
1425}
1426
1427/**
1428 * Service call handler for the host.
1429 * @copydoc VBOXHGCMSVCFNTABLE::pfnHostCall
1430 * @thread hgcm
1431 */
1432int Service::hostCall(uint32_t eFunction, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1433{
1434 int rc = VERR_NOT_SUPPORTED;
1435 LogFlowFunc(("fn=%RU32, cParms=%RU32, paParms=0x%p\n",
1436 eFunction, cParms, paParms));
1437 try
1438 {
1439 switch (eFunction)
1440 {
1441 /**
1442 * Host
1443 */
1444 case HOST_CANCEL_PENDING_WAITS:
1445 {
1446 LogFlowFunc(("HOST_CANCEL_PENDING_WAITS\n"));
1447 ClientStateMapIter itClientState = mClientStateMap.begin();
1448 while (itClientState != mClientStateMap.end())
1449 {
1450 int rc2 = itClientState->second.CancelWaiting(VINF_SUCCESS /* Pending rc. */);
1451 if (RT_FAILURE(rc2))
1452 LogFlowFunc(("Cancelling waiting for client ID=%RU32 failed with rc=%Rrc",
1453 itClientState->first, rc2));
1454 itClientState++;
1455 }
1456 rc = VINF_SUCCESS;
1457 break;
1458 }
1459
1460 default:
1461 rc = hostProcessCommand(eFunction, cParms, paParms);
1462 break;
1463 }
1464 }
1465 catch (std::bad_alloc)
1466 {
1467 rc = VERR_NO_MEMORY;
1468 }
1469
1470 return rc;
1471}
1472
1473int Service::uninit()
1474{
1475 return VINF_SUCCESS;
1476}
1477
1478} /* namespace guestControl */
1479
1480using guestControl::Service;
1481
1482/**
1483 * @copydoc VBOXHGCMSVCLOAD
1484 */
1485extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *pTable)
1486{
1487 int rc = VINF_SUCCESS;
1488
1489 LogFlowFunc(("pTable=%p\n", pTable));
1490
1491 if (!VALID_PTR(pTable))
1492 {
1493 rc = VERR_INVALID_PARAMETER;
1494 }
1495 else
1496 {
1497 LogFlowFunc(("pTable->cbSize=%d, pTable->u32Version=0x%08X\n", pTable->cbSize, pTable->u32Version));
1498
1499 if ( pTable->cbSize != sizeof (VBOXHGCMSVCFNTABLE)
1500 || pTable->u32Version != VBOX_HGCM_SVC_VERSION)
1501 {
1502 rc = VERR_VERSION_MISMATCH;
1503 }
1504 else
1505 {
1506 std::auto_ptr<Service> apService;
1507 /* No exceptions may propagate outside. */
1508 try {
1509 apService = std::auto_ptr<Service>(new Service(pTable->pHelpers));
1510 } catch (int rcThrown) {
1511 rc = rcThrown;
1512 } catch (...) {
1513 rc = VERR_UNRESOLVED_ERROR;
1514 }
1515
1516 if (RT_SUCCESS(rc))
1517 {
1518 /*
1519 * We don't need an additional client data area on the host,
1520 * because we're a class which can have members for that :-).
1521 */
1522 pTable->cbClient = 0;
1523
1524 /* Register functions. */
1525 pTable->pfnUnload = Service::svcUnload;
1526 pTable->pfnConnect = Service::svcConnect;
1527 pTable->pfnDisconnect = Service::svcDisconnect;
1528 pTable->pfnCall = Service::svcCall;
1529 pTable->pfnHostCall = Service::svcHostCall;
1530 pTable->pfnSaveState = NULL; /* The service is stateless, so the normal */
1531 pTable->pfnLoadState = NULL; /* construction done before restoring suffices */
1532 pTable->pfnRegisterExtension = Service::svcRegisterExtension;
1533
1534 /* Service specific initialization. */
1535 pTable->pvService = apService.release();
1536 }
1537 }
1538 }
1539
1540 LogFlowFunc(("Returning %Rrc\n", rc));
1541 return rc;
1542}
1543
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