VirtualBox

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

Last change on this file was 104236, checked in by vboxsync, 2 months ago

macOS: Shared Clipboard: Prevent assertion on each guest -> host clipboard operation (scm fix), bugref:9437.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 105.4 KB
Line 
1/* $Id: VBoxSharedClipboardSvc.cpp 104236 2024-04-08 17:56:29Z 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 shClSvcClientMsgQueryFeatures(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 * @retval VERR_SHCLPB_NO_DATA if no clipboard data is available.
1389 * @param pClient Client to request to read data form.
1390 * @param fFormats The formats being requested, OR'ed together (VBOX_SHCL_FMT_XXX).
1391 * @param ppv Where to return the allocated data read.
1392 * Must be free'd by the caller.
1393 * @param pcb Where to return number of bytes read.
1394 */
1395int ShClSvcReadDataFromGuest(PSHCLCLIENT pClient, SHCLFORMAT fFormats, void **ppv, uint32_t *pcb)
1396{
1397 AssertPtrReturn(ppv, VERR_INVALID_POINTER);
1398 AssertPtrReturn(pcb, VERR_INVALID_POINTER);
1399
1400 LogFlowFuncEnter();
1401
1402 /* Request data from the guest and wait for data to arrive. */
1403 PSHCLEVENT pEvent;
1404 int rc = ShClSvcReadDataFromGuestAsync(pClient, fFormats, &pEvent);
1405 if (RT_SUCCESS(rc))
1406 {
1407 PSHCLEVENTPAYLOAD pPayload;
1408 rc = ShClEventWait(pEvent, SHCL_TIMEOUT_DEFAULT_MS, &pPayload);
1409 if (RT_SUCCESS(rc))
1410 {
1411 if ( pPayload
1412 && pPayload->cbData)
1413 {
1414 *ppv = pPayload->pvData;
1415 *pcb = pPayload->cbData;
1416
1417 LogFlowFunc(("pv=%p, cb=%RU32\n", pPayload->pvData, pPayload->cbData));
1418 }
1419 else
1420 rc = VERR_SHCLPB_NO_DATA;
1421 }
1422
1423 ShClEventRelease(pEvent);
1424 }
1425
1426 if ( RT_FAILURE(rc)
1427 && rc != VERR_SHCLPB_NO_DATA)
1428 LogRel(("Shared Clipboard: Reading data from guest failed with %Rrc\n", rc));
1429 return rc;
1430}
1431
1432/**
1433 * Signals the host that clipboard data from the guest has been received.
1434 *
1435 * @returns VBox status code. Returns VERR_NOT_FOUND when related event ID was not found.
1436 * @param pClient Client the guest clipboard data was received from.
1437 * @param pCmdCtx Client command context.
1438 * @param uFormat Clipboard format of data received.
1439 * @param pvData Pointer to clipboard data received. This can be
1440 * NULL if @a cbData is zero.
1441 * @param cbData Size (in bytes) of clipboard data received.
1442 * This can be zero.
1443 *
1444 * @thread Backend thread.
1445 */
1446int ShClSvcGuestDataSignal(PSHCLCLIENT pClient, PSHCLCLIENTCMDCTX pCmdCtx, SHCLFORMAT uFormat, void *pvData, uint32_t cbData)
1447{
1448 LogFlowFuncEnter();
1449 RT_NOREF(uFormat);
1450
1451 /*
1452 * Validate input.
1453 */
1454 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1455 AssertPtrReturn(pCmdCtx, VERR_INVALID_POINTER);
1456 if (cbData > 0)
1457 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
1458
1459 const SHCLEVENTID idEvent = VBOX_SHCL_CONTEXTID_GET_EVENT(pCmdCtx->uContextID);
1460 AssertMsgReturn(idEvent != NIL_SHCLEVENTID, ("NIL event in context ID %#RX64\n", pCmdCtx->uContextID), VERR_WRONG_ORDER);
1461
1462 PSHCLEVENT pEvent = ShClEventSourceGetFromId(&pClient->EventSrc, idEvent);
1463#if defined(RT_OS_DARWIN)
1464 /* We do not wait for guest clipboard availability event on macOS. Rather,
1465 * we paste directly into pasteboard when guest sends its clipboard data.
1466 * Do not assert here. */
1467 if (!RT_VALID_PTR(pEvent))
1468 return VINF_SUCCESS;
1469#endif
1470
1471 AssertMsgReturn(pEvent != NULL, ("Event %#x not found\n", idEvent), VERR_NOT_FOUND);
1472
1473 /*
1474 * Make a copy of the data so we can attach it to the signal.
1475 *
1476 * Note! We still signal the waiter should we run out of memory,
1477 * because otherwise it will be stuck waiting.
1478 */
1479 int rc = VINF_SUCCESS;
1480 PSHCLEVENTPAYLOAD pPayload = NULL;
1481 if (cbData > 0)
1482 rc = ShClPayloadAlloc(idEvent, pvData, cbData, &pPayload);
1483
1484 /*
1485 * Signal the event.
1486 */
1487 int rc2 = ShClEventSignal(pEvent, pPayload);
1488 if (RT_FAILURE(rc2))
1489 {
1490 rc = rc2;
1491 ShClPayloadFree(pPayload);
1492 LogRel(("Shared Clipboard: Signalling of guest clipboard data to the host failed: %Rrc\n", rc));
1493 }
1494
1495 LogFlowFuncLeaveRC(rc);
1496 return rc;
1497}
1498
1499/**
1500 * Reports clipboard formats to the guest.
1501 *
1502 * @note Host backend callers must check if it's active (use
1503 * ShClSvcIsBackendActive) before calling to prevent mixing up the
1504 * VRDE clipboard.
1505 *
1506 * @returns VBox status code.
1507 * @param pClient Client to report clipboard formats to.
1508 * @param fFormats The formats to report (VBOX_SHCL_FMT_XXX), zero
1509 * is okay (empty the clipboard).
1510 *
1511 * @thread Backend thread.
1512 */
1513int ShClSvcReportFormats(PSHCLCLIENT pClient, SHCLFORMATS fFormats)
1514{
1515 AssertPtrReturn(pClient, VERR_INVALID_POINTER);
1516
1517 LogFlowFunc(("fFormats=%#x\n", fFormats));
1518
1519 /*
1520 * Check if the service mode allows this operation and whether the guest is
1521 * supposed to be reading from the host. Otherwise, silently ignore reporting
1522 * formats and return VINF_SUCCESS in order to do not trigger client
1523 * termination in svcConnect().
1524 */
1525 uint32_t uMode = ShClSvcGetMode();
1526 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1527 || uMode == VBOX_SHCL_MODE_HOST_TO_GUEST)
1528 { /* likely */ }
1529 else
1530 return VINF_SUCCESS;
1531
1532#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1533 bool fSkipTransfers = false;
1534 if (!(g_fTransferMode & VBOX_SHCL_TRANSFER_MODE_F_ENABLED))
1535 {
1536 LogRel2(("Shared Clipboard: File transfers are disabled, skipping reporting those to the guest\n"));
1537 fSkipTransfers = true;
1538 }
1539 else if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_TRANSFERS))
1540 {
1541 LogRel2(("Shared Clipboard: File transfers not supported by installed Guest Addtions, skipping reporting those to the guest\n"));
1542 fSkipTransfers = true;
1543 }
1544
1545 if (fSkipTransfers)
1546 fFormats &= ~VBOX_SHCL_FMT_URI_LIST;
1547#endif
1548
1549#ifdef LOG_ENABLED
1550 char *pszFmts = ShClFormatsToStrA(fFormats);
1551 AssertPtrReturn(pszFmts, VERR_NO_MEMORY);
1552 LogRel2(("Shared Clipboard: Reporting formats '%s' to guest\n", pszFmts));
1553 RTStrFree(pszFmts);
1554#endif
1555
1556 int rc;
1557
1558 /*
1559 * Check if the HGCM callback can handle this first.
1560 * This is needed in order to not mess up the clipboard if VRDE is active, for example.
1561 */
1562 if (g_ExtState.pfnExtension) /* Extension set? */
1563 {
1564 SHCLEXTPARMS parms;
1565 RT_ZERO(parms);
1566
1567 parms.u.ReportFormats.uFormats = fFormats;
1568
1569 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_GUEST, &parms, sizeof(parms));
1570 if (rc == VERR_NOT_SUPPORTED)
1571 {
1572 /* Not handled by the extension, continue below. */
1573 }
1574 else /* Handled by the extension, bail out. */
1575 return rc;
1576 }
1577
1578 /*
1579 * Allocate a message, populate parameters and post it to the client.
1580 */
1581 PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient, VBOX_SHCL_HOST_MSG_FORMATS_REPORT, 2);
1582 if (pMsg)
1583 {
1584 HGCMSvcSetU32(&pMsg->aParms[0], VBOX_SHCL_HOST_MSG_FORMATS_REPORT);
1585 HGCMSvcSetU32(&pMsg->aParms[1], fFormats);
1586
1587 shClSvcClientLock(pClient);
1588
1589 rc = shClSvcMsgAddAndWakeupClient(pClient, pMsg);
1590
1591 shClSvcClientUnlock(pClient);
1592 }
1593 else
1594 rc = VERR_NO_MEMORY;
1595
1596 if (RT_FAILURE(rc))
1597 LogRel(("Shared Clipboard: Reporting formats %#x to guest failed with %Rrc\n", fFormats, rc));
1598
1599 LogFlowFuncLeaveRC(rc);
1600 return rc;
1601}
1602
1603
1604/**
1605 * Implements VBOX_SHCL_GUEST_FN_REPORT_FORMATS.
1606 *
1607 * @returns VBox status code.
1608 * @param pClient The client state.
1609 * @param cParms Number of parameters.
1610 * @param paParms Array of parameters.
1611 */
1612static int shClSvcClientMsgReportFormats(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1613{
1614 /*
1615 * Check if the service mode allows this operation and whether the guest is
1616 * supposed to be reading from the host.
1617 */
1618 uint32_t uMode = ShClSvcGetMode();
1619 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1620 || uMode == VBOX_SHCL_MODE_GUEST_TO_HOST)
1621 { /* likely */ }
1622 else
1623 return VERR_ACCESS_DENIED;
1624
1625 /*
1626 * Digest parameters.
1627 */
1628 ASSERT_GUEST_RETURN( cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS
1629 || ( cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B
1630 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)),
1631 VERR_WRONG_PARAMETER_COUNT);
1632
1633 uintptr_t iParm = 0;
1634 if (cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B)
1635 {
1636 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1637 /* no defined value, so just ignore it */
1638 iParm++;
1639 }
1640 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1641 uint32_t const fFormats = paParms[iParm].u.uint32;
1642 iParm++;
1643 if (cParms == VBOX_SHCL_CPARMS_REPORT_FORMATS_61B)
1644 {
1645 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1646 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1647 iParm++;
1648 }
1649 Assert(iParm == cParms);
1650
1651 /*
1652 * Report the formats.
1653 *
1654 * We ignore empty reports if the guest isn't the clipboard owner, this
1655 * prevents a freshly booted guest with an empty clibpoard from clearing
1656 * the host clipboard on startup. Likewise, when a guest shutdown it will
1657 * typically issue an empty report in case it's the owner, we don't want
1658 * that to clear host content either.
1659 */
1660 int rc;
1661 if (!fFormats)
1662 rc = VINF_SUCCESS;
1663 else
1664 {
1665 rc = RTCritSectEnter(&g_CritSect);
1666 if (RT_SUCCESS(rc))
1667 {
1668 if (g_ExtState.pfnExtension)
1669 {
1670 SHCLEXTPARMS parms;
1671 RT_ZERO(parms);
1672
1673 parms.u.ReportFormats.uFormats = fFormats;
1674
1675 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_HOST, &parms, sizeof(parms));
1676 }
1677 else
1678 rc = VERR_NOT_SUPPORTED;
1679
1680 /* Let the backend implementation know if the extension above didn't handle the format(s). */
1681 if (rc == VERR_NOT_SUPPORTED)
1682 {
1683#ifdef LOG_ENABLED
1684 char *pszFmts = ShClFormatsToStrA(fFormats);
1685 if (pszFmts)
1686 {
1687 LogRel2(("Shared Clipboard: Guest reported formats '%s' to host\n", pszFmts));
1688 RTStrFree(pszFmts);
1689 }
1690#endif
1691 rc = ShClBackendReportFormats(&g_ShClBackend, pClient, fFormats);
1692 if (RT_FAILURE(rc))
1693 LogRel(("Shared Clipboard: Reporting guest clipboard formats to the host failed with %Rrc\n", rc));
1694 }
1695
1696 RTCritSectLeave(&g_CritSect);
1697 }
1698 else
1699 LogRel2(("Shared Clipboard: Unable to take internal lock while receiving guest clipboard announcement: %Rrc\n", rc));
1700 }
1701
1702 return rc;
1703}
1704
1705/**
1706 * Implements VBOX_SHCL_GUEST_FN_DATA_READ.
1707 *
1708 * Called when the guest wants to read host clipboard data.
1709 *
1710 * @returns VBox status code.
1711 * @retval VINF_BUFFER_OVERFLOW if the guest supplied a smaller buffer than needed in order to read the host clipboard data.
1712 * @param pClient Client that wants to read host clipboard data.
1713 * @param cParms Number of HGCM parameters supplied in \a paParms.
1714 * @param paParms Array of HGCM parameters.
1715 */
1716static int shClSvcClientMsgDataRead(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1717{
1718 LogFlowFuncEnter();
1719
1720 /*
1721 * Check if the service mode allows this operation and whether the guest is
1722 * supposed to be reading from the host.
1723 */
1724 uint32_t uMode = ShClSvcGetMode();
1725 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1726 || uMode == VBOX_SHCL_MODE_HOST_TO_GUEST)
1727 { /* likely */ }
1728 else
1729 return VERR_ACCESS_DENIED;
1730
1731 /*
1732 * Digest parameters.
1733 *
1734 * We are dragging some legacy here from the 6.1 dev cycle, a 5 parameter
1735 * variant which prepends a 64-bit context ID (RAZ as meaning not defined),
1736 * a 32-bit flag (MBZ, no defined meaning) and switches the last two parameters.
1737 */
1738 ASSERT_GUEST_RETURN( cParms == VBOX_SHCL_CPARMS_DATA_READ
1739 || ( cParms == VBOX_SHCL_CPARMS_DATA_READ_61B
1740 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID)),
1741 VERR_WRONG_PARAMETER_COUNT);
1742
1743 uintptr_t iParm = 0;
1744 SHCLCLIENTCMDCTX cmdCtx;
1745 RT_ZERO(cmdCtx);
1746 if (cParms == VBOX_SHCL_CPARMS_DATA_READ_61B)
1747 {
1748 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1749 /* This has no defined meaning and was never used, however the guest passed stuff, so ignore it and leave idContext=0. */
1750 iParm++;
1751 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1752 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1753 iParm++;
1754 }
1755
1756 SHCLFORMAT uFormat = VBOX_SHCL_FMT_NONE;
1757 uint32_t cbData = 0;
1758 void *pvData = NULL;
1759
1760 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1761 uFormat = paParms[iParm].u.uint32;
1762 iParm++;
1763 if (cParms != VBOX_SHCL_CPARMS_DATA_READ_61B)
1764 {
1765 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1766 pvData = paParms[iParm].u.pointer.addr;
1767 cbData = paParms[iParm].u.pointer.size;
1768 iParm++;
1769 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /*cbDataReturned*/
1770 iParm++;
1771 }
1772 else
1773 {
1774 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /*cbDataReturned*/
1775 iParm++;
1776 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1777 pvData = paParms[iParm].u.pointer.addr;
1778 cbData = paParms[iParm].u.pointer.size;
1779 iParm++;
1780 }
1781 Assert(iParm == cParms);
1782
1783 /*
1784 * For some reason we need to do this (makes absolutely no sense to bird).
1785 */
1786 /** @todo r=bird: I really don't get why you need the State.POD.uFormat
1787 * member. I'm sure there is a reason. Incomplete code? */
1788 if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
1789 {
1790 if (pClient->State.POD.uFormat == VBOX_SHCL_FMT_NONE)
1791 pClient->State.POD.uFormat = uFormat;
1792 }
1793
1794#ifdef LOG_ENABLED
1795 char *pszFmt = ShClFormatsToStrA(uFormat);
1796 AssertPtrReturn(pszFmt, VERR_NO_MEMORY);
1797 LogRel2(("Shared Clipboard: Guest wants to read %RU32 bytes host clipboard data in format '%s'\n", cbData, pszFmt));
1798 RTStrFree(pszFmt);
1799#endif
1800
1801 /*
1802 * Do the reading.
1803 */
1804 uint32_t cbActual = 0;
1805
1806 int rc = RTCritSectEnter(&g_CritSect);
1807 AssertRCReturn(rc, rc);
1808
1809 /* If there is a service extension active, try reading data from it first. */
1810 if (g_ExtState.pfnExtension)
1811 {
1812 SHCLEXTPARMS parms;
1813 RT_ZERO(parms);
1814
1815 parms.u.ReadWriteData.uFormat = uFormat;
1816 parms.u.ReadWriteData.pvData = pvData;
1817 parms.u.ReadWriteData.cbData = cbData;
1818
1819 g_ExtState.fReadingData = true;
1820
1821 /* Read clipboard data from the extension. */
1822 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_DATA_READ, &parms, sizeof(parms));
1823
1824 LogRel2(("Shared Clipboard: Read extension clipboard data (fDelayedAnnouncement=%RTbool, fDelayedFormats=%#x, max %RU32 bytes), got %RU32 bytes: rc=%Rrc\n",
1825 g_ExtState.fDelayedAnnouncement, g_ExtState.fDelayedFormats, cbData, parms.u.ReadWriteData.cbData, rc));
1826
1827 /* Did the extension send the clipboard formats yet?
1828 * Otherwise, do this now. */
1829 if (g_ExtState.fDelayedAnnouncement)
1830 {
1831 int rc2 = ShClSvcReportFormats(pClient, g_ExtState.fDelayedFormats);
1832 AssertRC(rc2);
1833
1834 g_ExtState.fDelayedAnnouncement = false;
1835 g_ExtState.fDelayedFormats = 0;
1836 }
1837
1838 g_ExtState.fReadingData = false;
1839
1840 if (RT_SUCCESS(rc))
1841 cbActual = parms.u.ReadWriteData.cbData;
1842 }
1843 else
1844 rc = VERR_NOT_SUPPORTED;
1845
1846 /* Try reading from the backend if the extension above didn't handle the read. */
1847 if (rc == VERR_NOT_SUPPORTED)
1848 {
1849 rc = ShClBackendReadData(&g_ShClBackend, pClient, &cmdCtx, uFormat, pvData, cbData, &cbActual);
1850 if (RT_SUCCESS(rc))
1851 LogRel2(("Shared Clipboard: Read host clipboard data (max %RU32 bytes), got %RU32 bytes\n", cbData, cbActual));
1852 else
1853 LogRel(("Shared Clipboard: Reading host clipboard data failed with %Rrc\n", rc));
1854 }
1855
1856 if (RT_SUCCESS(rc))
1857 {
1858 /* Return the actual size required to fullfil the request. */
1859 if (cParms != VBOX_SHCL_CPARMS_DATA_READ_61B)
1860 HGCMSvcSetU32(&paParms[2], cbActual);
1861 else
1862 HGCMSvcSetU32(&paParms[3], cbActual);
1863
1864 /* If the data to return exceeds the buffer the guest supplies, tell it (and let it try again). */
1865 if (cbActual >= cbData)
1866 rc = VINF_BUFFER_OVERFLOW;
1867 }
1868
1869 RTCritSectLeave(&g_CritSect);
1870
1871 LogFlowFuncLeaveRC(rc);
1872 return rc;
1873}
1874
1875/**
1876 * Implements VBOX_SHCL_GUEST_FN_DATA_WRITE.
1877 *
1878 * Called when the guest writes clipboard data to the host.
1879 *
1880 * @returns VBox status code.
1881 * @param pClient Client that wants to read host clipboard data.
1882 * @param cParms Number of HGCM parameters supplied in \a paParms.
1883 * @param paParms Array of HGCM parameters.
1884 */
1885static int shClSvcClientMsgDataWrite(PSHCLCLIENT pClient, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
1886{
1887 LogFlowFuncEnter();
1888
1889 /*
1890 * Check if the service mode allows this operation and whether the guest is
1891 * supposed to be reading from the host.
1892 */
1893 uint32_t uMode = ShClSvcGetMode();
1894 if ( uMode == VBOX_SHCL_MODE_BIDIRECTIONAL
1895 || uMode == VBOX_SHCL_MODE_GUEST_TO_HOST)
1896 { /* likely */ }
1897 else
1898 return VERR_ACCESS_DENIED;
1899
1900 const bool fReportsContextID = RT_BOOL(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID);
1901
1902 /*
1903 * Digest parameters.
1904 *
1905 * There are 3 different format here, formatunately no parameters have been
1906 * switch around so it's plain sailing compared to the DATA_READ message.
1907 */
1908 ASSERT_GUEST_RETURN(fReportsContextID
1909 ? cParms == VBOX_SHCL_CPARMS_DATA_WRITE || cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B
1910 : cParms == VBOX_SHCL_CPARMS_DATA_WRITE_OLD,
1911 VERR_WRONG_PARAMETER_COUNT);
1912
1913 uintptr_t iParm = 0;
1914 SHCLCLIENTCMDCTX cmdCtx;
1915 RT_ZERO(cmdCtx);
1916 if (cParms > VBOX_SHCL_CPARMS_DATA_WRITE_OLD)
1917 {
1918 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_64BIT, VERR_WRONG_PARAMETER_TYPE);
1919 cmdCtx.uContextID = paParms[iParm].u.uint64;
1920 iParm++;
1921 }
1922 else
1923 {
1924 /* Older Guest Additions (< 6.1) did not supply a context ID.
1925 * We dig it out from our saved context ID list then a bit down below. */
1926 }
1927
1928 if (cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B)
1929 {
1930 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE);
1931 ASSERT_GUEST_RETURN(paParms[iParm].u.uint32 == 0, VERR_INVALID_FLAGS);
1932 iParm++;
1933 }
1934
1935 SHCLFORMAT uFormat = VBOX_SHCL_FMT_NONE;
1936 uint32_t cbData = 0;
1937 void *pvData = NULL;
1938
1939 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* Format bit. */
1940 uFormat = paParms[iParm].u.uint32;
1941 iParm++;
1942 if (cParms == VBOX_SHCL_CPARMS_DATA_WRITE_61B)
1943 {
1944 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_32BIT, VERR_WRONG_PARAMETER_TYPE); /* "cbData" - duplicates buffer size. */
1945 iParm++;
1946 }
1947 ASSERT_GUEST_RETURN(paParms[iParm].type == VBOX_HGCM_SVC_PARM_PTR, VERR_WRONG_PARAMETER_TYPE); /* Data buffer */
1948 pvData = paParms[iParm].u.pointer.addr;
1949 cbData = paParms[iParm].u.pointer.size;
1950 iParm++;
1951 Assert(iParm == cParms);
1952
1953 /*
1954 * Handle / check context ID.
1955 */
1956 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. */
1957 {
1958 PSHCLCLIENTLEGACYCID pCID = NULL;
1959 PSHCLCLIENTLEGACYCID pCIDIter;
1960 RTListForEach(&pClient->Legacy.lstCID, pCIDIter, SHCLCLIENTLEGACYCID, Node) /* Slow, but does the job for now. */
1961 {
1962 if (pCIDIter->uFormat == uFormat)
1963 {
1964 pCID = pCIDIter;
1965 break;
1966 }
1967 }
1968
1969 ASSERT_GUEST_MSG_RETURN(pCID != NULL, ("Context ID for format %#x not found\n", uFormat), VERR_INVALID_CONTEXT);
1970 cmdCtx.uContextID = pCID->uCID;
1971
1972 /* Not needed anymore; clean up. */
1973 Assert(pClient->Legacy.cCID);
1974 pClient->Legacy.cCID--;
1975 RTListNodeRemove(&pCID->Node);
1976 RTMemFree(pCID);
1977 }
1978
1979 uint64_t const idCtxExpected = VBOX_SHCL_CONTEXTID_MAKE(pClient->State.uSessionID, pClient->EventSrc.uID,
1980 VBOX_SHCL_CONTEXTID_GET_EVENT(cmdCtx.uContextID));
1981 ASSERT_GUEST_MSG_RETURN(cmdCtx.uContextID == idCtxExpected,
1982 ("Wrong context ID: %#RX64, expected %#RX64\n", cmdCtx.uContextID, idCtxExpected),
1983 VERR_INVALID_CONTEXT);
1984
1985 /*
1986 * For some reason we need to do this (makes absolutely no sense to bird).
1987 */
1988 /** @todo r=bird: I really don't get why you need the State.POD.uFormat
1989 * member. I'm sure there is a reason. Incomplete code? */
1990 if (!(pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID))
1991 {
1992 if (pClient->State.POD.uFormat == VBOX_SHCL_FMT_NONE)
1993 pClient->State.POD.uFormat = uFormat;
1994 }
1995
1996#ifdef LOG_ENABLED
1997 char *pszFmt = ShClFormatsToStrA(uFormat);
1998 if (pszFmt)
1999 {
2000 LogRel2(("Shared Clipboard: Guest writes %RU32 bytes clipboard data in format '%s' to host\n", cbData, pszFmt));
2001 RTStrFree(pszFmt);
2002 }
2003#endif
2004
2005 /*
2006 * Write the data to the active host side clipboard.
2007 */
2008 int rc = RTCritSectEnter(&g_CritSect);
2009 AssertRCReturn(rc, rc);
2010
2011 if (g_ExtState.pfnExtension)
2012 {
2013 SHCLEXTPARMS parms;
2014 RT_ZERO(parms);
2015
2016 parms.u.ReadWriteData.uFormat = uFormat;
2017 parms.u.ReadWriteData.pvData = pvData;
2018 parms.u.ReadWriteData.cbData = cbData;
2019
2020 rc = g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_DATA_WRITE, &parms, sizeof(parms));
2021 }
2022 else
2023 rc = VERR_NOT_SUPPORTED;
2024
2025 /* Let the backend implementation know if the extension above didn't handle the write. */
2026 if (rc == VERR_NOT_SUPPORTED)
2027 {
2028 rc = ShClBackendWriteData(&g_ShClBackend, pClient, &cmdCtx, uFormat, pvData, cbData);
2029 if (RT_FAILURE(rc))
2030 LogRel(("Shared Clipboard: Writing guest clipboard data to the host failed with %Rrc\n", rc));
2031
2032 int rc2; /* Don't return internals back to the guest. */
2033 rc2 = ShClSvcGuestDataSignal(pClient, &cmdCtx, uFormat, pvData, cbData); /* To complete pending events, if any. */
2034 if (RT_FAILURE(rc2))
2035 LogRel(("Shared Clipboard: Signalling host about guest clipboard data failed with %Rrc\n", rc2));
2036 AssertRC(rc2);
2037 }
2038
2039 RTCritSectLeave(&g_CritSect);
2040
2041 LogFlowFuncLeaveRC(rc);
2042 return rc;
2043}
2044
2045/**
2046 * Implements the VBOX_SHCL_GUEST_FN_ERROR.
2047 *
2048 * @returns VBox status code.
2049 * @param cParms Number of HGCM parameters supplied in \a paParms.
2050 * @param paParms Array of HGCM parameters.
2051 * @param pRc Where to store the received error code.
2052 */
2053static int shClSvcClientMsgError(uint32_t cParms, VBOXHGCMSVCPARM paParms[], int *pRc)
2054{
2055 AssertPtrReturn(paParms, VERR_INVALID_PARAMETER);
2056 AssertPtrReturn(pRc, VERR_INVALID_PARAMETER);
2057
2058 int rc;
2059
2060 if (cParms == VBOX_SHCL_CPARMS_ERROR)
2061 {
2062 rc = HGCMSvcGetU32(&paParms[1], (uint32_t *)pRc); /** @todo int vs. uint32_t !!! */
2063 }
2064 else
2065 rc = VERR_INVALID_PARAMETER;
2066
2067 LogFlowFuncLeaveRC(rc);
2068 return rc;
2069}
2070
2071static int svcInit(VBOXHGCMSVCFNTABLE *pTable)
2072{
2073 int rc = RTCritSectInit(&g_CritSect);
2074
2075 if (RT_SUCCESS(rc))
2076 {
2077 shClSvcModeSet(VBOX_SHCL_MODE_OFF);
2078
2079 rc = ShClBackendInit(ShClSvcGetBackend(), pTable);
2080
2081 /* Clean up on failure, because 'svnUnload' will not be called
2082 * if the 'svcInit' returns an error.
2083 */
2084 if (RT_FAILURE(rc))
2085 {
2086 RTCritSectDelete(&g_CritSect);
2087 }
2088 }
2089
2090 return rc;
2091}
2092
2093static DECLCALLBACK(int) svcUnload(void *)
2094{
2095 LogFlowFuncEnter();
2096
2097 ShClBackendDestroy(ShClSvcGetBackend());
2098
2099 RTCritSectDelete(&g_CritSect);
2100
2101 return VINF_SUCCESS;
2102}
2103
2104static DECLCALLBACK(int) svcDisconnect(void *, uint32_t u32ClientID, void *pvClient)
2105{
2106 LogFunc(("u32ClientID=%RU32\n", u32ClientID));
2107
2108 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2109 AssertPtr(pClient);
2110
2111 /* In order to communicate with guest service, HGCM VRDP clipboard extension
2112 * needs to know its connection client ID. Currently, in svcConnect() we always
2113 * cache ID of the first ever connected client. When client disconnects,
2114 * we need to forget its ID and let svcConnect() to pick up the next ID when a new
2115 * connection will be requested by guest service (see #10115). */
2116 if (g_ExtState.uClientID == u32ClientID)
2117 {
2118 g_ExtState.uClientID = 0;
2119 }
2120
2121 ShClBackendDisconnect(&g_ShClBackend, pClient);
2122
2123 shClSvcClientDestroy(pClient);
2124
2125 return VINF_SUCCESS;
2126}
2127
2128static DECLCALLBACK(int) svcConnect(void *, uint32_t u32ClientID, void *pvClient, uint32_t fRequestor, bool fRestoring)
2129{
2130 RT_NOREF(fRequestor, fRestoring);
2131
2132 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2133 AssertPtr(pvClient);
2134
2135 int rc = shClSvcClientInit(pClient, u32ClientID);
2136 if (RT_SUCCESS(rc))
2137 {
2138 /* Assign weak pointer to client map. */
2139 /** @todo r=bird: The g_mapClients is only there for looking up
2140 * g_ExtState.uClientID (unserialized btw), so why not use store the
2141 * pClient value directly in g_ExtState instead of the ID? It cannot
2142 * crash any worse that racing map insertion/removal. */
2143 g_mapClients[u32ClientID] = pClient; /** @todo Handle OOM / collisions? */
2144 rc = ShClBackendConnect(&g_ShClBackend, pClient, ShClSvcGetHeadless());
2145 if (RT_SUCCESS(rc))
2146 {
2147 /* Sync the host clipboard content with the client. */
2148 rc = ShClBackendSync(&g_ShClBackend, pClient);
2149 if (RT_SUCCESS(rc))
2150 {
2151 /* For now we ASSUME that the first client that connects is in charge for
2152 communicating with the service extension. */
2153 /** @todo This isn't optimal, but only the guest really knows which client is in
2154 * focus on the console. See @bugref{10115} for details. */
2155 if (g_ExtState.uClientID == 0)
2156 g_ExtState.uClientID = u32ClientID;
2157
2158 /* The sync could return VINF_NO_CHANGE if nothing has changed on the host, but
2159 older Guest Additions didn't use RT_SUCCESS to but == VINF_SUCCESS to check for
2160 success. So just return VINF_SUCCESS here to not break older Guest Additions. */
2161 LogFunc(("Successfully connected client %#x%s\n",
2162 u32ClientID, g_ExtState.uClientID == u32ClientID ? " - Use by ExtState too" : ""));
2163 return VINF_SUCCESS;
2164 }
2165
2166 LogFunc(("ShClBackendSync failed: %Rrc\n", rc));
2167 ShClBackendDisconnect(&g_ShClBackend, pClient);
2168 }
2169 else
2170 LogFunc(("ShClBackendConnect failed: %Rrc\n", rc));
2171 shClSvcClientDestroy(pClient);
2172 }
2173 else
2174 LogFunc(("shClSvcClientInit failed: %Rrc\n", rc));
2175 LogFlowFuncLeaveRC(rc);
2176 return rc;
2177}
2178
2179static DECLCALLBACK(void) svcCall(void *,
2180 VBOXHGCMCALLHANDLE callHandle,
2181 uint32_t u32ClientID,
2182 void *pvClient,
2183 uint32_t u32Function,
2184 uint32_t cParms,
2185 VBOXHGCMSVCPARM paParms[],
2186 uint64_t tsArrival)
2187{
2188 RT_NOREF(u32ClientID, pvClient, tsArrival);
2189 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2190 AssertPtr(pClient);
2191
2192#ifdef LOG_ENABLED
2193 Log2Func(("u32ClientID=%RU32, fn=%RU32 (%s), cParms=%RU32, paParms=%p\n",
2194 u32ClientID, u32Function, ShClGuestMsgToStr(u32Function), cParms, paParms));
2195 for (uint32_t i = 0; i < cParms; i++)
2196 {
2197 switch (paParms[i].type)
2198 {
2199 case VBOX_HGCM_SVC_PARM_32BIT:
2200 Log3Func((" paParms[%RU32]: type uint32_t - value %RU32\n", i, paParms[i].u.uint32));
2201 break;
2202 case VBOX_HGCM_SVC_PARM_64BIT:
2203 Log3Func((" paParms[%RU32]: type uint64_t - value %RU64\n", i, paParms[i].u.uint64));
2204 break;
2205 case VBOX_HGCM_SVC_PARM_PTR:
2206 Log3Func((" paParms[%RU32]: type ptr - value 0x%p (%RU32 bytes)\n",
2207 i, paParms[i].u.pointer.addr, paParms[i].u.pointer.size));
2208 break;
2209 case VBOX_HGCM_SVC_PARM_PAGES:
2210 Log3Func((" paParms[%RU32]: type pages - cb=%RU32, cPages=%RU16\n",
2211 i, paParms[i].u.Pages.cb, paParms[i].u.Pages.cPages));
2212 break;
2213 default:
2214 AssertFailed();
2215 }
2216 }
2217 Log2Func(("Client state: fFlags=0x%x, fGuestFeatures0=0x%x, fGuestFeatures1=0x%x\n",
2218 pClient->State.fFlags, pClient->State.fGuestFeatures0, pClient->State.fGuestFeatures1));
2219#endif
2220
2221 int rc;
2222 switch (u32Function)
2223 {
2224 case VBOX_SHCL_GUEST_FN_MSG_OLD_GET_WAIT:
2225 RTCritSectEnter(&pClient->CritSect);
2226 rc = shClSvcClientMsgOldGet(pClient, callHandle, cParms, paParms);
2227 RTCritSectLeave(&pClient->CritSect);
2228 break;
2229
2230 case VBOX_SHCL_GUEST_FN_CONNECT:
2231 LogRel(("Shared Clipboard: 6.1.0 beta or rc Guest Additions detected. Please upgrade!\n"));
2232 rc = VERR_NOT_IMPLEMENTED;
2233 break;
2234
2235 case VBOX_SHCL_GUEST_FN_NEGOTIATE_CHUNK_SIZE:
2236 rc = shClSvcClientNegogiateChunkSize(pClient, callHandle, cParms, paParms);
2237 break;
2238
2239 case VBOX_SHCL_GUEST_FN_REPORT_FEATURES:
2240 rc = shClSvcClientReportFeatures(pClient, callHandle, cParms, paParms);
2241 break;
2242
2243 case VBOX_SHCL_GUEST_FN_QUERY_FEATURES:
2244 rc = shClSvcClientMsgQueryFeatures(callHandle, cParms, paParms);
2245 break;
2246
2247 case VBOX_SHCL_GUEST_FN_MSG_PEEK_NOWAIT:
2248 RTCritSectEnter(&pClient->CritSect);
2249 rc = shClSvcClientMsgPeek(pClient, callHandle, cParms, paParms, false /*fWait*/);
2250 RTCritSectLeave(&pClient->CritSect);
2251 break;
2252
2253 case VBOX_SHCL_GUEST_FN_MSG_PEEK_WAIT:
2254 RTCritSectEnter(&pClient->CritSect);
2255 rc = shClSvcClientMsgPeek(pClient, callHandle, cParms, paParms, true /*fWait*/);
2256 RTCritSectLeave(&pClient->CritSect);
2257 break;
2258
2259 case VBOX_SHCL_GUEST_FN_MSG_GET:
2260 RTCritSectEnter(&pClient->CritSect);
2261 rc = shClSvcClientMsgGet(pClient, callHandle, cParms, paParms);
2262 RTCritSectLeave(&pClient->CritSect);
2263 break;
2264
2265 case VBOX_SHCL_GUEST_FN_MSG_CANCEL:
2266 RTCritSectEnter(&pClient->CritSect);
2267 rc = shClSvcClientMsgCancel(pClient, cParms);
2268 RTCritSectLeave(&pClient->CritSect);
2269 break;
2270
2271 case VBOX_SHCL_GUEST_FN_REPORT_FORMATS:
2272 rc = shClSvcClientMsgReportFormats(pClient, cParms, paParms);
2273 break;
2274
2275 case VBOX_SHCL_GUEST_FN_DATA_READ:
2276 rc = shClSvcClientMsgDataRead(pClient, cParms, paParms);
2277 break;
2278
2279 case VBOX_SHCL_GUEST_FN_DATA_WRITE:
2280 rc = shClSvcClientMsgDataWrite(pClient, cParms, paParms);
2281 break;
2282
2283 case VBOX_SHCL_GUEST_FN_ERROR:
2284 {
2285 int rcGuest;
2286 rc = shClSvcClientMsgError(cParms,paParms, &rcGuest);
2287 if (RT_SUCCESS(rc))
2288 {
2289 LogRel(("Shared Clipboard: Error reported from guest side: %Rrc\n", rcGuest));
2290
2291 shClSvcClientLock(pClient);
2292
2293 /* Reset message queue. */
2294 shClSvcMsgQueueReset(pClient);
2295
2296#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2297 /* Reset transfer state. */
2298 shClSvcTransferDestroyAll(pClient);
2299#endif
2300 shClSvcClientUnlock(pClient);
2301 }
2302 break;
2303 }
2304
2305 default:
2306 {
2307#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2308 if ( u32Function <= VBOX_SHCL_GUEST_FN_LAST
2309 && (pClient->State.fGuestFeatures0 & VBOX_SHCL_GF_0_CONTEXT_ID) )
2310 {
2311 if (g_fTransferMode & VBOX_SHCL_TRANSFER_MODE_F_ENABLED)
2312 rc = ShClSvcTransferMsgClientHandler(pClient, callHandle, u32Function, cParms, paParms, tsArrival);
2313 else
2314 {
2315 LogRel2(("Shared Clipboard: File transfers are disabled for this VM\n"));
2316 rc = VERR_ACCESS_DENIED;
2317 }
2318 }
2319 else
2320#endif
2321 {
2322 LogRel2(("Shared Clipboard: Unknown guest function: %u (%#x)\n", u32Function, u32Function));
2323 rc = VERR_NOT_IMPLEMENTED;
2324 }
2325 break;
2326 }
2327 }
2328
2329 LogFlowFunc(("[Client %RU32] rc=%Rrc\n", pClient->State.uClientID, rc));
2330
2331 if (rc != VINF_HGCM_ASYNC_EXECUTE)
2332 g_pHelpers->pfnCallComplete(callHandle, rc);
2333}
2334
2335/**
2336 * Initializes a Shared Clipboard service's client state.
2337 *
2338 * @returns VBox status code.
2339 * @param pClientState Client state to initialize.
2340 * @param uClientID Client ID (HGCM) to use for this client state.
2341 */
2342int shClSvcClientStateInit(PSHCLCLIENTSTATE pClientState, uint32_t uClientID)
2343{
2344 LogFlowFuncEnter();
2345
2346 shclSvcClientStateReset(pClientState);
2347
2348 /* Register the client. */
2349 pClientState->uClientID = uClientID;
2350
2351 return VINF_SUCCESS;
2352}
2353
2354/**
2355 * Destroys a Shared Clipboard service's client state.
2356 *
2357 * @returns VBox status code.
2358 * @param pClientState Client state to destroy.
2359 */
2360int shClSvcClientStateDestroy(PSHCLCLIENTSTATE pClientState)
2361{
2362 RT_NOREF(pClientState);
2363
2364 LogFlowFuncEnter();
2365
2366 return VINF_SUCCESS;
2367}
2368
2369/**
2370 * Resets a Shared Clipboard service's client state.
2371 *
2372 * @param pClientState Client state to reset.
2373 */
2374void shclSvcClientStateReset(PSHCLCLIENTSTATE pClientState)
2375{
2376 LogFlowFuncEnter();
2377
2378 pClientState->fGuestFeatures0 = VBOX_SHCL_GF_NONE;
2379 pClientState->fGuestFeatures1 = VBOX_SHCL_GF_NONE;
2380
2381 pClientState->cbChunkSize = VBOX_SHCL_DEFAULT_CHUNK_SIZE; /** @todo Make this configurable. */
2382 pClientState->enmSource = SHCLSOURCE_INVALID;
2383 pClientState->fFlags = SHCLCLIENTSTATE_FLAGS_NONE;
2384
2385 pClientState->POD.enmDir = SHCLTRANSFERDIR_UNKNOWN;
2386 pClientState->POD.uFormat = VBOX_SHCL_FMT_NONE;
2387 pClientState->POD.cbToReadWriteTotal = 0;
2388 pClientState->POD.cbReadWritten = 0;
2389
2390#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2391 pClientState->Transfers.enmTransferDir = SHCLTRANSFERDIR_UNKNOWN;
2392#endif
2393}
2394
2395/*
2396 * We differentiate between a function handler for the guest and one for the host.
2397 */
2398static DECLCALLBACK(int) svcHostCall(void *,
2399 uint32_t u32Function,
2400 uint32_t cParms,
2401 VBOXHGCMSVCPARM paParms[])
2402{
2403 int rc = VINF_SUCCESS;
2404
2405 LogFlowFunc(("u32Function=%RU32 (%s), cParms=%RU32, paParms=%p\n",
2406 u32Function, ShClHostFunctionToStr(u32Function), cParms, paParms));
2407
2408 switch (u32Function)
2409 {
2410 case VBOX_SHCL_HOST_FN_SET_MODE:
2411 {
2412 if (cParms != 1)
2413 {
2414 rc = VERR_INVALID_PARAMETER;
2415 }
2416 else
2417 {
2418 uint32_t u32Mode = VBOX_SHCL_MODE_OFF;
2419
2420 rc = HGCMSvcGetU32(&paParms[0], &u32Mode);
2421 if (RT_SUCCESS(rc))
2422 rc = shClSvcModeSet(u32Mode);
2423 }
2424
2425 break;
2426 }
2427
2428#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2429 case VBOX_SHCL_HOST_FN_SET_TRANSFER_MODE:
2430 {
2431 if (cParms != 1)
2432 {
2433 rc = VERR_INVALID_PARAMETER;
2434 }
2435 else
2436 {
2437 uint32_t fTransferMode;
2438 rc = HGCMSvcGetU32(&paParms[0], &fTransferMode);
2439 if (RT_SUCCESS(rc))
2440 rc = shClSvcTransferModeSet(fTransferMode);
2441 }
2442 break;
2443 }
2444#endif
2445 case VBOX_SHCL_HOST_FN_SET_HEADLESS:
2446 {
2447 if (cParms != 1)
2448 {
2449 rc = VERR_INVALID_PARAMETER;
2450 }
2451 else
2452 {
2453 uint32_t uHeadless;
2454 rc = HGCMSvcGetU32(&paParms[0], &uHeadless);
2455 if (RT_SUCCESS(rc))
2456 {
2457 g_fHeadless = RT_BOOL(uHeadless);
2458 LogRel(("Shared Clipboard: Service running in %s mode\n", g_fHeadless ? "headless" : "normal"));
2459 }
2460 }
2461 break;
2462 }
2463
2464 default:
2465 {
2466#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
2467 rc = ShClSvcTransferMsgHostHandler(u32Function, cParms, paParms);
2468#else
2469 rc = VERR_NOT_IMPLEMENTED;
2470#endif
2471 break;
2472 }
2473 }
2474
2475 LogFlowFuncLeaveRC(rc);
2476 return rc;
2477}
2478
2479#ifndef UNIT_TEST
2480
2481/**
2482 * SSM descriptor table for the SHCLCLIENTLEGACYCID structure.
2483 *
2484 * @note Saving the ListEntry attribute is not necessary, as this gets used on runtime only.
2485 */
2486static SSMFIELD const s_aShClSSMClientLegacyCID[] =
2487{
2488 SSMFIELD_ENTRY(SHCLCLIENTLEGACYCID, uCID),
2489 SSMFIELD_ENTRY(SHCLCLIENTLEGACYCID, enmType),
2490 SSMFIELD_ENTRY(SHCLCLIENTLEGACYCID, uFormat),
2491 SSMFIELD_ENTRY_TERM()
2492};
2493
2494/**
2495 * SSM descriptor table for the SHCLCLIENTSTATE structure.
2496 *
2497 * @note Saving the session ID not necessary, as they're not persistent across
2498 * state save/restore.
2499 */
2500static SSMFIELD const s_aShClSSMClientState[] =
2501{
2502 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures0),
2503 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures1),
2504 SSMFIELD_ENTRY(SHCLCLIENTSTATE, cbChunkSize),
2505 SSMFIELD_ENTRY(SHCLCLIENTSTATE, enmSource),
2506 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fFlags),
2507 SSMFIELD_ENTRY_TERM()
2508};
2509
2510/**
2511 * VBox 6.1 Beta 1 version of s_aShClSSMClientState (no flags).
2512 */
2513static SSMFIELD const s_aShClSSMClientState61B1[] =
2514{
2515 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures0),
2516 SSMFIELD_ENTRY(SHCLCLIENTSTATE, fGuestFeatures1),
2517 SSMFIELD_ENTRY(SHCLCLIENTSTATE, cbChunkSize),
2518 SSMFIELD_ENTRY(SHCLCLIENTSTATE, enmSource),
2519 SSMFIELD_ENTRY_TERM()
2520};
2521
2522/**
2523 * SSM descriptor table for the SHCLCLIENTPODSTATE structure.
2524 */
2525static SSMFIELD const s_aShClSSMClientPODState[] =
2526{
2527 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, enmDir),
2528 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, uFormat),
2529 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, cbToReadWriteTotal),
2530 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, cbReadWritten),
2531 SSMFIELD_ENTRY(SHCLCLIENTPODSTATE, tsLastReadWrittenMs),
2532 SSMFIELD_ENTRY_TERM()
2533};
2534
2535/**
2536 * SSM descriptor table for the SHCLCLIENTURISTATE structure.
2537 */
2538static SSMFIELD const s_aShClSSMClientTransferState[] =
2539{
2540 SSMFIELD_ENTRY(SHCLCLIENTTRANSFERSTATE, enmTransferDir),
2541 SSMFIELD_ENTRY_TERM()
2542};
2543
2544/**
2545 * SSM descriptor table for the header of the SHCLCLIENTMSG structure.
2546 * The actual message parameters will be serialized separately.
2547 */
2548static SSMFIELD const s_aShClSSMClientMsgHdr[] =
2549{
2550 SSMFIELD_ENTRY(SHCLCLIENTMSG, idMsg),
2551 SSMFIELD_ENTRY(SHCLCLIENTMSG, cParms),
2552 SSMFIELD_ENTRY_TERM()
2553};
2554
2555/**
2556 * SSM descriptor table for what used to be the VBOXSHCLMSGCTX structure but is
2557 * now part of SHCLCLIENTMSG.
2558 */
2559static SSMFIELD const s_aShClSSMClientMsgCtx[] =
2560{
2561 SSMFIELD_ENTRY(SHCLCLIENTMSG, idCtx),
2562 SSMFIELD_ENTRY_TERM()
2563};
2564#endif /* !UNIT_TEST */
2565
2566static DECLCALLBACK(int) svcSaveState(void *, uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM)
2567{
2568 LogFlowFuncEnter();
2569
2570#ifndef UNIT_TEST
2571 /*
2572 * When the state will be restored, pending requests will be reissued
2573 * by VMMDev. The service therefore must save state as if there were no
2574 * pending request.
2575 * Pending requests, if any, will be completed in svcDisconnect.
2576 */
2577 RT_NOREF(u32ClientID);
2578 LogFunc(("u32ClientID=%RU32\n", u32ClientID));
2579
2580 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2581 AssertPtr(pClient);
2582
2583 /* Write Shared Clipboard saved state version. */
2584 pVMM->pfnSSMR3PutU32(pSSM, VBOX_SHCL_SAVED_STATE_VER_CURRENT);
2585
2586 int rc = pVMM->pfnSSMR3PutStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /*fFlags*/, &s_aShClSSMClientState[0], NULL);
2587 AssertRCReturn(rc, rc);
2588
2589 rc = pVMM->pfnSSMR3PutStructEx(pSSM, &pClient->State.POD, sizeof(pClient->State.POD), 0 /*fFlags*/, &s_aShClSSMClientPODState[0], NULL);
2590 AssertRCReturn(rc, rc);
2591
2592 rc = pVMM->pfnSSMR3PutStructEx(pSSM, &pClient->State.Transfers, sizeof(pClient->State.Transfers), 0 /*fFlags*/, &s_aShClSSMClientTransferState[0], NULL);
2593 AssertRCReturn(rc, rc);
2594
2595 /* Serialize the client's internal message queue. */
2596 rc = pVMM->pfnSSMR3PutU64(pSSM, pClient->cMsgAllocated);
2597 AssertRCReturn(rc, rc);
2598
2599 PSHCLCLIENTMSG pMsg;
2600 RTListForEach(&pClient->MsgQueue, pMsg, SHCLCLIENTMSG, ListEntry)
2601 {
2602 pVMM->pfnSSMR3PutStructEx(pSSM, pMsg, sizeof(SHCLCLIENTMSG), 0 /*fFlags*/, &s_aShClSSMClientMsgHdr[0], NULL);
2603 pVMM->pfnSSMR3PutStructEx(pSSM, pMsg, sizeof(SHCLCLIENTMSG), 0 /*fFlags*/, &s_aShClSSMClientMsgCtx[0], NULL);
2604
2605 for (uint32_t iParm = 0; iParm < pMsg->cParms; iParm++)
2606 HGCMSvcSSMR3Put(&pMsg->aParms[iParm], pSSM, pVMM);
2607 }
2608
2609 rc = pVMM->pfnSSMR3PutU64(pSSM, pClient->Legacy.cCID);
2610 AssertRCReturn(rc, rc);
2611
2612 PSHCLCLIENTLEGACYCID pCID;
2613 RTListForEach(&pClient->Legacy.lstCID, pCID, SHCLCLIENTLEGACYCID, Node)
2614 {
2615 rc = pVMM->pfnSSMR3PutStructEx(pSSM, pCID, sizeof(SHCLCLIENTLEGACYCID), 0 /*fFlags*/, &s_aShClSSMClientLegacyCID[0], NULL);
2616 AssertRCReturn(rc, rc);
2617 }
2618#else /* UNIT_TEST */
2619 RT_NOREF(u32ClientID, pvClient, pSSM, pVMM);
2620#endif /* UNIT_TEST */
2621 return VINF_SUCCESS;
2622}
2623
2624#ifndef UNIT_TEST
2625static int svcLoadStateV0(uint32_t u32ClientID, void *pvClient, PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, uint32_t uVersion)
2626{
2627 RT_NOREF(u32ClientID, pvClient, pSSM, uVersion);
2628
2629 uint32_t uMarker;
2630 int rc = pVMM->pfnSSMR3GetU32(pSSM, &uMarker); /* Begin marker. */
2631 AssertRC(rc);
2632 Assert(uMarker == UINT32_C(0x19200102) /* SSMR3STRUCT_BEGIN */);
2633
2634 rc = pVMM->pfnSSMR3Skip(pSSM, sizeof(uint32_t)); /* Client ID */
2635 AssertRCReturn(rc, rc);
2636
2637 bool fValue;
2638 rc = pVMM->pfnSSMR3GetBool(pSSM, &fValue); /* fHostMsgQuit */
2639 AssertRCReturn(rc, rc);
2640
2641 rc = pVMM->pfnSSMR3GetBool(pSSM, &fValue); /* fHostMsgReadData */
2642 AssertRCReturn(rc, rc);
2643
2644 rc = pVMM->pfnSSMR3GetBool(pSSM, &fValue); /* fHostMsgFormats */
2645 AssertRCReturn(rc, rc);
2646
2647 uint32_t fFormats;
2648 rc = pVMM->pfnSSMR3GetU32(pSSM, &fFormats); /* u32RequestedFormat */
2649 AssertRCReturn(rc, rc);
2650
2651 rc = pVMM->pfnSSMR3GetU32(pSSM, &uMarker); /* End marker. */
2652 AssertRCReturn(rc, rc);
2653 Assert(uMarker == UINT32_C(0x19920406) /* SSMR3STRUCT_END */);
2654
2655 return VINF_SUCCESS;
2656}
2657#endif /* UNIT_TEST */
2658
2659static DECLCALLBACK(int) svcLoadState(void *, uint32_t u32ClientID, void *pvClient,
2660 PSSMHANDLE pSSM, PCVMMR3VTABLE pVMM, uint32_t uVersion)
2661{
2662 LogFlowFuncEnter();
2663
2664#ifndef UNIT_TEST
2665
2666 RT_NOREF(u32ClientID, uVersion);
2667
2668 PSHCLCLIENT pClient = (PSHCLCLIENT)pvClient;
2669 AssertPtr(pClient);
2670
2671 /* Restore the client data. */
2672 uint32_t lenOrVer;
2673 int rc = pVMM->pfnSSMR3GetU32(pSSM, &lenOrVer);
2674 AssertRCReturn(rc, rc);
2675
2676 LogFunc(("u32ClientID=%RU32, lenOrVer=%#RX64\n", u32ClientID, lenOrVer));
2677
2678 if (lenOrVer == VBOX_SHCL_SAVED_STATE_VER_3_1)
2679 return svcLoadStateV0(u32ClientID, pvClient, pSSM, pVMM, uVersion);
2680
2681 if ( lenOrVer >= VBOX_SHCL_SAVED_STATE_VER_6_1B2
2682 && lenOrVer <= VBOX_SHCL_SAVED_STATE_VER_CURRENT)
2683 {
2684 if (lenOrVer >= VBOX_SHCL_SAVED_STATE_VER_6_1RC1)
2685 {
2686 pVMM->pfnSSMR3GetStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /* fFlags */,
2687 &s_aShClSSMClientState[0], NULL);
2688 pVMM->pfnSSMR3GetStructEx(pSSM, &pClient->State.POD, sizeof(pClient->State.POD), 0 /* fFlags */,
2689 &s_aShClSSMClientPODState[0], NULL);
2690 }
2691 else
2692 pVMM->pfnSSMR3GetStructEx(pSSM, &pClient->State, sizeof(pClient->State), 0 /* fFlags */,
2693 &s_aShClSSMClientState61B1[0], NULL);
2694 rc = pVMM->pfnSSMR3GetStructEx(pSSM, &pClient->State.Transfers, sizeof(pClient->State.Transfers), 0 /* fFlags */,
2695 &s_aShClSSMClientTransferState[0], NULL);
2696 AssertRCReturn(rc, rc);
2697
2698 /* Load the client's internal message queue. */
2699 uint64_t cMsgs;
2700 rc = pVMM->pfnSSMR3GetU64(pSSM, &cMsgs);
2701 AssertRCReturn(rc, rc);
2702 AssertLogRelMsgReturn(cMsgs < _16K, ("Too many messages: %u (%x)\n", cMsgs, cMsgs), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
2703
2704 for (uint64_t i = 0; i < cMsgs; i++)
2705 {
2706 union
2707 {
2708 SHCLCLIENTMSG Msg;
2709 uint8_t abPadding[RT_UOFFSETOF(SHCLCLIENTMSG, aParms) + sizeof(VBOXHGCMSVCPARM) * 2];
2710 } u;
2711
2712 pVMM->pfnSSMR3GetStructEx(pSSM, &u.Msg, RT_UOFFSETOF(SHCLCLIENTMSG, aParms), 0 /*fFlags*/,
2713 &s_aShClSSMClientMsgHdr[0], NULL);
2714 rc = pVMM->pfnSSMR3GetStructEx(pSSM, &u.Msg, RT_UOFFSETOF(SHCLCLIENTMSG, aParms), 0 /*fFlags*/,
2715 &s_aShClSSMClientMsgCtx[0], NULL);
2716 AssertRCReturn(rc, rc);
2717
2718 AssertLogRelMsgReturn(u.Msg.cParms <= VMMDEV_MAX_HGCM_PARMS,
2719 ("Too many HGCM message parameters: %u (%#x)\n", u.Msg.cParms, u.Msg.cParms),
2720 VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
2721
2722 PSHCLCLIENTMSG pMsg = shClSvcMsgAlloc(pClient, u.Msg.idMsg, u.Msg.cParms);
2723 AssertReturn(pMsg, VERR_NO_MEMORY);
2724 pMsg->idCtx = u.Msg.idCtx;
2725
2726 for (uint32_t p = 0; p < pMsg->cParms; p++)
2727 {
2728 rc = HGCMSvcSSMR3Get(&pMsg->aParms[p], pSSM, pVMM);
2729 AssertRCReturnStmt(rc, shClSvcMsgFree(pClient, pMsg), rc);
2730 }
2731
2732 RTCritSectEnter(&pClient->CritSect);
2733 shClSvcMsgAdd(pClient, pMsg, true /* fAppend */);
2734 RTCritSectLeave(&pClient->CritSect);
2735 }
2736
2737 if (lenOrVer >= VBOX_SHCL_SAVED_STATE_LEGACY_CID)
2738 {
2739 uint64_t cCID;
2740 rc = pVMM->pfnSSMR3GetU64(pSSM, &cCID);
2741 AssertRCReturn(rc, rc);
2742 AssertLogRelMsgReturn(cCID < _16K, ("Too many context IDs: %u (%x)\n", cCID, cCID), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
2743
2744 for (uint64_t i = 0; i < cCID; i++)
2745 {
2746 PSHCLCLIENTLEGACYCID pCID = (PSHCLCLIENTLEGACYCID)RTMemAlloc(sizeof(SHCLCLIENTLEGACYCID));
2747 AssertPtrReturn(pCID, VERR_NO_MEMORY);
2748
2749 pVMM->pfnSSMR3GetStructEx(pSSM, pCID, sizeof(SHCLCLIENTLEGACYCID), 0 /* fFlags */,
2750 &s_aShClSSMClientLegacyCID[0], NULL);
2751 RTListAppend(&pClient->Legacy.lstCID, &pCID->Node);
2752 }
2753 }
2754 }
2755 else
2756 {
2757 LogRel(("Shared Clipboard: Unsupported saved state version (%#x)\n", lenOrVer));
2758 return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
2759 }
2760
2761 /* Actual host data are to be reported to guest (SYNC). */
2762 ShClBackendSync(&g_ShClBackend, pClient);
2763
2764#else /* UNIT_TEST */
2765 RT_NOREF(u32ClientID, pvClient, pSSM, pVMM, uVersion);
2766#endif /* UNIT_TEST */
2767 return VINF_SUCCESS;
2768}
2769
2770static DECLCALLBACK(int) extCallback(uint32_t u32Function, uint32_t u32Format, void *pvData, uint32_t cbData)
2771{
2772 RT_NOREF(pvData, cbData);
2773
2774 LogFlowFunc(("u32Function=%RU32\n", u32Function));
2775
2776 int rc = VINF_SUCCESS;
2777
2778 /* Figure out if the client in charge for the service extension still is connected. */
2779 ClipboardClientMap::const_iterator itClient = g_mapClients.find(g_ExtState.uClientID);
2780 if (itClient != g_mapClients.end())
2781 {
2782 PSHCLCLIENT pClient = itClient->second;
2783 AssertPtr(pClient);
2784
2785 switch (u32Function)
2786 {
2787 /* The service extension announces formats to the host. */
2788 case VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_HOST:
2789 {
2790 LogFlowFunc(("VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_HOST: g_ExtState.fReadingData=%RTbool\n", g_ExtState.fReadingData));
2791 if (!g_ExtState.fReadingData)
2792 rc = ShClSvcReportFormats(pClient, u32Format);
2793 else
2794 {
2795 g_ExtState.fDelayedAnnouncement = true;
2796 g_ExtState.fDelayedFormats = u32Format;
2797 rc = VINF_SUCCESS;
2798 }
2799 break;
2800 }
2801
2802 /* The service extension wants read data from the guest. */
2803 case VBOX_CLIPBOARD_EXT_FN_DATA_READ:
2804 {
2805 PSHCLEVENT pEvent;
2806 rc = ShClSvcReadDataFromGuestAsync(pClient, u32Format, &pEvent);
2807 if (RT_SUCCESS(rc))
2808 {
2809 PSHCLEVENTPAYLOAD pPayload;
2810 rc = ShClEventWait(pEvent, SHCL_TIMEOUT_DEFAULT_MS, &pPayload);
2811 if (RT_SUCCESS(rc))
2812 {
2813 if (pPayload)
2814 {
2815 memcpy(pvData, pPayload->pvData, RT_MIN(cbData, pPayload->cbData));
2816 /** @todo r=andy How is this supposed to work wrt returning number of bytes read? */
2817
2818 ShClPayloadFree(pPayload);
2819 pPayload = NULL;
2820 }
2821 else
2822 {
2823 pvData = NULL;
2824 }
2825 }
2826
2827 ShClEventRelease(pEvent);
2828 }
2829 break;
2830 }
2831
2832 default:
2833 /* Just skip other messages. */
2834 break;
2835 }
2836 }
2837 else
2838 rc = VERR_NOT_FOUND;
2839
2840 LogFlowFuncLeaveRC(rc);
2841 return rc;
2842}
2843
2844static DECLCALLBACK(int) svcRegisterExtension(void *, PFNHGCMSVCEXT pfnExtension, void *pvExtension)
2845{
2846 LogFlowFunc(("pfnExtension=%p\n", pfnExtension));
2847
2848 SHCLEXTPARMS parms;
2849 RT_ZERO(parms);
2850
2851 /*
2852 * Reference counting for service extension registration is done a few
2853 * layers up (in ConsoleVRDPServer::ClipboardCreate()).
2854 */
2855
2856 int rc = RTCritSectEnter(&g_CritSect);
2857 AssertLogRelRCReturn(rc, rc);
2858
2859 if (pfnExtension)
2860 {
2861 /* Install extension. */
2862 g_ExtState.pfnExtension = pfnExtension;
2863 g_ExtState.pvExtension = pvExtension;
2864
2865 parms.u.SetCallback.pfnCallback = extCallback;
2866
2867 g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_SET_CALLBACK, &parms, sizeof(parms));
2868
2869 LogRel2(("Shared Clipboard: registered service extension\n"));
2870 }
2871 else
2872 {
2873 if (g_ExtState.pfnExtension)
2874 g_ExtState.pfnExtension(g_ExtState.pvExtension, VBOX_CLIPBOARD_EXT_FN_SET_CALLBACK, &parms, sizeof(parms));
2875
2876 /* Uninstall extension. */
2877 g_ExtState.pvExtension = NULL;
2878 g_ExtState.pfnExtension = NULL;
2879
2880 LogRel2(("Shared Clipboard: de-registered service extension\n"));
2881 }
2882
2883 RTCritSectLeave(&g_CritSect);
2884
2885 return VINF_SUCCESS;
2886}
2887
2888extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *pTable)
2889{
2890 int rc = VINF_SUCCESS;
2891
2892 LogFlowFunc(("pTable=%p\n", pTable));
2893
2894 if (!RT_VALID_PTR(pTable))
2895 {
2896 rc = VERR_INVALID_PARAMETER;
2897 }
2898 else
2899 {
2900 LogFunc(("pTable->cbSize = %d, ptable->u32Version = 0x%08X\n", pTable->cbSize, pTable->u32Version));
2901
2902 if ( pTable->cbSize != sizeof (VBOXHGCMSVCFNTABLE)
2903 || pTable->u32Version != VBOX_HGCM_SVC_VERSION)
2904 {
2905 rc = VERR_VERSION_MISMATCH;
2906 }
2907 else
2908 {
2909 g_pHelpers = pTable->pHelpers;
2910
2911 pTable->cbClient = sizeof(SHCLCLIENT);
2912
2913 /* Map legacy clients to root. */
2914 pTable->idxLegacyClientCategory = HGCM_CLIENT_CATEGORY_ROOT;
2915
2916 /* Limit the number of clients to 128 in each category (should be enough),
2917 but set kernel clients to 1. */
2918 for (uintptr_t i = 0; i < RT_ELEMENTS(pTable->acMaxClients); i++)
2919 pTable->acMaxClients[i] = 128;
2920 pTable->acMaxClients[HGCM_CLIENT_CATEGORY_KERNEL] = 1;
2921
2922 /* Only 16 pending calls per client (1 should be enough). */
2923 for (uintptr_t i = 0; i < RT_ELEMENTS(pTable->acMaxClients); i++)
2924 pTable->acMaxCallsPerClient[i] = 16;
2925
2926 pTable->pfnUnload = svcUnload;
2927 pTable->pfnConnect = svcConnect;
2928 pTable->pfnDisconnect = svcDisconnect;
2929 pTable->pfnCall = svcCall;
2930 pTable->pfnHostCall = svcHostCall;
2931 pTable->pfnSaveState = svcSaveState;
2932 pTable->pfnLoadState = svcLoadState;
2933 pTable->pfnRegisterExtension = svcRegisterExtension;
2934 pTable->pfnNotify = NULL;
2935 pTable->pvService = NULL;
2936
2937 /* Service specific initialization. */
2938 rc = svcInit(pTable);
2939 }
2940 }
2941
2942 LogFlowFunc(("Returning %Rrc\n", rc));
2943 return rc;
2944}
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use