VirtualBox

source: vbox/trunk/src/VBox/HostServices/SharedClipboard/VBoxSharedClipboardSvc.cpp@ 82799

Last change on this file since 82799 was 82540, checked in by vboxsync, 5 years ago

VBoxSharedClipboardSvc.cpp: doxygen fix. bugref:9437

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 88.8 KB
Line 
1/* $Id: VBoxSharedClipboardSvc.cpp 82540 2019-12-10 13:04:09Z vboxsync $ */
2/** @file
3 * Shared Clipboard Service - Host service entry points.
4 */
5
6/*
7 * Copyright (C) 2006-2019 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
19/** @page pg_hostclip The Shared Clipboard Host Service
20 *
21 * The shared clipboard host service is the host half of the clibpoard proxying
22 * between the host and the guest. The guest parts live in VBoxClient, VBoxTray
23 * and VBoxService depending on the OS, with code shared between host and guest
24 * under src/VBox/GuestHost/SharedClipboard/.
25 *
26 * The service is split into a platform-independent core and platform-specific
27 * backends. The service defines two communication protocols - one to
28 * communicate with the clipboard service running on the guest, and one to
29 * communicate with the backend. These will be described in a very skeletal
30 * fashion here.
31 *
32 * r=bird: The "two communication protocols" does not seems to be factual, there
33 * is only one protocol, the first one mentioned. It cannot be backend
34 * specific, because the guest/host protocol is platform and backend agnostic in
35 * nature. You may call it versions, but I take a great dislike to "protocol
36 * versions" here, as you've just extended the existing protocol with a feature
37 * that allows to transfer files and directories too. See @bugref{9437#c39}.
38 *
39 *
40 * @section sec_hostclip_guest_proto The guest communication protocol
41 *
42 * The guest clipboard service communicates with the host service over HGCM
43 * (the host is a HGCM service). HGCM is connection based, so the guest side
44 * has to connect before anything else can be done. (Windows hosts currently
45 * only support one simultaneous connection.) Once it has connected, it can
46 * send messages to the host services, some of which will receive immediate
47 * replies from the host, others which will block till a reply becomes
48 * available. The latter is because HGCM does't allow the host to initiate
49 * communication, it must be guest triggered. The HGCM service is single
50 * threaded, so it doesn't matter if the guest tries to send lots of requests in
51 * parallel, the service will process them one at the time.
52 *
53 * There are currently four messages defined. The first is
54 * VBOX_SHCL_GUEST_FN_MSG_GET / VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT, which waits
55 * for a message from the host. If a host message is sent while the guest is
56 * not waiting, it will be queued until the guest requests it. The host code
57 * only supports a single simultaneous GET call from one client guest.
58 *
59 * The second guest message is VBOX_SHCL_GUEST_FN_REPORT_FORMATS, which tells
60 * the host that the guest has new clipboard data available. The third is
61 * VBOX_SHCL_GUEST_FN_DATA_READ, which asks the host to send its clipboard data
62 * and waits until it arrives. The host supports at most one simultaneous
63 * VBOX_SHCL_GUEST_FN_DATA_READ call from a guest - if a second call is made
64 * before the first has returned, the first will be aborted.
65 *
66 * The last guest message is VBOX_SHCL_GUEST_FN_DATA_WRITE, which is used to
67 * send the contents of the guest clipboard to the host. This call should be
68 * used after the host has requested data from the guest.
69 *
70 *
71 * @section sec_hostclip_backend_proto The communication protocol with the
72 * platform-specific backend
73 *
74 * The initial protocol implementation (called protocol v0) was very simple,
75 * and could only handle simple data (like copied text and so on). It also
76 * was limited to two (2) fixed parameters at all times.
77 *
78 * Since VBox 6.1 a newer protocol (v1) has been established to also support
79 * file transfers. This protocol uses a (per-client) message queue instead
80 * (see VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT vs. VBOX_SHCL_GUEST_FN_GET_HOST_MSG).
81 *
82 * To distinguish the old (legacy) or new(er) protocol, the VBOX_SHCL_GUEST_FN_CONNECT
83 * message has been introduced. If an older guest does not send this message,
84 * an appropriate translation will be done to serve older Guest Additions (< 6.1).
85 *
86 * The protocol also support out-of-order messages by using so-called "context IDs",
87 * which are generated by the host. A context ID consists of a so-called "source event ID"
88 * and a so-called "event ID". Each HGCM client has an own, random, source event ID and
89 * generates non-deterministic event IDs so that the guest side does not known what
90 * comes next; the guest side has to reply with the same conext ID which was sent by
91 * the host request.
92 *
93 * Also see the protocol changelog at VBoxShClSvc.h.
94 *
95 *
96 * @section sec_uri_intro Transferring files
97 *
98 * Since VBox x.x.x transferring files via Shared Clipboard is supported.
99 * See the VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS define for supported / enabled
100 * platforms. This is called "Shared Clipboard transfers".
101 *
102 * Copying files / directories from guest A to guest B requires the host
103 * service to act as a proxy and cache, as we don't allow direct VM-to-VM
104 * communication. Copying from / to the host also is taken into account.
105 *
106 * At the moment a transfer is a all-or-nothing operation, e.g. it either
107 * completes or fails completely. There might be callbacks in the future
108 * to e.g. skip failing entries.
109 *
110 * Known limitations:
111 *
112 * - Support for VRDE (VRDP) is not implemented yet (see #9498).
113 * - Unicode support on Windows hosts / guests is not enabled (yet).
114 * - Symbolic links / Windows junctions are not allowed.
115 * - Windows alternate data streams (ADS) are not allowed.
116 * - No support for ACLs yet.
117 * - No (maybe never) support for NT4.
118 *
119 * @section sec_transfers_areas Clipboard areas.
120 *
121 * For larger / longer transfers there might be file data
122 * temporarily cached on the host, which has not been transferred to the
123 * destination yet. Such a cache is called a "Shared Clipboard Area", which
124 * in turn is identified by a unique ID across all VMs running on the same
125 * host. To control the access (and needed cleanup) of such clipboard areas,
126 * VBoxSVC (Main) is used for this task. A Shared Clipboard client can register,
127 * unregister, attach to and detach from a clipboard area. If all references
128 * to a clipboard area are released, a clipboard area gets detroyed automatically
129 * by VBoxSVC.
130 *
131 * By default a clipboard area lives in the user's temporary directory in the
132 * sub folder "VirtualBox Shared Clipboards/clipboard-<ID>". VBoxSVC does not
133 * do any file locking in a clipboard area, but keeps the clipboard areas's
134 * directory open to prevent deletion by third party processes.
135 *
136 * @todo We might use some VFS / container (IPRT?) for this instead of the
137 * host's file system directly?
138 * bird> Yes, but may take some work as we don't have the pick and choose
139 * kind of VFS containers implemented yet.
140 *
141 * @section sec_transfer_structure Transfer handling structure
142 *
143 * All structures / classes are designed for running on both, on the guest
144 * (via VBoxTray / VBoxClient) or on the host (host service) to avoid code
145 * duplication where applicable.
146 *
147 * Per HGCM client there is a so-called "transfer context", which in turn can
148 * have one or mulitple so-called "Shared Clipboard transfer" objects. At the
149 * moment we only support on concurrent Shared Clipboard transfer per transfer
150 * context. It's being used for reading from a source or writing to destination,
151 * depening on its direction. An Shared Clipboard transfer can have optional
152 * callbacks which might be needed by various implementations. Also, transfers
153 * optionally can run in an asynchronous thread to prevent blocking the UI while
154 * running.
155 *
156 * A Shared Clipboard transfer can maintain its own clipboard area; for the host
157 * service such a clipboard area is coupled to a clipboard area registered or
158 * attached with VBoxSVC. This is needed because multiple transfers from
159 * multiple VMs (n:n) can rely on the same clipboard area, so there needs a
160 * master keeping tracking of a clipboard area. To minimize IPC traffic only the
161 * minimum de/attaching is done at the moment. A clipboard area gets cleaned up
162 * (i.e. physically deleted) if no references are held to it anymore, or if
163 * VBoxSVC goes down.
164 *
165 * @section sec_transfer_providers Transfer providers
166 *
167 * For certain implementations (for example on Windows guests / hosts, using
168 * IDataObject and IStream objects) a more flexible approach reqarding reading /
169 * writing is needed. For this so-called transfer providers abstract the way of how
170 * data is being read / written in the current context (host / guest), while
171 * the rest of the code stays the same.
172 *
173 * @section sec_transfer_protocol Transfer protocol
174 *
175 * The host service issues commands which the guest has to respond with an own
176 * message to. The protocol itself is designed so that it has primitives to list
177 * directories and open/close/read/write file system objects.
178 *
179 * Note that this is different from the DnD approach, as Shared Clipboard transfers
180 * need to be deeper integrated within the host / guest OS (i.e. for progress UI),
181 * and this might require non-monolithic / random access APIs to achieve.
182 *
183 * As there can be multiple file system objects (fs objects) selected for transfer,
184 * a transfer can be queried for its root entries, which then contains the top-level
185 * elements. Based on these elements, (a) (recursive) listing(s) can be performed
186 * to (partially) walk down into directories and query fs object information. The
187 * provider provides appropriate interface for this, even if not all implementations
188 * might need this mechanism.
189 *
190 * An Shared Clipboard transfer has three stages:
191 * - 1. Announcement: An Shared Clipboard transfer-compatible format (currently only one format available)
192 * has been announced, the destination side creates a transfer object, which then,
193 * depending on the actual implementation, can be used to tell the OS that
194 * there is transfer (file) data available.
195 * At this point this just acts as a (kind-of) promise to the OS that we
196 * can provide (file) data at some later point in time.
197 *
198 * - 2. Initialization: As soon as the OS requests the (file) data, mostly triggered
199 * by the user starting a paste operation (CTRL + V), the transfer get initialized
200 * on the destination side, which in turn lets the source know that a transfer
201 * is going to happen.
202 *
203 * - 3. Transfer: At this stage the actual transfer from source to the destination takes
204 * place. How the actual transfer is structurized (e.g. which files / directories
205 * are transferred in which order) depends on the destination implementation. This
206 * is necessary in order to fulfill requirements on the destination side with
207 * regards to ETA calculation or other dependencies.
208 * Both sides can abort or cancel the transfer at any time.
209 */
210
211
212/*********************************************************************************************************************************
213* Header Files *
214*********************************************************************************************************************************/
215#define LOG_GROUP LOG_GROUP_SHARED_CLIPBOARD
216#include <VBox/log.h>
217
218#include <VBox/GuestHost/clipboard-helper.h>
219#include <VBox/HostServices/Service.h>
220#include <VBox/HostServices/VBoxClipboardSvc.h>
221#include <VBox/HostServices/VBoxClipboardExt.h>
222
223#include <VBox/AssertGuest.h>
224#include <VBox/err.h>
225#include <VBox/VMMDev.h>
226#include <VBox/vmm/ssm.h>
227
228#include <iprt/mem.h>
229#include <iprt/string.h>
230#include <iprt/assert.h>
231#include <iprt/critsect.h>
232#include <iprt/rand.h>
233
234#include "VBoxSharedClipboardSvc-internal.h"
235#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
236# include "VBoxSharedClipboardSvc-transfers.h"
237#endif
238
239using namespace HGCM;
240
241
242/*********************************************************************************************************************************
243* Defined Constants And Macros *
244*********************************************************************************************************************************/
245/** @name The saved state versions for the shared clipboard service.
246 *
247 * @note We set bit 31 because prior to version 0x80000002 there would be a
248 * structure size rather than a version number. Setting bit 31 dispells
249 * any possible ambiguity.
250 *
251 * @{ */
252/** The current saved state version. */
253#define VBOX_SHCL_SAVED_STATE_VER_CURRENT VBOX_SHCL_SAVED_STATE_VER_6_1RC1
254/** Adds the client's POD state and client state flags.
255 * @since 6.1 RC1 */
256#define VBOX_SHCL_SAVED_STATE_VER_6_1RC1 UINT32_C(0x80000004)
257/** First attempt saving state during @bugref{9437} development.
258 * @since 6.1 BETA 2 */
259#define VBOX_SHCL_SAVED_STATE_VER_6_1B2 UINT32_C(0x80000003)
260/** First structured version.
261 * @since 3.1 / r53668 */
262#define VBOX_SHCL_SAVED_STATE_VER_3_1 UINT32_C(0x80000002)
263/** This was just a state memory dump, including pointers and everything.
264 * @note This is not supported any more. Sorry. */
265#define VBOX_SHCL_SAVED_STATE_VER_NOT_SUPP (ARCH_BITS == 64 ? UINT32_C(72) : UINT32_C(48))
266/** @} */
267
268
269/*********************************************************************************************************************************
270* Global Variables *
271*********************************************************************************************************************************/
272PVBOXHGCMSVCHELPERS g_pHelpers;
273
274static RTCRITSECT g_CritSect;
275/** Global Shared Clipboard mode. */
276static uint32_t g_uMode = VBOX_SHCL_MODE_OFF;
277#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
278/** Global Shared Clipboard (file) transfer mode. */
279uint32_t g_fTransferMode = VBOX_SHCL_TRANSFER_MODE_DISABLED;
280#endif
281
282/** Is the clipboard running in headless mode? */
283static bool g_fHeadless = false;
284
285/** Holds the service extension state. */
286SHCLEXTSTATE g_ExtState = { 0 };
287
288/** Global map of all connected clients. */
289ClipboardClientMap g_mapClients;
290
291/** Global list of all clients which are queued up (deferred return) and ready
292 * to process new commands. The key is the (unique) client ID. */
293ClipboardClientQueue g_listClientsDeferred;
294
295/** Host feature mask (VBOX_SHCL_HF_0_XXX) for VBOX_SHCL_GUEST_FN_REPORT_FEATURES
296 * and VBOX_SHCL_GUEST_FN_QUERY_FEATURES. */
297static uint64_t const g_fHostFeatures0 = VBOX_SHCL_HF_0_CONTEXT_ID
298#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
299 | VBOX_SHCL_HF_0_TRANSFERS
300#endif
301 ;
302
303
304/**
305 * Returns the current Shared Clipboard service mode.
306 *
307 * @returns Current Shared Clipboard service mode.
308 */
309uint32_t ShClSvcGetMode(void)
310{
311 return g_uMode;
312}
313
314/**
315 * Getter for headless setting. Also needed by testcase.
316 *
317 * @returns Whether service currently running in headless mode or not.
318 */
319bool ShClSvcGetHeadless(void)
320{
321 return g_fHeadless;
322}
323
324static int shClSvcModeSet(uint32_t uMode)
325{
326 int rc = VERR_NOT_SUPPORTED;
327
328 switch (uMode)
329 {
330 case VBOX_SHCL_MODE_OFF:
331 RT_FALL_THROUGH();
332 case VBOX_SHCL_MODE_HOST_TO_GUEST:
333 RT_FALL_THROUGH();
334 case VBOX_SHCL_MODE_GUEST_TO_HOST:
335 RT_FALL_THROUGH();
336 case VBOX_SHCL_MODE_BIDIRECTIONAL:
337 {
338 g_uMode = uMode;
339
340 rc = VINF_SUCCESS;
341 break;
342 }
343
344 default:
345 {
346 g_uMode = VBOX_SHCL_MODE_OFF;
347 break;
348 }
349 }
350
351 LogFlowFuncLeaveRC(rc);
352 return rc;
353}
354
355bool ShClSvcLock(void)
356{
357 return RT_SUCCESS(RTCritSectEnter(&g_CritSect));
358}
359
360void ShClSvcUnlock(void)
361{
362 int rc2 = RTCritSectLeave(&g_CritSect);
363 AssertRC(rc2);
364}
365
366/**
367 * Resets a client's state message queue.
368 *
369 * @param pClient Pointer to the client data structure to reset message queue for.
370 * @note Caller enters pClient->CritSect.
371 */
372void shClSvcMsgQueueReset(PSHCLCLIENT pClient)
373{
374 Assert(RTCritSectIsOwner(&pClient->CritSect));
375 LogFlowFuncEnter();
376
377 while (!RTListIsEmpty(&pClient->MsgQueue))
378 {
379 PSHCLCLIENTMSG pMsg = RTListRemoveFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
380 shClSvcMsgFree(pClient, pMsg);
381 }
382}
383
384/**
385 * Allocates a new clipboard message.
386 *
387 * @returns Allocated clipboard message, or NULL on failure.
388 * @param pClient The client which is target of this message.
389 * @param idMsg The message ID (VBOX_SHCL_HOST_MSG_XXX) to use
390 * @param cParms The number of parameters the message takes.
391 */
392PSHCLCLIENTMSG shClSvcMsgAlloc(PSHCLCLIENT pClient, uint32_t idMsg, uint32_t cParms)
393{
394 RT_NOREF(pClient);
395 PSHCLCLIENTMSG pMsg = (PSHCLCLIENTMSG)RTMemAllocZ(RT_UOFFSETOF_DYN(SHCLCLIENTMSG, aParms[cParms]));
396 if (pMsg)
397 {
398 uint32_t cAllocated = ASMAtomicIncU32(&pClient->cAllocatedMessages);
399 if (cAllocated <= 4096)
400 {
401 RTListInit(&pMsg->ListEntry);
402 pMsg->cParms = cParms;
403 pMsg->idMsg = idMsg;
404 return pMsg;
405 }
406 AssertMsgFailed(("Too many messages allocated for client %u! (%u)\n", pClient->State.uClientID, cAllocated));
407 ASMAtomicDecU32(&pClient->cAllocatedMessages);
408 RTMemFree(pMsg);
409 }
410 return NULL;
411}
412
413/**
414 * Frees a formerly allocated clipboard message.
415 *
416 * @param pClient The client which was the target of this message.
417 * @param pMsg Clipboard message to free.
418 */
419void shClSvcMsgFree(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg)
420{
421 RT_NOREF(pClient);
422 /** @todo r=bird: Do accounting. */
423 if (pMsg)
424 {
425 pMsg->idMsg = UINT32_C(0xdeadface);
426 RTMemFree(pMsg);
427
428 uint32_t cAllocated = ASMAtomicDecU32(&pClient->cAllocatedMessages);
429 Assert(cAllocated < UINT32_MAX / 2);
430 RT_NOREF(cAllocated);
431 }
432}
433
434/**
435 * Sets the VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT and VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT
436 * return parameters.
437 *
438 * @param pMsg Message to set return parameters to.
439 * @param paDstParms The peek parameter vector.
440 * @param cDstParms The number of peek parameters (at least two).
441 * @remarks ASSUMES the parameters has been cleared by clientMsgPeek.
442 */
443static void shClSvcMsgSetPeekReturn(PSHCLCLIENTMSG pMsg, PVBOXHGCMSVCPARM paDstParms, uint32_t cDstParms)
444{
445 Assert(cDstParms >= 2);
446 if (paDstParms[0].type == VBOX_HGCM_SVC_PARM_32BIT)
447 paDstParms[0].u.uint32 = pMsg->idMsg;
448 else
449 paDstParms[0].u.uint64 = pMsg->idMsg;
450 paDstParms[1].u.uint32 = pMsg->cParms;
451
452 uint32_t i = RT_MIN(cDstParms, pMsg->cParms + 2);
453 while (i-- > 2)
454 switch (pMsg->aParms[i - 2].type)
455 {
456 case VBOX_HGCM_SVC_PARM_32BIT: paDstParms[i].u.uint32 = ~(uint32_t)sizeof(uint32_t); break;
457 case VBOX_HGCM_SVC_PARM_64BIT: paDstParms[i].u.uint32 = ~(uint32_t)sizeof(uint64_t); break;
458 case VBOX_HGCM_SVC_PARM_PTR: paDstParms[i].u.uint32 = pMsg->aParms[i - 2].u.pointer.size; break;
459 }
460}
461
462/**
463 * Sets the VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT return parameters.
464 *
465 * @returns VBox status code.
466 * @param pMsg The message which parameters to return to the guest.
467 * @param paDstParms The peek parameter vector.
468 * @param cDstParms The number of peek parameters should be exactly two
469 */
470static int shClSvcMsgSetOldWaitReturn(PSHCLCLIENTMSG pMsg, PVBOXHGCMSVCPARM paDstParms, uint32_t cDstParms)
471{
472 /*
473 * Assert sanity.
474 */
475 AssertPtr(pMsg);
476 AssertPtrReturn(paDstParms, VERR_INVALID_POINTER);
477 AssertReturn(cDstParms >= 2, VERR_INVALID_PARAMETER);
478
479 Assert(pMsg->cParms == 2);
480 Assert(pMsg->aParms[0].u.uint32 == pMsg->idMsg);
481 switch (pMsg->idMsg)
482 {
483 case VBOX_SHCL_HOST_MSG_READ_DATA:
484 case VBOX_SHCL_HOST_MSG_FORMATS_REPORT:
485 break;
486 default:
487 AssertFailed();
488 }
489
490 /*
491 * Set the parameters.
492 */
493 if (pMsg->cParms > 0)
494 paDstParms[0] = pMsg->aParms[0];
495 if (pMsg->cParms > 1)
496 paDstParms[1] = pMsg->aParms[1];
497 return VINF_SUCCESS;
498}
499
500/**
501 * Adds a new message to a client'S message queue.
502 *
503 * @returns IPRT status code.
504 * @param pClient Pointer to the client data structure to add new message to.
505 * @param pMsg Pointer to message to add. The queue then owns the pointer.
506 * @param fAppend Whether to append or prepend the message to the queue.
507 *
508 * @note Caller must enter critical section.
509 */
510void shClSvcMsgAdd(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg, bool fAppend)
511{
512 Assert(RTCritSectIsOwned(&pClient->CritSect));
513 AssertPtr(pMsg);
514
515 LogFlowFunc(("idMsg=%s (%RU32) cParms=%RU32 fAppend=%RTbool\n",
516 ShClHostMsgToStr(pMsg->idMsg), pMsg->idMsg, pMsg->cParms, fAppend));
517
518 if (fAppend)
519 RTListAppend(&pClient->MsgQueue, &pMsg->ListEntry);
520 else
521 RTListPrepend(&pClient->MsgQueue, &pMsg->ListEntry);
522}
523
524
525/**
526 * Appends a message to the client's queue and wake it up.
527 *
528 * @returns VBox status code, though the message is consumed regardless of what
529 * is returned.
530 * @param pClient The client to queue the message on.
531 * @param pMsg The message to queue. Ownership is always
532 * transfered to the queue.
533 *
534 * @note Caller must enter critical section.
535 */
536int shClSvcMsgAddAndWakeupClient(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg)
537{
538 Assert(RTCritSectIsOwned(&pClient->CritSect));
539 AssertPtr(pMsg);
540 AssertPtr(pClient);
541 LogFlowFunc(("idMsg=%s (%u) cParms=%u\n", ShClHostMsgToStr(pMsg->idMsg), pMsg->idMsg, pMsg->cParms));
542
543 RTListAppend(&pClient->MsgQueue, &pMsg->ListEntry);
544 return shClSvcClientWakeup(pClient);
545}
546
547/**
548 * Initializes a Shared Clipboard client.
549 *
550 * @param pClient Client to initialize.
551 * @param uClientID HGCM client ID to assign client to.
552 */
553int shClSvcClientInit(PSHCLCLIENT pClient, uint32_t uClientID)
554{
555 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
556
557 /* Assign the client ID. */
558 pClient->State.uClientID = uClientID;
559 RTListInit(&pClient->MsgQueue);
560 pClient->cAllocatedMessages = 0;
561
562 LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));
563
564 int rc = RTCritSectInit(&pClient->CritSect);
565 if (RT_SUCCESS(rc))
566 {
567 /* Create the client's own event source. */
568 rc = ShClEventSourceCreate(&pClient->EventSrc, 0 /* ID, ignored */);
569 if (RT_SUCCESS(rc))
570 {
571 LogFlowFunc(("[Client %RU32] Using event source %RU32\n", uClientID, pClient->EventSrc.uID));
572
573 /* Reset the client state. */
574 shclSvcClientStateReset(&pClient->State);
575
576 /* (Re-)initialize the client state. */
577 rc = shClSvcClientStateInit(&pClient->State, uClientID);
578
579#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
580 if (RT_SUCCESS(rc))
581 rc = ShClTransferCtxInit(&pClient->TransferCtx);
582#endif
583 }
584 }
585
586 LogFlowFuncLeaveRC(rc);
587 return rc;
588}
589
590/**
591 * Destroys a Shared Clipboard client.
592 *
593 * @param pClient Client to destroy.
594 */
595void shClSvcClientDestroy(PSHCLCLIENT pClient)
596{
597 AssertPtrReturnVoid(pClient);
598
599 LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));
600
601 /* Make sure to send a quit message to the guest so that it can terminate gracefully. */
602 RTCritSectEnter(&pClient->CritSect);
603 if (pClient->Pending.uType)
604 {
605 if (pClient->Pending.cParms > 1)
606 HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_QUIT);
607 if (pClient->Pending.cParms > 2)
608 HGCMSvcSetU32(&pClient->Pending.paParms[1], 0);
609 g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, VINF_SUCCESS);
610 pClient->Pending.uType = 0;
611 pClient->Pending.cParms = 0;
612 pClient->Pending.hHandle = NULL;
613 pClient->Pending.paParms = NULL;
614 }
615 RTCritSectLeave(&pClient->CritSect);
616
617 ShClEventSourceDestroy(&pClient->EventSrc);
618
619 shClSvcClientStateDestroy(&pClient->State);
620
621 int rc2 = RTCritSectDelete(&pClient->CritSect);
622 AssertRC(rc2);
623
624 ClipboardClientMap::iterator itClient = g_mapClients.find(pClient->State.uClientID);
625 if (itClient != g_mapClients.end())
626 {
627 g_mapClients.erase(itClient);
628 }
629 else
630 AssertFailed();
631
632 LogFlowFuncLeave();
633}
634
635/**
636 * Resets a Shared Clipboard client.
637 *
638 * @param pClient Client to reset.
639 */
640void shClSvcClientReset(PSHCLCLIENT pClient)
641{
642 if (!pClient)
643 return;
644
645 LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));
646 RTCritSectEnter(&pClient->CritSect);
647
648 /* Reset message queue. */
649 shClSvcMsgQueueReset(pClient);
650
651 /* Reset event source. */
652 ShClEventSourceReset(&pClient->EventSrc);
653
654 /* Reset pending state. */
655 RT_ZERO(pClient->Pending);
656
657#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
658 shClSvcClientTransfersReset(pClient);
659#endif
660
661 shclSvcClientStateReset(&pClient->State);
662
663 RTCritSectLeave(&pClient->CritSect);
664}
665
666/**
667 * Implements VBOX_SHCL_GUEST_FN_REPORT_FEATURES.
668 *
669 * @returns VBox status code.
670 * @retval VINF_HGCM_ASYNC_EXECUTE on success (we complete the message here).
671 * @retval VERR_ACCESS_DENIED if not master
672 * @retval VERR_INVALID_PARAMETER if bit 63 in the 2nd parameter isn't set.
673 * @retval VERR_WRONG_PARAMETER_COUNT
674 *
675 * @param pClient The client state.
676 * @param hCall The client's call handle.
677 * @param cParms Number of parameters.
678 * @param paParms Array of parameters.
679 */
680int shClSvcClientReportFeatures(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall,
681 uint32_t cParms, VBOXHGCMSVCPARM paParms[])
682{
683 /*
684 * Validate the request.
685 */
686 ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
687 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
688 uint64_t const fFeatures0 = paParms[0].u.uint64;
689 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
690 uint64_t const fFeatures1 = paParms[1].u.uint64;
691 ASSERT_GUEST_RETURN(fFeatures1 & VBOX_SHCL_GF_1_MUST_BE_ONE, VERR_INVALID_PARAMETER);
692
693 /*
694 * Do the work.
695 */
696 paParms[0].u.uint64 = g_fHostFeatures0;
697 paParms[1].u.uint64 = 0;
698
699 int rc = g_pHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
700 if (RT_SUCCESS(rc))
701 {
702 pClient->State.fGuestFeatures0 = fFeatures0;
703 pClient->State.fGuestFeatures1 = fFeatures1;
704 Log(("[Client %RU32] features: %#RX64 %#RX64\n", pClient->State.uClientID, fFeatures0, fFeatures1));
705 }
706 else
707 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
708
709 return VINF_HGCM_ASYNC_EXECUTE;
710}
711
712/**
713 * Implements VBOX_SHCL_GUEST_FN_QUERY_FEATURES.
714 *
715 * @returns VBox status code.
716 * @retval VINF_HGCM_ASYNC_EXECUTE on success (we complete the message here).
717 * @retval VERR_WRONG_PARAMETER_COUNT
718 *
719 * @param hCall The client's call handle.
720 * @param cParms Number of parameters.
721 * @param paParms Array of parameters.
722 */
723int shClSvcClientQueryFeatures(VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
724{
725 /*
726 * Validate the request.
727 */
728 ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
729 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
730 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
731 ASSERT_GUEST(paParms[1].u.uint64 & RT_BIT_64(63));
732
733 /*
734 * Do the work.
735 */
736 paParms[0].u.uint64 = g_fHostFeatures0;
737 paParms[1].u.uint64 = 0;
738 int rc = g_pHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
739 if (RT_FAILURE(rc))
740 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
741
742 return VINF_HGCM_ASYNC_EXECUTE;
743}
744
745/**
746 * Implements VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT and VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT.
747 *
748 * @returns VBox status code.
749 * @retval VINF_SUCCESS if a message was pending and is being returned.
750 * @retval VERR_TRY_AGAIN if no message pending and not blocking.
751 * @retval VERR_RESOURCE_BUSY if another read already made a waiting call.
752 * @retval VINF_HGCM_ASYNC_EXECUTE if message wait is pending.
753 *
754 * @param pClient The client state.
755 * @param hCall The client's call handle.
756 * @param cParms Number of parameters.
757 * @param paParms Array of parameters.
758 * @param fWait Set if we should wait for a message, clear if to return
759 * immediately.
760 *
761 * @note Caller takes and leave the client's critical section.
762 */
763static int shClSvcClientMsgPeek(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool fWait)
764{
765 /*
766 * Validate the request.
767 */
768 ASSERT_GUEST_MSG_RETURN(cParms >= 2, ("cParms=%u!\n", cParms), VERR_WRONG_PARAMETER_COUNT);
769
770 uint64_t idRestoreCheck = 0;
771 uint32_t i = 0;
772 if (paParms[i].type == VBOX_HGCM_SVC_PARM_64BIT)
773 {
774 idRestoreCheck = paParms[0].u.uint64;
775 paParms[0].u.uint64 = 0;
776 i++;
777 }
778 for (; i < cParms; i++)
779 {
780 ASSERT_GUEST_MSG_RETURN(paParms[i].type == VBOX_HGCM_SVC_PARM_32BIT, ("#%u type=%u\n", i, paParms[i].type),
781 VERR_WRONG_PARAMETER_TYPE);
782 paParms[i].u.uint32 = 0;
783 }
784
785 /*
786 * Check restore session ID.
787 */
788 if (idRestoreCheck != 0)
789 {
790 uint64_t idRestore = g_pHelpers->pfnGetVMMDevSessionId(g_pHelpers);
791 if (idRestoreCheck != idRestore)
792 {
793 paParms[0].u.uint64 = idRestore;
794 LogFlowFunc(("[Client %RU32] VBOX_SHCL_GUEST_FN_MSG_PEEK_XXX -> VERR_VM_RESTORED (%#RX64 -> %#RX64)\n",
795 pClient->State.uClientID, idRestoreCheck, idRestore));
796 return VERR_VM_RESTORED;
797 }
798 Assert(!g_pHelpers->pfnIsCallRestored(hCall));
799 }
800
801 /*
802 * Return information about the first message if one is pending in the list.
803 */
804 PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
805 if (pFirstMsg)
806 {
807 shClSvcMsgSetPeekReturn(pFirstMsg, paParms, cParms);
808 LogFlowFunc(("[Client %RU32] VBOX_SHCL_GUEST_FN_MSG_PEEK_XXX -> VINF_SUCCESS (idMsg=%s (%u), cParms=%u)\n",
809 pClient->State.uClientID, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
810 return VINF_SUCCESS;
811 }
812
813 /*
814 * If we cannot wait, fail the call.
815 */
816 if (!fWait)
817 {
818 LogFlowFunc(("[Client %RU32] GUEST_MSG_PEEK_NOWAIT -> VERR_TRY_AGAIN\n", pClient->State.uClientID));
819 return VERR_TRY_AGAIN;
820 }
821
822 /*
823 * Wait for the host to queue a message for this client.
824 */
825 ASSERT_GUEST_MSG_RETURN(pClient->Pending.uType == 0, ("Already pending! (idClient=%RU32)\n",
826 pClient->State.uClientID), VERR_RESOURCE_BUSY);
827 pClient->Pending.hHandle = hCall;
828 pClient->Pending.cParms = cParms;
829 pClient->Pending.paParms = paParms;
830 pClient->Pending.uType = VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT;
831 LogFlowFunc(("[Client %RU32] Is now in pending mode...\n", pClient->State.uClientID));
832 return VINF_HGCM_ASYNC_EXECUTE;
833}
834
835/**
836 * Implements VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT.
837 *
838 * @returns VBox status code.
839 * @retval VINF_SUCCESS if a message was pending and is being returned.
840 * @retval VINF_HGCM_ASYNC_EXECUTE if message wait is pending.
841 *
842 * @param pClient The client state.
843 * @param hCall The client's call handle.
844 * @param cParms Number of parameters.
845 * @param paParms Array of parameters.
846 *
847 * @note Caller takes and leave the client's critical section.
848 */
849static int shClSvcClientMsgOldGet(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
850{
851 /*
852 * Validate input.
853 */
854 ASSERT_GUEST_RETURN(cParms == VBOX_SHCL_CPARMS_GET_HOST_MSG_OLD, VERR_WRONG_PARAMETER_COUNT);
855 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* id32Msg */
856 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* f32Formats */
857
858 paParms[0].u.uint32 = 0;
859 paParms[1].u.uint32 = 0;
860
861 /*
862 * If there is a message pending we can return immediately.
863 */
864 int rc;
865 PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
866 if (pFirstMsg)
867 {
868 LogFlowFunc(("[Client %RU32] uMsg=%s (%RU32), cParms=%RU32\n", pClient->State.uClientID,
869 ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
870
871 rc = shClSvcMsgSetOldWaitReturn(pFirstMsg, paParms, cParms);
872 AssertPtr(g_pHelpers);
873 rc = g_pHelpers->pfnCallComplete(hCall, rc);
874 if (rc != VERR_CANCELLED)
875 {
876 RTListNodeRemove(&pFirstMsg->ListEntry);
877 shClSvcMsgFree(pClient, pFirstMsg);
878
879 rc = VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
880 }
881 }
882 /*
883 * Otherwise we must wait.
884 */
885 else
886 {
887 ASSERT_GUEST_MSG_RETURN(pClient->Pending.uType == 0, ("Already pending! (idClient=%RU32)\n", pClient->State.uClientID),
888 VERR_RESOURCE_BUSY);
889
890 pClient->Pending.hHandle = hCall;
891 pClient->Pending.cParms = cParms;
892 pClient->Pending.paParms = paParms;
893 pClient->Pending.uType = VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT;
894
895 rc = VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
896
897 LogFlowFunc(("[Client %RU32] Is now in pending mode...\n", pClient->State.uClientID));
898 }
899
900 LogFlowFunc(("[Client %RU32] rc=%Rrc\n", pClient->State.uClientID, rc));
901 return rc;
902}
903
904/**
905 * Implements VBOX_SHCL_GUEST_FN_MSG_GET.
906 *
907 * @returns VBox status code.
908 * @retval VINF_SUCCESS if message retrieved and removed from the pending queue.
909 * @retval VERR_TRY_AGAIN if no message pending.
910 * @retval VERR_BUFFER_OVERFLOW if a parmeter buffer is too small. The buffer
911 * size was updated to reflect the required size, though this isn't yet
912 * forwarded to the guest. (The guest is better of using peek with
913 * parameter count + 2 parameters to get the sizes.)
914 * @retval VERR_MISMATCH if the incoming message ID does not match the pending.
915 * @retval VINF_HGCM_ASYNC_EXECUTE if message was completed already.
916 *
917 * @param pClient The client state.
918 * @param hCall The client's call handle.
919 * @param cParms Number of parameters.
920 * @param paParms Array of parameters.
921 *
922 * @note Called from within pClient->CritSect.
923 */
924static int shClSvcClientMsgGet(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
925{
926 /*
927 * Validate the request.
928 */
929 uint32_t const idMsgExpected = cParms > 0 && paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT ? paParms[0].u.uint32
930 : cParms > 0 && paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT ? paParms[0].u.uint64
931 : UINT32_MAX;
932
933 /*
934 * Return information about the first message if one is pending in the list.
935 */
936 PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
937 if (pFirstMsg)
938 {
939 LogFlowFunc(("First message is: %s (%u), cParms=%RU32\n", ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
940
941 ASSERT_GUEST_MSG_RETURN(pFirstMsg->idMsg == idMsgExpected || idMsgExpected == UINT32_MAX,
942 ("idMsg=%u (%s) cParms=%u, caller expected %u (%s) and %u\n",
943 pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->cParms,
944 idMsgExpected, ShClHostMsgToStr(idMsgExpected), cParms),
945 VERR_MISMATCH);
946 ASSERT_GUEST_MSG_RETURN(pFirstMsg->cParms == cParms,
947 ("idMsg=%u (%s) cParms=%u, caller expected %u (%s) and %u\n",
948 pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->cParms,
949 idMsgExpected, ShClHostMsgToStr(idMsgExpected), cParms),
950 VERR_WRONG_PARAMETER_COUNT);
951
952 /* Check the parameter types. */
953 for (uint32_t i = 0; i < cParms; i++)
954 ASSERT_GUEST_MSG_RETURN(pFirstMsg->aParms[i].type == paParms[i].type,
955 ("param #%u: type %u, caller expected %u (idMsg=%u %s)\n", i, pFirstMsg->aParms[i].type,
956 paParms[i].type, pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg)),
957 VERR_WRONG_PARAMETER_TYPE);
958 /*
959 * Copy out the parameters.
960 *
961 * No assertions on buffer overflows, and keep going till the end so we can
962 * communicate all the required buffer sizes.
963 */
964 int rc = VINF_SUCCESS;
965 for (uint32_t i = 0; i < cParms; i++)
966 switch (pFirstMsg->aParms[i].type)
967 {
968 case VBOX_HGCM_SVC_PARM_32BIT:
969 paParms[i].u.uint32 = pFirstMsg->aParms[i].u.uint32;
970 break;
971
972 case VBOX_HGCM_SVC_PARM_64BIT:
973 paParms[i].u.uint64 = pFirstMsg->aParms[i].u.uint64;
974 break;
975
976 case VBOX_HGCM_SVC_PARM_PTR:
977 {
978 uint32_t const cbSrc = pFirstMsg->aParms[i].u.pointer.size;
979 uint32_t const cbDst = paParms[i].u.pointer.size;
980 paParms[i].u.pointer.size = cbSrc; /** @todo Check if this is safe in other layers...
981 * Update: Safe, yes, but VMMDevHGCM doesn't pass it along. */
982 if (cbSrc <= cbDst)
983 memcpy(paParms[i].u.pointer.addr, pFirstMsg->aParms[i].u.pointer.addr, cbSrc);
984 else
985 {
986 AssertMsgFailed(("#%u: cbSrc=%RU32 is bigger than cbDst=%RU32\n", i, cbSrc, cbDst));
987 rc = VERR_BUFFER_OVERFLOW;
988 }
989 break;
990 }
991
992 default:
993 AssertMsgFailed(("#%u: %u\n", i, pFirstMsg->aParms[i].type));
994 rc = VERR_INTERNAL_ERROR;
995 break;
996 }
997 if (RT_SUCCESS(rc))
998 {
999 /*
1000 * Complete the message and remove the pending message unless the
1001 * guest raced us and cancelled this call in the meantime.
1002 */
1003 AssertPtr(g_pHelpers);
1004 rc = g_pHelpers->pfnCallComplete(hCall, rc);
1005
1006 LogFlowFunc(("[Client %RU32] pfnCallComplete -> %Rrc\n", pClient->State.uClientID, rc));
1007
1008 if (rc != VERR_CANCELLED)
1009 {
1010 RTListNodeRemove(&pFirstMsg->ListEntry);
1011 shClSvcMsgFree(pClient, pFirstMsg);
1012 }
1013
1014 return VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
1015 }
1016
1017 LogFlowFunc(("[Client %RU32] Returning %Rrc\n", pClient->State.uClientID, rc));
1018 return rc;
1019 }
1020
1021 paParms[0].u.uint32 = 0;
1022 paParms[1].u.uint32 = 0;
1023 LogFlowFunc(("[Client %RU32] -> VERR_TRY_AGAIN\n", pClient->State.uClientID));
1024 return VERR_TRY_AGAIN;
1025}
1026
1027/**
1028 * Implements VBOX_SHCL_GUEST_FN_MSG_GET.
1029 *
1030 * @returns VBox status code.
1031 * @retval VINF_SUCCESS if message retrieved and removed from the pending queue.
1032 * @retval VERR_TRY_AGAIN if no message pending.
1033 * @retval VERR_MISMATCH if the incoming message ID does not match the pending.
1034 * @retval VINF_HGCM_ASYNC_EXECUTE if message was completed already.
1035 *
1036 * @param pClient The client state.
1037 * @param cParms Number of parameters.
1038 *
1039 * @note Called from within pClient->CritSect.
1040 */
1041static int shClSvcClientMsgCancel(PSHCLCLIENT pClient, uint32_t cParms)
1042{
1043 /*
1044 * Validate the request.
1045 */
1046 ASSERT_GUEST_MSG_RETURN(cParms == 0, ("cParms=%u!\n", cParms), VERR_WRONG_PARAMETER_COUNT);
1047
1048 /*
1049 * Execute.
1050 */
1051 if (pClient->Pending.uType != 0)
1052 {
1053 LogFlowFunc(("[Client %RU32] Cancelling waiting thread, isPending=%d, pendingNumParms=%RU32, m_idSession=%x\n",
1054 pClient->State.uClientID, pClient->Pending.uType, pClient->Pending.cParms, pClient->State.uSessionID));
1055
1056 /*
1057 * The PEEK call is simple: At least two parameters, all set to zero before sleeping.
1058 */
1059 int rcComplete;
1060 if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT)
1061 {
1062 Assert(pClient->Pending.cParms >= 2);
1063 if (pClient->Pending.paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT)
1064 HGCMSvcSetU64(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
1065 else
1066 HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
1067 rcComplete = VINF_TRY_AGAIN;
1068 }
1069 /*
1070 * The MSG_OLD call is complicated, though we're
1071 * generally here to wake up someone who is peeking and have two parameters.
1072 * If there aren't two parameters, fail the call.
1073 */
1074 else
1075 {
1076 Assert(pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT);
1077 if (pClient->Pending.cParms > 0)
1078 HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
1079 if (pClient->Pending.cParms > 1)
1080 HGCMSvcSetU32(&pClient->Pending.paParms[1], 0);
1081 rcComplete = pClient->Pending.cParms == 2 ? VINF_SUCCESS : VERR_TRY_AGAIN;
1082 }
1083
1084 g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, rcComplete);
1085
1086 pClient->Pending.hHandle = NULL;
1087 pClient->Pending.paParms = NULL;
1088 pClient->Pending.cParms = 0;
1089 pClient->Pending.uType = 0;
1090 return VINF_SUCCESS;
1091 }
1092 return VWRN_NOT_FOUND;
1093}
1094
1095
1096/**
1097 * Wakes up a pending client (i.e. waiting for new messages).
1098 *
1099 * @returns VBox status code.
1100 * @retval VINF_NO_CHANGE if the client is not in pending mode.
1101 *
1102 * @param pClient Client to wake up.
1103 * @note Caller must enter pClient->CritSect.
1104 */
1105int shClSvcClientWakeup(PSHCLCLIENT pClient)
1106{
1107 Assert(RTCritSectIsOwner(&pClient->CritSect));
1108 int rc = VINF_NO_CHANGE;
1109
1110 if (pClient->Pending.uType != 0)
1111 {
1112 LogFunc(("[Client %RU32] Waking up ...\n", pClient->State.uClientID));
1113
1114 PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
1115 AssertReturn(pFirstMsg, VERR_INTERNAL_ERROR);
1116
1117 LogFunc(("[Client %RU32] Current host message is %s (%RU32), cParms=%RU32\n",
1118 pClient->State.uClientID, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
1119
1120 if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT)
1121 shClSvcMsgSetPeekReturn(pFirstMsg, pClient->Pending.paParms, pClient->Pending.cParms);
1122 else if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT) /* Legacy, Guest Additions < 6.1. */
1123 shClSvcMsgSetOldWaitReturn(pFirstMsg, pClient->Pending.paParms, pClient->Pending.cParms);
1124 else
1125 AssertMsgFailedReturn(("pClient->Pending.uType=%u\n", pClient->Pending.uType), VERR_INTERNAL_ERROR_3);
1126
1127 rc = g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, VINF_SUCCESS);
1128
1129 if ( rc != VERR_CANCELLED
1130 && pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT)
1131 {
1132 RTListNodeRemove(&pFirstMsg->ListEntry);
1133 shClSvcMsgFree(pClient, pFirstMsg);
1134 }
1135
1136 pClient->Pending.hHandle = NULL;
1137 pClient->Pending.paParms = NULL;
1138 pClient->Pending.cParms = 0;
1139 pClient->Pending.uType = 0;
1140 }
1141 else
1142 LogFunc(("[Client %RU32] Not in pending state, skipping wakeup\n", pClient->State.uClientID));
1143
1144 return rc;
1145}
1146
1147/**
1148 * Requests to read clipboard data from the guest.
1149 *
1150 * @returns VBox status code.
1151 * @param pClient Client to request to read data form.
1152 * @param fFormat The format being requested (VBOX_SHCL_FMT_XXX).
1153 * @param pidEvent Event ID for waiting for new data. Optional.
1154 */
1155int ShClSvcDataReadRequest(PSHCLCLIENT pClient, SHCLFORMAT fFormat, PSHCLEVENTID pidEvent)
1156{
1157 LogFlowFuncEnter();
1158 if (pidEvent)
1159 *pidEvent = 0;
1160 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1161
1162 /*
1163 * Allocate a message.
1164 */
1165 int rc;
1166 PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient,
1167 pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID
1168 ? VBOX_SHCL_HOST_MSG_READ_DATA_CID : VBOX_SHCL_HOST_MSG_READ_DATA,
1169 2);
1170 if (pMsg)
1171 {
1172 /*
1173 * Enter the critical section and generate an event.
1174 */
1175 RTCritSectEnter(&pClient->CritSect);
1176
1177 const SHCLEVENTID idEvent = ShClEventIdGenerateAndRegister(&pClient->EventSrc);
1178 if (idEvent != 0)
1179 {
1180 LogFlowFunc(("fFormat=%#x idEvent=%#x\n", fFormat, idEvent));
1181
1182 /*
1183 * Format the message
1184 */
1185 if (pMsg->idMsg == VBOX_SHCL_HOST_MSG_READ_DATA_CID)
1186 HGCMSvcSetU64(&pMsg->aParms[0], VBOX_SHCL_CONTEXTID_MAKE(pClient->State.uSessionID, pClient->EventSrc.uID, idEvent));
1187 else
1188 HGCMSvcSetU32(&pMsg->aParms[0], VBOX_SHCL_HOST_MSG_READ_DATA);
1189 HGCMSvcSetU32(&pMsg->aParms[1], fFormat);
1190
1191 /*
1192 * Queue it and wake up the client if it's waiting on a message.
1193 */
1194 shClSvcMsgAddAndWakeupClient(pClient, pMsg);
1195 if (pidEvent)
1196 *pidEvent = idEvent;
1197 rc = VINF_SUCCESS;
1198 }
1199 else
1200 rc = VERR_TRY_AGAIN;
1201
1202 RTCritSectLeave(&pClient->CritSect);
1203 }
1204 else
1205 rc = VERR_NO_MEMORY;
1206
1207 LogFlowFuncLeaveRC(rc);
1208 return rc;
1209}
1210
1211int ShClSvcDataReadSignal(PSHCLCLIENT pClient, PSHCLCLIENTCMDCTX pCmdCtx,
1212 PSHCLDATABLOCK pData)
1213{
1214 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1215 AssertPtrReturn(pCmdCtx, VERR_INVALID_POINTER);
1216 AssertPtrReturn(pData, VERR_INVALID_POINTER);
1217
1218 LogFlowFuncEnter();
1219
1220 SHCLEVENTID uEvent;
1221 if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)) /* Legacy, Guest Additions < 6.1. */
1222 {
1223 /* Older Guest Additions (<= VBox 6.0) did not have any context ID handling, so we ASSUME that the last event registered
1224 * is the one we want to handle (as this all was a synchronous protocol anyway). */
1225 uEvent = ShClEventGetLast(&pClient->EventSrc);
1226 }
1227 else
1228 uEvent = VBOX_SHCL_CONTEXTID_GET_EVENT(pCmdCtx->uContextID);
1229
1230 int rc = VINF_SUCCESS;
1231
1232 PSHCLEVENTPAYLOAD pPayload = NULL;
1233 if (pData->cbData)
1234 rc = ShClPayloadAlloc(uEvent, pData->pvData, pData->cbData, &pPayload);
1235
1236 if (RT_SUCCESS(rc))
1237 {
1238 RTCritSectEnter(&pClient->CritSect);
1239 rc = ShClEventSignal(&pClient->EventSrc, uEvent, pPayload);
1240 RTCritSectLeave(&pClient->CritSect);
1241 if (RT_FAILURE(rc))
1242 ShClPayloadFree(pPayload);
1243 }
1244
1245 LogFlowFuncLeaveRC(rc);
1246 return rc;
1247}
1248
1249/**
1250 * Reports available VBox clipboard formats to the guest.
1251 *
1252 * @returns VBox status code.
1253 * @param pClient Client to request to read data form.
1254 * @param fFormats The formats to report (VBOX_SHCL_FMT_XXX), zero
1255 * is okay (empty the clipboard).
1256 */
1257int ShClSvcHostReportFormats(PSHCLCLIENT pClient, SHCLFORMATS fFormats)
1258{
1259 LogFlowFuncEnter();
1260 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1261
1262#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1263 /*
1264 * If transfer mode is set to disabled, don't report the URI list format to the guest.
1265 */
1266 if (!(g_fTransferMode & VBOX_SHCL_TRANSFER_MODE_ENABLED))
1267 {
1268 LogFlowFunc(("fFormats=%#x -> %#x\n", fFormats, fFormats & ~VBOX_SHCL_FMT_URI_LIST));
1269 fFormats &= ~VBOX_SHCL_FMT_URI_LIST;
1270 }
1271#endif
1272 LogRel2(("Shared Clipboard: Reporting formats %#x to guest\n", fFormats));
1273
1274 /*
1275 * Allocate a message, populate parameters and post it to the client.
1276 */
1277 int rc;
1278 PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient, VBOX_SHCL_HOST_MSG_FORMATS_REPORT, 2);
1279 if (pMsg)
1280 {
1281 HGCMSvcSetU32(&pMsg->aParms[0], VBOX_SHCL_HOST_MSG_FORMATS_REPORT);
1282 HGCMSvcSetU32(&pMsg->aParms[1], fFormats);
1283
1284 RTCritSectEnter(&pClient->CritSect);
1285 shClSvcMsgAddAndWakeupClient(pClient, pMsg);
1286 RTCritSectLeave(&pClient->CritSect);
1287
1288 /*
1289 * ...
1290 */
1291#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1292# error fixme
1293 /* If we announce an URI list, create a transfer locally and also tell the guest to create
1294 * a transfer on the guest side. */
1295 if (fFormats & VBOX_SHCL_FMT_URI_LIST)
1296 {
1297 rc = shClSvcTransferStart(pClient, SHCLTRANSFERDIR_TO_REMOTE, SHCLSOURCE_LOCAL,
1298 NULL /* pTransfer */);
1299 if (RT_FAILURE(rc))
1300 LogRel(("Shared Clipboard: Initializing host write transfer failed with %Rrc\n", rc));
1301 }
1302 else
1303#endif
1304 {
1305 pClient->State.fFlags |= SHCLCLIENTSTATE_FLAGS_READ_ACTIVE;
1306 rc = VINF_SUCCESS;
1307 }
1308 /** @todo r=bird: shouldn't we also call shClSvcSetSource(pClient, SHCLSOURCE_LOCAL) here??
1309 * Looks like the caller of this function does it, but only on windows. Very helpful. */
1310 }
1311 else
1312 rc = VERR_NO_MEMORY;
1313
1314 LogFlowFuncLeaveRC(rc);
1315 return rc;
1316}
1317
1318
1319/**
1320 * Handles the VBOX_SHCL_GUEST_FN_REPORT_FORMATS message from the guest.
1321 */
1322static int shClSvcClientReportFormats(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1323{
1324 /*
1325 * Check if the service mode allows this operation and whether the guest is
1326 * supposed to be reading from the host.
1327 */
1328 uint32_t uMode = ShClSvcGetMode();
1329 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1330 || uMode == VBOX_SHCL_MODE_GUEST_TO_HOST)
1331 { /* likely */ }
1332 else
1333 return VERR_ACCESS_DENIED;
1334
1335 /*
1336 * Digest parameters.
1337 */
1338 ASSERT_GUEST_RETURN( cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS
1339 || ( cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B
1340 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)),
1341 VERR_WRONG_PARAMETER_COUNT);
1342
1343 uintptr_t iParm = 0;
1344 if (cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B)
1345 {
1346 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1347 /* no defined value, so just ignore it */
1348 iParm++;
1349 }
1350 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1351 uint32_t const fFormats = paParms[iParm].u.uint32;
1352 iParm++;
1353 if (cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B)
1354 {
1355 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1356 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1357 iParm++;
1358 }
1359 Assert(iParm == cParms);
1360
1361 /*
1362 * Report the formats.
1363 *
1364 * We ignore empty reports if the guest isn't the clipboard owner, this
1365 * prevents a freshly booted guest with an empty clibpoard from clearing
1366 * the host clipboard on startup. Likewise, when a guest shutdown it will
1367 * typically issue an empty report in case it's the owner, we don't want
1368 * that to clear host content either.
1369 */
1370 int rc;
1371 if (!fFormats && pClient->State.enmSource != SHCLSOURCE_REMOTE)
1372 rc = VINF_SUCCESS;
1373 else
1374 {
1375 rc = shClSvcSetSource(pClient, SHCLSOURCE_REMOTE);
1376 if (RT_SUCCESS(rc))
1377 {
1378 if (g_ExtState.pfnExtension)
1379 {
1380 SHCLEXTPARMS parms;
1381 RT_ZERO(parms);
1382 parms.uFormat = fFormats;
1383
1384 g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_FORMAT_ANNOUNCE, &parms, sizeof(parms));
1385 }
1386 else
1387 {
1388 SHCLCLIENTCMDCTX CmdCtx;
1389 RT_ZERO(CmdCtx);
1390
1391 SHCLFORMATDATA FormatData;
1392 FormatData.fFlags = 0;
1393 FormatData.Formats = fFormats;
1394 rc = ShClSvcImplFormatAnnounce(pClient, &CmdCtx, &FormatData);
1395 }
1396
1397 /** @todo r=bird: I'm not sure if the guest should be automatically allowed
1398 * to write the host clipboard now. It would make more sense to disallow
1399 * host clipboard reads until the host reports formats.
1400 *
1401 * The writes should only really be allowed upon request from the host,
1402 * shouldn't they? (Though, I'm not sure, maybe there are situations
1403 * where the guest side will just want to push the content over
1404 * immediately while it's still available, I don't quite recall now...
1405 */
1406 if (RT_SUCCESS(rc))
1407 pClient->State.fFlags |= SHCLCLIENTSTATE_FLAGS_WRITE_ACTIVE;
1408 }
1409 }
1410
1411 return rc;
1412}
1413
1414/**
1415 * Handles the VBOX_SHCL_GUEST_FN_DATA_READ message from the guest.
1416 */
1417static int shClSvcClientReadData(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1418{
1419 LogFlowFuncEnter();
1420
1421 /*
1422 * Check if the service mode allows this operation and whether the guest is
1423 * supposed to be reading from the host.
1424 */
1425 uint32_t uMode = ShClSvcGetMode();
1426 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1427 || uMode == VBOX_SHCL_MODE_HOST_TO_GUEST)
1428 { /* likely */ }
1429 else
1430 return VERR_ACCESS_DENIED;
1431
1432 /// @todo r=bird: The management of the SHCLCLIENTSTATE_FLAGS_READ_ACTIVE
1433 /// makes it impossible for the guest to retrieve more than one format from
1434 /// the clipboard. I.e. it can either get the TEXT or the HTML rendering,
1435 /// but not both. So, I've disable the check. */
1436 //ASSERT_GUEST_RETURN(pClient->State.fFlags & SHCLCLIENTSTATE_FLAGS_READ_ACTIVE, VERR_WRONG_ORDER);
1437
1438 /*
1439 * Digest parameters.
1440 *
1441 * We are dragging some legacy here from the 6.1 dev cycle, a 5 parameter
1442 * variant which prepends a 64-bit context ID (RAZ as meaning not defined),
1443 * a 32-bit flag (MBZ, no defined meaning) and switches the last two parameters.
1444 */
1445 ASSERT_GUEST_RETURN( cParms == VBOX_SHCL_CPARMS_DATA_READ
1446 || ( cParms == VBOX_SHCL_CPARMS_DATA_READ_61B
1447 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)),
1448 VERR_WRONG_PARAMETER_COUNT);
1449
1450 uintptr_t iParm = 0;
1451 SHCLCLIENTCMDCTX cmdCtx;
1452 RT_ZERO(cmdCtx);
1453 if (cParms == VBOX_SHCL_CPARMS_DATA_READ_61B)
1454 {
1455 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1456 /* This has no defined meaning and was never used, however the guest passed stuff, so ignore it and leave idContext=0. */
1457 iParm++;
1458 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1459 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1460 iParm++;
1461 }
1462
1463 SHCLDATABLOCK dataBlock;
1464 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1465 dataBlock.uFormat = paParms[iParm].u.uint32;
1466 iParm++;
1467 if (cParms != VBOX_SHCL_CPARMS_DATA_READ_61B)
1468 {
1469 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1470 dataBlock.pvData = paParms[iParm].u.pointer.addr;
1471 dataBlock.cbData = paParms[iParm].u.pointer.size;
1472 iParm++;
1473 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /*cbDataReturned*/
1474 iParm++;
1475 }
1476 else
1477 {
1478 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /*cbDataReturned*/
1479 iParm++;
1480 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1481 dataBlock.pvData = paParms[iParm].u.pointer.addr;
1482 dataBlock.cbData = paParms[iParm].u.pointer.size;
1483 iParm++;
1484 }
1485 Assert(iParm == cParms);
1486
1487 /*
1488 * For some reason we need to do this (makes absolutely no sense to bird).
1489 */
1490 /** @todo r=bird: I really don't get why you need the State.POD.uFormat
1491 * member. I'm sure there is a reason. Incomplete code? */
1492 if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
1493 {
1494 if (pClient->State.POD.uFormat == VBOX_SHCL_FMT_NONE)
1495 pClient->State.POD.uFormat = dataBlock.uFormat;
1496 /// @todo r=bird: This actively breaks copying different types of data into the
1497 /// guest (first copy a text snippet, then you cannot copy any bitmaps), so I've
1498 /// disabled it.
1499 //ASSERT_GUEST_MSG_RETURN(pClient->State.POD.uFormat == dataBlock.uFormat,
1500 // ("Requested %#x, POD.uFormat=%#x\n", dataBlock.uFormat, pClient->State.POD.uFormat),
1501 // VERR_BAD_EXE_FORMAT /*VERR_INTERNAL_ERROR*/);
1502 }
1503
1504 /*
1505 * Do the reading.
1506 */
1507 int rc;
1508 uint32_t cbActual = 0;
1509
1510 /* If there is a service extension active, try reading data from it first. */
1511 if (g_ExtState.pfnExtension)
1512 {
1513 SHCLEXTPARMS parms;
1514 RT_ZERO(parms);
1515
1516 parms.uFormat = dataBlock.uFormat;
1517 parms.u.pvData = dataBlock.pvData;
1518 parms.cbData = dataBlock.cbData;
1519
1520 g_ExtState.fReadingData = true;
1521
1522 /* Read clipboard data from the extension. */
1523 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_DATA_READ, &parms, sizeof(parms));
1524 LogRelFlowFunc(("DATA/Ext: fDelayedAnnouncement=%RTbool fDelayedFormats=%#x cbData=%RU32->%RU32 rc=%Rrc\n",
1525 g_ExtState.fDelayedAnnouncement, g_ExtState.fDelayedFormats, dataBlock.cbData, parms.cbData, rc));
1526
1527 /* Did the extension send the clipboard formats yet?
1528 * Otherwise, do this now. */
1529 if (g_ExtState.fDelayedAnnouncement)
1530 {
1531 int rc2 = ShClSvcHostReportFormats(pClient, g_ExtState.fDelayedFormats);
1532 AssertRC(rc2);
1533
1534 g_ExtState.fDelayedAnnouncement = false;
1535 g_ExtState.fDelayedFormats = 0;
1536 }
1537
1538 g_ExtState.fReadingData = false;
1539
1540 if (RT_SUCCESS(rc))
1541 cbActual = parms.cbData;
1542 }
1543 else
1544 {
1545 rc = ShClSvcImplReadData(pClient, &cmdCtx, &dataBlock, &cbActual);
1546 LogRelFlowFunc(("DATA/Host: cbData=%RU32->%RU32 rc=%Rrc\n", dataBlock.cbData, cbActual, rc));
1547 }
1548
1549 if (RT_SUCCESS(rc))
1550 {
1551 /* Return the actual size required to fullfil the request. */
1552 if (cParms != VBOX_SHCL_CPARMS_DATA_READ_61B)
1553 HGCMSvcSetU32(&paParms[2], cbActual);
1554 else
1555 HGCMSvcSetU32(&paParms[3], cbActual);
1556
1557 /* If the data to return exceeds the buffer the guest supplies, tell it (and let it try again). */
1558 if (cbActual >= dataBlock.cbData)
1559 rc = VINF_BUFFER_OVERFLOW;
1560
1561 if (rc == VINF_SUCCESS)
1562 {
1563 /* Only remove "read active" flag after successful read again. */
1564 /** @todo r=bird: This doesn't make any effing sense. What if the guest
1565 * wants to read another format??? */
1566 pClient->State.fFlags &= ~SHCLCLIENTSTATE_FLAGS_READ_ACTIVE;
1567 }
1568 }
1569
1570 LogFlowFuncLeaveRC(rc);
1571 return rc;
1572}
1573
1574int shClSvcClientWriteData(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1575{
1576 LogFlowFuncEnter();
1577
1578 /*
1579 * Check if the service mode allows this operation and whether the guest is
1580 * supposed to be reading from the host.
1581 */
1582 uint32_t uMode = ShClSvcGetMode();
1583 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1584 || uMode == VBOX_SHCL_MODE_GUEST_TO_HOST)
1585 { /* likely */ }
1586 else
1587 return VERR_ACCESS_DENIED;
1588
1589 /** @todo r=bird: This whole active flag stuff is broken, so disabling for now. */
1590 //if (pClient->State.fFlags & SHCLCLIENTSTATE_FLAGS_WRITE_ACTIVE)
1591 //{ /* likely */ }
1592 //else
1593 // return VERR_WRONG_ORDER;
1594
1595 /*
1596 * Digest parameters.
1597 *
1598 * There are 3 different format here, formatunately no parameters have been
1599 * switch around so it's plain sailing compared to the DATA_READ message.
1600 */
1601 ASSERT_GUEST_RETURN(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID
1602 ? cParms == VBOX_SHCL_CPARMS_DATA_WRITE || cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B
1603 : cParms == VBOX_SHCL_CPARMS_DATA_WRITE_OLD,
1604 VERR_WRONG_PARAMETER_COUNT);
1605
1606 uintptr_t iParm = 0;
1607 SHCLCLIENTCMDCTX cmdCtx;
1608 RT_ZERO(cmdCtx);
1609 if (cParms > VBOX_SHCL_CPARMS_DATA_WRITE_OLD)
1610 {
1611 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1612 cmdCtx.uContextID = paParms[iParm].u.uint64;
1613 uint64_t const idCtxExpected = VBOX_SHCL_CONTEXTID_MAKE(pClient->State.uSessionID, pClient->EventSrc.uID,
1614 VBOX_SHCL_CONTEXTID_GET_EVENT(cmdCtx.uContextID));
1615 ASSERT_GUEST_MSG_RETURN(cmdCtx.uContextID == idCtxExpected,
1616 ("Wrong context ID: %#RX64, expected %#RX64\n", cmdCtx.uContextID, idCtxExpected),
1617 VERR_INVALID_CONTEXT);
1618 iParm++;
1619 }
1620 else
1621 {
1622 /** @todo supply CID from client state? Setting it in ShClSvcDataReadRequest? */
1623 }
1624 if (cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B)
1625 {
1626 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1627 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1628 iParm++;
1629 }
1630 SHCLDATABLOCK dataBlock;
1631 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* Format bit. */
1632 dataBlock.uFormat = paParms[iParm].u.uint32;
1633 iParm++;
1634 if (cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B)
1635 {
1636 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* "cbData" - duplicates buffer size. */
1637 iParm++;
1638 }
1639 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1640 dataBlock.pvData = paParms[iParm].u.pointer.addr;
1641 dataBlock.cbData = paParms[iParm].u.pointer.size;
1642 iParm++;
1643 Assert(iParm == cParms);
1644
1645 /*
1646 * For some reason we need to do this (makes absolutely no sense to bird).
1647 */
1648 /** @todo r=bird: I really don't get why you need the State.POD.uFormat
1649 * member. I'm sure there is a reason. Incomplete code? */
1650 if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
1651 {
1652 if (pClient->State.POD.uFormat == VBOX_SHCL_FMT_NONE)
1653 pClient->State.POD.uFormat = dataBlock.uFormat;
1654 /** @todo r=bird: this must be buggy to, I've disabled it without testing
1655 * though. */
1656 //ASSERT_GUEST_MSG_RETURN(pClient->State.POD.uFormat == dataBlock.uFormat,
1657 // ("Requested %#x, POD.uFormat=%#x\n", dataBlock.uFormat, pClient->State.POD.uFormat),
1658 // VERR_BAD_EXE_FORMAT /*VERR_INTERNAL_ERROR*/);
1659 }
1660
1661 /*
1662 * Write the data to the active host side clipboard.
1663 */
1664 int rc;
1665 if (g_ExtState.pfnExtension)
1666 {
1667 SHCLEXTPARMS parms;
1668 RT_ZERO(parms);
1669 parms.uFormat = dataBlock.uFormat;
1670 parms.u.pvData = dataBlock.pvData;
1671 parms.cbData = dataBlock.cbData;
1672
1673 g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_DATA_WRITE, &parms, sizeof(parms));
1674 rc = VINF_SUCCESS;
1675 }
1676 else
1677 rc = ShClSvcImplWriteData(pClient, &cmdCtx, &dataBlock);
1678 if (RT_SUCCESS(rc))
1679 {
1680 /* Remove "write active" flag after successful read again. */
1681 /** @todo r=bird: This doesn't make any effing sense. What if the host
1682 * wants to have the guest write it another format??? */
1683 pClient->State.fFlags &= ~SHCLCLIENTSTATE_FLAGS_WRITE_ACTIVE;
1684 }
1685
1686 LogFlowFuncLeaveRC(rc);
1687 return rc;
1688}
1689
1690/**
1691 * Gets an error from HGCM service parameters.
1692 *
1693 * @returns VBox status code.
1694 * @param cParms Number of HGCM parameters supplied in \a paParms.
1695 * @param paParms Array of HGCM parameters.
1696 * @param pRc Where to store the received error code.
1697 */
1698static int shClSvcClientError(uint32_t cParms, VBOXHGCMSVCPARM paParms[], int *pRc)
1699{
1700 AssertPtrReturn(paParms, VERR_INVALID_PARAMETER);
1701 AssertPtrReturn(pRc, VERR_INVALID_PARAMETER);
1702
1703 int rc;
1704
1705 if (cParms == VBOX_SHCL_CPARMS_ERROR)
1706 {
1707 rc = HGCMSvcGetU32(&paParms[1], (uint32_t *)pRc); /** @todo int vs. uint32_t !!! */
1708 }
1709 else
1710 rc = VERR_INVALID_PARAMETER;
1711
1712 LogFlowFuncLeaveRC(rc);
1713 return rc;
1714}
1715
1716int shClSvcSetSource(PSHCLCLIENT pClient, SHCLSOURCE enmSource)
1717{
1718 if (!pClient) /* If no client connected (anymore), bail out. */
1719 return VINF_SUCCESS;
1720
1721 int rc = VINF_SUCCESS;
1722
1723 if (ShClSvcLock())
1724 {
1725 pClient->State.enmSource = enmSource;
1726
1727 LogFlowFunc(("Source of client %RU32 is now %RU32\n", pClient->State.uClientID, pClient->State.enmSource));
1728
1729 ShClSvcUnlock();
1730 }
1731
1732 LogFlowFuncLeaveRC(rc);
1733 return rc;
1734}
1735
1736static int svcInit(void)
1737{
1738 int rc = RTCritSectInit(&g_CritSect);
1739
1740 if (RT_SUCCESS(rc))
1741 {
1742 shClSvcModeSet(VBOX_SHCL_MODE_OFF);
1743
1744 rc = ShClSvcImplInit();
1745
1746 /* Clean up on failure, because 'svnUnload' will not be called
1747 * if the 'svcInit' returns an error.
1748 */
1749 if (RT_FAILURE(rc))
1750 {
1751 RTCritSectDelete(&g_CritSect);
1752 }
1753 }
1754
1755 return rc;
1756}
1757
1758static DECLCALLBACK(int) svcUnload(void *)
1759{
1760 LogFlowFuncEnter();
1761
1762 ShClSvcImplDestroy();
1763
1764 RTCritSectDelete(&g_CritSect);
1765
1766 return VINF_SUCCESS;
1767}
1768
1769static DECLCALLBACK(int) svcDisconnect(void *, uint32_t u32ClientID, void *pvClient)
1770{
1771 RT_NOREF(u32ClientID);
1772
1773 LogFunc(("u32ClientID=%RU32\n", u32ClientID));
1774
1775 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
1776 AssertPtr(pClient);
1777
1778#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1779 shClSvcClientTransfersReset(pClient);
1780#endif
1781
1782 ShClSvcImplDisconnect(pClient);
1783
1784 shClSvcClientDestroy(pClient);
1785
1786 return VINF_SUCCESS;
1787}
1788
1789static DECLCALLBACK(int) svcConnect(void *, uint32_t u32ClientID, void *pvClient, uint32_t fRequestor, bool fRestoring)
1790{
1791 RT_NOREF(fRequestor, fRestoring);
1792
1793 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
1794 AssertPtr(pvClient);
1795
1796 int rc = shClSvcClientInit(pClient, u32ClientID);
1797 if (RT_SUCCESS(rc))
1798 {
1799 rc = ShClSvcImplConnect(pClient, ShClSvcGetHeadless());
1800 if (RT_SUCCESS(rc))
1801 {
1802 /* Sync the host clipboard content with the client. */
1803 rc = ShClSvcImplSync(pClient);
1804 if (rc == VINF_NO_CHANGE)
1805 {
1806 /*
1807 * The sync could return VINF_NO_CHANGE if nothing has changed on the host, but older
1808 * Guest Additions rely on the fact that only VINF_SUCCESS indicates a successful connect
1809 * to the host service (instead of using RT_SUCCESS()).
1810 *
1811 * So implicitly set VINF_SUCCESS here to not break older Guest Additions.
1812 */
1813 rc = VINF_SUCCESS;
1814 }
1815
1816 if (RT_SUCCESS(rc))
1817 {
1818 /* Assign weak pointer to client map .*/
1819 g_mapClients[u32ClientID] = pClient; /** @todo Handle OOM / collisions? */
1820
1821 /* For now we ASSUME that the first client ever connected is in charge for
1822 * communicating withe the service extension.
1823 *
1824 ** @todo This needs to be fixed ASAP w/o breaking older guest / host combos. */
1825 if (g_ExtState.uClientID == 0)
1826 g_ExtState.uClientID = u32ClientID;
1827 }
1828 }
1829 }
1830
1831 LogFlowFuncLeaveRC(rc);
1832 return rc;
1833}
1834
1835static DECLCALLBACK(void) svcCall(void *,
1836 VBOXHGCMCALLHANDLE callHandle,
1837 uint32_t u32ClientID,
1838 void *pvClient,
1839 uint32_t u32Function,
1840 uint32_t cParms,
1841 VBOXHGCMSVCPARM paParms[],
1842 uint64_t tsArrival)
1843{
1844 RT_NOREF(u32ClientID, pvClient, tsArrival);
1845 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
1846 AssertPtr(pClient);
1847
1848#ifdef LOG_ENABLED
1849 LogFunc(("u32ClientID=%RU32, fn=%RU32 (%s), cParms=%RU32, paParms=%p\n",
1850 u32ClientID, u32Function, ShClGuestMsgToStr(u32Function), cParms, paParms));
1851 for (uint32_t i = 0; i < cParms; i++)
1852 {
1853 /** @todo parameters other than 32 bit */
1854 LogFunc((" paParms[%d]: type %RU32 - value %RU32\n", i, paParms[i].type, paParms[i].u.uint32));
1855 }
1856 LogFunc(("Client state: fFlags=0x%x, fGuestFeatures0=0x%x, fGuestFeatures1=0x%x\n",
1857 pClient->State.fFlags, pClient->State.fGuestFeatures0, pClient->State.fGuestFeatures1));
1858#endif
1859
1860 int rc;
1861 switch (u32Function)
1862 {
1863 case VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT:
1864 RTCritSectEnter(&pClient->CritSect);
1865 rc = shClSvcClientMsgOldGet(pClient, callHandle, cParms, paParms);
1866 RTCritSectLeave(&pClient->CritSect);
1867 break;
1868
1869 case VBOX_SHCL_GUEST_FN_CONNECT:
1870 LogRel(("6.1.0 beta or rc additions detected. Please upgrade!\n"));
1871 rc = VERR_NOT_IMPLEMENTED;
1872 break;
1873
1874 case VBOX_SHCL_GUEST_FN_REPORT_FEATURES:
1875 rc = shClSvcClientReportFeatures(pClient, callHandle, cParms, paParms);
1876 break;
1877
1878 case VBOX_SHCL_GUEST_FN_QUERY_FEATURES:
1879 rc = shClSvcClientQueryFeatures(callHandle, cParms, paParms);
1880 break;
1881
1882 case VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT:
1883 RTCritSectEnter(&pClient->CritSect);
1884 rc = shClSvcClientMsgPeek(pClient, callHandle, cParms, paParms, false /*fWait*/);
1885 RTCritSectLeave(&pClient->CritSect);
1886 break;
1887
1888 case VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT:
1889 RTCritSectEnter(&pClient->CritSect);
1890 rc = shClSvcClientMsgPeek(pClient, callHandle, cParms, paParms, true /*fWait*/);
1891 RTCritSectLeave(&pClient->CritSect);
1892 break;
1893
1894 case VBOX_SHCL_GUEST_FN_MSG_GET:
1895 RTCritSectEnter(&pClient->CritSect);
1896 rc = shClSvcClientMsgGet(pClient, callHandle, cParms, paParms);
1897 RTCritSectLeave(&pClient->CritSect);
1898 break;
1899
1900 case VBOX_SHCL_GUEST_FN_MSG_CANCEL:
1901 RTCritSectEnter(&pClient->CritSect);
1902 rc = shClSvcClientMsgCancel(pClient, cParms);
1903 RTCritSectLeave(&pClient->CritSect);
1904 break;
1905
1906 case VBOX_SHCL_GUEST_FN_REPORT_FORMATS:
1907 rc = shClSvcClientReportFormats(pClient, cParms, paParms);
1908 break;
1909
1910 case VBOX_SHCL_GUEST_FN_DATA_READ:
1911 rc = shClSvcClientReadData(pClient, cParms, paParms);
1912 break;
1913
1914 case VBOX_SHCL_GUEST_FN_DATA_WRITE:
1915 rc = shClSvcClientWriteData(pClient, cParms, paParms);
1916 break;
1917
1918 case VBOX_SHCL_GUEST_FN_ERROR:
1919 {
1920 int rcGuest;
1921 rc = shClSvcClientError(cParms,paParms, &rcGuest);
1922 if (RT_SUCCESS(rc))
1923 {
1924 LogRel(("Shared Clipboard: Error from guest side: %Rrc\n", rcGuest));
1925
1926 /* Reset client state and start over. */
1927 shclSvcClientStateReset(&pClient->State);
1928#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1929 shClSvcClientTransfersReset(pClient);
1930#endif
1931 }
1932 break;
1933 }
1934
1935 default:
1936 {
1937#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1938 if ( u32Function <= VBOX_SHCL_GUEST_FN_LAST
1939 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID) )
1940 {
1941 if (g_fTransferMode & VBOX_SHCL_TRANSFER_MODE_ENABLED)
1942 rc = shClSvcTransferHandler(pClient, callHandle, u32Function, cParms, paParms, tsArrival);
1943 else
1944 {
1945 LogRel2(("Shared Clipboard: File transfers are disabled for this VM\n"));
1946 rc = VERR_ACCESS_DENIED;
1947 }
1948 }
1949 else
1950#endif
1951 {
1952 LogRel2(("Shared Clipboard: Unknown guest function: %u (%#x)\n", u32Function, u32Function));
1953 rc = VERR_NOT_IMPLEMENTED;
1954 }
1955 break;
1956 }
1957 }
1958
1959 LogFlowFunc(("[Client %RU32] rc=%Rrc\n", pClient->State.uClientID, rc));
1960
1961 if (rc != VINF_HGCM_ASYNC_EXECUTE)
1962 g_pHelpers->pfnCallComplete(callHandle, rc);
1963}
1964
1965/**
1966 * Initializes a Shared Clipboard service's client state.
1967 *
1968 * @returns VBox status code.
1969 * @param pClientState Client state to initialize.
1970 * @param uClientID Client ID (HGCM) to use for this client state.
1971 */
1972int shClSvcClientStateInit(PSHCLCLIENTSTATE pClientState, uint32_t uClientID)
1973{
1974 LogFlowFuncEnter();
1975
1976 shclSvcClientStateReset(pClientState);
1977
1978 /* Register the client. */
1979 pClientState->uClientID = uClientID;
1980
1981 return VINF_SUCCESS;
1982}
1983
1984/**
1985 * Destroys a Shared Clipboard service's client state.
1986 *
1987 * @returns VBox status code.
1988 * @param pClientState Client state to destroy.
1989 */
1990int shClSvcClientStateDestroy(PSHCLCLIENTSTATE pClientState)
1991{
1992 RT_NOREF(pClientState);
1993
1994 LogFlowFuncEnter();
1995
1996 return VINF_SUCCESS;
1997}
1998
1999/**
2000 * Resets a Shared Clipboard service's client state.
2001 *
2002 * @param pClientState Client state to reset.
2003 */
2004void shclSvcClientStateReset(PSHCLCLIENTSTATE pClientState)
2005{
2006 LogFlowFuncEnter();
2007
2008 pClientState->fGuestFeatures0 = VBOX_SHCL_GF_NONE;
2009 pClientState->fGuestFeatures1 = VBOX_SHCL_GF_NONE;
2010
2011 pClientState->cbChunkSize = _64K; /** Make this configurable. */
2012 pClientState->enmSource = SHCLSOURCE_INVALID;
2013 pClientState->fFlags = SHCLCLIENTSTATE_FLAGS_NONE;
2014
2015 pClientState->POD.enmDir = SHCLTRANSFERDIR_UNKNOWN;
2016 pClientState->POD.uFormat = VBOX_SHCL_FMT_NONE;
2017 pClientState->POD.cbToReadWriteTotal = 0;
2018 pClientState->POD.cbReadWritten = 0;
2019
2020#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2021 pClientState->Transfers.enmTransferDir = SHCLTRANSFERDIR_UNKNOWN;
2022#endif
2023
2024
2025}
2026
2027/*
2028 * We differentiate between a function handler for the guest and one for the host.
2029 */
2030static DECLCALLBACK(int) svcHostCall(void *,
2031 uint32_t u32Function,
2032 uint32_t cParms,
2033 VBOXHGCMSVCPARM paParms[])
2034{
2035 int rc = VINF_SUCCESS;
2036
2037 LogFlowFunc(("u32Function=%RU32 (%s), cParms=%RU32, paParms=%p\n",
2038 u32Function, ShClHostFunctionToStr(u32Function), cParms, paParms));
2039
2040 switch (u32Function)
2041 {
2042 case VBOX_SHCL_HOST_FN_SET_MODE:
2043 {
2044 if (cParms != 1)
2045 {
2046 rc = VERR_INVALID_PARAMETER;
2047 }
2048 else
2049 {
2050 uint32_t u32Mode = VBOX_SHCL_MODE_OFF;
2051
2052 rc = HGCMSvcGetU32(&paParms[0], &u32Mode);
2053 if (RT_SUCCESS(rc))
2054 rc = shClSvcModeSet(u32Mode);
2055 }
2056
2057 break;
2058 }
2059
2060#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2061 case VBOX_SHCL_HOST_FN_SET_TRANSFER_MODE:
2062 {
2063 if (cParms != 1)
2064 {
2065 rc = VERR_INVALID_PARAMETER;
2066 }
2067 else
2068 {
2069 uint32_t fTransferMode;
2070 rc = HGCMSvcGetU32(&paParms[0], &fTransferMode);
2071 if (RT_SUCCESS(rc))
2072 rc = shClSvcTransferModeSet(fTransferMode);
2073 }
2074 break;
2075 }
2076#endif
2077 case VBOX_SHCL_HOST_FN_SET_HEADLESS:
2078 {
2079 if (cParms != 1)
2080 {
2081 rc = VERR_INVALID_PARAMETER;
2082 }
2083 else
2084 {
2085 uint32_t uHeadless;
2086 rc = HGCMSvcGetU32(&paParms[0], &uHeadless);
2087 if (RT_SUCCESS(rc))
2088 {
2089 g_fHeadless = RT_BOOL(uHeadless);
2090 LogRel(("Shared Clipboard: Service running in %s mode\n", g_fHeadless ? "headless" : "normal"));
2091 }
2092 }
2093 break;
2094 }
2095
2096 default:
2097 {
2098#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2099 rc = shClSvcTransferHostHandler(u32Function, cParms, paParms);
2100#else
2101 rc = VERR_NOT_IMPLEMENTED;
2102#endif
2103 break;
2104 }
2105 }
2106
2107 LogFlowFuncLeaveRC(rc);
2108 return rc;
2109}
2110
2111#ifndef UNIT_TEST
2112/**
2113 * SSM descriptor table for the SHCLCLIENTSTATE structure.
2114 *
2115 * @note Saving the session ID not necessary, as they're not persistent across
2116 * state save/restore.
2117 */
2118static SSMFIELD const s_aShClSSMClientState[] =
2119{
2120 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures0),
2121 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures1),
2122 SSMFIELD_ENTRY(SHCLCLIENTSTATE, cbChunkSize),
2123 SSMFIELD_ENTRY(SHCLCLIENTSTATE, enmSource),
2124 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fFlags),
2125 SSMFIELD_ENTRY_TERM()
2126};
2127
2128/**
2129 * VBox 6.1 Beta 1 version of s_aShClSSMClientState (no flags).
2130 */
2131static SSMFIELD const s_aShClSSMClientState61B1[] =
2132{
2133 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures0),
2134 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures1),
2135 SSMFIELD_ENTRY(SHCLCLIENTSTATE, cbChunkSize),
2136 SSMFIELD_ENTRY(SHCLCLIENTSTATE, enmSource),
2137 SSMFIELD_ENTRY_TERM()
2138};
2139
2140/**
2141 * SSM descriptor table for the SHCLCLIENTPODSTATE structure.
2142 */
2143static SSMFIELD const s_aShClSSMClientPODState[] =
2144{
2145 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, enmDir),
2146 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, uFormat),
2147 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, cbToReadWriteTotal),
2148 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, cbReadWritten),
2149 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, tsLastReadWrittenMs),
2150 SSMFIELD_ENTRY_TERM()
2151};
2152
2153/**
2154 * SSM descriptor table for the SHCLCLIENTURISTATE structure.
2155 */
2156static SSMFIELD const s_aShClSSMClientTransferState[] =
2157{
2158 SSMFIELD_ENTRY(SHCLCLIENTTRANSFERSTATE, enmTransferDir),
2159 SSMFIELD_ENTRY_TERM()
2160};
2161
2162/**
2163 * SSM descriptor table for the header of the SHCLCLIENTMSG structure.
2164 * The actual message parameters will be serialized separately.
2165 */
2166static SSMFIELD const s_aShClSSMClientMsgHdr[] =
2167{
2168 SSMFIELD_ENTRY(SHCLCLIENTMSG, idMsg),
2169 SSMFIELD_ENTRY(SHCLCLIENTMSG, cParms),
2170 SSMFIELD_ENTRY_TERM()
2171};
2172
2173/**
2174 * SSM descriptor table for what used to be the VBOXSHCLMSGCTX structure but is
2175 * now part of SHCLCLIENTMSG.
2176 */
2177static SSMFIELD const s_aShClSSMClientMsgCtx[] =
2178{
2179 SSMFIELD_ENTRY(SHCLCLIENTMSG, idContext),
2180 SSMFIELD_ENTRY_TERM()
2181};
2182#endif /* !UNIT_TEST */
2183
2184static DECLCALLBACK(int) svcSaveState(void *, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM)
2185{
2186 LogFlowFuncEnter();
2187
2188#ifndef UNIT_TEST
2189 /*
2190 * When the state will be restored, pending requests will be reissued
2191 * by VMMDev. The service therefore must save state as if there were no
2192 * pending request.
2193 * Pending requests, if any, will be completed in svcDisconnect.
2194 */
2195 RT_NOREF(u32ClientID);
2196 LogFunc(("u32ClientID=%RU32\n", u32ClientID));
2197
2198 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2199 AssertPtr(pClient);
2200
2201 /* Write Shared Clipboard saved state version. */
2202 SSMR3PutU32(pSSM, VBOX_SHCL_SAVED_STATE_VER_CURRENT);
2203
2204 int rc = SSMR3PutStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /*fFlags*/, &s_aShClSSMClientState[0], NULL);
2205 AssertRCReturn(rc, rc);
2206
2207 rc = SSMR3PutStructEx(pSSM, &pClient->State.POD, sizeof(pClient->State.POD), 0 /*fFlags*/, &s_aShClSSMClientPODState[0], NULL);
2208 AssertRCReturn(rc, rc);
2209
2210 rc = SSMR3PutStructEx(pSSM, &pClient->State.Transfers, sizeof(pClient->State.Transfers), 0 /*fFlags*/, &s_aShClSSMClientTransferState[0], NULL);
2211 AssertRCReturn(rc, rc);
2212
2213 /* Serialize the client's internal message queue. */
2214 uint32_t cMsgs = 0;
2215 PSHCLCLIENTMSG pMsg;
2216 RTListForEach(&pClient->MsgQueue, pMsg, SHCLCLIENTMSG, ListEntry)
2217 {
2218 cMsgs += 1;
2219 }
2220
2221 rc = SSMR3PutU64(pSSM, cMsgs);
2222 AssertRCReturn(rc, rc);
2223
2224 RTListForEach(&pClient->MsgQueue, pMsg, SHCLCLIENTMSG, ListEntry)
2225 {
2226 SSMR3PutStructEx(pSSM, pMsg, sizeof(SHCLCLIENTMSG), 0 /*fFlags*/, &s_aShClSSMClientMsgHdr[0], NULL);
2227 SSMR3PutStructEx(pSSM, pMsg, sizeof(SHCLCLIENTMSG), 0 /*fFlags*/, &s_aShClSSMClientMsgCtx[0], NULL);
2228
2229 for (uint32_t iParm = 0; iParm < pMsg->cParms; iParm++)
2230 HGCMSvcSSMR3Put(&pMsg->aParms[iParm], pSSM);
2231 }
2232
2233#else /* UNIT_TEST */
2234 RT_NOREF3(u32ClientID, pvClient, pSSM);
2235#endif /* UNIT_TEST */
2236 return VINF_SUCCESS;
2237}
2238
2239#ifndef UNIT_TEST
2240static int svcLoadStateV0(uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, uint32_t uVersion)
2241{
2242 RT_NOREF(u32ClientID, pvClient, pSSM, uVersion);
2243
2244 uint32_t uMarker;
2245 int rc = SSMR3GetU32(pSSM, &uMarker); /* Begin marker. */
2246 AssertRC(rc);
2247 Assert(uMarker == UINT32_C(0x19200102) /* SSMR3STRUCT_BEGIN */);
2248
2249 rc = SSMR3Skip(pSSM, sizeof(uint32_t)); /* Client ID */
2250 AssertRCReturn(rc, rc);
2251
2252 bool fValue;
2253 rc = SSMR3GetBool(pSSM, &fValue); /* fHostMsgQuit */
2254 AssertRCReturn(rc, rc);
2255
2256 rc = SSMR3GetBool(pSSM, &fValue); /* fHostMsgReadData */
2257 AssertRCReturn(rc, rc);
2258
2259 rc = SSMR3GetBool(pSSM, &fValue); /* fHostMsgFormats */
2260 AssertRCReturn(rc, rc);
2261
2262 uint32_t fFormats;
2263 rc = SSMR3GetU32(pSSM, &fFormats); /* u32RequestedFormat */
2264 AssertRCReturn(rc, rc);
2265
2266 rc = SSMR3GetU32(pSSM, &uMarker); /* End marker. */
2267 AssertRCReturn(rc, rc);
2268 Assert(uMarker == UINT32_C(0x19920406) /* SSMR3STRUCT_END */);
2269
2270 return VINF_SUCCESS;
2271}
2272#endif /* UNIT_TEST */
2273
2274static DECLCALLBACK(int) svcLoadState(void *, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, uint32_t uVersion)
2275{
2276 LogFlowFuncEnter();
2277
2278#ifndef UNIT_TEST
2279
2280 RT_NOREF(u32ClientID, uVersion);
2281
2282 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2283 AssertPtr(pClient);
2284
2285 /* Restore the client data. */
2286 uint32_t lenOrVer;
2287 int rc = SSMR3GetU32(pSSM, &lenOrVer);
2288 AssertRCReturn(rc, rc);
2289
2290 LogFunc(("u32ClientID=%RU32, lenOrVer=%#RX64\n", u32ClientID, lenOrVer));
2291
2292 if (lenOrVer == VBOX_SHCL_SAVED_STATE_VER_3_1)
2293 return svcLoadStateV0(u32ClientID, pvClient, pSSM, uVersion);
2294
2295 if ( lenOrVer >= VBOX_SHCL_SAVED_STATE_VER_6_1B2
2296 && lenOrVer <= VBOX_SHCL_SAVED_STATE_VER_CURRENT)
2297 {
2298 if (lenOrVer >= VBOX_SHCL_SAVED_STATE_VER_6_1RC1)
2299 {
2300 SSMR3GetStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /* fFlags */, &s_aShClSSMClientState[0], NULL);
2301 SSMR3GetStructEx(pSSM, &pClient->State.POD, sizeof(pClient->State.POD), 0 /* fFlags */,
2302 &s_aShClSSMClientPODState[0], NULL);
2303 }
2304 else
2305 SSMR3GetStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /* fFlags */, &s_aShClSSMClientState61B1[0], NULL);
2306 rc = SSMR3GetStructEx(pSSM, &pClient->State.Transfers, sizeof(pClient->State.Transfers), 0 /* fFlags */,
2307 &s_aShClSSMClientTransferState[0], NULL);
2308 AssertRCReturn(rc, rc);
2309
2310 /* Load the client's internal message queue. */
2311 uint64_t cMsgs;
2312 rc = SSMR3GetU64(pSSM, &cMsgs);
2313 AssertRCReturn(rc, rc);
2314 AssertLogRelMsgReturn(cMsgs < _16K, ("Too many messages: %u (%x)\n", cMsgs, cMsgs), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
2315
2316 for (uint64_t i = 0; i < cMsgs; i++)
2317 {
2318 union
2319 {
2320 SHCLCLIENTMSG Msg;
2321 uint8_t abPadding[RT_UOFFSETOF(SHCLCLIENTMSG, aParms) + sizeof(VBOXHGCMSVCPARM) * 2];
2322 } u;
2323
2324 SSMR3GetStructEx(pSSM, &u.Msg, RT_UOFFSETOF(SHCLCLIENTMSG, aParms), 0 /*fFlags*/, &s_aShClSSMClientMsgHdr[0], NULL);
2325 rc = SSMR3GetStructEx(pSSM, &u.Msg, RT_UOFFSETOF(SHCLCLIENTMSG, aParms), 0 /*fFlags*/, &s_aShClSSMClientMsgCtx[0], NULL);
2326 AssertRCReturn(rc, rc);
2327
2328 AssertLogRelMsgReturn(u.Msg.cParms <= VMMDEV_MAX_HGCM_PARMS,
2329 ("Too many HGCM message parameters: %u (%#x)\n", u.Msg.cParms, u.Msg.cParms),
2330 VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
2331
2332 PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient, u.Msg.idMsg, u.Msg.cParms);
2333 AssertReturn(pMsg, VERR_NO_MEMORY);
2334 pMsg->idContext = u.Msg.idContext;
2335
2336 for (uint32_t p = 0; p < pMsg->cParms; p++)
2337 {
2338 rc = HGCMSvcSSMR3Get(&pMsg->aParms[p], pSSM);
2339 AssertRCReturnStmt(rc, shClSvcMsgFree(pClient, pMsg), rc);
2340 }
2341
2342 shClSvcMsgAdd(pClient, pMsg, true /* fAppend */);
2343 }
2344 }
2345 else
2346 {
2347 LogRel(("Shared Clipboard: Unsupported saved state version (%#x)\n", lenOrVer));
2348 return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
2349 }
2350
2351 /* Actual host data are to be reported to guest (SYNC). */
2352 ShClSvcImplSync(pClient);
2353
2354#else /* UNIT_TEST */
2355 RT_NOREF(u32ClientID, pvClient, pSSM, uVersion);
2356#endif /* UNIT_TEST */
2357 return VINF_SUCCESS;
2358}
2359
2360static DECLCALLBACK(int) extCallback(uint32_t u32Function, uint32_t u32Format, void *pvData, uint32_t cbData)
2361{
2362 RT_NOREF(pvData, cbData);
2363
2364 LogFlowFunc(("u32Function=%RU32\n", u32Function));
2365
2366 int rc = VINF_SUCCESS;
2367
2368 /* Figure out if the client in charge for the service extension still is connected. */
2369 ClipboardClientMap::const_iterator itClient = g_mapClients.find(g_ExtState.uClientID);
2370 if (itClient != g_mapClients.end())
2371 {
2372 PSHCLCLIENT pClient = itClient->second;
2373 AssertPtr(pClient);
2374
2375 switch (u32Function)
2376 {
2377 /* The service extension announces formats to the guest. */
2378 case VBOX_CLIPBOARD_EXT_FN_FORMAT_ANNOUNCE:
2379 {
2380 LogFlowFunc(("VBOX_CLIPBOARD_EXT_FN_FORMAT_ANNOUNCE: g_ExtState.fReadingData=%RTbool\n", g_ExtState.fReadingData));
2381 if (!g_ExtState.fReadingData)
2382 rc = ShClSvcHostReportFormats(pClient, u32Format);
2383 else
2384 {
2385 g_ExtState.fDelayedAnnouncement = true;
2386 g_ExtState.fDelayedFormats = u32Format;
2387 rc = VINF_SUCCESS;
2388 }
2389 break;
2390 }
2391
2392 /* The service extension wants read data from the guest. */
2393 case VBOX_CLIPBOARD_EXT_FN_DATA_READ:
2394 rc = ShClSvcDataReadRequest(pClient, u32Format, NULL /* puEvent */);
2395 break;
2396
2397 default:
2398 /* Just skip other messages. */
2399 break;
2400 }
2401 }
2402 else
2403 rc = VERR_NOT_FOUND;
2404
2405 LogFlowFuncLeaveRC(rc);
2406 return rc;
2407}
2408
2409static DECLCALLBACK(int) svcRegisterExtension(void *, PFNHGCMSVCEXT pfnExtension, void *pvExtension)
2410{
2411 LogFlowFunc(("pfnExtension=%p\n", pfnExtension));
2412
2413 SHCLEXTPARMS parms;
2414 RT_ZERO(parms);
2415
2416 if (pfnExtension)
2417 {
2418 /* Install extension. */
2419 g_ExtState.pfnExtension = pfnExtension;
2420 g_ExtState.pvExtension = pvExtension;
2421
2422 parms.u.pfnCallback = extCallback;
2423
2424 g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_SET_CALLBACK, &parms, sizeof(parms));
2425 }
2426 else
2427 {
2428 if (g_ExtState.pfnExtension)
2429 g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_SET_CALLBACK, &parms, sizeof(parms));
2430
2431 /* Uninstall extension. */
2432 g_ExtState.pfnExtension = NULL;
2433 g_ExtState.pvExtension = NULL;
2434 }
2435
2436 return VINF_SUCCESS;
2437}
2438
2439extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *pTable)
2440{
2441 int rc = VINF_SUCCESS;
2442
2443 LogFlowFunc(("pTable=%p\n", pTable));
2444
2445 if (!VALID_PTR(pTable))
2446 {
2447 rc = VERR_INVALID_PARAMETER;
2448 }
2449 else
2450 {
2451 LogFunc(("pTable->cbSize = %d, ptable->u32Version = 0x%08X\n", pTable->cbSize, pTable->u32Version));
2452
2453 if ( pTable->cbSize != sizeof (VBOXHGCMSVCFNTABLE)
2454 || pTable->u32Version != VBOX_HGCM_SVC_VERSION)
2455 {
2456 rc = VERR_VERSION_MISMATCH;
2457 }
2458 else
2459 {
2460 g_pHelpers = pTable->pHelpers;
2461
2462 pTable->cbClient = sizeof(SHCLCLIENT);
2463
2464 pTable->pfnUnload = svcUnload;
2465 pTable->pfnConnect = svcConnect;
2466 pTable->pfnDisconnect = svcDisconnect;
2467 pTable->pfnCall = svcCall;
2468 pTable->pfnHostCall = svcHostCall;
2469 pTable->pfnSaveState = svcSaveState;
2470 pTable->pfnLoadState = svcLoadState;
2471 pTable->pfnRegisterExtension = svcRegisterExtension;
2472 pTable->pfnNotify = NULL;
2473 pTable->pvService = NULL;
2474
2475 /* Service specific initialization. */
2476 rc = svcInit();
2477 }
2478 }
2479
2480 LogFlowFunc(("Returning %Rrc\n", rc));
2481 return rc;
2482}
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