VirtualBox

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

Last change on this file since 100765 was 100655, checked in by vboxsync, 17 months ago

Shared Clipboard/VRDE: Integrated the logic of ShClSvcIsBackendActive() in ShClSvcReportFormats(), so that the specific backends don't need to be in charge for that anymore. Renamed VBOX_CLIPBOARD_EXT_FN_FORMAT_ANNOUNCE -> VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_HOST to emphasize its usage. Added VBOX_CLIPBOARD_EXT_FN_FORMAT_REPORT_TO_GUEST; see comment for details.

The whole concept of VRDE being a (one and only) service extension nowadays isn't optimal anymore and needs to be replaced with a more generic mechanism, which is out of this scope for this task. So just adapt this as needed and keep the current way.

bugref:9437

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

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