VirtualBox

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

Last change on this file since 103131 was 100881, checked in by vboxsync, 14 months ago

Shared Clipboard: Docs. bugref:9437

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 104.7 KB
Line 
1/* $Id: VBoxSharedClipboardSvc.cpp 100881 2023-08-15 14:33:57Z vboxsync $ */
2/** @file
3 * Shared Clipboard Service - Host service entry points.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/** @page pg_hostclip The Shared Clipboard Host Service
30 *
31 * The shared clipboard host service is the host half of the clibpoard proxying
32 * between the host and the guest. The guest parts live in VBoxClient, VBoxTray
33 * and VBoxService depending on the OS, with code shared between host and guest
34 * under src/VBox/GuestHost/SharedClipboard/.
35 *
36 * The service is split into a platform-independent core and platform-specific
37 * backends. The backends also make use of the aforementioned shared guest/host
38 * clipboard code, to avoid code duplication.
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 7.1 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 * At the moment a transfer is a all-or-nothing operation, e.g. it either
103 * completes or fails completely.
104 *
105 * Known limitations:
106 *
107 * - On Linux hosts / guests only single files per transfer is supported, as we
108 * use a HTTP server to provide the files to the desktop file managers (Nemo,
109 * Nautilus, Dolphin, ++).
110 * - Support for VRDE (VRDP) is not implemented yet (see #9498).
111 * - Unicode support on Windows hosts / guests is not enabled (yet).
112 * - Symbolic links / Windows junctions are not allowed.
113 * - Windows alternate data streams (ADS) are not allowed.
114 * - No support for ACLs yet.
115 * - No (maybe never) support for NT4.
116
117 * @section sec_transfer_structure Transfer handling structure
118 *
119 * All structures / classes are designed for running on both, on the guest
120 * (via VBoxTray / VBoxClient) or on the host (host service) to avoid code
121 * duplication where applicable.
122 *
123 * The terms "source" and "destination" in the source code depend on the current
124 * context the code is being run, e.g. host -> guest (H->G) or guest -> host (G->H)
125 * directions.
126 *
127 * Per HGCM client there is a so-called "transfer context", which in turn can
128 * have one or mulitple transfer objects. This is being used for reading from
129 * a source or writing to destination, depending on its direction.
130 *
131 * A transfer consists of the following mechanisms:
132 * - a general callback table for hooking into creation, initialization and so on.
133 * - a provider interface which performs the actual transfer operations.
134 *
135 * Involved components:
136 * - VBoxSharedClipboardSvc as host service
137 * - VBoxTray for Windows guests
138 * - VBoxClient for Linux guests
139 * - VbglR3 for common guest code used by VBoxTray / VBoxClient
140 * - Common code in GuestHost/SharedClipboard
141 * - Main for implementing event plumbing to API clients + controlling clipboard modes
142 *
143 * Also, transfers optionally can run in a separate thread to prevent blocking
144 * the UI while running.
145 *
146 * @section sec_transfer_protocol Transfer protocol
147 *
148 * The host service issues commands which the guest has to respond with an own
149 * message to. The protocol itself is designed so that it has primitives to list
150 * directories and open/close/read/write file system objects.
151 *
152 * A transfer is identified (on a per-VM basis) through its transfer ID.
153 * This transfer ID is part of a so-called "context ID" (CID), which must be part of (almost) every transfer-related HGCM message.
154 * Transfer IDs always are created and communicated by the host.
155 *
156 * As there can be multiple file system objects (fs objects) selected to transfer,
157 * a transfer can be queried for its root entries, which then contains the top-level
158 * elements. Based on these elements, (a) (recursive) listing(s) can be performed
159 * to (partially) walk down into directories and query fs object information. The
160 * provider provides appropriate interface for this, even if not all implementations
161 * might need this mechanism.
162 *
163 * The following describes the protocol flow, where the source and destination depends on the transfer direction:
164 *
165 * - For host -> guest (H->G) transfers:
166 * Source is the host, whereas the guest is the destination.
167 * - For guest -> host (G->H) transfers:
168 * Source is the guest, whereas the host is the destination.
169 *
170 * An Shared Clipboard transfer has three stages:
171 *
172 * - Stage 1: Announcement (by the source)
173 * - Stage 2: Initialization (by the source + by the destination)
174 * - Stage 3: Start
175 *
176 * Transfer statuses are handled by the VBOX_SHCL_HOST_MSG_TRANSFER_STATUS /
177 * VBOX_SHCL_GUEST_FN_REPLY + VBOX_SHCL_TX_REPLYMSGTYPE_TRANSFER_STATUS HGCM messages.
178 *
179 * Both sides can abort or cancel the transfer at any time via an ERROR transfer status.
180 *
181 * For host -> guest transfers:
182 *
183 * - Stage 1:
184 * - A (possible) transfer gets announced by the host by announcing the format VBOX_SHCL_FMT_URI_LIST to the guest.
185 * - Stage 2:
186 * - As soon as the guest wants to make use of the transfer ("pasting into file manager"),
187 * it requests a transfer ID from the host via sending the transfer status REQUESTED to the host.
188 * - The host received the REQUESTED status from the guest, creating a transfer locally and acknowledges the transfer ID
189 * via the REQUESTED status to the guest. Reports ERROR status to the guest otherwise.
190 * - The guest received the REQUESTED status from the host, then creating the transfer on its
191 * side with the transfer ID received from the host.
192 * - The guest sends back the INITIALIZED status to the host on success, or ERROR on error.
193 * - The host sends the INITIALIZED status, telling the guest that the host is ready to operate on the transfer.
194 *
195 * For guest -> host transfers:
196 *
197 * - Stage 1:
198 * - A (possible) transfer gets announced by the guest by announcing the format VBOX_SHCL_FMT_URI_LIST to the host.
199 * - Stage 2:
200 * - As soon as the host wants to make use of the transfer ("pasting into file manager"),
201 * it creates and initialized a transfer (with a transfer ID) locally and reports it to the guest with an INITIALIZED status.
202 * - The guest receives the INITIALIZED status from the host and creates + initializes a transfer on its
203 * side with the transfer ID received from the host.
204 */
205
206
207/*********************************************************************************************************************************
208* Header Files *
209*********************************************************************************************************************************/
210#define LOG_GROUP LOG_GROUP_SHARED_CLIPBOARD
211#include <VBox/log.h>
212#include <VBox/vmm/vmmr3vtable.h> /* must be included before hgcmsvc.h */
213
214#include <VBox/GuestHost/clipboard-helper.h>
215#include <VBox/HostServices/Service.h>
216#include <VBox/HostServices/VBoxClipboardSvc.h>
217#include <VBox/HostServices/VBoxClipboardExt.h>
218
219#include <VBox/AssertGuest.h>
220#include <VBox/err.h>
221#include <VBox/VMMDev.h>
222#include <VBox/vmm/ssm.h>
223
224#include <iprt/mem.h>
225#include <iprt/string.h>
226#include <iprt/assert.h>
227#include <iprt/critsect.h>
228#include <iprt/rand.h>
229
230#include "VBoxSharedClipboardSvc-internal.h"
231#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
232# include "VBoxSharedClipboardSvc-transfers.h"
233#endif
234
235using namespace HGCM;
236
237
238/*********************************************************************************************************************************
239* Defined Constants And Macros *
240*********************************************************************************************************************************/
241/** @name The saved state versions for the shared clipboard service.
242 *
243 * @note We set bit 31 because prior to version 0x80000002 there would be a
244 * structure size rather than a version number. Setting bit 31 dispells
245 * any possible ambiguity.
246 *
247 * @{ */
248/** The current saved state version. */
249#define VBOX_SHCL_SAVED_STATE_VER_CURRENT VBOX_SHCL_SAVED_STATE_LEGACY_CID
250/** Adds the legacy context ID list. */
251#define VBOX_SHCL_SAVED_STATE_LEGACY_CID UINT32_C(0x80000005)
252/** Adds the client's POD state and client state flags.
253 * @since 6.1 RC1 */
254#define VBOX_SHCL_SAVED_STATE_VER_6_1RC1 UINT32_C(0x80000004)
255/** First attempt saving state during @bugref{9437} development.
256 * @since 6.1 BETA 2 */
257#define VBOX_SHCL_SAVED_STATE_VER_6_1B2 UINT32_C(0x80000003)
258/** First structured version.
259 * @since 3.1 / r53668 */
260#define VBOX_SHCL_SAVED_STATE_VER_3_1 UINT32_C(0x80000002)
261/** This was just a state memory dump, including pointers and everything.
262 * @note This is not supported any more. Sorry. */
263#define VBOX_SHCL_SAVED_STATE_VER_NOT_SUPP (ARCH_BITS == 64 ? UINT32_C(72) : UINT32_C(48))
264/** @} */
265
266
267/*********************************************************************************************************************************
268* Global Variables *
269*********************************************************************************************************************************/
270/** The backend instance data.
271 * Only one backend at a time is supported currently. */
272SHCLBACKEND g_ShClBackend;
273PVBOXHGCMSVCHELPERS g_pHelpers;
274
275static RTCRITSECT g_CritSect; /** @todo r=andy Put this into some instance struct, avoid globals. */
276/** Global Shared Clipboard mode. */
277static uint32_t g_uMode = VBOX_SHCL_MODE_OFF;
278#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
279/** Global Shared Clipboard (file) transfer mode. */
280uint32_t g_fTransferMode = VBOX_SHCL_TRANSFER_MODE_F_NONE;
281#endif
282
283/** Is the clipboard running in headless mode? */
284static bool g_fHeadless = false;
285
286/** Holds the service extension state. */
287SHCLEXTSTATE g_ExtState = { 0 };
288
289/** Global map of all connected clients. */
290ClipboardClientMap g_mapClients;
291
292/** Global list of all clients which are queued up (deferred return) and ready
293 * to process new commands. The key is the (unique) client ID. */
294ClipboardClientQueue g_listClientsDeferred;
295
296/** Host feature mask (VBOX_SHCL_HF_0_XXX) for VBOX_SHCL_GUEST_FN_REPORT_FEATURES
297 * and VBOX_SHCL_GUEST_FN_QUERY_FEATURES. */
298static uint64_t const g_fHostFeatures0 = VBOX_SHCL_HF_0_CONTEXT_ID
299#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
300 | VBOX_SHCL_HF_0_TRANSFERS
301#endif
302 ;
303
304
305/**
306 * Returns the current Shared Clipboard service mode.
307 *
308 * @returns Current Shared Clipboard service mode.
309 */
310uint32_t ShClSvcGetMode(void)
311{
312 return g_uMode;
313}
314
315/**
316 * Returns the Shared Clipboard backend in use.
317 *
318 * @returns Pointer to backend instance.
319 */
320PSHCLBACKEND ShClSvcGetBackend(void)
321{
322 return &g_ShClBackend;
323}
324
325/**
326 * Getter for headless setting. Also needed by testcase.
327 *
328 * @returns Whether service currently running in headless mode or not.
329 */
330bool ShClSvcGetHeadless(void)
331{
332 return g_fHeadless;
333}
334
335static int shClSvcModeSet(uint32_t uMode)
336{
337 int rc = VERR_NOT_SUPPORTED;
338
339 switch (uMode)
340 {
341 case VBOX_SHCL_MODE_OFF:
342 RT_FALL_THROUGH();
343 case VBOX_SHCL_MODE_HOST_TO_GUEST:
344 RT_FALL_THROUGH();
345 case VBOX_SHCL_MODE_GUEST_TO_HOST:
346 RT_FALL_THROUGH();
347 case VBOX_SHCL_MODE_BIDIRECTIONAL:
348 {
349 g_uMode = uMode;
350
351 rc = VINF_SUCCESS;
352 break;
353 }
354
355 default:
356 {
357 g_uMode = VBOX_SHCL_MODE_OFF;
358 break;
359 }
360 }
361
362 LogFlowFuncLeaveRC(rc);
363 return rc;
364}
365
366/**
367 * Takes the global Shared Clipboard service lock.
368 *
369 * @returns \c true if locking was successful, or \c false if not.
370 */
371bool ShClSvcLock(void)
372{
373 return RT_SUCCESS(RTCritSectEnter(&g_CritSect));
374}
375
376/**
377 * Unlocks the formerly locked global Shared Clipboard service lock.
378 */
379void ShClSvcUnlock(void)
380{
381 int rc2 = RTCritSectLeave(&g_CritSect);
382 AssertRC(rc2);
383}
384
385/**
386 * Resets a client's state message queue.
387 *
388 * @param pClient Pointer to the client data structure to reset message queue for.
389 * @note Caller enters pClient->CritSect.
390 */
391void shClSvcMsgQueueReset(PSHCLCLIENT pClient)
392{
393 Assert(RTCritSectIsOwner(&pClient->CritSect));
394 LogFlowFuncEnter();
395
396 while (!RTListIsEmpty(&pClient->MsgQueue))
397 {
398 PSHCLCLIENTMSG pMsg = RTListRemoveFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
399 shClSvcMsgFree(pClient, pMsg);
400 }
401 pClient->cMsgAllocated = 0;
402
403 while (!RTListIsEmpty(&pClient->Legacy.lstCID))
404 {
405 PSHCLCLIENTLEGACYCID pCID = RTListRemoveFirst(&pClient->Legacy.lstCID, SHCLCLIENTLEGACYCID, Node);
406 RTMemFree(pCID);
407 }
408 pClient->Legacy.cCID = 0;
409}
410
411/**
412 * Allocates a new clipboard message.
413 *
414 * @returns Allocated clipboard message, or NULL on failure.
415 * @param pClient The client which is target of this message.
416 * @param idMsg The message ID (VBOX_SHCL_HOST_MSG_XXX) to use
417 * @param cParms The number of parameters the message takes.
418 */
419PSHCLCLIENTMSG shClSvcMsgAlloc(PSHCLCLIENT pClient, uint32_t idMsg, uint32_t cParms)
420{
421 RT_NOREF(pClient);
422 PSHCLCLIENTMSG pMsg = (PSHCLCLIENTMSG)RTMemAllocZ(RT_UOFFSETOF_DYN(SHCLCLIENTMSG, aParms[cParms]));
423 if (pMsg)
424 {
425 uint32_t cAllocated = ASMAtomicIncU32(&pClient->cMsgAllocated);
426 if (cAllocated <= 4096)
427 {
428 RTListInit(&pMsg->ListEntry);
429 pMsg->cParms = cParms;
430 pMsg->idMsg = idMsg;
431 return pMsg;
432 }
433 AssertMsgFailed(("Too many messages allocated for client %u! (%u)\n", pClient->State.uClientID, cAllocated));
434 ASMAtomicDecU32(&pClient->cMsgAllocated);
435 RTMemFree(pMsg);
436 }
437 return NULL;
438}
439
440/**
441 * Frees a formerly allocated clipboard message.
442 *
443 * @param pClient The client which was the target of this message.
444 * @param pMsg Clipboard message to free.
445 */
446void shClSvcMsgFree(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg)
447{
448 RT_NOREF(pClient);
449 /** @todo r=bird: Do accounting. */
450 if (pMsg)
451 {
452 pMsg->idMsg = UINT32_C(0xdeadface);
453 RTMemFree(pMsg);
454
455 uint32_t cAllocated = ASMAtomicDecU32(&pClient->cMsgAllocated);
456 Assert(cAllocated < UINT32_MAX / 2);
457 RT_NOREF(cAllocated);
458 }
459}
460
461/**
462 * Sets the VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT and VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT
463 * return parameters.
464 *
465 * @param pMsg Message to set return parameters to.
466 * @param paDstParms The peek parameter vector.
467 * @param cDstParms The number of peek parameters (at least two).
468 * @remarks ASSUMES the parameters has been cleared by clientMsgPeek.
469 */
470static void shClSvcMsgSetPeekReturn(PSHCLCLIENTMSG pMsg, PVBOXHGCMSVCPARM paDstParms, uint32_t cDstParms)
471{
472 Assert(cDstParms >= 2);
473 if (paDstParms[0].type == VBOX_HGCM_SVC_PARM_32BIT)
474 paDstParms[0].u.uint32 = pMsg->idMsg;
475 else
476 paDstParms[0].u.uint64 = pMsg->idMsg;
477 paDstParms[1].u.uint32 = pMsg->cParms;
478
479 uint32_t i = RT_MIN(cDstParms, pMsg->cParms + 2);
480 while (i-- > 2)
481 switch (pMsg->aParms[i - 2].type)
482 {
483 case VBOX_HGCM_SVC_PARM_32BIT: paDstParms[i].u.uint32 = ~(uint32_t)sizeof(uint32_t); break;
484 case VBOX_HGCM_SVC_PARM_64BIT: paDstParms[i].u.uint32 = ~(uint32_t)sizeof(uint64_t); break;
485 case VBOX_HGCM_SVC_PARM_PTR: paDstParms[i].u.uint32 = pMsg->aParms[i - 2].u.pointer.size; break;
486 }
487}
488
489/**
490 * Sets the VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT return parameters.
491 *
492 * @returns VBox status code.
493 * @param pMsg The message which parameters to return to the guest.
494 * @param paDstParms The peek parameter vector.
495 * @param cDstParms The number of peek parameters should be exactly two
496 */
497static int shClSvcMsgSetOldWaitReturn(PSHCLCLIENTMSG pMsg, PVBOXHGCMSVCPARM paDstParms, uint32_t cDstParms)
498{
499 /*
500 * Assert sanity.
501 */
502 AssertPtr(pMsg);
503 AssertPtrReturn(paDstParms, VERR_INVALID_POINTER);
504 AssertReturn(cDstParms >= 2, VERR_INVALID_PARAMETER);
505
506 Assert(pMsg->cParms == 2);
507 Assert(pMsg->aParms[0].u.uint32 == pMsg->idMsg);
508 switch (pMsg->idMsg)
509 {
510 case VBOX_SHCL_HOST_MSG_READ_DATA:
511 case VBOX_SHCL_HOST_MSG_FORMATS_REPORT:
512 break;
513 default:
514 AssertFailed();
515 }
516
517 /*
518 * Set the parameters.
519 */
520 if (pMsg->cParms > 0)
521 paDstParms[0] = pMsg->aParms[0];
522 if (pMsg->cParms > 1)
523 paDstParms[1] = pMsg->aParms[1];
524 return VINF_SUCCESS;
525}
526
527/**
528 * Adds a new message to a client'S message queue.
529 *
530 * @param pClient Pointer to the client data structure to add new message to.
531 * @param pMsg Pointer to message to add. The queue then owns the pointer.
532 * @param fAppend Whether to append or prepend the message to the queue.
533 *
534 * @note Caller must enter critical section.
535 */
536void shClSvcMsgAdd(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg, bool fAppend)
537{
538 Assert(RTCritSectIsOwner(&pClient->CritSect));
539 AssertPtr(pMsg);
540
541 LogFlowFunc(("idMsg=%s (%RU32) cParms=%RU32 fAppend=%RTbool\n",
542 ShClHostMsgToStr(pMsg->idMsg), pMsg->idMsg, pMsg->cParms, fAppend));
543
544 if (fAppend)
545 RTListAppend(&pClient->MsgQueue, &pMsg->ListEntry);
546 else
547 RTListPrepend(&pClient->MsgQueue, &pMsg->ListEntry);
548}
549
550
551/**
552 * Appends a message to the client's queue and wake it up.
553 *
554 * @returns VBox status code, though the message is consumed regardless of what
555 * is returned.
556 * @param pClient The client to queue the message on.
557 * @param pMsg The message to queue. Ownership is always
558 * transfered to the queue.
559 *
560 * @note Caller must enter critical section.
561 */
562int shClSvcMsgAddAndWakeupClient(PSHCLCLIENT pClient, PSHCLCLIENTMSG pMsg)
563{
564 Assert(RTCritSectIsOwner(&pClient->CritSect));
565 AssertPtr(pMsg);
566 AssertPtr(pClient);
567 LogFlowFunc(("idMsg=%s (%u) cParms=%u\n", ShClHostMsgToStr(pMsg->idMsg), pMsg->idMsg, pMsg->cParms));
568
569 RTListAppend(&pClient->MsgQueue, &pMsg->ListEntry);
570 return shClSvcClientWakeup(pClient); /** @todo r=andy Remove message if waking up failed? */
571}
572
573/**
574 * Initializes a Shared Clipboard client.
575 *
576 * @param pClient Client to initialize.
577 * @param uClientID HGCM client ID to assign client to.
578 */
579int shClSvcClientInit(PSHCLCLIENT pClient, uint32_t uClientID)
580{
581 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
582
583 /* Assign the client ID. */
584 pClient->State.uClientID = uClientID;
585
586 RTListInit(&pClient->MsgQueue);
587 pClient->cMsgAllocated = 0;
588
589 RTListInit(&pClient->Legacy.lstCID);
590 pClient->Legacy.cCID = 0;
591
592 LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));
593
594 int rc = RTCritSectInit(&pClient->CritSect);
595 if (RT_SUCCESS(rc))
596 {
597 /* Create the client's own event source. */
598 rc = ShClEventSourceCreate(&pClient->EventSrc, 0 /* ID, ignored */);
599 if (RT_SUCCESS(rc))
600 {
601 LogFlowFunc(("[Client %RU32] Using event source %RU32\n", uClientID, pClient->EventSrc.uID));
602
603 /* Reset the client state. */
604 shclSvcClientStateReset(&pClient->State);
605
606 /* (Re-)initialize the client state. */
607 rc = shClSvcClientStateInit(&pClient->State, uClientID);
608
609#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
610 if (RT_SUCCESS(rc))
611 rc = ShClTransferCtxInit(&pClient->Transfers.Ctx);
612#endif
613 }
614 }
615
616 LogFlowFuncLeaveRC(rc);
617 return rc;
618}
619
620/**
621 * Destroys a Shared Clipboard client.
622 *
623 * @param pClient Client to destroy.
624 */
625void shClSvcClientDestroy(PSHCLCLIENT pClient)
626{
627 AssertPtrReturnVoid(pClient);
628
629 LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));
630
631 /* Make sure to send a quit message to the guest so that it can terminate gracefully. */
632 shClSvcClientLock(pClient);
633
634 if (pClient->Pending.uType)
635 {
636 if (pClient->Pending.cParms > 1)
637 HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_QUIT);
638 if (pClient->Pending.cParms > 2)
639 HGCMSvcSetU32(&pClient->Pending.paParms[1], 0);
640 g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, VINF_SUCCESS);
641 pClient->Pending.uType = 0;
642 pClient->Pending.cParms = 0;
643 pClient->Pending.hHandle = NULL;
644 pClient->Pending.paParms = NULL;
645 }
646
647#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
648 shClSvcTransferDestroyAll(pClient);
649 ShClTransferCtxDestroy(&pClient->Transfers.Ctx);
650#endif
651
652 ShClEventSourceDestroy(&pClient->EventSrc);
653
654 shClSvcClientUnlock(pClient);
655
656 shClSvcClientStateDestroy(&pClient->State);
657
658 PSHCLCLIENTLEGACYCID pCidIter, pCidIterNext;
659 RTListForEachSafe(&pClient->Legacy.lstCID, pCidIter, pCidIterNext, SHCLCLIENTLEGACYCID, Node)
660 RTMemFree(pCidIter);
661
662 int rc2 = RTCritSectDelete(&pClient->CritSect);
663 AssertRC(rc2);
664
665 ClipboardClientMap::iterator itClient = g_mapClients.find(pClient->State.uClientID);
666 if (itClient != g_mapClients.end())
667 g_mapClients.erase(itClient);
668 else
669 AssertFailed();
670
671 LogFlowFuncLeave();
672}
673
674void shClSvcClientLock(PSHCLCLIENT pClient)
675{
676 int rc2 = RTCritSectEnter(&pClient->CritSect);
677 AssertRC(rc2);
678}
679
680void shClSvcClientUnlock(PSHCLCLIENT pClient)
681{
682 int rc2 = RTCritSectLeave(&pClient->CritSect);
683 AssertRC(rc2);
684}
685
686/**
687 * Resets a Shared Clipboard client.
688 *
689 * @param pClient Client to reset.
690 */
691void shClSvcClientReset(PSHCLCLIENT pClient)
692{
693 if (!pClient)
694 return;
695
696 LogFlowFunc(("[Client %RU32]\n", pClient->State.uClientID));
697 RTCritSectEnter(&pClient->CritSect);
698
699 /* Reset message queue. */
700 shClSvcMsgQueueReset(pClient);
701
702 /* Reset event source. */
703 ShClEventSourceReset(&pClient->EventSrc);
704
705 /* Reset pending state. */
706 RT_ZERO(pClient->Pending);
707
708#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
709 shClSvcTransferDestroyAll(pClient);
710#endif
711
712 shclSvcClientStateReset(&pClient->State);
713
714 RTCritSectLeave(&pClient->CritSect);
715}
716
717static int shClSvcClientNegogiateChunkSize(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall,
718 uint32_t cParms, VBOXHGCMSVCPARM paParms[])
719{
720 /*
721 * Validate the request.
722 */
723 ASSERT_GUEST_RETURN(cParms == VBOX_SHCL_CPARMS_NEGOTIATE_CHUNK_SIZE, VERR_WRONG_PARAMETER_COUNT);
724 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
725 uint32_t const cbClientMaxChunkSize = paParms[0].u.uint32;
726 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
727 uint32_t const cbClientChunkSize = paParms[1].u.uint32;
728
729 uint32_t const cbHostMaxChunkSize = VBOX_SHCL_MAX_CHUNK_SIZE; /** @todo Make this configurable. */
730
731 /*
732 * Do the work.
733 */
734 if (cbClientChunkSize == 0) /* Does the client want us to choose? */
735 {
736 paParms[0].u.uint32 = cbHostMaxChunkSize; /* Maximum */
737 paParms[1].u.uint32 = RT_MIN(pClient->State.cbChunkSize, cbHostMaxChunkSize); /* Preferred */
738
739 }
740 else /* The client told us what it supports, so update and report back. */
741 {
742 paParms[0].u.uint32 = RT_MIN(cbClientMaxChunkSize, cbHostMaxChunkSize); /* Maximum */
743 paParms[1].u.uint32 = RT_MIN(cbClientMaxChunkSize, pClient->State.cbChunkSize); /* Preferred */
744 }
745
746 int rc = g_pHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
747 if (RT_SUCCESS(rc))
748 {
749 Log(("[Client %RU32] chunk size: %#RU32, max: %#RU32\n",
750 pClient->State.uClientID, paParms[1].u.uint32, paParms[0].u.uint32));
751 }
752 else
753 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
754
755 return VINF_HGCM_ASYNC_EXECUTE;
756}
757
758/**
759 * Implements VBOX_SHCL_GUEST_FN_REPORT_FEATURES.
760 *
761 * @returns VBox status code.
762 * @retval VINF_HGCM_ASYNC_EXECUTE on success (we complete the message here).
763 * @retval VERR_ACCESS_DENIED if not master
764 * @retval VERR_INVALID_PARAMETER if bit 63 in the 2nd parameter isn't set.
765 * @retval VERR_WRONG_PARAMETER_COUNT
766 *
767 * @param pClient The client state.
768 * @param hCall The client's call handle.
769 * @param cParms Number of parameters.
770 * @param paParms Array of parameters.
771 */
772static int shClSvcClientReportFeatures(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall,
773 uint32_t cParms, VBOXHGCMSVCPARM paParms[])
774{
775 /*
776 * Validate the request.
777 */
778 ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
779 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
780 uint64_t const fFeatures0 = paParms[0].u.uint64;
781 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
782 uint64_t const fFeatures1 = paParms[1].u.uint64;
783 ASSERT_GUEST_RETURN(fFeatures1 & VBOX_SHCL_GF_1_MUST_BE_ONE, VERR_INVALID_PARAMETER);
784
785 /*
786 * Do the work.
787 */
788 paParms[0].u.uint64 = g_fHostFeatures0;
789 paParms[1].u.uint64 = 0;
790
791 int rc = g_pHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
792 if (RT_SUCCESS(rc))
793 {
794 pClient->State.fGuestFeatures0 = fFeatures0;
795 pClient->State.fGuestFeatures1 = fFeatures1;
796 LogRel2(("Shared Clipboard: Guest reported the following features: %#RX64\n",
797 pClient->State.fGuestFeatures0)); /* Note: fFeatures1 not used yet. */
798 if (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_TRANSFERS)
799 LogRel2(("Shared Clipboard: Guest supports file transfers\n"));
800 }
801 else
802 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
803
804 return VINF_HGCM_ASYNC_EXECUTE;
805}
806
807/**
808 * Implements VBOX_SHCL_GUEST_FN_QUERY_FEATURES.
809 *
810 * @returns VBox status code.
811 * @retval VINF_HGCM_ASYNC_EXECUTE on success (we complete the message here).
812 * @retval VERR_WRONG_PARAMETER_COUNT
813 *
814 * @param hCall The client's call handle.
815 * @param cParms Number of parameters.
816 * @param paParms Array of parameters.
817 */
818static int shClSvcClientQueryFeatures(VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
819{
820 /*
821 * Validate the request.
822 */
823 ASSERT_GUEST_RETURN(cParms == 2, VERR_WRONG_PARAMETER_COUNT);
824 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
825 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
826 ASSERT_GUEST(paParms[1].u.uint64 & RT_BIT_64(63));
827
828 /*
829 * Do the work.
830 */
831 paParms[0].u.uint64 = g_fHostFeatures0;
832 paParms[1].u.uint64 = 0;
833 int rc = g_pHelpers->pfnCallComplete(hCall, VINF_SUCCESS);
834 if (RT_FAILURE(rc))
835 LogFunc(("pfnCallComplete -> %Rrc\n", rc));
836
837 return VINF_HGCM_ASYNC_EXECUTE;
838}
839
840/**
841 * Implements VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT and VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT.
842 *
843 * @returns VBox status code.
844 * @retval VINF_SUCCESS if a message was pending and is being returned.
845 * @retval VERR_TRY_AGAIN if no message pending and not blocking.
846 * @retval VERR_RESOURCE_BUSY if another read already made a waiting call.
847 * @retval VINF_HGCM_ASYNC_EXECUTE if message wait is pending.
848 *
849 * @param pClient The client state.
850 * @param hCall The client's call handle.
851 * @param cParms Number of parameters.
852 * @param paParms Array of parameters.
853 * @param fWait Set if we should wait for a message, clear if to return
854 * immediately.
855 *
856 * @note Caller takes and leave the client's critical section.
857 */
858static int shClSvcClientMsgPeek(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[], bool fWait)
859{
860 /*
861 * Validate the request.
862 */
863 ASSERT_GUEST_MSG_RETURN(cParms >= 2, ("cParms=%u!\n", cParms), VERR_WRONG_PARAMETER_COUNT);
864
865 uint64_t idRestoreCheck = 0;
866 uint32_t i = 0;
867 if (paParms[i].type == VBOX_HGCM_SVC_PARM_64BIT)
868 {
869 idRestoreCheck = paParms[0].u.uint64;
870 paParms[0].u.uint64 = 0;
871 i++;
872 }
873 for (; i < cParms; i++)
874 {
875 ASSERT_GUEST_MSG_RETURN(paParms[i].type == VBOX_HGCM_SVC_PARM_32BIT, ("#%u type=%u\n", i, paParms[i].type),
876 VERR_WRONG_PARAMETER_TYPE);
877 paParms[i].u.uint32 = 0;
878 }
879
880 /*
881 * Check restore session ID.
882 */
883 if (idRestoreCheck != 0)
884 {
885 uint64_t idRestore = g_pHelpers->pfnGetVMMDevSessionId(g_pHelpers);
886 if (idRestoreCheck != idRestore)
887 {
888 paParms[0].u.uint64 = idRestore;
889 LogFlowFunc(("[Client %RU32] VBOX_SHCL_GUEST_FN_MSG_PEEK_XXX -> VERR_VM_RESTORED (%#RX64 -> %#RX64)\n",
890 pClient->State.uClientID, idRestoreCheck, idRestore));
891 return VERR_VM_RESTORED;
892 }
893 Assert(!g_pHelpers->pfnIsCallRestored(hCall));
894 }
895
896 /*
897 * Return information about the first message if one is pending in the list.
898 */
899 PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
900 if (pFirstMsg)
901 {
902 shClSvcMsgSetPeekReturn(pFirstMsg, paParms, cParms);
903 LogFlowFunc(("[Client %RU32] VBOX_SHCL_GUEST_FN_MSG_PEEK_XXX -> VINF_SUCCESS (idMsg=%s (%u), cParms=%u)\n",
904 pClient->State.uClientID, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
905 return VINF_SUCCESS;
906 }
907
908 /*
909 * If we cannot wait, fail the call.
910 */
911 if (!fWait)
912 {
913 LogFlowFunc(("[Client %RU32] GUEST_MSG_PEEK_NOWAIT -> VERR_TRY_AGAIN\n", pClient->State.uClientID));
914 return VERR_TRY_AGAIN;
915 }
916
917 /*
918 * Wait for the host to queue a message for this client.
919 */
920 ASSERT_GUEST_MSG_RETURN(pClient->Pending.uType == 0, ("Already pending! (idClient=%RU32)\n",
921 pClient->State.uClientID), VERR_RESOURCE_BUSY);
922 pClient->Pending.hHandle = hCall;
923 pClient->Pending.cParms = cParms;
924 pClient->Pending.paParms = paParms;
925 pClient->Pending.uType = VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT;
926 LogFlowFunc(("[Client %RU32] Is now in pending mode...\n", pClient->State.uClientID));
927 return VINF_HGCM_ASYNC_EXECUTE;
928}
929
930/**
931 * Implements VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT.
932 *
933 * @returns VBox status code.
934 * @retval VINF_SUCCESS if a message was pending and is being returned.
935 * @retval VINF_HGCM_ASYNC_EXECUTE if message wait is pending.
936 *
937 * @param pClient The client state.
938 * @param hCall The client's call handle.
939 * @param cParms Number of parameters.
940 * @param paParms Array of parameters.
941 *
942 * @note Caller takes and leave the client's critical section.
943 */
944static int shClSvcClientMsgOldGet(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
945{
946 /*
947 * Validate input.
948 */
949 ASSERT_GUEST_RETURN(cParms == VBOX_SHCL_CPARMS_GET_HOST_MSG_OLD, VERR_WRONG_PARAMETER_COUNT);
950 ASSERT_GUEST_RETURN(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* id32Msg */
951 ASSERT_GUEST_RETURN(paParms[1].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* f32Formats */
952
953 paParms[0].u.uint32 = 0;
954 paParms[1].u.uint32 = 0;
955
956 /*
957 * If there is a message pending we can return immediately.
958 */
959 int rc;
960 PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
961 if (pFirstMsg)
962 {
963 LogFlowFunc(("[Client %RU32] uMsg=%s (%RU32), cParms=%RU32\n", pClient->State.uClientID,
964 ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
965
966 rc = shClSvcMsgSetOldWaitReturn(pFirstMsg, paParms, cParms);
967 AssertPtr(g_pHelpers);
968 rc = g_pHelpers->pfnCallComplete(hCall, rc);
969 if (rc != VERR_CANCELLED)
970 {
971 RTListNodeRemove(&pFirstMsg->ListEntry);
972 shClSvcMsgFree(pClient, pFirstMsg);
973
974 rc = VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
975 }
976 }
977 /*
978 * Otherwise we must wait.
979 */
980 else
981 {
982 ASSERT_GUEST_MSG_RETURN(pClient->Pending.uType == 0, ("Already pending! (idClient=%RU32)\n", pClient->State.uClientID),
983 VERR_RESOURCE_BUSY);
984
985 pClient->Pending.hHandle = hCall;
986 pClient->Pending.cParms = cParms;
987 pClient->Pending.paParms = paParms;
988 pClient->Pending.uType = VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT;
989
990 rc = VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
991
992 LogFlowFunc(("[Client %RU32] Is now in pending mode...\n", pClient->State.uClientID));
993 }
994
995 LogFlowFunc(("[Client %RU32] rc=%Rrc\n", pClient->State.uClientID, rc));
996 return rc;
997}
998
999/**
1000 * Implements VBOX_SHCL_GUEST_FN_MSG_GET.
1001 *
1002 * @returns VBox status code.
1003 * @retval VINF_SUCCESS if message retrieved and removed from the pending queue.
1004 * @retval VERR_TRY_AGAIN if no message pending.
1005 * @retval VERR_BUFFER_OVERFLOW if a parmeter buffer is too small. The buffer
1006 * size was updated to reflect the required size, though this isn't yet
1007 * forwarded to the guest. (The guest is better of using peek with
1008 * parameter count + 2 parameters to get the sizes.)
1009 * @retval VERR_MISMATCH if the incoming message ID does not match the pending.
1010 * @retval VINF_HGCM_ASYNC_EXECUTE if message was completed already.
1011 *
1012 * @param pClient The client state.
1013 * @param hCall The client's call handle.
1014 * @param cParms Number of parameters.
1015 * @param paParms Array of parameters.
1016 *
1017 * @note Called from within pClient->CritSect.
1018 */
1019static int shClSvcClientMsgGet(PSHCLCLIENT pClient, VBOXHGCMCALLHANDLE hCall, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1020{
1021 /*
1022 * Validate the request.
1023 */
1024 uint32_t const idMsgExpected = cParms > 0 && paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT ? paParms[0].u.uint32
1025 : cParms > 0 && paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT ? paParms[0].u.uint64
1026 : UINT32_MAX;
1027
1028 /*
1029 * Return information about the first message if one is pending in the list.
1030 */
1031 PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
1032 if (pFirstMsg)
1033 {
1034 LogFlowFunc(("First message is: %s (%u), cParms=%RU32\n", ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
1035
1036 ASSERT_GUEST_MSG_RETURN(pFirstMsg->idMsg == idMsgExpected || idMsgExpected == UINT32_MAX,
1037 ("idMsg=%u (%s) cParms=%u, caller expected %u (%s) and %u\n",
1038 pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->cParms,
1039 idMsgExpected, ShClHostMsgToStr(idMsgExpected), cParms),
1040 VERR_MISMATCH);
1041 ASSERT_GUEST_MSG_RETURN(pFirstMsg->cParms == cParms,
1042 ("idMsg=%u (%s) cParms=%u, caller expected %u (%s) and %u\n",
1043 pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->cParms,
1044 idMsgExpected, ShClHostMsgToStr(idMsgExpected), cParms),
1045 VERR_WRONG_PARAMETER_COUNT);
1046
1047 /* Check the parameter types. */
1048 for (uint32_t i = 0; i < cParms; i++)
1049 ASSERT_GUEST_MSG_RETURN(pFirstMsg->aParms[i].type == paParms[i].type,
1050 ("param #%u: type %u, caller expected %u (idMsg=%u %s)\n", i, pFirstMsg->aParms[i].type,
1051 paParms[i].type, pFirstMsg->idMsg, ShClHostMsgToStr(pFirstMsg->idMsg)),
1052 VERR_WRONG_PARAMETER_TYPE);
1053 /*
1054 * Copy out the parameters.
1055 *
1056 * No assertions on buffer overflows, and keep going till the end so we can
1057 * communicate all the required buffer sizes.
1058 */
1059 int rc = VINF_SUCCESS;
1060 for (uint32_t i = 0; i < cParms; i++)
1061 switch (pFirstMsg->aParms[i].type)
1062 {
1063 case VBOX_HGCM_SVC_PARM_32BIT:
1064 paParms[i].u.uint32 = pFirstMsg->aParms[i].u.uint32;
1065 break;
1066
1067 case VBOX_HGCM_SVC_PARM_64BIT:
1068 paParms[i].u.uint64 = pFirstMsg->aParms[i].u.uint64;
1069 break;
1070
1071 case VBOX_HGCM_SVC_PARM_PTR:
1072 {
1073 uint32_t const cbSrc = pFirstMsg->aParms[i].u.pointer.size;
1074 uint32_t const cbDst = paParms[i].u.pointer.size;
1075 paParms[i].u.pointer.size = cbSrc; /** @todo Check if this is safe in other layers...
1076 * Update: Safe, yes, but VMMDevHGCM doesn't pass it along. */
1077 if (cbSrc <= cbDst)
1078 memcpy(paParms[i].u.pointer.addr, pFirstMsg->aParms[i].u.pointer.addr, cbSrc);
1079 else
1080 {
1081 AssertMsgFailed(("#%u: cbSrc=%RU32 is bigger than cbDst=%RU32\n", i, cbSrc, cbDst));
1082 rc = VERR_BUFFER_OVERFLOW;
1083 }
1084 break;
1085 }
1086
1087 default:
1088 AssertMsgFailed(("#%u: %u\n", i, pFirstMsg->aParms[i].type));
1089 rc = VERR_INTERNAL_ERROR;
1090 break;
1091 }
1092 if (RT_SUCCESS(rc))
1093 {
1094 /*
1095 * Complete the message and remove the pending message unless the
1096 * guest raced us and cancelled this call in the meantime.
1097 */
1098 AssertPtr(g_pHelpers);
1099 rc = g_pHelpers->pfnCallComplete(hCall, rc);
1100
1101 LogFlowFunc(("[Client %RU32] pfnCallComplete -> %Rrc\n", pClient->State.uClientID, rc));
1102
1103 if (rc != VERR_CANCELLED)
1104 {
1105 RTListNodeRemove(&pFirstMsg->ListEntry);
1106 shClSvcMsgFree(pClient, pFirstMsg);
1107 }
1108
1109 return VINF_HGCM_ASYNC_EXECUTE; /* The caller must not complete it. */
1110 }
1111
1112 LogFlowFunc(("[Client %RU32] Returning %Rrc\n", pClient->State.uClientID, rc));
1113 return rc;
1114 }
1115
1116 paParms[0].u.uint32 = 0;
1117 paParms[1].u.uint32 = 0;
1118 LogFlowFunc(("[Client %RU32] -> VERR_TRY_AGAIN\n", pClient->State.uClientID));
1119 return VERR_TRY_AGAIN;
1120}
1121
1122/**
1123 * Implements VBOX_SHCL_GUEST_FN_MSG_GET.
1124 *
1125 * @returns VBox status code.
1126 * @retval VINF_SUCCESS if message retrieved and removed from the pending queue.
1127 * @retval VERR_TRY_AGAIN if no message pending.
1128 * @retval VERR_MISMATCH if the incoming message ID does not match the pending.
1129 * @retval VINF_HGCM_ASYNC_EXECUTE if message was completed already.
1130 *
1131 * @param pClient The client state.
1132 * @param cParms Number of parameters.
1133 *
1134 * @note Called from within pClient->CritSect.
1135 */
1136static int shClSvcClientMsgCancel(PSHCLCLIENT pClient, uint32_t cParms)
1137{
1138 /*
1139 * Validate the request.
1140 */
1141 ASSERT_GUEST_MSG_RETURN(cParms == 0, ("cParms=%u!\n", cParms), VERR_WRONG_PARAMETER_COUNT);
1142
1143 /*
1144 * Execute.
1145 */
1146 if (pClient->Pending.uType != 0)
1147 {
1148 LogFlowFunc(("[Client %RU32] Cancelling waiting thread, isPending=%d, pendingNumParms=%RU32, m_idSession=%x\n",
1149 pClient->State.uClientID, pClient->Pending.uType, pClient->Pending.cParms, pClient->State.uSessionID));
1150
1151 /*
1152 * The PEEK call is simple: At least two parameters, all set to zero before sleeping.
1153 */
1154 int rcComplete;
1155 if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT)
1156 {
1157 Assert(pClient->Pending.cParms >= 2);
1158 if (pClient->Pending.paParms[0].type == VBOX_HGCM_SVC_PARM_64BIT)
1159 HGCMSvcSetU64(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
1160 else
1161 HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
1162 rcComplete = VINF_TRY_AGAIN;
1163 }
1164 /*
1165 * The MSG_OLD call is complicated, though we're
1166 * generally here to wake up someone who is peeking and have two parameters.
1167 * If there aren't two parameters, fail the call.
1168 */
1169 else
1170 {
1171 Assert(pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT);
1172 if (pClient->Pending.cParms > 0)
1173 HGCMSvcSetU32(&pClient->Pending.paParms[0], VBOX_SHCL_HOST_MSG_CANCELED);
1174 if (pClient->Pending.cParms > 1)
1175 HGCMSvcSetU32(&pClient->Pending.paParms[1], 0);
1176 rcComplete = pClient->Pending.cParms == 2 ? VINF_SUCCESS : VERR_TRY_AGAIN;
1177 }
1178
1179 g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, rcComplete);
1180
1181 pClient->Pending.hHandle = NULL;
1182 pClient->Pending.paParms = NULL;
1183 pClient->Pending.cParms = 0;
1184 pClient->Pending.uType = 0;
1185 return VINF_SUCCESS;
1186 }
1187 return VWRN_NOT_FOUND;
1188}
1189
1190
1191/**
1192 * Wakes up a pending client (i.e. waiting for new messages).
1193 *
1194 * @returns VBox status code.
1195 * @retval VINF_NO_CHANGE if the client is not in pending mode.
1196 * @param pClient Client to wake up.
1197 *
1198 * @note Caller must enter critical section.
1199 */
1200int shClSvcClientWakeup(PSHCLCLIENT pClient)
1201{
1202 Assert(RTCritSectIsOwner(&pClient->CritSect));
1203 int rc = VINF_NO_CHANGE;
1204
1205 if (pClient->Pending.uType != 0)
1206 {
1207 LogFunc(("[Client %RU32] Waking up ...\n", pClient->State.uClientID));
1208
1209 PSHCLCLIENTMSG pFirstMsg = RTListGetFirst(&pClient->MsgQueue, SHCLCLIENTMSG, ListEntry);
1210 AssertReturn(pFirstMsg, VERR_INTERNAL_ERROR);
1211
1212 LogFunc(("[Client %RU32] Current host message is %s (%RU32), cParms=%RU32\n",
1213 pClient->State.uClientID, ShClHostMsgToStr(pFirstMsg->idMsg), pFirstMsg->idMsg, pFirstMsg->cParms));
1214
1215 if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT)
1216 shClSvcMsgSetPeekReturn(pFirstMsg, pClient->Pending.paParms, pClient->Pending.cParms);
1217 else if (pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT) /* Legacy, Guest Additions < 6.1. */
1218 shClSvcMsgSetOldWaitReturn(pFirstMsg, pClient->Pending.paParms, pClient->Pending.cParms);
1219 else
1220 AssertMsgFailedReturn(("pClient->Pending.uType=%u\n", pClient->Pending.uType), VERR_INTERNAL_ERROR_3);
1221
1222 rc = g_pHelpers->pfnCallComplete(pClient->Pending.hHandle, VINF_SUCCESS);
1223
1224 if ( rc != VERR_CANCELLED
1225 && pClient->Pending.uType == VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT)
1226 {
1227 RTListNodeRemove(&pFirstMsg->ListEntry);
1228 shClSvcMsgFree(pClient, pFirstMsg);
1229 }
1230
1231 pClient->Pending.hHandle = NULL;
1232 pClient->Pending.paParms = NULL;
1233 pClient->Pending.cParms = 0;
1234 pClient->Pending.uType = 0;
1235 }
1236 else
1237 LogFunc(("[Client %RU32] Not in pending state, skipping wakeup\n", pClient->State.uClientID));
1238
1239 return rc;
1240}
1241
1242/**
1243 * Reads clipboard data from the guest, asynchronous version.
1244 *
1245 * @returns VBox status code.
1246 * @param pClient Client to request to read data form.
1247 * @param fFormats The formats being requested, OR'ed together (VBOX_SHCL_FMT_XXX).
1248 * @param ppEvent Where to return the event for waiting for new data on success.
1249 * Must be released by the caller with ShClEventRelease(). Optional.
1250 *
1251 * @thread On X11: Called from the X11 event thread.
1252 * @thread On Windows: Called from the Windows event thread.
1253 *
1254 * @note This will locally initialize a transfer if VBOX_SHCL_FMT_URI_LIST is being requested from the guest.
1255 */
1256int ShClSvcReadDataFromGuestAsync(PSHCLCLIENT pClient, SHCLFORMATS fFormats, PSHCLEVENT *ppEvent)
1257{
1258 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1259
1260 LogFlowFunc(("fFormats=%#x\n", fFormats));
1261
1262 int rc = VERR_NOT_SUPPORTED;
1263
1264 /* Generate a separate message for every (valid) format we support. */
1265 while (fFormats)
1266 {
1267 /* Pick the next format to get from the mask: */
1268 /** @todo Make format reporting precedence configurable? */
1269 SHCLFORMAT fFormat;
1270 if (fFormats & VBOX_SHCL_FMT_UNICODETEXT)
1271 fFormat = VBOX_SHCL_FMT_UNICODETEXT;
1272 else if (fFormats & VBOX_SHCL_FMT_BITMAP)
1273 fFormat = VBOX_SHCL_FMT_BITMAP;
1274 else if (fFormats & VBOX_SHCL_FMT_HTML)
1275 fFormat = VBOX_SHCL_FMT_HTML;
1276#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1277 else if (fFormats & VBOX_SHCL_FMT_URI_LIST)
1278 fFormat = VBOX_SHCL_FMT_URI_LIST;
1279#endif
1280 else
1281 AssertMsgFailedBreak(("%#x\n", fFormats));
1282
1283 /* Remove it from the mask. */
1284 fFormats &= ~fFormat;
1285
1286#ifdef LOG_ENABLED
1287 char *pszFmt = ShClFormatsToStrA(fFormat);
1288 AssertPtrReturn(pszFmt, VERR_NO_MEMORY);
1289 LogRel2(("Shared Clipboard: Requesting guest clipboard data in format '%s'\n", pszFmt));
1290 RTStrFree(pszFmt);
1291#endif
1292 /*
1293 * Allocate messages, one for each format.
1294 */
1295 PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient,
1296 pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID
1297 ? VBOX_SHCL_HOST_MSG_READ_DATA_CID : VBOX_SHCL_HOST_MSG_READ_DATA,
1298 2);
1299 if (pMsg)
1300 {
1301 shClSvcClientLock(pClient);
1302
1303 PSHCLEVENT pEvent;
1304 rc = ShClEventSourceGenerateAndRegisterEvent(&pClient->EventSrc, &pEvent);
1305 if (RT_SUCCESS(rc))
1306 {
1307 LogFlowFunc(("fFormats=%#x -> fFormat=%#x, idEvent=%#x\n", fFormats, fFormat, pEvent->idEvent));
1308
1309 const uint64_t uCID = VBOX_SHCL_CONTEXTID_MAKE(pClient->State.uSessionID, pClient->EventSrc.uID, pEvent->idEvent);
1310
1311 rc = VINF_SUCCESS;
1312
1313 /* Save the context ID in our legacy cruft if we have to deal with old(er) Guest Additions (< 6.1). */
1314 if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
1315 {
1316 AssertStmt(pClient->Legacy.cCID < 4096, rc = VERR_TOO_MUCH_DATA);
1317 if (RT_SUCCESS(rc))
1318 {
1319 PSHCLCLIENTLEGACYCID pCID = (PSHCLCLIENTLEGACYCID)RTMemAlloc(sizeof(SHCLCLIENTLEGACYCID));
1320 if (pCID)
1321 {
1322 pCID->uCID = uCID;
1323 pCID->enmType = 0; /* Not used yet. */
1324 pCID->uFormat = fFormat;
1325 RTListAppend(&pClient->Legacy.lstCID, &pCID->Node);
1326 pClient->Legacy.cCID++;
1327 }
1328 else
1329 rc = VERR_NO_MEMORY;
1330 }
1331 }
1332
1333 if (RT_SUCCESS(rc))
1334 {
1335 /*
1336 * Format the message.
1337 */
1338 if (pMsg->idMsg == VBOX_SHCL_HOST_MSG_READ_DATA_CID)
1339 HGCMSvcSetU64(&pMsg->aParms[0], uCID);
1340 else
1341 HGCMSvcSetU32(&pMsg->aParms[0], VBOX_SHCL_HOST_MSG_READ_DATA);
1342 HGCMSvcSetU32(&pMsg->aParms[1], fFormat);
1343
1344 shClSvcMsgAdd(pClient, pMsg, true /* fAppend */);
1345 /* Wake up the client to let it know that there are new messages. */
1346 shClSvcClientWakeup(pClient);
1347
1348 /* Return event to caller. */
1349 if (ppEvent)
1350 *ppEvent = pEvent;
1351 }
1352
1353 /* Remove event from list if caller did not request event handle or in case
1354 * of failure (in this case caller should not release event). */
1355 if ( RT_FAILURE(rc)
1356 || !ppEvent)
1357 {
1358 ShClEventRelease(pEvent);
1359 pEvent = NULL;
1360 }
1361 }
1362 else
1363 rc = VERR_SHCLPB_MAX_EVENTS_REACHED;
1364
1365 if (RT_FAILURE(rc))
1366 shClSvcMsgFree(pClient, pMsg);
1367
1368 shClSvcClientUnlock(pClient);
1369 }
1370 else
1371 rc = VERR_NO_MEMORY;
1372
1373 if (RT_FAILURE(rc))
1374 break;
1375 }
1376
1377 if (RT_FAILURE(rc))
1378 LogRel(("Shared Clipboard: Requesting guest clipboard data failed with %Rrc\n", rc));
1379
1380 LogFlowFuncLeaveRC(rc);
1381 return rc;
1382}
1383
1384/**
1385 * Reads clipboard data from the guest.
1386 *
1387 * @returns VBox status code.
1388 * @param pClient Client to request to read data form.
1389 * @param fFormats The formats being requested, OR'ed together (VBOX_SHCL_FMT_XXX).
1390 * @param ppv Where to return the allocated data read.
1391 * Must be free'd by the caller.
1392 * @param pcb Where to return number of bytes read.
1393 */
1394int ShClSvcReadDataFromGuest(PSHCLCLIENT pClient, SHCLFORMAT fFormats, void **ppv, uint32_t *pcb)
1395{
1396 LogFlowFuncEnter();
1397
1398 /* Request data from the guest and wait for data to arrive. */
1399 PSHCLEVENT pEvent;
1400 int rc = ShClSvcReadDataFromGuestAsync(pClient, fFormats, &pEvent);
1401 if (RT_SUCCESS(rc))
1402 {
1403 PSHCLEVENTPAYLOAD pPayload;
1404 rc = ShClEventWait(pEvent, SHCL_TIMEOUT_DEFAULT_MS, &pPayload);
1405 if (RT_SUCCESS(rc))
1406 {
1407 if ( !pPayload
1408 || !pPayload->cbData)
1409 {
1410 rc = VERR_NO_DATA;
1411 }
1412 else
1413 {
1414 *ppv = pPayload->pvData;
1415 *pcb = pPayload->cbData;
1416 }
1417 }
1418
1419 ShClEventRelease(pEvent);
1420 }
1421
1422 if (RT_FAILURE(rc))
1423 LogRel(("Shared Clipboard: Reading data from guest failed with %Rrc\n", rc));
1424
1425 LogFlowFuncLeaveRC(rc);
1426 return rc;
1427}
1428
1429/**
1430 * Signals the host that clipboard data from the guest has been received.
1431 *
1432 * @returns VBox status code. Returns VERR_NOT_FOUND when related event ID was not found.
1433 * @param pClient Client the guest clipboard data was received from.
1434 * @param pCmdCtx Client command context.
1435 * @param uFormat Clipboard format of data received.
1436 * @param pvData Pointer to clipboard data received. This can be
1437 * NULL if @a cbData is zero.
1438 * @param cbData Size (in bytes) of clipboard data received.
1439 * This can be zero.
1440 *
1441 * @thread Backend thread.
1442 */
1443int ShClSvcGuestDataSignal(PSHCLCLIENT pClient, PSHCLCLIENTCMDCTX pCmdCtx, SHCLFORMAT uFormat, void *pvData, uint32_t cbData)
1444{
1445 LogFlowFuncEnter();
1446 RT_NOREF(uFormat);
1447
1448 /*
1449 * Validate input.
1450 */
1451 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1452 AssertPtrReturn(pCmdCtx, VERR_INVALID_POINTER);
1453 if (cbData > 0)
1454 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
1455
1456 const SHCLEVENTID idEvent = VBOX_SHCL_CONTEXTID_GET_EVENT(pCmdCtx->uContextID);
1457 AssertMsgReturn(idEvent != NIL_SHCLEVENTID, ("NIL event in context ID %#RX64\n", pCmdCtx->uContextID), VERR_WRONG_ORDER);
1458
1459 PSHCLEVENT pEvent = ShClEventSourceGetFromId(&pClient->EventSrc, idEvent);
1460 AssertMsgReturn(pEvent != NULL, ("Event %#x not found\n", idEvent), VERR_NOT_FOUND);
1461
1462 /*
1463 * Make a copy of the data so we can attach it to the signal.
1464 *
1465 * Note! We still signal the waiter should we run out of memory,
1466 * because otherwise it will be stuck waiting.
1467 */
1468 int rc = VINF_SUCCESS;
1469 PSHCLEVENTPAYLOAD pPayload = NULL;
1470 if (cbData > 0)
1471 rc = ShClPayloadAlloc(idEvent, pvData, cbData, &pPayload);
1472
1473 /*
1474 * Signal the event.
1475 */
1476 int rc2 = ShClEventSignal(pEvent, pPayload);
1477 if (RT_FAILURE(rc2))
1478 {
1479 rc = rc2;
1480 ShClPayloadFree(pPayload);
1481 LogRel(("Shared Clipboard: Signalling of guest clipboard data to the host failed: %Rrc\n", rc));
1482 }
1483
1484 LogFlowFuncLeaveRC(rc);
1485 return rc;
1486}
1487
1488/**
1489 * Reports clipboard formats to the guest.
1490 *
1491 * @note Host backend callers must check if it's active (use
1492 * ShClSvcIsBackendActive) before calling to prevent mixing up the
1493 * VRDE clipboard.
1494 *
1495 * @returns VBox status code.
1496 * @param pClient Client to report clipboard formats to.
1497 * @param fFormats The formats to report (VBOX_SHCL_FMT_XXX), zero
1498 * is okay (empty the clipboard).
1499 *
1500 * @thread Backend thread.
1501 */
1502int ShClSvcReportFormats(PSHCLCLIENT pClient, SHCLFORMATS fFormats)
1503{
1504 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1505
1506 LogFlowFunc(("fFormats=%#x\n", fFormats));
1507
1508 /*
1509 * Check if the service mode allows this operation and whether the guest is
1510 * supposed to be reading from the host. Otherwise, silently ignore reporting
1511 * formats and return VINF_SUCCESS in order to do not trigger client
1512 * termination in svcConnect().
1513 */
1514 uint32_t uMode = ShClSvcGetMode();
1515 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1516 || uMode == VBOX_SHCL_MODE_HOST_TO_GUEST)
1517 { /* likely */ }
1518 else
1519 return VINF_SUCCESS;
1520
1521#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1522 bool fSkipTransfers = false;
1523 if (!(g_fTransferMode & VBOX_SHCL_TRANSFER_MODE_F_ENABLED))
1524 {
1525 LogRel2(("Shared Clipboard: File transfers are disabled, skipping reporting those to the guest\n"));
1526 fSkipTransfers = true;
1527 }
1528 else if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_TRANSFERS))
1529 {
1530 LogRel2(("Shared Clipboard: File transfers not supported by installed Guest Addtions, skipping reporting those to the guest\n"));
1531 fSkipTransfers = true;
1532 }
1533
1534 if (fSkipTransfers)
1535 fFormats &= ~VBOX_SHCL_FMT_URI_LIST;
1536#endif
1537
1538#ifdef LOG_ENABLED
1539 char *pszFmts = ShClFormatsToStrA(fFormats);
1540 AssertPtrReturn(pszFmts, VERR_NO_MEMORY);
1541 LogRel2(("Shared Clipboard: Reporting formats '%s' to guest\n", pszFmts));
1542 RTStrFree(pszFmts);
1543#endif
1544
1545 int rc;
1546
1547 /*
1548 * Check if the HGCM callback can handle this first.
1549 * This is needed in order to not mess up the clipboard if VRDE is active, for example.
1550 */
1551 if (g_ExtState.pfnExtension) /* Extension set? */
1552 {
1553 SHCLEXTPARMS parms;
1554 RT_ZERO(parms);
1555
1556 parms.u.ReportFormats.uFormats = fFormats;
1557
1558 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_GUEST, &parms, sizeof(parms));
1559 if (rc == VERR_NOT_SUPPORTED)
1560 {
1561 /* Not handled by the extension, continue below. */
1562 }
1563 else /* Handled by the extension, bail out. */
1564 return rc;
1565 }
1566
1567 /*
1568 * Allocate a message, populate parameters and post it to the client.
1569 */
1570 PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient, VBOX_SHCL_HOST_MSG_FORMATS_REPORT, 2);
1571 if (pMsg)
1572 {
1573 HGCMSvcSetU32(&pMsg->aParms[0], VBOX_SHCL_HOST_MSG_FORMATS_REPORT);
1574 HGCMSvcSetU32(&pMsg->aParms[1], fFormats);
1575
1576 shClSvcClientLock(pClient);
1577
1578 rc = shClSvcMsgAddAndWakeupClient(pClient, pMsg);
1579
1580 shClSvcClientUnlock(pClient);
1581 }
1582 else
1583 rc = VERR_NO_MEMORY;
1584
1585 if (RT_FAILURE(rc))
1586 LogRel(("Shared Clipboard: Reporting formats %#x to guest failed with %Rrc\n", fFormats, rc));
1587
1588 LogFlowFuncLeaveRC(rc);
1589 return rc;
1590}
1591
1592
1593/**
1594 * Handles the VBOX_SHCL_GUEST_FN_REPORT_FORMATS message from the guest.
1595 */
1596static int shClSvcClientReportFormats(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1597{
1598 /*
1599 * Check if the service mode allows this operation and whether the guest is
1600 * supposed to be reading from the host.
1601 */
1602 uint32_t uMode = ShClSvcGetMode();
1603 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1604 || uMode == VBOX_SHCL_MODE_GUEST_TO_HOST)
1605 { /* likely */ }
1606 else
1607 return VERR_ACCESS_DENIED;
1608
1609 /*
1610 * Digest parameters.
1611 */
1612 ASSERT_GUEST_RETURN( cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS
1613 || ( cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B
1614 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)),
1615 VERR_WRONG_PARAMETER_COUNT);
1616
1617 uintptr_t iParm = 0;
1618 if (cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B)
1619 {
1620 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1621 /* no defined value, so just ignore it */
1622 iParm++;
1623 }
1624 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1625 uint32_t const fFormats = paParms[iParm].u.uint32;
1626 iParm++;
1627 if (cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B)
1628 {
1629 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1630 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1631 iParm++;
1632 }
1633 Assert(iParm == cParms);
1634
1635 /*
1636 * Report the formats.
1637 *
1638 * We ignore empty reports if the guest isn't the clipboard owner, this
1639 * prevents a freshly booted guest with an empty clibpoard from clearing
1640 * the host clipboard on startup. Likewise, when a guest shutdown it will
1641 * typically issue an empty report in case it's the owner, we don't want
1642 * that to clear host content either.
1643 */
1644 int rc;
1645 if (!fFormats)
1646 rc = VINF_SUCCESS;
1647 else
1648 {
1649 rc = RTCritSectEnter(&g_CritSect);
1650 if (RT_SUCCESS(rc))
1651 {
1652 if (g_ExtState.pfnExtension)
1653 {
1654 SHCLEXTPARMS parms;
1655 RT_ZERO(parms);
1656
1657 parms.u.ReportFormats.uFormats = fFormats;
1658
1659 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_HOST, &parms, sizeof(parms));
1660 }
1661 else
1662 rc = VERR_NOT_SUPPORTED;
1663
1664 /* Let the backend implementation know if the extension above didn't handle the format(s). */
1665 if (rc == VERR_NOT_SUPPORTED)
1666 {
1667#ifdef LOG_ENABLED
1668 char *pszFmts = ShClFormatsToStrA(fFormats);
1669 if (pszFmts)
1670 {
1671 LogRel2(("Shared Clipboard: Guest reported formats '%s' to host\n", pszFmts));
1672 RTStrFree(pszFmts);
1673 }
1674#endif
1675 rc = ShClBackendReportFormats(&g_ShClBackend, pClient, fFormats);
1676 if (RT_FAILURE(rc))
1677 LogRel(("Shared Clipboard: Reporting guest clipboard formats to the host failed with %Rrc\n", rc));
1678 }
1679
1680 RTCritSectLeave(&g_CritSect);
1681 }
1682 else
1683 LogRel2(("Shared Clipboard: Unable to take internal lock while receiving guest clipboard announcement: %Rrc\n", rc));
1684 }
1685
1686 return rc;
1687}
1688
1689/**
1690 * Called when the guest wants to read host clipboard data.
1691 * Handles the VBOX_SHCL_GUEST_FN_DATA_READ message.
1692 *
1693 * @returns VBox status code.
1694 * @retval VINF_BUFFER_OVERFLOW if the guest supplied a smaller buffer than needed in order to read the host clipboard data.
1695 * @param pClient Client that wants to read host clipboard data.
1696 * @param cParms Number of HGCM parameters supplied in \a paParms.
1697 * @param paParms Array of HGCM parameters.
1698 */
1699static int shClSvcClientReadData(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1700{
1701 LogFlowFuncEnter();
1702
1703 /*
1704 * Check if the service mode allows this operation and whether the guest is
1705 * supposed to be reading from the host.
1706 */
1707 uint32_t uMode = ShClSvcGetMode();
1708 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1709 || uMode == VBOX_SHCL_MODE_HOST_TO_GUEST)
1710 { /* likely */ }
1711 else
1712 return VERR_ACCESS_DENIED;
1713
1714 /*
1715 * Digest parameters.
1716 *
1717 * We are dragging some legacy here from the 6.1 dev cycle, a 5 parameter
1718 * variant which prepends a 64-bit context ID (RAZ as meaning not defined),
1719 * a 32-bit flag (MBZ, no defined meaning) and switches the last two parameters.
1720 */
1721 ASSERT_GUEST_RETURN( cParms == VBOX_SHCL_CPARMS_DATA_READ
1722 || ( cParms == VBOX_SHCL_CPARMS_DATA_READ_61B
1723 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)),
1724 VERR_WRONG_PARAMETER_COUNT);
1725
1726 uintptr_t iParm = 0;
1727 SHCLCLIENTCMDCTX cmdCtx;
1728 RT_ZERO(cmdCtx);
1729 if (cParms == VBOX_SHCL_CPARMS_DATA_READ_61B)
1730 {
1731 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1732 /* This has no defined meaning and was never used, however the guest passed stuff, so ignore it and leave idContext=0. */
1733 iParm++;
1734 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1735 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1736 iParm++;
1737 }
1738
1739 SHCLFORMAT uFormat = VBOX_SHCL_FMT_NONE;
1740 uint32_t cbData = 0;
1741 void *pvData = NULL;
1742
1743 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1744 uFormat = paParms[iParm].u.uint32;
1745 iParm++;
1746 if (cParms != VBOX_SHCL_CPARMS_DATA_READ_61B)
1747 {
1748 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1749 pvData = paParms[iParm].u.pointer.addr;
1750 cbData = paParms[iParm].u.pointer.size;
1751 iParm++;
1752 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /*cbDataReturned*/
1753 iParm++;
1754 }
1755 else
1756 {
1757 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /*cbDataReturned*/
1758 iParm++;
1759 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1760 pvData = paParms[iParm].u.pointer.addr;
1761 cbData = paParms[iParm].u.pointer.size;
1762 iParm++;
1763 }
1764 Assert(iParm == cParms);
1765
1766 /*
1767 * For some reason we need to do this (makes absolutely no sense to bird).
1768 */
1769 /** @todo r=bird: I really don't get why you need the State.POD.uFormat
1770 * member. I'm sure there is a reason. Incomplete code? */
1771 if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
1772 {
1773 if (pClient->State.POD.uFormat == VBOX_SHCL_FMT_NONE)
1774 pClient->State.POD.uFormat = uFormat;
1775 }
1776
1777#ifdef LOG_ENABLED
1778 char *pszFmt = ShClFormatsToStrA(uFormat);
1779 AssertPtrReturn(pszFmt, VERR_NO_MEMORY);
1780 LogRel2(("Shared Clipboard: Guest wants to read %RU32 bytes host clipboard data in format '%s'\n", cbData, pszFmt));
1781 RTStrFree(pszFmt);
1782#endif
1783
1784 /*
1785 * Do the reading.
1786 */
1787 uint32_t cbActual = 0;
1788
1789 int rc = RTCritSectEnter(&g_CritSect);
1790 AssertRCReturn(rc, rc);
1791
1792 /* If there is a service extension active, try reading data from it first. */
1793 if (g_ExtState.pfnExtension)
1794 {
1795 SHCLEXTPARMS parms;
1796 RT_ZERO(parms);
1797
1798 parms.u.ReadWriteData.uFormat = uFormat;
1799 parms.u.ReadWriteData.pvData = pvData;
1800 parms.u.ReadWriteData.cbData = cbData;
1801
1802 g_ExtState.fReadingData = true;
1803
1804 /* Read clipboard data from the extension. */
1805 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_DATA_READ, &parms, sizeof(parms));
1806
1807 LogRel2(("Shared Clipboard: Read extension clipboard data (fDelayedAnnouncement=%RTbool, fDelayedFormats=%#x, max %RU32 bytes), got %RU32 bytes: rc=%Rrc\n",
1808 g_ExtState.fDelayedAnnouncement, g_ExtState.fDelayedFormats, cbData, parms.u.ReadWriteData.cbData, rc));
1809
1810 /* Did the extension send the clipboard formats yet?
1811 * Otherwise, do this now. */
1812 if (g_ExtState.fDelayedAnnouncement)
1813 {
1814 int rc2 = ShClSvcReportFormats(pClient, g_ExtState.fDelayedFormats);
1815 AssertRC(rc2);
1816
1817 g_ExtState.fDelayedAnnouncement = false;
1818 g_ExtState.fDelayedFormats = 0;
1819 }
1820
1821 g_ExtState.fReadingData = false;
1822
1823 if (RT_SUCCESS(rc))
1824 cbActual = parms.u.ReadWriteData.cbData;
1825 }
1826 else
1827 rc = VERR_NOT_SUPPORTED;
1828
1829 /* Try reading from the backend if the extension above didn't handle the read. */
1830 if (rc == VERR_NOT_SUPPORTED)
1831 {
1832 rc = ShClBackendReadData(&g_ShClBackend, pClient, &cmdCtx, uFormat, pvData, cbData, &cbActual);
1833 if (RT_SUCCESS(rc))
1834 LogRel2(("Shared Clipboard: Read host clipboard data (max %RU32 bytes), got %RU32 bytes\n", cbData, cbActual));
1835 else
1836 LogRel(("Shared Clipboard: Reading host clipboard data failed with %Rrc\n", rc));
1837 }
1838
1839 if (RT_SUCCESS(rc))
1840 {
1841 /* Return the actual size required to fullfil the request. */
1842 if (cParms != VBOX_SHCL_CPARMS_DATA_READ_61B)
1843 HGCMSvcSetU32(&paParms[2], cbActual);
1844 else
1845 HGCMSvcSetU32(&paParms[3], cbActual);
1846
1847 /* If the data to return exceeds the buffer the guest supplies, tell it (and let it try again). */
1848 if (cbActual >= cbData)
1849 rc = VINF_BUFFER_OVERFLOW;
1850 }
1851
1852 RTCritSectLeave(&g_CritSect);
1853
1854 LogFlowFuncLeaveRC(rc);
1855 return rc;
1856}
1857
1858/**
1859 * Called when the guest writes clipboard data to the host.
1860 * Handles the VBOX_SHCL_GUEST_FN_DATA_WRITE message.
1861 *
1862 * @returns VBox status code.
1863 * @param pClient Client that wants to read host clipboard data.
1864 * @param cParms Number of HGCM parameters supplied in \a paParms.
1865 * @param paParms Array of HGCM parameters.
1866 */
1867static int shClSvcClientWriteData(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1868{
1869 LogFlowFuncEnter();
1870
1871 /*
1872 * Check if the service mode allows this operation and whether the guest is
1873 * supposed to be reading from the host.
1874 */
1875 uint32_t uMode = ShClSvcGetMode();
1876 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1877 || uMode == VBOX_SHCL_MODE_GUEST_TO_HOST)
1878 { /* likely */ }
1879 else
1880 return VERR_ACCESS_DENIED;
1881
1882 const bool fReportsContextID = RT_BOOL(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID);
1883
1884 /*
1885 * Digest parameters.
1886 *
1887 * There are 3 different format here, formatunately no parameters have been
1888 * switch around so it's plain sailing compared to the DATA_READ message.
1889 */
1890 ASSERT_GUEST_RETURN(fReportsContextID
1891 ? cParms == VBOX_SHCL_CPARMS_DATA_WRITE || cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B
1892 : cParms == VBOX_SHCL_CPARMS_DATA_WRITE_OLD,
1893 VERR_WRONG_PARAMETER_COUNT);
1894
1895 uintptr_t iParm = 0;
1896 SHCLCLIENTCMDCTX cmdCtx;
1897 RT_ZERO(cmdCtx);
1898 if (cParms > VBOX_SHCL_CPARMS_DATA_WRITE_OLD)
1899 {
1900 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1901 cmdCtx.uContextID = paParms[iParm].u.uint64;
1902 iParm++;
1903 }
1904 else
1905 {
1906 /* Older Guest Additions (< 6.1) did not supply a context ID.
1907 * We dig it out from our saved context ID list then a bit down below. */
1908 }
1909
1910 if (cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B)
1911 {
1912 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1913 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1914 iParm++;
1915 }
1916
1917 SHCLFORMAT uFormat = VBOX_SHCL_FMT_NONE;
1918 uint32_t cbData = 0;
1919 void *pvData = NULL;
1920
1921 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* Format bit. */
1922 uFormat = paParms[iParm].u.uint32;
1923 iParm++;
1924 if (cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B)
1925 {
1926 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* "cbData" - duplicates buffer size. */
1927 iParm++;
1928 }
1929 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1930 pvData = paParms[iParm].u.pointer.addr;
1931 cbData = paParms[iParm].u.pointer.size;
1932 iParm++;
1933 Assert(iParm == cParms);
1934
1935 /*
1936 * Handle / check context ID.
1937 */
1938 if (!fReportsContextID) /* Do we have to deal with old(er) GAs (< 6.1) which don't support context IDs? Dig out the context ID then. */
1939 {
1940 PSHCLCLIENTLEGACYCID pCID = NULL;
1941 PSHCLCLIENTLEGACYCID pCIDIter;
1942 RTListForEach(&pClient->Legacy.lstCID, pCIDIter, SHCLCLIENTLEGACYCID, Node) /* Slow, but does the job for now. */
1943 {
1944 if (pCIDIter->uFormat == uFormat)
1945 {
1946 pCID = pCIDIter;
1947 break;
1948 }
1949 }
1950
1951 ASSERT_GUEST_MSG_RETURN(pCID != NULL, ("Context ID for format %#x not found\n", uFormat), VERR_INVALID_CONTEXT);
1952 cmdCtx.uContextID = pCID->uCID;
1953
1954 /* Not needed anymore; clean up. */
1955 Assert(pClient->Legacy.cCID);
1956 pClient->Legacy.cCID--;
1957 RTListNodeRemove(&pCID->Node);
1958 RTMemFree(pCID);
1959 }
1960
1961 uint64_t const idCtxExpected = VBOX_SHCL_CONTEXTID_MAKE(pClient->State.uSessionID, pClient->EventSrc.uID,
1962 VBOX_SHCL_CONTEXTID_GET_EVENT(cmdCtx.uContextID));
1963 ASSERT_GUEST_MSG_RETURN(cmdCtx.uContextID == idCtxExpected,
1964 ("Wrong context ID: %#RX64, expected %#RX64\n", cmdCtx.uContextID, idCtxExpected),
1965 VERR_INVALID_CONTEXT);
1966
1967 /*
1968 * For some reason we need to do this (makes absolutely no sense to bird).
1969 */
1970 /** @todo r=bird: I really don't get why you need the State.POD.uFormat
1971 * member. I'm sure there is a reason. Incomplete code? */
1972 if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
1973 {
1974 if (pClient->State.POD.uFormat == VBOX_SHCL_FMT_NONE)
1975 pClient->State.POD.uFormat = uFormat;
1976 }
1977
1978#ifdef LOG_ENABLED
1979 char *pszFmt = ShClFormatsToStrA(uFormat);
1980 if (pszFmt)
1981 {
1982 LogRel2(("Shared Clipboard: Guest writes %RU32 bytes clipboard data in format '%s' to host\n", cbData, pszFmt));
1983 RTStrFree(pszFmt);
1984 }
1985#endif
1986
1987 /*
1988 * Write the data to the active host side clipboard.
1989 */
1990 int rc = RTCritSectEnter(&g_CritSect);
1991 AssertRCReturn(rc, rc);
1992
1993 if (g_ExtState.pfnExtension)
1994 {
1995 SHCLEXTPARMS parms;
1996 RT_ZERO(parms);
1997
1998 parms.u.ReadWriteData.uFormat = uFormat;
1999 parms.u.ReadWriteData.pvData = pvData;
2000 parms.u.ReadWriteData.cbData = cbData;
2001
2002 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_DATA_WRITE, &parms, sizeof(parms));
2003 }
2004 else
2005 rc = VERR_NOT_SUPPORTED;
2006
2007 /* Let the backend implementation know if the extension above didn't handle the write. */
2008 if (rc == VERR_NOT_SUPPORTED)
2009 {
2010 rc = ShClBackendWriteData(&g_ShClBackend, pClient, &cmdCtx, uFormat, pvData, cbData);
2011 if (RT_FAILURE(rc))
2012 LogRel(("Shared Clipboard: Writing guest clipboard data to the host failed with %Rrc\n", rc));
2013
2014 int rc2; /* Don't return internals back to the guest. */
2015 rc2 = ShClSvcGuestDataSignal(pClient, &cmdCtx, uFormat, pvData, cbData); /* To complete pending events, if any. */
2016 if (RT_FAILURE(rc2))
2017 LogRel(("Shared Clipboard: Signalling host about guest clipboard data failed with %Rrc\n", rc2));
2018 AssertRC(rc2);
2019 }
2020
2021 RTCritSectLeave(&g_CritSect);
2022
2023 LogFlowFuncLeaveRC(rc);
2024 return rc;
2025}
2026
2027/**
2028 * Gets an error from HGCM service parameters.
2029 *
2030 * @returns VBox status code.
2031 * @param cParms Number of HGCM parameters supplied in \a paParms.
2032 * @param paParms Array of HGCM parameters.
2033 * @param pRc Where to store the received error code.
2034 */
2035static int shClSvcClientError(uint32_t cParms, VBOXHGCMSVCPARM paParms[], int *pRc)
2036{
2037 AssertPtrReturn(paParms, VERR_INVALID_PARAMETER);
2038 AssertPtrReturn(pRc, VERR_INVALID_PARAMETER);
2039
2040 int rc;
2041
2042 if (cParms == VBOX_SHCL_CPARMS_ERROR)
2043 {
2044 rc = HGCMSvcGetU32(&paParms[1], (uint32_t *)pRc); /** @todo int vs. uint32_t !!! */
2045 }
2046 else
2047 rc = VERR_INVALID_PARAMETER;
2048
2049 LogFlowFuncLeaveRC(rc);
2050 return rc;
2051}
2052
2053static int svcInit(VBOXHGCMSVCFNTABLE *pTable)
2054{
2055 int rc = RTCritSectInit(&g_CritSect);
2056
2057 if (RT_SUCCESS(rc))
2058 {
2059 shClSvcModeSet(VBOX_SHCL_MODE_OFF);
2060
2061 rc = ShClBackendInit(ShClSvcGetBackend(), pTable);
2062
2063 /* Clean up on failure, because 'svnUnload' will not be called
2064 * if the 'svcInit' returns an error.
2065 */
2066 if (RT_FAILURE(rc))
2067 {
2068 RTCritSectDelete(&g_CritSect);
2069 }
2070 }
2071
2072 return rc;
2073}
2074
2075static DECLCALLBACK(int) svcUnload(void *)
2076{
2077 LogFlowFuncEnter();
2078
2079 ShClBackendDestroy(ShClSvcGetBackend());
2080
2081 RTCritSectDelete(&g_CritSect);
2082
2083 return VINF_SUCCESS;
2084}
2085
2086static DECLCALLBACK(int) svcDisconnect(void *, uint32_t u32ClientID, void *pvClient)
2087{
2088 LogFunc(("u32ClientID=%RU32\n", u32ClientID));
2089
2090 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2091 AssertPtr(pClient);
2092
2093 /* In order to communicate with guest service, HGCM VRDP clipboard extension
2094 * needs to know its connection client ID. Currently, in svcConnect() we always
2095 * cache ID of the first ever connected client. When client disconnects,
2096 * we need to forget its ID and let svcConnect() to pick up the next ID when a new
2097 * connection will be requested by guest service (see #10115). */
2098 if (g_ExtState.uClientID == u32ClientID)
2099 {
2100 g_ExtState.uClientID = 0;
2101 }
2102
2103 ShClBackendDisconnect(&g_ShClBackend, pClient);
2104
2105 shClSvcClientDestroy(pClient);
2106
2107 return VINF_SUCCESS;
2108}
2109
2110static DECLCALLBACK(int) svcConnect(void *, uint32_t u32ClientID, void *pvClient, uint32_t fRequestor, bool fRestoring)
2111{
2112 RT_NOREF(fRequestor, fRestoring);
2113
2114 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2115 AssertPtr(pvClient);
2116
2117 int rc = shClSvcClientInit(pClient, u32ClientID);
2118 if (RT_SUCCESS(rc))
2119 {
2120 /* Assign weak pointer to client map. */
2121 /** @todo r=bird: The g_mapClients is only there for looking up
2122 * g_ExtState.uClientID (unserialized btw), so why not use store the
2123 * pClient value directly in g_ExtState instead of the ID? It cannot
2124 * crash any worse that racing map insertion/removal. */
2125 g_mapClients[u32ClientID] = pClient; /** @todo Handle OOM / collisions? */
2126 rc = ShClBackendConnect(&g_ShClBackend, pClient, ShClSvcGetHeadless());
2127 if (RT_SUCCESS(rc))
2128 {
2129 /* Sync the host clipboard content with the client. */
2130 rc = ShClBackendSync(&g_ShClBackend, pClient);
2131 if (RT_SUCCESS(rc))
2132 {
2133 /* For now we ASSUME that the first client that connects is in charge for
2134 communicating with the service extension. */
2135 /** @todo This isn't optimal, but only the guest really knows which client is in
2136 * focus on the console. See @bugref{10115} for details. */
2137 if (g_ExtState.uClientID == 0)
2138 g_ExtState.uClientID = u32ClientID;
2139
2140 /* The sync could return VINF_NO_CHANGE if nothing has changed on the host, but
2141 older Guest Additions didn't use RT_SUCCESS to but == VINF_SUCCESS to check for
2142 success. So just return VINF_SUCCESS here to not break older Guest Additions. */
2143 LogFunc(("Successfully connected client %#x%s\n",
2144 u32ClientID, g_ExtState.uClientID == u32ClientID ? " - Use by ExtState too" : ""));
2145 return VINF_SUCCESS;
2146 }
2147
2148 LogFunc(("ShClBackendSync failed: %Rrc\n", rc));
2149 ShClBackendDisconnect(&g_ShClBackend, pClient);
2150 }
2151 else
2152 LogFunc(("ShClBackendConnect failed: %Rrc\n", rc));
2153 shClSvcClientDestroy(pClient);
2154 }
2155 else
2156 LogFunc(("shClSvcClientInit failed: %Rrc\n", rc));
2157 LogFlowFuncLeaveRC(rc);
2158 return rc;
2159}
2160
2161static DECLCALLBACK(void) svcCall(void *,
2162 VBOXHGCMCALLHANDLE callHandle,
2163 uint32_t u32ClientID,
2164 void *pvClient,
2165 uint32_t u32Function,
2166 uint32_t cParms,
2167 VBOXHGCMSVCPARM paParms[],
2168 uint64_t tsArrival)
2169{
2170 RT_NOREF(u32ClientID, pvClient, tsArrival);
2171 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2172 AssertPtr(pClient);
2173
2174#ifdef LOG_ENABLED
2175 Log2Func(("u32ClientID=%RU32, fn=%RU32 (%s), cParms=%RU32, paParms=%p\n",
2176 u32ClientID, u32Function, ShClGuestMsgToStr(u32Function), cParms, paParms));
2177 for (uint32_t i = 0; i < cParms; i++)
2178 {
2179 switch (paParms[i].type)
2180 {
2181 case VBOX_HGCM_SVC_PARM_32BIT:
2182 Log3Func((" paParms[%RU32]: type uint32_t - value %RU32\n", i, paParms[i].u.uint32));
2183 break;
2184 case VBOX_HGCM_SVC_PARM_64BIT:
2185 Log3Func((" paParms[%RU32]: type uint64_t - value %RU64\n", i, paParms[i].u.uint64));
2186 break;
2187 case VBOX_HGCM_SVC_PARM_PTR:
2188 Log3Func((" paParms[%RU32]: type ptr - value 0x%p (%RU32 bytes)\n",
2189 i, paParms[i].u.pointer.addr, paParms[i].u.pointer.size));
2190 break;
2191 case VBOX_HGCM_SVC_PARM_PAGES:
2192 Log3Func((" paParms[%RU32]: type pages - cb=%RU32, cPages=%RU16\n",
2193 i, paParms[i].u.Pages.cb, paParms[i].u.Pages.cPages));
2194 break;
2195 default:
2196 AssertFailed();
2197 }
2198 }
2199 Log2Func(("Client state: fFlags=0x%x, fGuestFeatures0=0x%x, fGuestFeatures1=0x%x\n",
2200 pClient->State.fFlags, pClient->State.fGuestFeatures0, pClient->State.fGuestFeatures1));
2201#endif
2202
2203 int rc;
2204 switch (u32Function)
2205 {
2206 case VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT:
2207 RTCritSectEnter(&pClient->CritSect);
2208 rc = shClSvcClientMsgOldGet(pClient, callHandle, cParms, paParms);
2209 RTCritSectLeave(&pClient->CritSect);
2210 break;
2211
2212 case VBOX_SHCL_GUEST_FN_CONNECT:
2213 LogRel(("Shared Clipboard: 6.1.0 beta or rc Guest Additions detected. Please upgrade!\n"));
2214 rc = VERR_NOT_IMPLEMENTED;
2215 break;
2216
2217 case VBOX_SHCL_GUEST_FN_NEGOTIATE_CHUNK_SIZE:
2218 rc = shClSvcClientNegogiateChunkSize(pClient, callHandle, cParms, paParms);
2219 break;
2220
2221 case VBOX_SHCL_GUEST_FN_REPORT_FEATURES:
2222 rc = shClSvcClientReportFeatures(pClient, callHandle, cParms, paParms);
2223 break;
2224
2225 case VBOX_SHCL_GUEST_FN_QUERY_FEATURES:
2226 rc = shClSvcClientQueryFeatures(callHandle, cParms, paParms);
2227 break;
2228
2229 case VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT:
2230 RTCritSectEnter(&pClient->CritSect);
2231 rc = shClSvcClientMsgPeek(pClient, callHandle, cParms, paParms, false /*fWait*/);
2232 RTCritSectLeave(&pClient->CritSect);
2233 break;
2234
2235 case VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT:
2236 RTCritSectEnter(&pClient->CritSect);
2237 rc = shClSvcClientMsgPeek(pClient, callHandle, cParms, paParms, true /*fWait*/);
2238 RTCritSectLeave(&pClient->CritSect);
2239 break;
2240
2241 case VBOX_SHCL_GUEST_FN_MSG_GET:
2242 RTCritSectEnter(&pClient->CritSect);
2243 rc = shClSvcClientMsgGet(pClient, callHandle, cParms, paParms);
2244 RTCritSectLeave(&pClient->CritSect);
2245 break;
2246
2247 case VBOX_SHCL_GUEST_FN_MSG_CANCEL:
2248 RTCritSectEnter(&pClient->CritSect);
2249 rc = shClSvcClientMsgCancel(pClient, cParms);
2250 RTCritSectLeave(&pClient->CritSect);
2251 break;
2252
2253 case VBOX_SHCL_GUEST_FN_REPORT_FORMATS:
2254 rc = shClSvcClientReportFormats(pClient, cParms, paParms);
2255 break;
2256
2257 case VBOX_SHCL_GUEST_FN_DATA_READ:
2258 rc = shClSvcClientReadData(pClient, cParms, paParms);
2259 break;
2260
2261 case VBOX_SHCL_GUEST_FN_DATA_WRITE:
2262 rc = shClSvcClientWriteData(pClient, cParms, paParms);
2263 break;
2264
2265 case VBOX_SHCL_GUEST_FN_ERROR:
2266 {
2267 int rcGuest;
2268 rc = shClSvcClientError(cParms,paParms, &rcGuest);
2269 if (RT_SUCCESS(rc))
2270 {
2271 LogRel(("Shared Clipboard: Error reported from guest side: %Rrc\n", rcGuest));
2272
2273 shClSvcClientLock(pClient);
2274
2275 /* Reset message queue. */
2276 shClSvcMsgQueueReset(pClient);
2277
2278#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2279 /* Reset transfer state. */
2280 shClSvcTransferDestroyAll(pClient);
2281#endif
2282 shClSvcClientUnlock(pClient);
2283 }
2284 break;
2285 }
2286
2287 default:
2288 {
2289#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2290 if ( u32Function <= VBOX_SHCL_GUEST_FN_LAST
2291 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID) )
2292 {
2293 if (g_fTransferMode & VBOX_SHCL_TRANSFER_MODE_F_ENABLED)
2294 rc = shClSvcTransferHandler(pClient, callHandle, u32Function, cParms, paParms, tsArrival);
2295 else
2296 {
2297 LogRel2(("Shared Clipboard: File transfers are disabled for this VM\n"));
2298 rc = VERR_ACCESS_DENIED;
2299 }
2300 }
2301 else
2302#endif
2303 {
2304 LogRel2(("Shared Clipboard: Unknown guest function: %u (%#x)\n", u32Function, u32Function));
2305 rc = VERR_NOT_IMPLEMENTED;
2306 }
2307 break;
2308 }
2309 }
2310
2311 LogFlowFunc(("[Client %RU32] rc=%Rrc\n", pClient->State.uClientID, rc));
2312
2313 if (rc != VINF_HGCM_ASYNC_EXECUTE)
2314 g_pHelpers->pfnCallComplete(callHandle, rc);
2315}
2316
2317/**
2318 * Initializes a Shared Clipboard service's client state.
2319 *
2320 * @returns VBox status code.
2321 * @param pClientState Client state to initialize.
2322 * @param uClientID Client ID (HGCM) to use for this client state.
2323 */
2324int shClSvcClientStateInit(PSHCLCLIENTSTATE pClientState, uint32_t uClientID)
2325{
2326 LogFlowFuncEnter();
2327
2328 shclSvcClientStateReset(pClientState);
2329
2330 /* Register the client. */
2331 pClientState->uClientID = uClientID;
2332
2333 return VINF_SUCCESS;
2334}
2335
2336/**
2337 * Destroys a Shared Clipboard service's client state.
2338 *
2339 * @returns VBox status code.
2340 * @param pClientState Client state to destroy.
2341 */
2342int shClSvcClientStateDestroy(PSHCLCLIENTSTATE pClientState)
2343{
2344 RT_NOREF(pClientState);
2345
2346 LogFlowFuncEnter();
2347
2348 return VINF_SUCCESS;
2349}
2350
2351/**
2352 * Resets a Shared Clipboard service's client state.
2353 *
2354 * @param pClientState Client state to reset.
2355 */
2356void shclSvcClientStateReset(PSHCLCLIENTSTATE pClientState)
2357{
2358 LogFlowFuncEnter();
2359
2360 pClientState->fGuestFeatures0 = VBOX_SHCL_GF_NONE;
2361 pClientState->fGuestFeatures1 = VBOX_SHCL_GF_NONE;
2362
2363 pClientState->cbChunkSize = VBOX_SHCL_DEFAULT_CHUNK_SIZE; /** @todo Make this configurable. */
2364 pClientState->enmSource = SHCLSOURCE_INVALID;
2365 pClientState->fFlags = SHCLCLIENTSTATE_FLAGS_NONE;
2366
2367 pClientState->POD.enmDir = SHCLTRANSFERDIR_UNKNOWN;
2368 pClientState->POD.uFormat = VBOX_SHCL_FMT_NONE;
2369 pClientState->POD.cbToReadWriteTotal = 0;
2370 pClientState->POD.cbReadWritten = 0;
2371
2372#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2373 pClientState->Transfers.enmTransferDir = SHCLTRANSFERDIR_UNKNOWN;
2374#endif
2375}
2376
2377/*
2378 * We differentiate between a function handler for the guest and one for the host.
2379 */
2380static DECLCALLBACK(int) svcHostCall(void *,
2381 uint32_t u32Function,
2382 uint32_t cParms,
2383 VBOXHGCMSVCPARM paParms[])
2384{
2385 int rc = VINF_SUCCESS;
2386
2387 LogFlowFunc(("u32Function=%RU32 (%s), cParms=%RU32, paParms=%p\n",
2388 u32Function, ShClHostFunctionToStr(u32Function), cParms, paParms));
2389
2390 switch (u32Function)
2391 {
2392 case VBOX_SHCL_HOST_FN_SET_MODE:
2393 {
2394 if (cParms != 1)
2395 {
2396 rc = VERR_INVALID_PARAMETER;
2397 }
2398 else
2399 {
2400 uint32_t u32Mode = VBOX_SHCL_MODE_OFF;
2401
2402 rc = HGCMSvcGetU32(&paParms[0], &u32Mode);
2403 if (RT_SUCCESS(rc))
2404 rc = shClSvcModeSet(u32Mode);
2405 }
2406
2407 break;
2408 }
2409
2410#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2411 case VBOX_SHCL_HOST_FN_SET_TRANSFER_MODE:
2412 {
2413 if (cParms != 1)
2414 {
2415 rc = VERR_INVALID_PARAMETER;
2416 }
2417 else
2418 {
2419 uint32_t fTransferMode;
2420 rc = HGCMSvcGetU32(&paParms[0], &fTransferMode);
2421 if (RT_SUCCESS(rc))
2422 rc = shClSvcTransferModeSet(fTransferMode);
2423 }
2424 break;
2425 }
2426#endif
2427 case VBOX_SHCL_HOST_FN_SET_HEADLESS:
2428 {
2429 if (cParms != 1)
2430 {
2431 rc = VERR_INVALID_PARAMETER;
2432 }
2433 else
2434 {
2435 uint32_t uHeadless;
2436 rc = HGCMSvcGetU32(&paParms[0], &uHeadless);
2437 if (RT_SUCCESS(rc))
2438 {
2439 g_fHeadless = RT_BOOL(uHeadless);
2440 LogRel(("Shared Clipboard: Service running in %s mode\n", g_fHeadless ? "headless" : "normal"));
2441 }
2442 }
2443 break;
2444 }
2445
2446 default:
2447 {
2448#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2449 rc = shClSvcTransferHostHandler(u32Function, cParms, paParms);
2450#else
2451 rc = VERR_NOT_IMPLEMENTED;
2452#endif
2453 break;
2454 }
2455 }
2456
2457 LogFlowFuncLeaveRC(rc);
2458 return rc;
2459}
2460
2461#ifndef UNIT_TEST
2462
2463/**
2464 * SSM descriptor table for the SHCLCLIENTLEGACYCID structure.
2465 *
2466 * @note Saving the ListEntry attribute is not necessary, as this gets used on runtime only.
2467 */
2468static SSMFIELD const s_aShClSSMClientLegacyCID[] =
2469{
2470 SSMFIELD_ENTRY(SHCLCLIENTLEGACYCID, uCID),
2471 SSMFIELD_ENTRY(SHCLCLIENTLEGACYCID, enmType),
2472 SSMFIELD_ENTRY(SHCLCLIENTLEGACYCID, uFormat),
2473 SSMFIELD_ENTRY_TERM()
2474};
2475
2476/**
2477 * SSM descriptor table for the SHCLCLIENTSTATE structure.
2478 *
2479 * @note Saving the session ID not necessary, as they're not persistent across
2480 * state save/restore.
2481 */
2482static SSMFIELD const s_aShClSSMClientState[] =
2483{
2484 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures0),
2485 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures1),
2486 SSMFIELD_ENTRY(SHCLCLIENTSTATE, cbChunkSize),
2487 SSMFIELD_ENTRY(SHCLCLIENTSTATE, enmSource),
2488 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fFlags),
2489 SSMFIELD_ENTRY_TERM()
2490};
2491
2492/**
2493 * VBox 6.1 Beta 1 version of s_aShClSSMClientState (no flags).
2494 */
2495static SSMFIELD const s_aShClSSMClientState61B1[] =
2496{
2497 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures0),
2498 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures1),
2499 SSMFIELD_ENTRY(SHCLCLIENTSTATE, cbChunkSize),
2500 SSMFIELD_ENTRY(SHCLCLIENTSTATE, enmSource),
2501 SSMFIELD_ENTRY_TERM()
2502};
2503
2504/**
2505 * SSM descriptor table for the SHCLCLIENTPODSTATE structure.
2506 */
2507static SSMFIELD const s_aShClSSMClientPODState[] =
2508{
2509 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, enmDir),
2510 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, uFormat),
2511 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, cbToReadWriteTotal),
2512 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, cbReadWritten),
2513 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, tsLastReadWrittenMs),
2514 SSMFIELD_ENTRY_TERM()
2515};
2516
2517/**
2518 * SSM descriptor table for the SHCLCLIENTURISTATE structure.
2519 */
2520static SSMFIELD const s_aShClSSMClientTransferState[] =
2521{
2522 SSMFIELD_ENTRY(SHCLCLIENTTRANSFERSTATE, enmTransferDir),
2523 SSMFIELD_ENTRY_TERM()
2524};
2525
2526/**
2527 * SSM descriptor table for the header of the SHCLCLIENTMSG structure.
2528 * The actual message parameters will be serialized separately.
2529 */
2530static SSMFIELD const s_aShClSSMClientMsgHdr[] =
2531{
2532 SSMFIELD_ENTRY(SHCLCLIENTMSG, idMsg),
2533 SSMFIELD_ENTRY(SHCLCLIENTMSG, cParms),
2534 SSMFIELD_ENTRY_TERM()
2535};
2536
2537/**
2538 * SSM descriptor table for what used to be the VBOXSHCLMSGCTX structure but is
2539 * now part of SHCLCLIENTMSG.
2540 */
2541static SSMFIELD const s_aShClSSMClientMsgCtx[] =
2542{
2543 SSMFIELD_ENTRY(SHCLCLIENTMSG, idCtx),
2544 SSMFIELD_ENTRY_TERM()
2545};
2546#endif /* !UNIT_TEST */
2547
2548static DECLCALLBACK(int) svcSaveState(void *, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM)
2549{
2550 LogFlowFuncEnter();
2551
2552#ifndef UNIT_TEST
2553 /*
2554 * When the state will be restored, pending requests will be reissued
2555 * by VMMDev. The service therefore must save state as if there were no
2556 * pending request.
2557 * Pending requests, if any, will be completed in svcDisconnect.
2558 */
2559 RT_NOREF(u32ClientID);
2560 LogFunc(("u32ClientID=%RU32\n", u32ClientID));
2561
2562 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2563 AssertPtr(pClient);
2564
2565 /* Write Shared Clipboard saved state version. */
2566 pVMM->pfnSSMR3PutU32(pSSM, VBOX_SHCL_SAVED_STATE_VER_CURRENT);
2567
2568 int rc = pVMM->pfnSSMR3PutStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /*fFlags*/, &s_aShClSSMClientState[0], NULL);
2569 AssertRCReturn(rc, rc);
2570
2571 rc = pVMM->pfnSSMR3PutStructEx(pSSM, &pClient->State.POD, sizeof(pClient->State.POD), 0 /*fFlags*/, &s_aShClSSMClientPODState[0], NULL);
2572 AssertRCReturn(rc, rc);
2573
2574 rc = pVMM->pfnSSMR3PutStructEx(pSSM, &pClient->State.Transfers, sizeof(pClient->State.Transfers), 0 /*fFlags*/, &s_aShClSSMClientTransferState[0], NULL);
2575 AssertRCReturn(rc, rc);
2576
2577 /* Serialize the client's internal message queue. */
2578 rc = pVMM->pfnSSMR3PutU64(pSSM, pClient->cMsgAllocated);
2579 AssertRCReturn(rc, rc);
2580
2581 PSHCLCLIENTMSG pMsg;
2582 RTListForEach(&pClient->MsgQueue, pMsg, SHCLCLIENTMSG, ListEntry)
2583 {
2584 pVMM->pfnSSMR3PutStructEx(pSSM, pMsg, sizeof(SHCLCLIENTMSG), 0 /*fFlags*/, &s_aShClSSMClientMsgHdr[0], NULL);
2585 pVMM->pfnSSMR3PutStructEx(pSSM, pMsg, sizeof(SHCLCLIENTMSG), 0 /*fFlags*/, &s_aShClSSMClientMsgCtx[0], NULL);
2586
2587 for (uint32_t iParm = 0; iParm < pMsg->cParms; iParm++)
2588 HGCMSvcSSMR3Put(&pMsg->aParms[iParm], pSSM, pVMM);
2589 }
2590
2591 rc = pVMM->pfnSSMR3PutU64(pSSM, pClient->Legacy.cCID);
2592 AssertRCReturn(rc, rc);
2593
2594 PSHCLCLIENTLEGACYCID pCID;
2595 RTListForEach(&pClient->Legacy.lstCID, pCID, SHCLCLIENTLEGACYCID, Node)
2596 {
2597 rc = pVMM->pfnSSMR3PutStructEx(pSSM, pCID, sizeof(SHCLCLIENTLEGACYCID), 0 /*fFlags*/, &s_aShClSSMClientLegacyCID[0], NULL);
2598 AssertRCReturn(rc, rc);
2599 }
2600#else /* UNIT_TEST */
2601 RT_NOREF(u32ClientID, pvClient, pSSM, pVMM);
2602#endif /* UNIT_TEST */
2603 return VINF_SUCCESS;
2604}
2605
2606#ifndef UNIT_TEST
2607static int svcLoadStateV0(uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, uint32_t uVersion)
2608{
2609 RT_NOREF(u32ClientID, pvClient, pSSM, uVersion);
2610
2611 uint32_t uMarker;
2612 int rc = pVMM->pfnSSMR3GetU32(pSSM, &uMarker); /* Begin marker. */
2613 AssertRC(rc);
2614 Assert(uMarker == UINT32_C(0x19200102) /* SSMR3STRUCT_BEGIN */);
2615
2616 rc = pVMM->pfnSSMR3Skip(pSSM, sizeof(uint32_t)); /* Client ID */
2617 AssertRCReturn(rc, rc);
2618
2619 bool fValue;
2620 rc = pVMM->pfnSSMR3GetBool(pSSM, &fValue); /* fHostMsgQuit */
2621 AssertRCReturn(rc, rc);
2622
2623 rc = pVMM->pfnSSMR3GetBool(pSSM, &fValue); /* fHostMsgReadData */
2624 AssertRCReturn(rc, rc);
2625
2626 rc = pVMM->pfnSSMR3GetBool(pSSM, &fValue); /* fHostMsgFormats */
2627 AssertRCReturn(rc, rc);
2628
2629 uint32_t fFormats;
2630 rc = pVMM->pfnSSMR3GetU32(pSSM, &fFormats); /* u32RequestedFormat */
2631 AssertRCReturn(rc, rc);
2632
2633 rc = pVMM->pfnSSMR3GetU32(pSSM, &uMarker); /* End marker. */
2634 AssertRCReturn(rc, rc);
2635 Assert(uMarker == UINT32_C(0x19920406) /* SSMR3STRUCT_END */);
2636
2637 return VINF_SUCCESS;
2638}
2639#endif /* UNIT_TEST */
2640
2641static DECLCALLBACK(int) svcLoadState(void *, uint32_t u32ClientID, void *pvClient,
2642 PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, uint32_t uVersion)
2643{
2644 LogFlowFuncEnter();
2645
2646#ifndef UNIT_TEST
2647
2648 RT_NOREF(u32ClientID, uVersion);
2649
2650 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2651 AssertPtr(pClient);
2652
2653 /* Restore the client data. */
2654 uint32_t lenOrVer;
2655 int rc = pVMM->pfnSSMR3GetU32(pSSM, &lenOrVer);
2656 AssertRCReturn(rc, rc);
2657
2658 LogFunc(("u32ClientID=%RU32, lenOrVer=%#RX64\n", u32ClientID, lenOrVer));
2659
2660 if (lenOrVer == VBOX_SHCL_SAVED_STATE_VER_3_1)
2661 return svcLoadStateV0(u32ClientID, pvClient, pSSM, pVMM, uVersion);
2662
2663 if ( lenOrVer >= VBOX_SHCL_SAVED_STATE_VER_6_1B2
2664 && lenOrVer <= VBOX_SHCL_SAVED_STATE_VER_CURRENT)
2665 {
2666 if (lenOrVer >= VBOX_SHCL_SAVED_STATE_VER_6_1RC1)
2667 {
2668 pVMM->pfnSSMR3GetStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /* fFlags */,
2669 &s_aShClSSMClientState[0], NULL);
2670 pVMM->pfnSSMR3GetStructEx(pSSM, &pClient->State.POD, sizeof(pClient->State.POD), 0 /* fFlags */,
2671 &s_aShClSSMClientPODState[0], NULL);
2672 }
2673 else
2674 pVMM->pfnSSMR3GetStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /* fFlags */,
2675 &s_aShClSSMClientState61B1[0], NULL);
2676 rc = pVMM->pfnSSMR3GetStructEx(pSSM, &pClient->State.Transfers, sizeof(pClient->State.Transfers), 0 /* fFlags */,
2677 &s_aShClSSMClientTransferState[0], NULL);
2678 AssertRCReturn(rc, rc);
2679
2680 /* Load the client's internal message queue. */
2681 uint64_t cMsgs;
2682 rc = pVMM->pfnSSMR3GetU64(pSSM, &cMsgs);
2683 AssertRCReturn(rc, rc);
2684 AssertLogRelMsgReturn(cMsgs < _16K, ("Too many messages: %u (%x)\n", cMsgs, cMsgs), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
2685
2686 for (uint64_t i = 0; i < cMsgs; i++)
2687 {
2688 union
2689 {
2690 SHCLCLIENTMSG Msg;
2691 uint8_t abPadding[RT_UOFFSETOF(SHCLCLIENTMSG, aParms) + sizeof(VBOXHGCMSVCPARM) * 2];
2692 } u;
2693
2694 pVMM->pfnSSMR3GetStructEx(pSSM, &u.Msg, RT_UOFFSETOF(SHCLCLIENTMSG, aParms), 0 /*fFlags*/,
2695 &s_aShClSSMClientMsgHdr[0], NULL);
2696 rc = pVMM->pfnSSMR3GetStructEx(pSSM, &u.Msg, RT_UOFFSETOF(SHCLCLIENTMSG, aParms), 0 /*fFlags*/,
2697 &s_aShClSSMClientMsgCtx[0], NULL);
2698 AssertRCReturn(rc, rc);
2699
2700 AssertLogRelMsgReturn(u.Msg.cParms <= VMMDEV_MAX_HGCM_PARMS,
2701 ("Too many HGCM message parameters: %u (%#x)\n", u.Msg.cParms, u.Msg.cParms),
2702 VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
2703
2704 PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient, u.Msg.idMsg, u.Msg.cParms);
2705 AssertReturn(pMsg, VERR_NO_MEMORY);
2706 pMsg->idCtx = u.Msg.idCtx;
2707
2708 for (uint32_t p = 0; p < pMsg->cParms; p++)
2709 {
2710 rc = HGCMSvcSSMR3Get(&pMsg->aParms[p], pSSM, pVMM);
2711 AssertRCReturnStmt(rc, shClSvcMsgFree(pClient, pMsg), rc);
2712 }
2713
2714 RTCritSectEnter(&pClient->CritSect);
2715 shClSvcMsgAdd(pClient, pMsg, true /* fAppend */);
2716 RTCritSectLeave(&pClient->CritSect);
2717 }
2718
2719 if (lenOrVer >= VBOX_SHCL_SAVED_STATE_LEGACY_CID)
2720 {
2721 uint64_t cCID;
2722 rc = pVMM->pfnSSMR3GetU64(pSSM, &cCID);
2723 AssertRCReturn(rc, rc);
2724 AssertLogRelMsgReturn(cCID < _16K, ("Too many context IDs: %u (%x)\n", cCID, cCID), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
2725
2726 for (uint64_t i = 0; i < cCID; i++)
2727 {
2728 PSHCLCLIENTLEGACYCID pCID = (PSHCLCLIENTLEGACYCID)RTMemAlloc(sizeof(SHCLCLIENTLEGACYCID));
2729 AssertPtrReturn(pCID, VERR_NO_MEMORY);
2730
2731 pVMM->pfnSSMR3GetStructEx(pSSM, pCID, sizeof(SHCLCLIENTLEGACYCID), 0 /* fFlags */,
2732 &s_aShClSSMClientLegacyCID[0], NULL);
2733 RTListAppend(&pClient->Legacy.lstCID, &pCID->Node);
2734 }
2735 }
2736 }
2737 else
2738 {
2739 LogRel(("Shared Clipboard: Unsupported saved state version (%#x)\n", lenOrVer));
2740 return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
2741 }
2742
2743 /* Actual host data are to be reported to guest (SYNC). */
2744 ShClBackendSync(&g_ShClBackend, pClient);
2745
2746#else /* UNIT_TEST */
2747 RT_NOREF(u32ClientID, pvClient, pSSM, pVMM, uVersion);
2748#endif /* UNIT_TEST */
2749 return VINF_SUCCESS;
2750}
2751
2752static DECLCALLBACK(int) extCallback(uint32_t u32Function, uint32_t u32Format, void *pvData, uint32_t cbData)
2753{
2754 RT_NOREF(pvData, cbData);
2755
2756 LogFlowFunc(("u32Function=%RU32\n", u32Function));
2757
2758 int rc = VINF_SUCCESS;
2759
2760 /* Figure out if the client in charge for the service extension still is connected. */
2761 ClipboardClientMap::const_iterator itClient = g_mapClients.find(g_ExtState.uClientID);
2762 if (itClient != g_mapClients.end())
2763 {
2764 PSHCLCLIENT pClient = itClient->second;
2765 AssertPtr(pClient);
2766
2767 switch (u32Function)
2768 {
2769 /* The service extension announces formats to the host. */
2770 case VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_HOST:
2771 {
2772 LogFlowFunc(("VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_HOST: g_ExtState.fReadingData=%RTbool\n", g_ExtState.fReadingData));
2773 if (!g_ExtState.fReadingData)
2774 rc = ShClSvcReportFormats(pClient, u32Format);
2775 else
2776 {
2777 g_ExtState.fDelayedAnnouncement = true;
2778 g_ExtState.fDelayedFormats = u32Format;
2779 rc = VINF_SUCCESS;
2780 }
2781 break;
2782 }
2783
2784 /* The service extension wants read data from the guest. */
2785 case VBOX_CLIPBOARD_EXT_FN_DATA_READ:
2786 {
2787 PSHCLEVENT pEvent;
2788 rc = ShClSvcReadDataFromGuestAsync(pClient, u32Format, &pEvent);
2789 if (RT_SUCCESS(rc))
2790 {
2791 PSHCLEVENTPAYLOAD pPayload;
2792 rc = ShClEventWait(pEvent, SHCL_TIMEOUT_DEFAULT_MS, &pPayload);
2793 if (RT_SUCCESS(rc))
2794 {
2795 if (pPayload)
2796 {
2797 memcpy(pvData, pPayload->pvData, RT_MIN(cbData, pPayload->cbData));
2798 /** @todo r=andy How is this supposed to work wrt returning number of bytes read? */
2799
2800 ShClPayloadFree(pPayload);
2801 pPayload = NULL;
2802 }
2803 else
2804 {
2805 pvData = NULL;
2806 }
2807 }
2808
2809 ShClEventRelease(pEvent);
2810 }
2811 break;
2812 }
2813
2814 default:
2815 /* Just skip other messages. */
2816 break;
2817 }
2818 }
2819 else
2820 rc = VERR_NOT_FOUND;
2821
2822 LogFlowFuncLeaveRC(rc);
2823 return rc;
2824}
2825
2826static DECLCALLBACK(int) svcRegisterExtension(void *, PFNHGCMSVCEXT pfnExtension, void *pvExtension)
2827{
2828 LogFlowFunc(("pfnExtension=%p\n", pfnExtension));
2829
2830 SHCLEXTPARMS parms;
2831 RT_ZERO(parms);
2832
2833 /*
2834 * Reference counting for service extension registration is done a few
2835 * layers up (in ConsoleVRDPServer::ClipboardCreate()).
2836 */
2837
2838 int rc = RTCritSectEnter(&g_CritSect);
2839 AssertLogRelRCReturn(rc, rc);
2840
2841 if (pfnExtension)
2842 {
2843 /* Install extension. */
2844 g_ExtState.pfnExtension = pfnExtension;
2845 g_ExtState.pvExtension = pvExtension;
2846
2847 parms.u.SetCallback.pfnCallback = extCallback;
2848
2849 g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_SET_CALLBACK, &parms, sizeof(parms));
2850
2851 LogRel2(("Shared Clipboard: registered service extension\n"));
2852 }
2853 else
2854 {
2855 if (g_ExtState.pfnExtension)
2856 g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_SET_CALLBACK, &parms, sizeof(parms));
2857
2858 /* Uninstall extension. */
2859 g_ExtState.pvExtension = NULL;
2860 g_ExtState.pfnExtension = NULL;
2861
2862 LogRel2(("Shared Clipboard: de-registered service extension\n"));
2863 }
2864
2865 RTCritSectLeave(&g_CritSect);
2866
2867 return VINF_SUCCESS;
2868}
2869
2870extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *pTable)
2871{
2872 int rc = VINF_SUCCESS;
2873
2874 LogFlowFunc(("pTable=%p\n", pTable));
2875
2876 if (!RT_VALID_PTR(pTable))
2877 {
2878 rc = VERR_INVALID_PARAMETER;
2879 }
2880 else
2881 {
2882 LogFunc(("pTable->cbSize = %d, ptable->u32Version = 0x%08X\n", pTable->cbSize, pTable->u32Version));
2883
2884 if ( pTable->cbSize != sizeof (VBOXHGCMSVCFNTABLE)
2885 || pTable->u32Version != VBOX_HGCM_SVC_VERSION)
2886 {
2887 rc = VERR_VERSION_MISMATCH;
2888 }
2889 else
2890 {
2891 g_pHelpers = pTable->pHelpers;
2892
2893 pTable->cbClient = sizeof(SHCLCLIENT);
2894
2895 /* Map legacy clients to root. */
2896 pTable->idxLegacyClientCategory = HGCM_CLIENT_CATEGORY_ROOT;
2897
2898 /* Limit the number of clients to 128 in each category (should be enough),
2899 but set kernel clients to 1. */
2900 for (uintptr_t i = 0; i < RT_ELEMENTS(pTable->acMaxClients); i++)
2901 pTable->acMaxClients[i] = 128;
2902 pTable->acMaxClients[HGCM_CLIENT_CATEGORY_KERNEL] = 1;
2903
2904 /* Only 16 pending calls per client (1 should be enough). */
2905 for (uintptr_t i = 0; i < RT_ELEMENTS(pTable->acMaxClients); i++)
2906 pTable->acMaxCallsPerClient[i] = 16;
2907
2908 pTable->pfnUnload = svcUnload;
2909 pTable->pfnConnect = svcConnect;
2910 pTable->pfnDisconnect = svcDisconnect;
2911 pTable->pfnCall = svcCall;
2912 pTable->pfnHostCall = svcHostCall;
2913 pTable->pfnSaveState = svcSaveState;
2914 pTable->pfnLoadState = svcLoadState;
2915 pTable->pfnRegisterExtension = svcRegisterExtension;
2916 pTable->pfnNotify = NULL;
2917 pTable->pvService = NULL;
2918
2919 /* Service specific initialization. */
2920 rc = svcInit(pTable);
2921 }
2922 }
2923
2924 LogFlowFunc(("Returning %Rrc\n", rc));
2925 return rc;
2926}
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