VirtualBox

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

最後變更 在這個檔案從100370是 100367,由 vboxsync 提交於 21 月 前

Shared Clipboard: More work on making the internal APIs more fine grained and easier to follow. bugref:9437

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

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