VirtualBox

source: vbox/trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxClipboard.cpp@ 92846

Last change on this file since 92846 was 92846, checked in by vboxsync, 3 years ago

Additions: Shared Clipboard: VBoxTray: unwrap CF_HTML content, bugref:10160.

This commit introduces unwrapping of CF_HTML payload when coping HTML data
from Windows guest.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 42.9 KB
Line 
1/* $Id: VBoxClipboard.cpp 92846 2021-12-09 12:33:57Z vboxsync $ */
2/** @file
3 * VBoxClipboard - Shared clipboard, Windows Guest Implementation.
4 */
5
6/*
7 * Copyright (C) 2006-2021 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_SHARED_CLIPBOARD
23#include <VBox/log.h>
24
25#include "VBoxTray.h"
26#include "VBoxHelpers.h"
27
28#include <iprt/asm.h>
29#include <iprt/errcore.h>
30#include <iprt/mem.h>
31#include <iprt/ldr.h>
32
33
34#include <VBox/GuestHost/SharedClipboard.h>
35#include <VBox/GuestHost/SharedClipboard-win.h>
36#include <VBox/GuestHost/clipboard-helper.h>
37#include <VBox/HostServices/VBoxClipboardSvc.h> /* Temp, remove. */
38#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
39# include <VBox/GuestHost/SharedClipboard-transfers.h>
40#endif
41
42#include <strsafe.h>
43
44#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
45# include <iprt/win/shlobj.h>
46# include <iprt/win/shlwapi.h>
47#endif
48
49
50/*********************************************************************************************************************************
51* Structures and Typedefs *
52*********************************************************************************************************************************/
53struct SHCLCONTEXT
54{
55 /** Pointer to the VBoxClient service environment. */
56 const VBOXSERVICEENV *pEnv;
57 /** Command context. */
58 VBGLR3SHCLCMDCTX CmdCtx;
59 /** Windows-specific context data. */
60 SHCLWINCTX Win;
61 /** Thread handle for window thread. */
62 RTTHREAD hThread;
63 /** Start indicator flag. */
64 bool fStarted;
65 /** Shutdown indicator flag. */
66 bool fShutdown;
67#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
68 /** Associated transfer data. */
69 SHCLTRANSFERCTX TransferCtx;
70#endif
71};
72
73
74/*********************************************************************************************************************************
75* Static variables *
76*********************************************************************************************************************************/
77/** Static clipboard context (since it is the single instance). Directly used in the windows proc. */
78static SHCLCONTEXT g_Ctx = { NULL };
79/** Static window class name. */
80static char s_szClipWndClassName[] = SHCL_WIN_WNDCLASS_NAME;
81
82
83/*********************************************************************************************************************************
84* Prototypes *
85*********************************************************************************************************************************/
86#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
87static DECLCALLBACK(int) vboxClipboardOnTransferInitCallback(PSHCLTXPROVIDERCTX pCtx);
88static DECLCALLBACK(int) vboxClipboardOnTransferStartCallback(PSHCLTXPROVIDERCTX pCtx);
89static DECLCALLBACK(void) vboxClipboardOnTransferCompleteCallback(PSHCLTXPROVIDERCTX pCtx, int rc);
90static DECLCALLBACK(void) vboxClipboardOnTransferErrorCallback(PSHCLTXPROVIDERCTX pCtx, int rc);
91#endif
92
93
94#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
95
96/**
97 * Cleanup helper function for transfer callbacks.
98 *
99 * @param pTransferCtx Pointer to transfer context that the transfer contains.
100 * @param pTransfer Pointer to transfer to cleanup.
101 */
102static void vboxClipboardTransferCallbackCleanup(PSHCLTRANSFERCTX pTransferCtx, PSHCLTRANSFER pTransfer)
103{
104 LogFlowFuncEnter();
105
106 if (!pTransferCtx || !pTransfer)
107 return;
108
109 if (pTransfer->pvUser) /* SharedClipboardWinTransferCtx */
110 {
111 delete pTransfer->pvUser;
112 pTransfer->pvUser = NULL;
113 }
114
115 int rc2 = ShClTransferCtxTransferUnregister(pTransferCtx, pTransfer->State.uID);
116 AssertRC(rc2);
117
118 ShClTransferDestroy(pTransfer);
119
120 RTMemFree(pTransfer);
121 pTransfer = NULL;
122}
123
124/** @copydoc SHCLTRANSFERCALLBACKTABLE::pfnOnInitialize */
125static DECLCALLBACK(int) vboxClipboardOnTransferInitCallback(PSHCLTRANSFERCALLBACKCTX pCbCtx)
126{
127 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pCbCtx->pvUser;
128 AssertPtr(pCtx);
129
130 LogFlowFunc(("pCtx=%p\n", pCtx));
131
132 RT_NOREF(pCtx);
133
134 return VINF_SUCCESS;
135}
136
137/** @copydoc SHCLTRANSFERCALLBACKTABLE::pfnOnStart */
138static DECLCALLBACK(int) vboxClipboardOnTransferStartCallback(PSHCLTRANSFERCALLBACKCTX pCbCtx)
139{
140 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pCbCtx->pvUser;
141 AssertPtr(pCtx);
142
143 PSHCLTRANSFER pTransfer = pCbCtx->pTransfer;
144 AssertPtr(pTransfer);
145
146 const SHCLTRANSFERDIR enmDir = ShClTransferGetDir(pTransfer);
147
148 LogFlowFunc(("pCtx=%p, idTransfer=%RU32, enmDir=%RU32\n", pCtx, ShClTransferGetID(pTransfer), enmDir));
149
150 int rc;
151
152 /* The guest wants to write local data to the host? */
153 if (enmDir == SHCLTRANSFERDIR_TO_REMOTE)
154 {
155 rc = SharedClipboardWinGetRoots(&pCtx->Win, pTransfer);
156 }
157 /* The guest wants to read data from a remote source. */
158 else if (enmDir == SHCLTRANSFERDIR_FROM_REMOTE)
159 {
160 /* The IDataObject *must* be created on the same thread as our (proxy) window, so post a message to it
161 * to do the stuff for us. */
162 PSHCLEVENT pEvent;
163 rc = ShClEventSourceGenerateAndRegisterEvent(&pTransfer->Events, &pEvent);
164 if (RT_SUCCESS(rc))
165 {
166 /* Don't want to rely on SendMessage (synchronous) here, so just post and wait the event getting signalled. */
167 ::PostMessage(pCtx->Win.hWnd, SHCL_WIN_WM_TRANSFER_START, (WPARAM)pTransfer, (LPARAM)pEvent->idEvent);
168
169 PSHCLEVENTPAYLOAD pPayload;
170 rc = ShClEventWait(pEvent, 30 * 1000 /* Timeout in ms */, &pPayload);
171 if (RT_SUCCESS(rc))
172 {
173 Assert(pPayload->cbData == sizeof(int));
174 rc = *(int *)pPayload->pvData;
175
176 ShClPayloadFree(pPayload);
177 }
178
179 ShClEventRelease(pEvent);
180 }
181 else
182 AssertFailedStmt(rc = VERR_SHCLPB_MAX_EVENTS_REACHED);
183 }
184 else
185 AssertFailedStmt(rc = VERR_NOT_SUPPORTED);
186
187 if (RT_FAILURE(rc))
188 LogRel(("Shared Clipboard: Starting transfer failed, rc=%Rrc\n", rc));
189
190 LogFlowFunc(("LEAVE: idTransfer=%RU32, rc=%Rrc\n", ShClTransferGetID(pTransfer), rc));
191 return rc;
192}
193
194/** @copydoc SHCLTRANSFERCALLBACKTABLE::pfnOnCompleted */
195static DECLCALLBACK(void) vboxClipboardOnTransferCompletedCallback(PSHCLTRANSFERCALLBACKCTX pCbCtx, int rcCompletion)
196{
197 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pCbCtx->pvUser;
198 AssertPtr(pCtx);
199
200 LogRel2(("Shared Clipboard: Transfer to destination %s\n",
201 rcCompletion == VERR_CANCELLED ? "canceled" : "complete"));
202
203 vboxClipboardTransferCallbackCleanup(&pCtx->TransferCtx, pCbCtx->pTransfer);
204}
205
206/** @copydoc SHCLTRANSFERCALLBACKTABLE::pfnOnError */
207static DECLCALLBACK(void) vboxClipboardOnTransferErrorCallback(PSHCLTRANSFERCALLBACKCTX pCbCtx, int rcError)
208{
209 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pCbCtx->pvUser;
210 AssertPtr(pCtx);
211
212 LogRel(("Shared Clipboard: Transfer to destination failed with %Rrc\n", rcError));
213
214 vboxClipboardTransferCallbackCleanup(&pCtx->TransferCtx, pCbCtx->pTransfer);
215}
216
217#endif /* VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS */
218
219static LRESULT vboxClipboardWinProcessMsg(PSHCLCONTEXT pCtx, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
220{
221 AssertPtr(pCtx);
222
223 const PSHCLWINCTX pWinCtx = &pCtx->Win;
224
225 LRESULT lresultRc = 0;
226
227 switch (msg)
228 {
229 case WM_CLIPBOARDUPDATE:
230 {
231 LogFunc(("WM_CLIPBOARDUPDATE: pWinCtx=%p\n", pWinCtx));
232
233 if (pCtx->fShutdown) /* If we're about to shut down, skip handling stuff here. */
234 break;
235
236 int rc = RTCritSectEnter(&pWinCtx->CritSect);
237 if (RT_SUCCESS(rc))
238 {
239 const HWND hWndClipboardOwner = GetClipboardOwner();
240
241 LogFunc(("WM_CLIPBOARDUPDATE: hWndOldClipboardOwner=%p, hWndNewClipboardOwner=%p\n",
242 pWinCtx->hWndClipboardOwnerUs, hWndClipboardOwner));
243
244 if (pWinCtx->hWndClipboardOwnerUs != hWndClipboardOwner)
245 {
246 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
247 AssertRC(rc2);
248
249 /* Clipboard was updated by another application.
250 * Report available formats to the host. */
251 SHCLFORMATS fFormats;
252 rc = SharedClipboardWinGetFormats(pWinCtx, &fFormats);
253 if (RT_SUCCESS(rc))
254 {
255 LogFunc(("WM_CLIPBOARDUPDATE: Reporting formats %#x\n", fFormats));
256 rc = VbglR3ClipboardReportFormats(pCtx->CmdCtx.idClient, fFormats);
257 }
258 }
259 else
260 {
261 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
262 AssertRC(rc2);
263 }
264 }
265
266 if (RT_FAILURE(rc))
267 LogRel(("Shared Clipboard: WM_CLIPBOARDUPDATE failed with %Rrc\n", rc));
268
269 break;
270 }
271
272 case WM_CHANGECBCHAIN:
273 {
274 LogFunc(("WM_CHANGECBCHAIN\n"));
275 lresultRc = SharedClipboardWinHandleWMChangeCBChain(pWinCtx, hwnd, msg, wParam, lParam);
276 break;
277 }
278
279 case WM_DRAWCLIPBOARD:
280 {
281 LogFlowFunc(("WM_DRAWCLIPBOARD: pWinCtx=%p\n", pWinCtx));
282
283 int rc = RTCritSectEnter(&pWinCtx->CritSect);
284 if (RT_SUCCESS(rc))
285 {
286 const HWND hWndClipboardOwner = GetClipboardOwner();
287
288 LogFunc(("WM_DRAWCLIPBOARD: hWndClipboardOwnerUs=%p, hWndNewClipboardOwner=%p\n",
289 pWinCtx->hWndClipboardOwnerUs, hWndClipboardOwner));
290
291 if (pWinCtx->hWndClipboardOwnerUs != hWndClipboardOwner)
292 {
293 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
294 AssertRC(rc2);
295
296 /* Clipboard was updated by another application. */
297 /* WM_DRAWCLIPBOARD always expects a return code of 0, so don't change "rc" here. */
298 SHCLFORMATS fFormats;
299 rc = SharedClipboardWinGetFormats(pWinCtx, &fFormats);
300 if ( RT_SUCCESS(rc)
301 && fFormats != VBOX_SHCL_FMT_NONE)
302 rc = VbglR3ClipboardReportFormats(pCtx->CmdCtx.idClient, fFormats);
303 }
304 else
305 {
306 int rc2 = RTCritSectLeave(&pWinCtx->CritSect);
307 AssertRC(rc2);
308 }
309 }
310
311 lresultRc = SharedClipboardWinChainPassToNext(pWinCtx, msg, wParam, lParam);
312 break;
313 }
314
315 case WM_TIMER:
316 {
317 int rc = SharedClipboardWinHandleWMTimer(pWinCtx);
318 AssertRC(rc);
319
320 break;
321 }
322
323 case WM_CLOSE:
324 {
325 /* Do nothing. Ignore the message. */
326 break;
327 }
328
329 case WM_RENDERFORMAT:
330 {
331 LogFunc(("WM_RENDERFORMAT\n"));
332
333 /* Insert the requested clipboard format data into the clipboard. */
334 const UINT cfFormat = (UINT)wParam;
335
336 const SHCLFORMAT fFormat = SharedClipboardWinClipboardFormatToVBox(cfFormat);
337
338 LogFunc(("WM_RENDERFORMAT: cfFormat=%u -> fFormat=0x%x\n", cfFormat, fFormat));
339
340 if (fFormat == VBOX_SHCL_FMT_NONE)
341 {
342 LogFunc(("WM_RENDERFORMAT: Unsupported format requested\n"));
343 SharedClipboardWinClear();
344 }
345 else
346 {
347 const uint32_t cbPrealloc = _4K;
348 uint32_t cb = 0;
349
350 /* Preallocate a buffer, most of small text transfers will fit into it. */
351 HANDLE hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, cbPrealloc);
352 if (hMem)
353 {
354 void *pMem = GlobalLock(hMem);
355 if (pMem)
356 {
357 /* Read the host data to the preallocated buffer. */
358 int rc = VbglR3ClipboardReadDataEx(&pCtx->CmdCtx, fFormat, pMem, cbPrealloc, &cb);
359 if (RT_SUCCESS(rc))
360 {
361 if (cb == 0)
362 {
363 /* 0 bytes returned means the clipboard is empty.
364 * Deallocate the memory and set hMem to NULL to get to
365 * the clipboard empty code path. */
366 GlobalUnlock(hMem);
367 GlobalFree(hMem);
368 hMem = NULL;
369 }
370 else if (cb > cbPrealloc)
371 {
372 GlobalUnlock(hMem);
373
374 LogRel2(("Shared Clipboard: Buffer too small (%RU32), needs %RU32 bytes\n", cbPrealloc, cb));
375
376 /* The preallocated buffer is too small, adjust the size. */
377 hMem = GlobalReAlloc(hMem, cb, 0);
378 if (hMem)
379 {
380 pMem = GlobalLock(hMem);
381 if (pMem)
382 {
383 /* Read the host data to the preallocated buffer. */
384 uint32_t cbNew = 0;
385 rc = VbglR3ClipboardReadDataEx(&pCtx->CmdCtx, fFormat, pMem, cb, &cbNew);
386 if ( RT_SUCCESS(rc)
387 && cbNew <= cb)
388 {
389 cb = cbNew;
390 }
391 else
392 {
393 LogRel(("Shared Clipboard: Receiving host data failed with %Rrc\n", rc));
394
395 GlobalUnlock(hMem);
396 GlobalFree(hMem);
397 hMem = NULL;
398 }
399 }
400 else
401 {
402 LogRel(("Shared Clipboard: Error locking reallocated host data buffer\n"));
403
404 GlobalFree(hMem);
405 hMem = NULL;
406 }
407 }
408 else
409 LogRel(("Shared Clipboard: No memory for reallocating host data buffer\n"));
410 }
411
412 if (hMem)
413 {
414 /* pMem is the address of the data. cb is the size of returned data. */
415 /* Verify the size of returned text, the memory block for clipboard
416 * must have the exact string size.
417 */
418 if (fFormat == VBOX_SHCL_FMT_UNICODETEXT)
419 {
420 size_t cbActual = 0;
421 HRESULT hrc = StringCbLengthW((LPWSTR)pMem, cb, &cbActual);
422 if (FAILED(hrc))
423 {
424 LogRel(("Shared Clipboard: Received host data is invalid (%RU32 vs. %zu)\n",
425 cb, cbActual));
426
427 /* Discard invalid data. */
428 GlobalUnlock(hMem);
429 GlobalFree(hMem);
430 hMem = NULL;
431 }
432 else
433 {
434 /* cbActual is the number of bytes, excluding those used
435 * for the terminating null character.
436 */
437 cb = (uint32_t)(cbActual + 2);
438 }
439 }
440 else if (fFormat == VBOX_SHCL_FMT_HTML)
441 {
442 /* Wrap content into CF_HTML clipboard format if needed. */
443 if (!SharedClipboardWinIsCFHTML((const char *)pMem))
444 {
445 char *pszWrapped = NULL;
446 uint32_t cbWrapped = 0;
447 rc = SharedClipboardWinConvertMIMEToCFHTML((const char *)pMem, cb, &pszWrapped, &cbWrapped);
448 if (RT_SUCCESS(rc))
449 {
450 if (GlobalUnlock(hMem) == 0)
451 {
452 hMem = GlobalReAlloc(hMem, cbWrapped, 0);
453 if (hMem)
454 {
455 pMem = GlobalLock(hMem);
456 if (pMem)
457 {
458 /* Copy wrapped content back to memory passed to system clipboard. */
459 memcpy(pMem, pszWrapped, cbWrapped);
460 cb = cbWrapped;
461 }
462 else
463 {
464 LogRel(("Shared Clipboard: Cannot lock memory, "
465 "HTML clipboard data won't be converted into CF_HTML clipboard format\n"));
466 GlobalFree(hMem);
467 hMem = NULL;
468 }
469 }
470 else
471 LogRel(("Shared Clipboard: Cannot re-allocate memory, "
472 "HTML clipboard data won't be converted into CF_HTML clipboard format\n"));
473 }
474 else
475 LogRel(("Shared Clipboard: Cannot unlock memory, "
476 "HTML clipboard data won't be converted into CF_HTML clipboard format\n"));
477
478 RTMemFree(pszWrapped);
479 }
480 else
481 LogRel(("Shared Clipboard: Cannot convert HTML clipboard data into CF_HTML clipboard format, rc=%Rrc\n", rc));
482 }
483 }
484 }
485
486 if (hMem)
487 {
488 GlobalUnlock(hMem);
489
490 hMem = GlobalReAlloc(hMem, cb, 0);
491 if (hMem)
492 {
493 /* 'hMem' contains the host clipboard data.
494 * size is 'cb' and format is 'format'. */
495 HANDLE hClip = SetClipboardData(cfFormat, hMem);
496 if (hClip)
497 {
498 /* The hMem ownership has gone to the system. Finish the processing. */
499 break;
500 }
501 else
502 LogRel(("Shared Clipboard: Setting host data buffer to clipboard failed with %ld\n",
503 GetLastError()));
504
505 /* Cleanup follows. */
506 }
507 else
508 LogRel(("Shared Clipboard: No memory for allocating final host data buffer\n"));
509 }
510 }
511
512 if (hMem)
513 GlobalUnlock(hMem);
514 }
515 else
516 LogRel(("Shared Clipboard: No memory for allocating host data buffer\n"));
517
518 if (hMem)
519 GlobalFree(hMem);
520 }
521 }
522
523 break;
524 }
525
526 case WM_RENDERALLFORMATS:
527 {
528 LogFunc(("WM_RENDERALLFORMATS\n"));
529
530 int rc = SharedClipboardWinHandleWMRenderAllFormats(pWinCtx, hwnd);
531 AssertRC(rc);
532
533 break;
534 }
535
536 case SHCL_WIN_WM_REPORT_FORMATS:
537 {
538 LogFunc(("SHCL_WIN_WM_REPORT_FORMATS\n"));
539
540 /* Announce available formats. Do not insert data -- will be inserted in WM_RENDERFORMAT. */
541 PVBGLR3CLIPBOARDEVENT pEvent = (PVBGLR3CLIPBOARDEVENT)lParam;
542 AssertPtr(pEvent);
543 Assert(pEvent->enmType == VBGLR3CLIPBOARDEVENTTYPE_REPORT_FORMATS);
544
545 const SHCLFORMATS fFormats = pEvent->u.fReportedFormats;
546
547 if (fFormats != VBOX_SHCL_FMT_NONE) /* Could arrive with some older GA versions. */
548 {
549#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
550 if (fFormats & VBOX_SHCL_FMT_URI_LIST)
551 {
552 LogFunc(("VBOX_SHCL_FMT_URI_LIST\n"));
553
554 /*
555 * Creating and starting the actual transfer will be done in vbglR3ClipboardTransferStart() as soon
556 * as the host announces the start of the transfer via a VBOX_SHCL_HOST_MSG_TRANSFER_STATUS message.
557 * Transfers always are controlled and initiated on the host side!
558 *
559 * So don't announce the transfer to the OS here yet. Don't touch the clipboard in any here; otherwise
560 * this will trigger a WM_DRAWCLIPBOARD or friends, which will result in fun bugs coming up.
561 */
562 }
563 else
564 {
565#endif
566 SharedClipboardWinClearAndAnnounceFormats(pWinCtx, fFormats, hwnd);
567#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
568 }
569#endif
570 }
571
572 LogFunc(("SHCL_WIN_WM_REPORT_FORMATS: fFormats=0x%x, lastErr=%ld\n", fFormats, GetLastError()));
573 break;
574 }
575
576 case SHCL_WIN_WM_READ_DATA:
577 {
578 /* Send data in the specified format to the host. */
579 PVBGLR3CLIPBOARDEVENT pEvent = (PVBGLR3CLIPBOARDEVENT)lParam;
580 AssertPtr(pEvent);
581 Assert(pEvent->enmType == VBGLR3CLIPBOARDEVENTTYPE_READ_DATA);
582
583 const SHCLFORMAT fFormat = (uint32_t)pEvent->u.fReadData;
584
585 LogFlowFunc(("SHCL_WIN_WM_READ_DATA: fFormat=%#x\n", fFormat));
586
587 int rc = SharedClipboardWinOpen(hwnd);
588 HANDLE hClip = NULL;
589 if (RT_SUCCESS(rc))
590 {
591 if (fFormat & VBOX_SHCL_FMT_BITMAP)
592 {
593 hClip = GetClipboardData(CF_DIB);
594 if (hClip != NULL)
595 {
596 LPVOID lp = GlobalLock(hClip);
597 if (lp != NULL)
598 {
599 rc = VbglR3ClipboardWriteDataEx(&pEvent->cmdCtx, fFormat, lp, (uint32_t)GlobalSize(hClip));
600
601 GlobalUnlock(hClip);
602 }
603 else
604 hClip = NULL;
605 }
606 }
607 else if (fFormat & VBOX_SHCL_FMT_UNICODETEXT)
608 {
609 hClip = GetClipboardData(CF_UNICODETEXT);
610 if (hClip != NULL)
611 {
612 LPWSTR uniString = (LPWSTR)GlobalLock(hClip);
613 if (uniString != NULL)
614 {
615 rc = VbglR3ClipboardWriteDataEx(&pEvent->cmdCtx,
616 fFormat, uniString, ((uint32_t)lstrlenW(uniString) + 1) * 2);
617
618 GlobalUnlock(hClip);
619 }
620 else
621 hClip = NULL;
622 }
623 }
624 else if (fFormat & VBOX_SHCL_FMT_HTML)
625 {
626 UINT format = RegisterClipboardFormat(SHCL_WIN_REGFMT_HTML);
627 if (format != 0)
628 {
629 hClip = GetClipboardData(format);
630 if (hClip != NULL)
631 {
632 LPVOID lp = GlobalLock(hClip);
633 if (lp != NULL)
634 {
635 /* Unwrap clipboard content from CF_HTML format if needed. */
636 if (SharedClipboardWinIsCFHTML((const char *)lp))
637 {
638 char *pszBuf = NULL;
639 uint32_t cbBuf = 0;
640
641 rc = SharedClipboardWinConvertCFHTMLToMIME((const char *)lp, (uint32_t)GlobalSize(hClip), &pszBuf, &cbBuf);
642 if (RT_SUCCESS(rc))
643 {
644 rc = VbglR3ClipboardWriteDataEx(&pEvent->cmdCtx, fFormat, pszBuf, cbBuf);
645 RTMemFree(pszBuf);
646 }
647 }
648 else
649 rc = VbglR3ClipboardWriteDataEx(&pEvent->cmdCtx, fFormat, lp, (uint32_t)GlobalSize(hClip));
650
651 GlobalUnlock(hClip);
652 }
653 else
654 hClip = NULL;
655 }
656 }
657 }
658
659 if (hClip == NULL)
660 LogFunc(("SHCL_WIN_WM_READ_DATA: hClip=NULL, lastError=%ld\n", GetLastError()));
661
662 SharedClipboardWinClose();
663 }
664
665 /* If the requested clipboard format is not available, we must send empty data. */
666 if (hClip == NULL)
667 VbglR3ClipboardWriteDataEx(&pEvent->cmdCtx, VBOX_SHCL_FMT_NONE, NULL, 0);
668 break;
669 }
670
671#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
672 case SHCL_WIN_WM_TRANSFER_START:
673 {
674 LogFunc(("SHCL_WIN_WM_TRANSFER_START\n"));
675
676 PSHCLTRANSFER pTransfer = (PSHCLTRANSFER)wParam;
677 AssertPtr(pTransfer);
678
679 const SHCLEVENTID idEvent = (SHCLEVENTID)lParam;
680
681 Assert(ShClTransferGetSource(pTransfer) == SHCLSOURCE_REMOTE); /* Sanity. */
682
683 int rcTransfer = SharedClipboardWinTransferCreate(pWinCtx, pTransfer);
684
685 PSHCLEVENTPAYLOAD pPayload = NULL;
686 int rc = ShClPayloadAlloc(idEvent, &rcTransfer, sizeof(rcTransfer), &pPayload);
687 if (RT_SUCCESS(rc))
688 {
689 rc = ShClEventSignal(&pTransfer->Events, idEvent, pPayload);
690 if (RT_FAILURE(rc))
691 ShClPayloadFree(pPayload);
692 }
693
694 break;
695 }
696#endif
697 case WM_DESTROY:
698 {
699 LogFunc(("WM_DESTROY\n"));
700
701 int rc = SharedClipboardWinHandleWMDestroy(pWinCtx);
702 AssertRC(rc);
703
704 /*
705 * Don't need to call PostQuitMessage cause
706 * the VBoxTray already finished a message loop.
707 */
708
709 break;
710 }
711
712 default:
713 {
714 LogFunc(("WM_ %p\n", msg));
715 lresultRc = DefWindowProc(hwnd, msg, wParam, lParam);
716 break;
717 }
718 }
719
720 LogFunc(("WM_ rc %d\n", lresultRc));
721 return lresultRc;
722}
723
724static LRESULT CALLBACK vboxClipboardWinWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
725
726static int vboxClipboardCreateWindow(PSHCLCONTEXT pCtx)
727{
728 AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
729
730 int rc = VINF_SUCCESS;
731
732 AssertPtr(pCtx->pEnv);
733 HINSTANCE hInstance = pCtx->pEnv->hInstance;
734 Assert(hInstance != 0);
735
736 /* Register the Window Class. */
737 WNDCLASSEX wc;
738 RT_ZERO(wc);
739
740 wc.cbSize = sizeof(WNDCLASSEX);
741
742 if (!GetClassInfoEx(hInstance, s_szClipWndClassName, &wc))
743 {
744 wc.style = CS_NOCLOSE;
745 wc.lpfnWndProc = vboxClipboardWinWndProc;
746 wc.hInstance = pCtx->pEnv->hInstance;
747 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
748 wc.lpszClassName = s_szClipWndClassName;
749
750 ATOM wndClass = RegisterClassEx(&wc);
751 if (wndClass == 0)
752 rc = RTErrConvertFromWin32(GetLastError());
753 }
754
755 if (RT_SUCCESS(rc))
756 {
757 const PSHCLWINCTX pWinCtx = &pCtx->Win;
758
759 /* Create the window. */
760 pWinCtx->hWnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
761 s_szClipWndClassName, s_szClipWndClassName,
762 WS_POPUPWINDOW,
763 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
764 if (pWinCtx->hWnd == NULL)
765 {
766 rc = VERR_NOT_SUPPORTED;
767 }
768 else
769 {
770 SetWindowPos(pWinCtx->hWnd, HWND_TOPMOST, -200, -200, 0, 0,
771 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
772
773 rc = SharedClipboardWinChainAdd(pWinCtx);
774 if (RT_SUCCESS(rc))
775 {
776 if (!SharedClipboardWinIsNewAPI(&pWinCtx->newAPI))
777 pWinCtx->oldAPI.timerRefresh = SetTimer(pWinCtx->hWnd, 0, 10 * 1000 /* 10s */, NULL);
778 }
779 }
780 }
781
782 LogFlowFuncLeaveRC(rc);
783 return rc;
784}
785
786static DECLCALLBACK(int) vboxClipboardWindowThread(RTTHREAD hThread, void *pvUser)
787{
788 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pvUser;
789 AssertPtr(pCtx);
790
791#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
792 HRESULT hr = OleInitialize(NULL);
793 if (FAILED(hr))
794 {
795 LogRel(("Shared Clipboard: Initializing OLE in window thread failed (%Rhrc) -- file transfers unavailable\n", hr));
796 /* Not critical, the rest of the clipboard might work. */
797 }
798 else
799 LogRel(("Shared Clipboard: Initialized OLE in window thread\n"));
800#endif
801
802 int rc = vboxClipboardCreateWindow(pCtx);
803 if (RT_FAILURE(rc))
804 {
805 LogRel(("Shared Clipboard: Unable to create window, rc=%Rrc\n", rc));
806 return rc;
807 }
808
809 pCtx->fStarted = true; /* Set started indicator. */
810
811 int rc2 = RTThreadUserSignal(hThread);
812 bool fSignalled = RT_SUCCESS(rc2);
813
814 LogRel2(("Shared Clipboard: Window thread running\n"));
815
816 if (RT_SUCCESS(rc))
817 {
818 for (;;)
819 {
820 MSG uMsg;
821 BOOL fRet;
822 while ((fRet = GetMessage(&uMsg, 0, 0, 0)) > 0)
823 {
824 TranslateMessage(&uMsg);
825 DispatchMessage(&uMsg);
826 }
827 Assert(fRet >= 0);
828
829 if (ASMAtomicReadBool(&pCtx->fShutdown))
830 break;
831
832 /** @todo Immediately drop on failure? */
833 }
834 }
835
836 if (!fSignalled)
837 {
838 rc2 = RTThreadUserSignal(hThread);
839 AssertRC(rc2);
840 }
841
842#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
843 OleSetClipboard(NULL); /* Make sure to flush the clipboard on destruction. */
844 OleUninitialize();
845#endif
846
847 LogRel(("Shared Clipboard: Window thread ended\n"));
848
849 LogFlowFuncLeaveRC(rc);
850 return rc;
851}
852
853static void vboxClipboardDestroy(PSHCLCONTEXT pCtx)
854{
855 AssertPtrReturnVoid(pCtx);
856
857 LogFlowFunc(("pCtx=%p\n", pCtx));
858
859 LogRel2(("Shared Clipboard: Destroying ...\n"));
860
861 const PSHCLWINCTX pWinCtx = &pCtx->Win;
862
863 if (pCtx->hThread != NIL_RTTHREAD)
864 {
865 int rcThread = VERR_WRONG_ORDER;
866 int rc = RTThreadWait(pCtx->hThread, 60 * 1000 /* Timeout in ms */, &rcThread);
867 LogFlowFunc(("Waiting for thread resulted in %Rrc (thread exited with %Rrc)\n",
868 rc, rcThread));
869 RT_NOREF(rc);
870 }
871
872 if (pWinCtx->hWnd)
873 {
874 DestroyWindow(pWinCtx->hWnd);
875 pWinCtx->hWnd = NULL;
876 }
877
878 UnregisterClass(s_szClipWndClassName, pCtx->pEnv->hInstance);
879
880 SharedClipboardWinCtxDestroy(&pCtx->Win);
881
882 LogRel2(("Shared Clipboard: Destroyed\n"));
883}
884
885static LRESULT CALLBACK vboxClipboardWinWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
886{
887 PSHCLCONTEXT pCtx = &g_Ctx; /** @todo r=andy Make pCtx available through SetWindowLongPtr() / GWL_USERDATA. */
888 AssertPtr(pCtx);
889
890 /* Forward with proper context. */
891 return vboxClipboardWinProcessMsg(pCtx, hWnd, uMsg, wParam, lParam);
892}
893
894DECLCALLBACK(int) VBoxShClInit(const PVBOXSERVICEENV pEnv, void **ppInstance)
895{
896 LogFlowFuncEnter();
897
898 PSHCLCONTEXT pCtx = &g_Ctx; /* Only one instance for now. */
899 AssertPtr(pCtx);
900
901 if (pCtx->pEnv)
902 {
903 /* Clipboard was already initialized. 2 or more instances are not supported. */
904 return VERR_NOT_SUPPORTED;
905 }
906
907 if (VbglR3AutoLogonIsRemoteSession())
908 {
909 /* Do not use clipboard for remote sessions. */
910 LogRel(("Shared Clipboard: Clipboard has been disabled for a remote session\n"));
911 return VERR_NOT_SUPPORTED;
912 }
913
914 pCtx->pEnv = pEnv;
915 pCtx->hThread = NIL_RTTHREAD;
916 pCtx->fStarted = false;
917 pCtx->fShutdown = false;
918
919 int rc = VINF_SUCCESS;
920
921#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
922 /*
923 * Set callbacks.
924 * Those will be registered within VbglR3 when a new transfer gets initialized.
925 */
926 RT_ZERO(pCtx->CmdCtx.Transfers.Callbacks);
927
928 pCtx->CmdCtx.Transfers.Callbacks.pvUser = pCtx; /* Assign context as user-provided callback data. */
929 pCtx->CmdCtx.Transfers.Callbacks.cbUser = sizeof(SHCLCONTEXT);
930
931 pCtx->CmdCtx.Transfers.Callbacks.pfnOnInitialize = vboxClipboardOnTransferInitCallback;
932 pCtx->CmdCtx.Transfers.Callbacks.pfnOnStart = vboxClipboardOnTransferStartCallback;
933 pCtx->CmdCtx.Transfers.Callbacks.pfnOnCompleted = vboxClipboardOnTransferCompletedCallback;
934 pCtx->CmdCtx.Transfers.Callbacks.pfnOnError = vboxClipboardOnTransferErrorCallback;
935#endif
936
937 if (RT_SUCCESS(rc))
938 {
939 rc = SharedClipboardWinCtxInit(&pCtx->Win);
940 if (RT_SUCCESS(rc))
941 rc = VbglR3ClipboardConnectEx(&pCtx->CmdCtx, VBOX_SHCL_GF_0_CONTEXT_ID);
942 if (RT_SUCCESS(rc))
943 {
944#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
945 rc = ShClTransferCtxInit(&pCtx->TransferCtx);
946#endif
947 if (RT_SUCCESS(rc))
948 {
949 /* Message pump thread for our proxy window. */
950 rc = RTThreadCreate(&pCtx->hThread, vboxClipboardWindowThread, pCtx /* pvUser */,
951 0, RTTHREADTYPE_MSG_PUMP, RTTHREADFLAGS_WAITABLE,
952 "shclwnd");
953 if (RT_SUCCESS(rc))
954 {
955 int rc2 = RTThreadUserWait(pCtx->hThread, 30 * 1000 /* Timeout in ms */);
956 AssertRC(rc2);
957
958 if (!pCtx->fStarted) /* Did the thread fail to start? */
959 rc = VERR_NOT_SUPPORTED; /* Report back Shared Clipboard as not being supported. */
960 }
961 }
962
963 if (RT_SUCCESS(rc))
964 {
965 *ppInstance = pCtx;
966 }
967 else
968 VbglR3ClipboardDisconnectEx(&pCtx->CmdCtx);
969 }
970 }
971
972 if (RT_FAILURE(rc))
973 LogRel(("Shared Clipboard: Unable to initialize, rc=%Rrc\n", rc));
974
975 LogFlowFuncLeaveRC(rc);
976 return rc;
977}
978
979DECLCALLBACK(int) VBoxShClWorker(void *pInstance, bool volatile *pfShutdown)
980{
981 AssertPtr(pInstance);
982 LogFlowFunc(("pInstance=%p\n", pInstance));
983
984 /*
985 * Tell the control thread that it can continue
986 * spawning services.
987 */
988 RTThreadUserSignal(RTThreadSelf());
989
990 const PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pInstance;
991 AssertPtr(pCtx);
992
993 const PSHCLWINCTX pWinCtx = &pCtx->Win;
994
995 LogRel2(("Shared Clipboard: Worker loop running\n"));
996
997#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
998 HRESULT hr = OleInitialize(NULL);
999 if (FAILED(hr))
1000 {
1001 LogRel(("Shared Clipboard: Initializing OLE in worker thread failed (%Rhrc) -- file transfers unavailable\n", hr));
1002 /* Not critical, the rest of the clipboard might work. */
1003 }
1004 else
1005 LogRel(("Shared Clipboard: Initialized OLE in worker thraed\n"));
1006#endif
1007
1008 int rc;
1009
1010 /* The thread waits for incoming messages from the host. */
1011 for (;;)
1012 {
1013 LogFlowFunc(("Waiting for host message (fUseLegacyProtocol=%RTbool, fHostFeatures=%#RX64) ...\n",
1014 pCtx->CmdCtx.fUseLegacyProtocol, pCtx->CmdCtx.fHostFeatures));
1015
1016 PVBGLR3CLIPBOARDEVENT pEvent = (PVBGLR3CLIPBOARDEVENT)RTMemAllocZ(sizeof(VBGLR3CLIPBOARDEVENT));
1017 AssertPtrBreakStmt(pEvent, rc = VERR_NO_MEMORY);
1018
1019 uint32_t idMsg = 0;
1020 uint32_t cParms = 0;
1021 rc = VbglR3ClipboardMsgPeekWait(&pCtx->CmdCtx, &idMsg, &cParms, NULL /* pidRestoreCheck */);
1022 if (RT_SUCCESS(rc))
1023 {
1024#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1025 rc = VbglR3ClipboardEventGetNextEx(idMsg, cParms, &pCtx->CmdCtx, &pCtx->TransferCtx, pEvent);
1026#else
1027 rc = VbglR3ClipboardEventGetNext(idMsg, cParms, &pCtx->CmdCtx, pEvent);
1028#endif
1029 }
1030
1031 if (RT_FAILURE(rc))
1032 {
1033 LogFlowFunc(("Getting next event failed with %Rrc\n", rc));
1034
1035 VbglR3ClipboardEventFree(pEvent);
1036 pEvent = NULL;
1037
1038 if (*pfShutdown)
1039 break;
1040
1041 /* Wait a bit before retrying. */
1042 RTThreadSleep(1000);
1043 continue;
1044 }
1045 else
1046 {
1047 AssertPtr(pEvent);
1048 LogFlowFunc(("Event uType=%RU32\n", pEvent->enmType));
1049
1050 switch (pEvent->enmType)
1051 {
1052 case VBGLR3CLIPBOARDEVENTTYPE_REPORT_FORMATS:
1053 {
1054 /* The host has announced available clipboard formats.
1055 * Forward the information to the window, so it can later
1056 * respond to WM_RENDERFORMAT message. */
1057 ::PostMessage(pWinCtx->hWnd, SHCL_WIN_WM_REPORT_FORMATS,
1058 0 /* wParam */, (LPARAM)pEvent /* lParam */);
1059
1060 pEvent = NULL; /* Consume pointer. */
1061 break;
1062 }
1063
1064 case VBGLR3CLIPBOARDEVENTTYPE_READ_DATA:
1065 {
1066 /* The host needs data in the specified format. */
1067 ::PostMessage(pWinCtx->hWnd, SHCL_WIN_WM_READ_DATA,
1068 0 /* wParam */, (LPARAM)pEvent /* lParam */);
1069
1070 pEvent = NULL; /* Consume pointer. */
1071 break;
1072 }
1073
1074 case VBGLR3CLIPBOARDEVENTTYPE_QUIT:
1075 {
1076 LogRel2(("Shared Clipboard: Host requested termination\n"));
1077 ASMAtomicXchgBool(pfShutdown, true);
1078 break;
1079 }
1080
1081#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1082 case VBGLR3CLIPBOARDEVENTTYPE_TRANSFER_STATUS:
1083 {
1084 /* Nothing to do here. */
1085 rc = VINF_SUCCESS;
1086 break;
1087 }
1088#endif
1089 case VBGLR3CLIPBOARDEVENTTYPE_NONE:
1090 {
1091 /* Nothing to do here. */
1092 rc = VINF_SUCCESS;
1093 break;
1094 }
1095
1096 default:
1097 {
1098 AssertMsgFailedBreakStmt(("Event type %RU32 not implemented\n", pEvent->enmType), rc = VERR_NOT_SUPPORTED);
1099 }
1100 }
1101
1102 if (pEvent)
1103 {
1104 VbglR3ClipboardEventFree(pEvent);
1105 pEvent = NULL;
1106 }
1107 }
1108
1109 if (*pfShutdown)
1110 break;
1111 }
1112
1113 LogRel2(("Shared Clipboard: Worker loop ended\n"));
1114
1115#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1116 OleSetClipboard(NULL); /* Make sure to flush the clipboard on destruction. */
1117 OleUninitialize();
1118#endif
1119
1120 LogFlowFuncLeaveRC(rc);
1121 return rc;
1122}
1123
1124DECLCALLBACK(int) VBoxShClStop(void *pInstance)
1125{
1126 AssertPtrReturn(pInstance, VERR_INVALID_POINTER);
1127
1128 LogFunc(("Stopping pInstance=%p\n", pInstance));
1129
1130 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pInstance;
1131 AssertPtr(pCtx);
1132
1133 /* Set shutdown indicator. */
1134 ASMAtomicWriteBool(&pCtx->fShutdown, true);
1135
1136 /* Let our clipboard know that we're going to shut down. */
1137 PostMessage(pCtx->Win.hWnd, WM_QUIT, 0, 0);
1138
1139 /* Disconnect from the host service.
1140 * This will also send a VBOX_SHCL_HOST_MSG_QUIT from the host so that we can break out from our message worker. */
1141 VbglR3ClipboardDisconnect(pCtx->CmdCtx.idClient);
1142 pCtx->CmdCtx.idClient = 0;
1143
1144 LogFlowFuncLeaveRC(VINF_SUCCESS);
1145 return VINF_SUCCESS;
1146}
1147
1148DECLCALLBACK(void) VBoxShClDestroy(void *pInstance)
1149{
1150 AssertPtrReturnVoid(pInstance);
1151
1152 PSHCLCONTEXT pCtx = (PSHCLCONTEXT)pInstance;
1153 AssertPtr(pCtx);
1154
1155 /* Make sure that we are disconnected. */
1156 Assert(pCtx->CmdCtx.idClient == 0);
1157
1158 vboxClipboardDestroy(pCtx);
1159
1160#ifdef VBOX_WITH_SHARED_CLIPBOARD_TRANSFERS
1161 ShClTransferCtxDestroy(&pCtx->TransferCtx);
1162#endif
1163
1164 return;
1165}
1166
1167/**
1168 * The service description.
1169 */
1170VBOXSERVICEDESC g_SvcDescClipboard =
1171{
1172 /* pszName. */
1173 "clipboard",
1174 /* pszDescription. */
1175 "Shared Clipboard",
1176 /* methods */
1177 VBoxShClInit,
1178 VBoxShClWorker,
1179 VBoxShClStop,
1180 VBoxShClDestroy
1181};
Note: See TracBrowser for help on using the repository browser.

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