FreeRDP
Loading...
Searching...
No Matches
xf_cliprdr.c
1
22#include <freerdp/config.h>
23
24#include <stdlib.h>
25#include <errno.h>
26
27#include <X11/Xlib.h>
28#include <X11/Xatom.h>
29
30#ifdef WITH_XFIXES
31#include <X11/extensions/Xfixes.h>
32#endif
33
34#include <winpr/crt.h>
35#include <winpr/assert.h>
36#include <winpr/image.h>
37#include <winpr/stream.h>
38#include <winpr/clipboard.h>
39#include <winpr/path.h>
40
41#include <freerdp/utils/signal.h>
42#include <freerdp/log.h>
43#include <freerdp/client/cliprdr.h>
44#include <freerdp/channels/channels.h>
45#include <freerdp/channels/cliprdr.h>
46
47#include <freerdp/client/client_cliprdr_file.h>
48
49#include "xf_cliprdr.h"
50#include "xf_event.h"
51#include "xf_utils.h"
52
53#define TAG CLIENT_TAG("x11.cliprdr")
54
55#define MAX_CLIPBOARD_FORMATS 255
56
57#define DEBUG_CLIPRDR(...) WLog_DBG(TAG, __VA_ARGS__)
58
59typedef struct
60{
61 Atom atom;
62 UINT32 formatToRequest;
63 UINT32 localFormat;
64 char* formatName;
65 BOOL isImage;
66} xfCliprdrFormat;
67
68typedef struct
69{
70 BYTE* data;
71 UINT32 data_length;
72} xfCachedData;
73
74typedef struct
75{
76 UINT32 localFormat;
77 UINT32 formatToRequest;
78 char* formatName;
79} RequestedFormat;
80
81typedef struct
82{
83 XSelectionEvent* expectedResponse;
84 RequestedFormat* requestedFormat;
85 BOOL data_raw_format;
86} SelectionResponse;
87
88struct xf_clipboard
89{
90 xfContext* xfc;
91 rdpChannels* channels;
92 CliprdrClientContext* context;
93
94 wClipboard* system;
95
96 Window root_window;
97 Atom clipboard_atom;
98 Atom property_atom;
99
100 Atom timestamp_property_atom;
101 Time selection_ownership_timestamp;
102
103 Atom raw_transfer_atom;
104 Atom raw_format_list_atom;
105
106 UINT32 numClientFormats;
107 xfCliprdrFormat clientFormats[20];
108
109 UINT32 numServerFormats;
110 CLIPRDR_FORMAT* serverFormats;
111
112 size_t numTargets;
113 Atom targets[20];
114
115 UINT32 requestedFormatId;
116
117 wHashTable* cachedData;
118 wHashTable* cachedRawData;
119
120 wArrayList* pending_responses;
121 wArrayList* queued_responses;
122
123 Window owner;
124 BOOL sync;
125
126 /* INCR mechanism */
127 Atom incr_atom;
128 BOOL incr_starts;
129 BYTE* incr_data;
130 size_t incr_data_length;
131 long event_mask;
132
133 /* XFixes extension */
134 int xfixes_event_base;
135 int xfixes_error_base;
136 BOOL xfixes_supported;
137
138 CliprdrFileContext* file;
139 BOOL isImageContent;
140 Atom* clientAvailableFormatAtoms;
141 size_t clientAvailableFormatAtomsCount;
142
143 wLog* log;
144};
145
146static const char mime_text_plain[] = "text/plain";
147static const char mime_text_utf8[] = "text/plain;charset=utf-8";
148static const char mime_uri_list[] = "text/uri-list";
149static const char mime_html[] = "text/html";
150static const char* mime_bitmap[] = { "image/bmp", "image/x-bmp", "image/x-MS-bmp",
151 "image/x-win-bitmap" };
152static const char mime_webp[] = "image/webp";
153static const char mime_png[] = "image/png";
154static const char mime_jpeg[] = "image/jpeg";
155static const char mime_tiff[] = "image/tiff";
156static const char* mime_images[] = { mime_webp, mime_png, mime_jpeg, mime_tiff };
157
158static const char mime_gnome_copied_files[] = "x-special/gnome-copied-files";
159static const char mime_mate_copied_files[] = "x-special/mate-copied-files";
160
161static const char type_FileGroupDescriptorW[] = "FileGroupDescriptorW";
162static const char type_HtmlFormat[] = "HTML Format";
163
164static void xf_cliprdr_clear_cached_data(xfClipboard* clipboard);
165static UINT xf_cliprdr_send_client_format_list(xfClipboard* clipboard);
166static void xf_cliprdr_set_selection_owner(xfContext* xfc, xfClipboard* clipboard, Time timestamp);
167
168static void requested_format_free(RequestedFormat** ppRequestedFormat)
169{
170 if (!ppRequestedFormat)
171 return;
172 if (!(*ppRequestedFormat))
173 return;
174
175 free((*ppRequestedFormat)->formatName);
176 free(*ppRequestedFormat);
177 *ppRequestedFormat = nullptr;
178}
179
180static BOOL requested_format_replace(RequestedFormat** ppRequestedFormat, UINT32 remoteFormatId,
181 UINT32 localFormatId, const char* formatName)
182{
183 if (!ppRequestedFormat)
184 return FALSE;
185
186 requested_format_free(ppRequestedFormat);
187 RequestedFormat* requested = calloc(1, sizeof(RequestedFormat));
188 if (!requested)
189 return FALSE;
190 requested->localFormat = localFormatId;
191 requested->formatToRequest = remoteFormatId;
192 if (formatName)
193 {
194 requested->formatName = _strdup(formatName);
195 if (!requested->formatName)
196 {
197 free(requested);
198 return FALSE;
199 }
200 }
201
202 *ppRequestedFormat = requested;
203 return TRUE;
204}
205
206static void selection_response_free(void* ptr)
207{
208 SelectionResponse* selection_response = (SelectionResponse*)ptr;
209 if (!selection_response)
210 return;
211
212 free(selection_response->expectedResponse);
213 requested_format_free(&selection_response->requestedFormat);
214 free(selection_response);
215}
216
217static void xf_cached_data_free(void* ptr)
218{
219 xfCachedData* cached_data = ptr;
220 if (!cached_data)
221 return;
222
223 free(cached_data->data);
224 free(cached_data);
225}
226
227static xfCachedData* xf_cached_data_new(BYTE* data, size_t data_length)
228{
229 if (data_length > UINT32_MAX)
230 return nullptr;
231
232 xfCachedData* cached_data = calloc(1, sizeof(xfCachedData));
233 if (!cached_data)
234 return nullptr;
235
236 cached_data->data = data;
237 cached_data->data_length = (UINT32)data_length;
238
239 return cached_data;
240}
241
242static xfCachedData* xf_cached_data_new_copy(const BYTE* data, size_t data_length)
243{
244 BYTE* copy = nullptr;
245 if (data_length > 0)
246 {
247 copy = calloc(data_length + 1, sizeof(BYTE));
248 if (!copy)
249 return nullptr;
250 memcpy(copy, data, data_length);
251 }
252
253 xfCachedData* cache = xf_cached_data_new(copy, data_length);
254 if (!cache)
255 free(copy);
256 return cache;
257}
258
259static void xf_clipboard_free_server_formats(xfClipboard* clipboard)
260{
261 WINPR_ASSERT(clipboard);
262 if (clipboard->serverFormats)
263 {
264 for (size_t i = 0; i < clipboard->numServerFormats; i++)
265 {
266 CLIPRDR_FORMAT* format = &clipboard->serverFormats[i];
267 free(format->formatName);
268 }
269
270 free(clipboard->serverFormats);
271 clipboard->serverFormats = nullptr;
272 }
273}
274
275static BOOL xf_cliprdr_update_owner(xfClipboard* clipboard)
276{
277 WINPR_ASSERT(clipboard);
278
279 xfContext* xfc = clipboard->xfc;
280 WINPR_ASSERT(xfc);
281
282 if (!clipboard->sync)
283 return FALSE;
284
285 Window owner =
286 LogDynAndXGetSelectionOwner(clipboard->log, xfc->display, clipboard->clipboard_atom);
287 if (clipboard->owner == owner)
288 return FALSE;
289
290 clipboard->owner = owner;
291 return TRUE;
292}
293
294static void xf_cliprdr_check_owner(xfClipboard* clipboard)
295{
296 if (xf_cliprdr_update_owner(clipboard))
297 xf_cliprdr_send_client_format_list(clipboard);
298}
299
300static BOOL xf_cliprdr_is_self_owned(xfClipboard* clipboard)
301{
302 xfContext* xfc = nullptr;
303
304 WINPR_ASSERT(clipboard);
305
306 xfc = clipboard->xfc;
307 WINPR_ASSERT(xfc);
308 return LogDynAndXGetSelectionOwner(clipboard->log, xfc->display, clipboard->clipboard_atom) ==
309 xfc->drawable;
310}
311
312static void xf_cliprdr_set_raw_transfer_enabled(xfClipboard* clipboard, BOOL enabled)
313{
314 UINT32 data = WINPR_ASSERTING_INT_CAST(uint32_t, enabled);
315 xfContext* xfc = nullptr;
316
317 WINPR_ASSERT(clipboard);
318
319 xfc = clipboard->xfc;
320 WINPR_ASSERT(xfc);
321 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
322 clipboard->raw_transfer_atom, XA_INTEGER, 32, PropModeReplace,
323 (const BYTE*)&data, 1);
324}
325
326static BOOL xf_cliprdr_is_raw_transfer_available(xfClipboard* clipboard)
327{
328 Atom type = 0;
329 int format = 0;
330 int result = 0;
331 unsigned long length = 0;
332 unsigned long bytes_left = 0;
333 UINT32* data = nullptr;
334 UINT32 is_enabled = 0;
335 Window owner = None;
336 xfContext* xfc = nullptr;
337
338 WINPR_ASSERT(clipboard);
339
340 xfc = clipboard->xfc;
341 WINPR_ASSERT(xfc);
342
343 owner = LogDynAndXGetSelectionOwner(clipboard->log, xfc->display, clipboard->clipboard_atom);
344
345 if (owner != None)
346 {
347 result = LogDynAndXGetWindowProperty(clipboard->log, xfc->display, owner,
348 clipboard->raw_transfer_atom, 0, 4, 0, XA_INTEGER,
349 &type, &format, &length, &bytes_left, (BYTE**)&data);
350 }
351
352 if (data)
353 {
354 is_enabled = *data;
355 XFree(data);
356 }
357
358 if ((owner == None) || (owner == xfc->drawable))
359 return FALSE;
360
361 if (result != Success)
362 return FALSE;
363
364 return is_enabled != 0;
365}
366
367static BOOL xf_cliprdr_formats_equal(const CLIPRDR_FORMAT* server, const xfCliprdrFormat* client)
368{
369 WINPR_ASSERT(server);
370 WINPR_ASSERT(client);
371
372 if (server->formatName && client->formatName)
373 {
374 /* The server may be using short format names while we store them in full form. */
375 return (0 == strncmp(server->formatName, client->formatName, strlen(server->formatName)));
376 }
377
378 if (!server->formatName && !client->formatName)
379 {
380 return (server->formatId == client->formatToRequest);
381 }
382
383 return FALSE;
384}
385
386WINPR_ATTR_NODISCARD
387static BOOL xf_cliprdr_is_atom_available(xfClipboard* clipboard, Atom atom)
388{
389 WINPR_ASSERT(clipboard);
390
391 char* name = Safe_XGetAtomName(clipboard->log, clipboard->xfc->display, atom);
392 for (size_t x = 0; x < clipboard->clientAvailableFormatAtomsCount; x++)
393 {
394 WINPR_ASSERT(clipboard->clientAvailableFormatAtoms);
395
396 Atom cur = clipboard->clientAvailableFormatAtoms[x];
397 if (cur == atom)
398 {
399 WLog_Print(clipboard->log, WLOG_DEBUG, "Atom [%s] available from local clipboard",
400 name);
401 free(name);
402 return TRUE;
403 }
404 }
405
406 WLog_Print(clipboard->log, WLOG_DEBUG, "Atom [%s] NOT available from local clipboard", name);
407 free(name);
408 return FALSE;
409}
410
411WINPR_ATTR_NODISCARD
412static const xfCliprdrFormat* xf_cliprdr_get_client_available_format_by_id(xfClipboard* clipboard,
413 UINT32 formatId)
414{
415 WINPR_ASSERT(clipboard);
416
417 const BOOL formatIsHtml = formatId == ClipboardGetFormatId(clipboard->system, type_HtmlFormat);
418 const BOOL fetchImage = clipboard->isImageContent && formatIsHtml;
419 for (size_t index = 0; index < clipboard->numClientFormats; index++)
420 {
421 const xfCliprdrFormat* format = &(clipboard->clientFormats[index]);
422
423 if (!xf_cliprdr_is_atom_available(clipboard, format->atom) && (formatId != CF_RAW))
424 continue;
425
426 if (fetchImage && format->isImage)
427 return format;
428
429 if (format->formatToRequest == formatId)
430 return format;
431 }
432
433 return nullptr;
434}
435
436static const xfCliprdrFormat* xf_cliprdr_get_client_format_by_atom(xfClipboard* clipboard,
437 Atom atom)
438{
439 WINPR_ASSERT(clipboard);
440
441 for (UINT32 i = 0; i < clipboard->numClientFormats; i++)
442 {
443 const xfCliprdrFormat* format = &(clipboard->clientFormats[i]);
444
445 if (format->atom == atom)
446 return format;
447 }
448
449 return nullptr;
450}
451
452static const CLIPRDR_FORMAT* xf_cliprdr_get_server_format_by_atom(xfClipboard* clipboard, Atom atom)
453{
454 WINPR_ASSERT(clipboard);
455
456 for (size_t i = 0; i < clipboard->numClientFormats; i++)
457 {
458 const xfCliprdrFormat* client_format = &(clipboard->clientFormats[i]);
459
460 if (client_format->atom == atom)
461 {
462 for (size_t j = 0; j < clipboard->numServerFormats; j++)
463 {
464 const CLIPRDR_FORMAT* server_format = &(clipboard->serverFormats[j]);
465
466 if (xf_cliprdr_formats_equal(server_format, client_format))
467 return server_format;
468 }
469 }
470 }
471
472 return nullptr;
473}
474
480static UINT xf_cliprdr_send_data_request(xfClipboard* clipboard, UINT32 formatId,
481 WINPR_ATTR_UNUSED const xfCliprdrFormat* cformat)
482{
483 CLIPRDR_FORMAT_DATA_REQUEST request = WINPR_C_ARRAY_INIT;
484 request.requestedFormatId = formatId;
485
486 DEBUG_CLIPRDR("requesting format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 "} [%s]", formatId,
487 ClipboardGetFormatIdString(formatId), cformat->localFormat, cformat->formatName);
488
489 WINPR_ASSERT(clipboard);
490 if (!clipboard->context)
491 return CHANNEL_RC_NOT_INITIALIZED;
492 WINPR_ASSERT(clipboard->context->ClientFormatDataRequest);
493 return clipboard->context->ClientFormatDataRequest(clipboard->context, &request);
494}
495
501static UINT xf_cliprdr_send_data_response(xfClipboard* clipboard, const xfCliprdrFormat* format,
502 const BYTE* data, size_t size)
503{
504 CLIPRDR_FORMAT_DATA_RESPONSE response = WINPR_C_ARRAY_INIT;
505
506 WINPR_ASSERT(clipboard);
507 if (!clipboard->context)
508 return CHANNEL_RC_NOT_INITIALIZED;
509
510 /* No request currently pending, do not send a response. */
511 if (clipboard->requestedFormatId == UINT32_MAX)
512 return CHANNEL_RC_OK;
513
514 if (size == 0)
515 {
516 if (format)
517 DEBUG_CLIPRDR("send CB_RESPONSE_FAIL response {format 0x%08" PRIx32
518 " [%s] {local 0x%08" PRIx32 "} [%s]",
519 format->formatToRequest,
520 ClipboardGetFormatIdString(format->formatToRequest), format->localFormat,
521 format->formatName);
522 else
523 DEBUG_CLIPRDR("send CB_RESPONSE_FAIL response");
524 }
525 else
526 {
527 WINPR_ASSERT(format);
528 DEBUG_CLIPRDR("send response format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 " [%s]} [%s]",
529 format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest),
530 format->localFormat,
531 ClipboardGetFormatName(clipboard->system, format->localFormat),
532 format->formatName);
533 }
534 /* Request handled, reset to invalid */
535 clipboard->requestedFormatId = UINT32_MAX;
536
537 response.common.msgFlags = (data) ? CB_RESPONSE_OK : CB_RESPONSE_FAIL;
538
539 WINPR_ASSERT(size <= UINT32_MAX);
540 response.common.dataLen = (UINT32)size;
541 response.requestedFormatData = data;
542
543 WINPR_ASSERT(clipboard->context->ClientFormatDataResponse);
544 return clipboard->context->ClientFormatDataResponse(clipboard->context, &response);
545}
546
547static wStream* xf_cliprdr_serialize_server_format_list(xfClipboard* clipboard)
548{
549 UINT32 formatCount = 0;
550
551 WINPR_ASSERT(clipboard);
552
553 /* Typical MS Word format list is about 80 bytes long. */
554 wStream* s = Stream_New(nullptr, 128);
555 if (!s)
556 {
557 WLog_Print(clipboard->log, WLOG_ERROR, "failed to allocate serialized format list");
558 goto error;
559 }
560
561 /* If present, the last format is always synthetic CF_RAW. Do not include it. */
562 formatCount = (clipboard->numServerFormats > 0) ? clipboard->numServerFormats - 1 : 0;
563 Stream_Write_UINT32(s, formatCount);
564
565 for (UINT32 i = 0; i < formatCount; i++)
566 {
567 CLIPRDR_FORMAT* format = &clipboard->serverFormats[i];
568 size_t name_length = format->formatName ? strlen(format->formatName) : 0;
569
570 DEBUG_CLIPRDR("server announced 0x%08" PRIx32 " [%s][%s]", format->formatId,
571 ClipboardGetFormatIdString(format->formatId), format->formatName);
572 if (!Stream_EnsureRemainingCapacity(s, sizeof(UINT32) + name_length + 1ull))
573 {
574 WLog_Print(clipboard->log, WLOG_ERROR, "failed to expand serialized format list");
575 goto error;
576 }
577
578 Stream_Write_UINT32(s, format->formatId);
579
580 if (format->formatName)
581 Stream_Write(s, format->formatName, name_length);
582
583 Stream_Write_UINT8(s, '\0');
584 }
585
586 Stream_SealLength(s);
587 return s;
588error:
589 Stream_Free(s, TRUE);
590 return nullptr;
591}
592
593static CLIPRDR_FORMAT* xf_cliprdr_parse_server_format_list(wLog* log, BYTE* data, size_t length,
594 UINT32* numFormats)
595{
596 WINPR_ASSERT(log);
597
598 CLIPRDR_FORMAT* formats = nullptr;
599
600 WINPR_ASSERT(data || (length == 0));
601 WINPR_ASSERT(numFormats);
602
603 wStream* s = Stream_New(data, length);
604 if (!s)
605 {
606 WLog_Print(log, WLOG_ERROR, "failed to allocate stream for parsing serialized format list");
607 goto error;
608 }
609
610 if (!Stream_CheckAndLogRequiredLength(TAG, s, sizeof(UINT32)))
611 goto error;
612
613 Stream_Read_UINT32(s, *numFormats);
614
615 if (*numFormats > MAX_CLIPBOARD_FORMATS)
616 {
617 WLog_Print(log, WLOG_ERROR, "unexpectedly large number of formats: %" PRIu32 "",
618 *numFormats);
619 goto error;
620 }
621
622 if (!(formats = (CLIPRDR_FORMAT*)calloc(*numFormats, sizeof(CLIPRDR_FORMAT))))
623 {
624 WLog_Print(log, WLOG_ERROR, "failed to allocate format list");
625 goto error;
626 }
627
628 for (UINT32 i = 0; i < *numFormats; i++)
629 {
630 const char* formatName = nullptr;
631 size_t formatNameLength = 0;
632
633 if (!Stream_CheckAndLogRequiredLength(TAG, s, sizeof(UINT32)))
634 goto error;
635
636 Stream_Read_UINT32(s, formats[i].formatId);
637 formatName = (const char*)Stream_Pointer(s);
638 formatNameLength = strnlen(formatName, Stream_GetRemainingLength(s));
639
640 if (formatNameLength == Stream_GetRemainingLength(s))
641 {
642 WLog_Print(log, WLOG_ERROR,
643 "missing terminating null byte, %" PRIuz " bytes left to read",
644 formatNameLength);
645 goto error;
646 }
647
648 formats[i].formatName = strndup(formatName, formatNameLength);
649 Stream_Seek(s, formatNameLength + 1);
650 }
651
652 Stream_Free(s, FALSE);
653 return formats;
654error:
655 Stream_Free(s, FALSE);
656 free(formats);
657 *numFormats = 0;
658 return nullptr;
659}
660
661static void xf_cliprdr_free_formats(CLIPRDR_FORMAT* formats, UINT32 numFormats)
662{
663 WINPR_ASSERT(formats || (numFormats == 0));
664
665 for (UINT32 i = 0; i < numFormats; i++)
666 {
667 free(formats[i].formatName);
668 }
669
670 free(formats);
671}
672
673static CLIPRDR_FORMAT* xf_cliprdr_get_raw_server_formats(xfClipboard* clipboard, UINT32* numFormats)
674{
675 Atom type = None;
676 int format = 0;
677 unsigned long length = 0;
678 unsigned long remaining = 0;
679 BYTE* data = nullptr;
680 CLIPRDR_FORMAT* formats = nullptr;
681 xfContext* xfc = nullptr;
682
683 WINPR_ASSERT(clipboard);
684 WINPR_ASSERT(numFormats);
685
686 xfc = clipboard->xfc;
687 WINPR_ASSERT(xfc);
688
689 *numFormats = 0;
690
691 Window owner =
692 LogDynAndXGetSelectionOwner(clipboard->log, xfc->display, clipboard->clipboard_atom);
693 LogDynAndXGetWindowProperty(
694 clipboard->log, xfc->display, owner, clipboard->raw_format_list_atom, 0, 4096, False,
695 clipboard->raw_format_list_atom, &type, &format, &length, &remaining, &data);
696
697 if (data && length > 0 && format == 8 && type == clipboard->raw_format_list_atom)
698 {
699 formats = xf_cliprdr_parse_server_format_list(clipboard->log, data, length, numFormats);
700 }
701 else
702 {
703 WLog_Print(clipboard->log, WLOG_ERROR,
704 "failed to retrieve raw format list: data=%p, length=%lu, format=%d, type=%lu "
705 "(expected=%lu)",
706 (void*)data, length, format, (unsigned long)type,
707 (unsigned long)clipboard->raw_format_list_atom);
708 }
709
710 if (data)
711 XFree(data);
712
713 return formats;
714}
715
716static BOOL xf_cliprdr_should_add_format(const CLIPRDR_FORMAT* formats, size_t count,
717 const xfCliprdrFormat* xformat)
718{
719 WINPR_ASSERT(formats);
720
721 if (!xformat)
722 return FALSE;
723
724 for (size_t x = 0; x < count; x++)
725 {
726 const CLIPRDR_FORMAT* format = &formats[x];
727 if (format->formatId == xformat->formatToRequest)
728 return FALSE;
729 }
730 return TRUE;
731}
732
733WINPR_ATTR_NODISCARD
734static CLIPRDR_FORMAT* xf_cliprdr_get_formats_from_targets(xfClipboard* clipboard,
735 UINT32* numFormats, Atom** atoms,
736 size_t* atomsCount)
737{
738 Atom atom = None;
739 BYTE* data = nullptr;
740 int format_property = 0;
741 unsigned long proplength = 0;
742 unsigned long bytes_left = 0;
743 CLIPRDR_FORMAT* formats = nullptr;
744
745 WINPR_ASSERT(clipboard);
746 WINPR_ASSERT(numFormats);
747 WINPR_ASSERT(atoms);
748 WINPR_ASSERT(atomsCount);
749
750 xfContext* xfc = clipboard->xfc;
751 WINPR_ASSERT(xfc);
752
753 *numFormats = 0;
754 *atomsCount = 0;
755 {
756 XFree(*atoms);
757 *atoms = nullptr;
758 }
759
760 LogDynAndXGetWindowProperty(clipboard->log, xfc->display, xfc->drawable,
761 clipboard->property_atom, 0, 200, 0, XA_ATOM, &atom,
762 &format_property, &proplength, &bytes_left, &data);
763
764 if (proplength > 0)
765 {
766 unsigned long length = proplength + 1;
767 if (!data)
768 {
769 WLog_Print(clipboard->log, WLOG_ERROR,
770 "XGetWindowProperty set length = %lu but data is nullptr", length);
771 goto out;
772 }
773
774 if (!(formats = (CLIPRDR_FORMAT*)calloc(length, sizeof(CLIPRDR_FORMAT))))
775 {
776 WLog_Print(clipboard->log, WLOG_ERROR, "failed to allocate %lu CLIPRDR_FORMAT structs",
777 length);
778 goto out;
779 }
780 }
781
782 {
783 BOOL isImage = FALSE;
784 BOOL hasHtml = FALSE;
785 const uint32_t htmlFormatId = ClipboardRegisterFormat(clipboard->system, type_HtmlFormat);
786 for (unsigned long i = 0; i < proplength; i++)
787 {
788 Atom tatom = WINPR_PACKED_ALIGN_CAST(Atom*, data)[i];
789 const xfCliprdrFormat* format = xf_cliprdr_get_client_format_by_atom(clipboard, tatom);
790
791 if (xf_cliprdr_should_add_format(formats, *numFormats, format))
792 {
793 CLIPRDR_FORMAT* cformat = &formats[*numFormats];
794 cformat->formatId = format->formatToRequest;
795
796 /* We do not want to double register a format, so check if HTML was already
797 * registered.
798 */
799 if (cformat->formatId == htmlFormatId)
800 hasHtml = TRUE;
801
802 /* These are standard image types that will always be registered regardless of
803 * actual image format. */
804 if (cformat->formatId == CF_TIFF)
805 isImage = TRUE;
806 else if (cformat->formatId == CF_DIB)
807 isImage = TRUE;
808 else if (cformat->formatId == CF_DIBV5)
809 isImage = TRUE;
810
811 if (format->formatName)
812 {
813 cformat->formatName = _strdup(format->formatName);
814 WINPR_ASSERT(cformat->formatName);
815 }
816 else
817 cformat->formatName = nullptr;
818
819 *numFormats += 1;
820 }
821 }
822
823 clipboard->isImageContent = isImage;
824 if (isImage && !hasHtml)
825 {
826 CLIPRDR_FORMAT* cformat = &formats[*numFormats];
827 cformat->formatId = htmlFormatId;
828 cformat->formatName = _strdup(type_HtmlFormat);
829
830 *numFormats += 1;
831 }
832 }
833out:
834
835 if (data && !atoms)
836 XFree(data);
837 else if (atoms && data)
838 {
839 *atoms = WINPR_PACKED_ALIGN_CAST(Atom*, data);
840 *atomsCount = proplength;
841 }
842
843 return formats;
844}
845
846WINPR_ATTR_NODISCARD
847static CLIPRDR_FORMAT* xf_cliprdr_get_client_formats(xfClipboard* clipboard, UINT32* numFormats,
848 Atom** atoms, size_t* atomsCount)
849{
850 CLIPRDR_FORMAT* formats = nullptr;
851
852 WINPR_ASSERT(clipboard);
853 WINPR_ASSERT(numFormats);
854 WINPR_ASSERT(atoms);
855 WINPR_ASSERT(atomsCount);
856
857 *numFormats = 0;
858 *atomsCount = 0;
859 {
860 XFree(*atoms);
861 *atoms = nullptr;
862 }
863
864 if (xf_cliprdr_is_raw_transfer_available(clipboard))
865 formats = xf_cliprdr_get_raw_server_formats(clipboard, numFormats);
866
867 if (*numFormats == 0)
868 {
869 xf_cliprdr_free_formats(formats, *numFormats);
870 formats = xf_cliprdr_get_formats_from_targets(clipboard, numFormats, atoms, atomsCount);
871 }
872
873 return formats;
874}
875
876static void xf_cliprdr_provide_server_format_list(xfClipboard* clipboard)
877{
878 wStream* formats = nullptr;
879 xfContext* xfc = nullptr;
880
881 WINPR_ASSERT(clipboard);
882
883 xfc = clipboard->xfc;
884 WINPR_ASSERT(xfc);
885
886 formats = xf_cliprdr_serialize_server_format_list(clipboard);
887
888 if (formats)
889 {
890 const size_t len = Stream_Length(formats);
891 WINPR_ASSERT(len <= INT32_MAX);
892 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
893 clipboard->raw_format_list_atom, clipboard->raw_format_list_atom,
894 8, PropModeReplace, Stream_Buffer(formats), (int)len);
895 }
896 else
897 {
898 LogDynAndXDeleteProperty(clipboard->log, xfc->display, xfc->drawable,
899 clipboard->raw_format_list_atom);
900 }
901
902 Stream_Free(formats, TRUE);
903}
904
905WINPR_ATTR_MALLOC(free, 1)
906static char* atomsToStringList(wLog* log, Display* display, const Atom* atoms, size_t count)
907{
908 WINPR_ASSERT(atoms || (count == 0));
909
910 char* str = calloc(1, sizeof(char));
911 if (!str)
912 return str;
913 size_t len = 0;
914 for (size_t x = 0; x < count; x++)
915 {
916 Atom atom = atoms[x];
917 char* name = Safe_XGetAtomName(log, display, atom);
918 if (name)
919 {
920 char* tmp = nullptr;
921 if (len > 0)
922 winpr_asprintf(&tmp, &len, "%s,%s", str, name);
923 else
924 {
925 tmp = name;
926 name = nullptr;
927 }
928 free(str);
929 str = tmp;
930 }
931 winpr_str_append(name, str, len, ",");
932 free(name);
933 }
934 return str;
935}
936
937static UINT xf_cliprdr_send_format_list(xfClipboard* clipboard, const CLIPRDR_FORMAT* formats,
938 UINT32 numFormats, Atom* atoms, size_t atomsCount)
939{
940 union
941 {
942 const CLIPRDR_FORMAT* cpv;
943 CLIPRDR_FORMAT* pv;
944 } cnv = { .cpv = formats };
945 const CLIPRDR_FORMAT_LIST formatList = { .common.msgFlags = 0,
946 .numFormats = numFormats,
947 .formats = cnv.pv,
948 .common.msgType = CB_FORMAT_LIST };
949 UINT ret = 0;
950
951 WINPR_ASSERT(clipboard);
952 WINPR_ASSERT(formats || (numFormats == 0));
953 WINPR_ASSERT(atoms || (atomsCount == 0));
954
955 /* xf_cliprdr_uninit() clears the context when the channel is torn down, but the X11
956 * event thread keeps processing clipboard events, e.g. while reconnecting. */
957 if (!clipboard->context)
958 return CHANNEL_RC_NOT_INITIALIZED;
959
960#if defined(WITH_DEBUG_CLIPRDR)
961 for (UINT32 x = 0; x < numFormats; x++)
962 {
963 const CLIPRDR_FORMAT* format = &formats[x];
964 DEBUG_CLIPRDR("announcing format 0x%08" PRIx32 " [%s] [%s]", format->formatId,
965 ClipboardGetFormatIdString(format->formatId), format->formatName);
966 }
967#endif
968
969 /* Ensure all pending requests are answered. */
970 xf_cliprdr_send_data_response(clipboard, nullptr, nullptr, 0);
971
972 xf_cliprdr_clear_cached_data(clipboard);
973
974 if (WLog_IsLevelActive(clipboard->log, WLOG_DEBUG))
975 {
976 char* list = atomsToStringList(clipboard->log, clipboard->xfc->display, atoms, atomsCount);
977 WLog_Print(clipboard->log, WLOG_DEBUG, "Updating available atoms[%" PRIuz "] : { %s }",
978 atomsCount, list);
979 free(list);
980 }
981 clipboard->clientAvailableFormatAtoms = atoms;
982 clipboard->clientAvailableFormatAtomsCount = atomsCount;
983
984 ret = cliprdr_file_context_notify_new_client_format_list(clipboard->file);
985 if (ret)
986 return ret;
987
988 WINPR_ASSERT(clipboard->context->ClientFormatList);
989 return clipboard->context->ClientFormatList(clipboard->context, &formatList);
990}
991
992static void xf_cliprdr_get_requested_targets(xfClipboard* clipboard)
993{
994 UINT32 numFormats = 0;
995 Atom* atoms = nullptr;
996 size_t atomsCount = 0;
997 CLIPRDR_FORMAT* formats =
998 xf_cliprdr_get_client_formats(clipboard, &numFormats, &atoms, &atomsCount);
999 xf_cliprdr_send_format_list(clipboard, formats, numFormats, atoms, atomsCount);
1000 xf_cliprdr_free_formats(formats, numFormats);
1001}
1002
1003static void xf_cliprdr_process_requested_data(xfClipboard* clipboard, BOOL hasData,
1004 const BYTE* data, size_t size)
1005{
1006 BOOL bSuccess = 0;
1007 UINT32 SrcSize = 0;
1008 UINT32 DstSize = 0;
1009 INT64 srcFormatId = -1;
1010 BYTE* pDstData = nullptr;
1011 const xfCliprdrFormat* format = nullptr;
1012
1013 WINPR_ASSERT(clipboard);
1014
1015 if (clipboard->incr_starts && hasData)
1016 return;
1017
1018 /* Reset incr_data_length, as we've reached the end of a possible incremental update.
1019 * this ensures on next event that the buffer is not reused. */
1020 clipboard->incr_data_length = 0;
1021
1022 format = xf_cliprdr_get_client_available_format_by_id(clipboard, clipboard->requestedFormatId);
1023
1024 if (!hasData || !data || !format)
1025 {
1026 xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
1027 return;
1028 }
1029
1030 switch (format->formatToRequest)
1031 {
1032 case CF_RAW:
1033 srcFormatId = CF_RAW;
1034 break;
1035
1036 case CF_TEXT:
1037 case CF_OEMTEXT:
1038 case CF_UNICODETEXT:
1039 srcFormatId = format->localFormat;
1040 break;
1041
1042 default:
1043 srcFormatId = format->localFormat;
1044 break;
1045 }
1046
1047 if (srcFormatId < 0)
1048 {
1049 xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
1050 return;
1051 }
1052
1053 ClipboardLock(clipboard->system);
1054 SrcSize = (UINT32)size;
1055 bSuccess = ClipboardSetData(clipboard->system, (UINT32)srcFormatId, data, SrcSize);
1056
1057 if (bSuccess)
1058 {
1059 DstSize = 0;
1060 pDstData =
1061 (BYTE*)ClipboardGetData(clipboard->system, clipboard->requestedFormatId, &DstSize);
1062 }
1063 ClipboardUnlock(clipboard->system);
1064
1065 if (!pDstData)
1066 {
1067 xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
1068 return;
1069 }
1070
1071 /*
1072 * File lists require a bit of postprocessing to convert them from WinPR's FILDESCRIPTOR
1073 * format to CLIPRDR_FILELIST expected by the server.
1074 *
1075 * We check for "FileGroupDescriptorW" format being registered (i.e., nonzero) in order
1076 * to not process CF_RAW as a file list in case WinPR does not support file transfers.
1077 */
1078 ClipboardLock(clipboard->system);
1079 if (format->formatToRequest &&
1080 (format->formatToRequest ==
1081 ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW)))
1082 {
1083 UINT error = NO_ERROR;
1084 FILEDESCRIPTORW* file_array = WINPR_PACKED_ALIGN_CAST(FILEDESCRIPTORW*, pDstData);
1085 UINT32 file_count = DstSize / sizeof(FILEDESCRIPTORW);
1086 pDstData = nullptr;
1087 DstSize = 0;
1088
1089 const UINT32 flags = cliprdr_file_context_remote_get_flags(clipboard->file);
1090 error = cliprdr_serialize_file_list_ex(flags, file_array, file_count, &pDstData, &DstSize);
1091
1092 if (error)
1093 WLog_Print(clipboard->log, WLOG_ERROR, "failed to serialize CLIPRDR_FILELIST: 0x%08X",
1094 error);
1095 else
1096 {
1097 UINT32 formatId = ClipboardGetFormatId(clipboard->system, mime_uri_list);
1098 UINT32 url_size = 0;
1099
1100 char* url = ClipboardGetData(clipboard->system, formatId, &url_size);
1101 cliprdr_file_context_update_client_data(clipboard->file, url, url_size);
1102 free(url);
1103 }
1104
1105 free(file_array);
1106 }
1107 ClipboardUnlock(clipboard->system);
1108
1109 xf_cliprdr_send_data_response(clipboard, format, pDstData, DstSize);
1110 free(pDstData);
1111}
1112
1113static BOOL xf_restore_input_flags(xfClipboard* clipboard)
1114{
1115 WINPR_ASSERT(clipboard);
1116
1117 xfContext* xfc = clipboard->xfc;
1118 WINPR_ASSERT(xfc);
1119
1120 if (clipboard->event_mask != 0)
1121 {
1122 LogDynAndXSelectInput(clipboard->log, xfc->display, xfc->drawable, clipboard->event_mask);
1123 clipboard->event_mask = 0;
1124 }
1125 return TRUE;
1126}
1127
1128static BOOL append(xfClipboard* clipboard, const void* sdata, size_t length)
1129{
1130 WINPR_ASSERT(clipboard);
1131
1132 const size_t size = length + clipboard->incr_data_length + 2;
1133 BYTE* data = realloc(clipboard->incr_data, size);
1134 if (!data)
1135 return FALSE;
1136 clipboard->incr_data = data;
1137 memcpy(&data[clipboard->incr_data_length], sdata, length);
1138 clipboard->incr_data_length += length;
1139 clipboard->incr_data[clipboard->incr_data_length + 0] = '\0';
1140 clipboard->incr_data[clipboard->incr_data_length + 1] = '\0';
1141 return TRUE;
1142}
1143
1144static BOOL xf_cliprdr_stop_incr(xfClipboard* clipboard)
1145{
1146 clipboard->incr_starts = FALSE;
1147 clipboard->incr_data_length = 0;
1148 return xf_restore_input_flags(clipboard);
1149}
1150
1151static BOOL xf_cliprdr_get_requested_data(xfClipboard* clipboard, Atom target)
1152{
1153 WINPR_ASSERT(clipboard);
1154
1155 xfContext* xfc = clipboard->xfc;
1156 WINPR_ASSERT(xfc);
1157
1158 const xfCliprdrFormat* format =
1159 xf_cliprdr_get_client_available_format_by_id(clipboard, clipboard->requestedFormatId);
1160
1161 if (!format || (format->atom != target))
1162 {
1163 xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
1164 return FALSE;
1165 }
1166
1167 Atom type = 0;
1168 BOOL has_data = FALSE;
1169 int format_property = 0;
1170 unsigned long length = 0;
1171 unsigned long total_bytes = 0;
1172 BYTE* property_data = nullptr;
1173 const int rc = LogDynAndXGetWindowProperty(
1174 clipboard->log, xfc->display, xfc->drawable, clipboard->property_atom, 0, 0, False, target,
1175 &type, &format_property, &length, &total_bytes, &property_data);
1176 if (property_data)
1177 XFree(property_data);
1178 if (rc != Success)
1179 {
1180 xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
1181 return FALSE;
1182 }
1183
1184 size_t len = 0;
1185
1186 /* No data, empty return */
1187 if ((total_bytes <= 0) && !clipboard->incr_starts)
1188 {
1189 xf_cliprdr_stop_incr(clipboard);
1190 }
1191 /* We have to read incremental updates */
1192 else if (type == clipboard->incr_atom)
1193 {
1194 xf_cliprdr_stop_incr(clipboard);
1195 clipboard->incr_starts = TRUE;
1196 has_data = TRUE; /* data will follow in PropertyNotify event */
1197 }
1198 else
1199 {
1200 BYTE* incremental_data = nullptr;
1201 unsigned long incremental_len = 0;
1202
1203 /* Incremental updates completed, pass data */
1204 len = clipboard->incr_data_length;
1205 if (total_bytes <= 0)
1206 {
1207 xf_cliprdr_stop_incr(clipboard);
1208 has_data = TRUE;
1209 }
1210 /* Read incremental data batch */
1211 else if (LogDynAndXGetWindowProperty(
1212 clipboard->log, xfc->display, xfc->drawable, clipboard->property_atom, 0,
1213 WINPR_ASSERTING_INT_CAST(int32_t, total_bytes), False, target, &type,
1214 &format_property, &incremental_len, &length, &incremental_data) == Success)
1215 {
1216 has_data = append(clipboard, incremental_data, incremental_len);
1217 len = clipboard->incr_data_length;
1218 }
1219
1220 if (incremental_data)
1221 XFree(incremental_data);
1222 }
1223
1224 LogDynAndXDeleteProperty(clipboard->log, xfc->display, xfc->drawable, clipboard->property_atom);
1225 xf_cliprdr_process_requested_data(clipboard, has_data, clipboard->incr_data, len);
1226
1227 return TRUE;
1228}
1229
1230static void xf_cliprdr_append_target(xfClipboard* clipboard, Atom target)
1231{
1232 WINPR_ASSERT(clipboard);
1233
1234 if (clipboard->numTargets >= ARRAYSIZE(clipboard->targets))
1235 return;
1236
1237 for (size_t i = 0; i < clipboard->numTargets; i++)
1238 {
1239 if (clipboard->targets[i] == target)
1240 return;
1241 }
1242
1243 clipboard->targets[clipboard->numTargets++] = target;
1244}
1245
1246static void xf_cliprdr_provide_targets(xfClipboard* clipboard, const XSelectionEvent* respond)
1247{
1248 xfContext* xfc = nullptr;
1249
1250 WINPR_ASSERT(clipboard);
1251
1252 xfc = clipboard->xfc;
1253 WINPR_ASSERT(xfc);
1254
1255 if (respond->property != None)
1256 {
1257 WINPR_ASSERT(clipboard->numTargets <= INT32_MAX);
1258 LogDynAndXChangeProperty(clipboard->log, xfc->display, respond->requestor,
1259 respond->property, XA_ATOM, 32, PropModeReplace,
1260 (const BYTE*)clipboard->targets, (int)clipboard->numTargets);
1261 }
1262}
1263
1264static void xf_cliprdr_provide_timestamp(xfClipboard* clipboard, const XSelectionEvent* respond)
1265{
1266 xfContext* xfc = nullptr;
1267
1268 WINPR_ASSERT(clipboard);
1269
1270 xfc = clipboard->xfc;
1271 WINPR_ASSERT(xfc);
1272
1273 if (respond->property != None)
1274 {
1275 LogDynAndXChangeProperty(clipboard->log, xfc->display, respond->requestor,
1276 respond->property, XA_INTEGER, 32, PropModeReplace,
1277 (const BYTE*)&clipboard->selection_ownership_timestamp, 1);
1278 }
1279}
1280
1281#define xf_cliprdr_provide_data(clipboard, respond, data, size) \
1282 xf_cliprdr_provide_data_((clipboard), (respond), (data), (size), __FILE__, __func__, __LINE__)
1283static void xf_cliprdr_provide_data_(xfClipboard* clipboard, const XSelectionEvent* respond,
1284 const BYTE* data, UINT32 size, const char* file,
1285 const char* fkt, size_t line)
1286{
1287 WINPR_ASSERT(clipboard);
1288
1289 xfContext* xfc = clipboard->xfc;
1290 WINPR_ASSERT(xfc);
1291
1292 if (respond->property != None)
1293 {
1294 LogDynAndXChangeProperty_ex(clipboard->log, file, fkt, line, xfc->display,
1295 respond->requestor, respond->property, respond->target, 8,
1296 PropModeReplace, data, WINPR_ASSERTING_INT_CAST(int32_t, size));
1297 }
1298}
1299
1300static void log_selection_event(xfContext* xfc, const XEvent* event)
1301{
1302 const DWORD level = WLOG_TRACE;
1303 static wLog* _log_cached_ptr = nullptr;
1304 if (!_log_cached_ptr)
1305 _log_cached_ptr = WLog_Get(TAG);
1306 if (WLog_IsLevelActive(_log_cached_ptr, level))
1307 {
1308
1309 switch (event->type)
1310 {
1311 case SelectionClear:
1312 {
1313 const XSelectionClearEvent* xevent = &event->xselectionclear;
1314 char* selection =
1315 Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection);
1316 WLog_Print(_log_cached_ptr, level, "got event %s [selection %s]",
1317 x11_event_string(event->type), selection);
1318 XFree(selection);
1319 }
1320 break;
1321 case SelectionNotify:
1322 {
1323 const XSelectionEvent* xevent = &event->xselection;
1324 char* selection =
1325 Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection);
1326 char* target = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->target);
1327 char* property = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->property);
1328 WLog_Print(_log_cached_ptr, level,
1329 "got event %s [selection %s, target %s, property %s]",
1330 x11_event_string(event->type), selection, target, property);
1331 XFree(selection);
1332 XFree(target);
1333 XFree(property);
1334 }
1335 break;
1336 case SelectionRequest:
1337 {
1338 const XSelectionRequestEvent* xevent = &event->xselectionrequest;
1339 char* selection =
1340 Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection);
1341 char* target = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->target);
1342 char* property = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->property);
1343 WLog_Print(_log_cached_ptr, level,
1344 "got event %s [selection %s, target %s, property %s]",
1345 x11_event_string(event->type), selection, target, property);
1346 XFree(selection);
1347 XFree(target);
1348 XFree(property);
1349 }
1350 break;
1351 case PropertyNotify:
1352 {
1353 const XPropertyEvent* xevent = &event->xproperty;
1354 char* atom = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->atom);
1355 WLog_Print(_log_cached_ptr, level, "got event %s [atom %s]",
1356 x11_event_string(event->type), atom);
1357 XFree(atom);
1358 }
1359 break;
1360 default:
1361 break;
1362 }
1363 }
1364}
1365
1366static BOOL xf_cliprdr_process_selection_notify(xfClipboard* clipboard,
1367 const XSelectionEvent* xevent)
1368{
1369 WINPR_ASSERT(clipboard);
1370 WINPR_ASSERT(xevent);
1371
1372 if (xevent->target == clipboard->targets[1])
1373 {
1374 if (xevent->property == None)
1375 {
1376 /* The owner refused to list its targets. Do not ask again from here:
1377 * xf_cliprdr_send_client_format_list would issue a new TARGETS request,
1378 * and an owner that keeps refusing (Xwayland can) turns that into a
1379 * busy loop that also sends the server a format list on every turn,
1380 * built from the stale TARGETS of the previous owner. Drop what was
1381 * cached and wait for the next owner change. */
1382 xf_cliprdr_send_format_list(clipboard, nullptr, 0, nullptr, 0);
1383 }
1384 else
1385 {
1386 xf_cliprdr_get_requested_targets(clipboard);
1387 }
1388
1389 return TRUE;
1390 }
1391 else
1392 {
1393 return xf_cliprdr_get_requested_data(clipboard, xevent->target);
1394 }
1395}
1396
1397void xf_cliprdr_clear_cached_data(xfClipboard* clipboard)
1398{
1399 WINPR_ASSERT(clipboard);
1400
1401 WLog_Print(clipboard->log, WLOG_DEBUG, "Clearing cached clipboard data");
1402 ClipboardLock(clipboard->system);
1403 ClipboardEmpty(clipboard->system);
1404
1405 HashTable_Clear(clipboard->cachedData);
1406 HashTable_Clear(clipboard->cachedRawData);
1407
1408 XFree(clipboard->clientAvailableFormatAtoms);
1409 clipboard->clientAvailableFormatAtoms = nullptr;
1410 clipboard->clientAvailableFormatAtomsCount = 0;
1411
1412 cliprdr_file_context_clear(clipboard->file);
1413
1414 xf_cliprdr_stop_incr(clipboard);
1415 ClipboardUnlock(clipboard->system);
1416}
1417
1418static void* format_to_cache_slot(UINT32 format)
1419{
1420 union
1421 {
1422 uintptr_t uptr;
1423 void* vptr;
1424 } cnv;
1425 cnv.uptr = 0x100000000ULL + format;
1426 return cnv.vptr;
1427}
1428
1429static UINT32 get_dst_format_id_for_local_request(xfClipboard* clipboard,
1430 const xfCliprdrFormat* format)
1431{
1432 UINT32 dstFormatId = 0;
1433
1434 WINPR_ASSERT(format);
1435
1436 if (!format->formatName)
1437 return format->localFormat;
1438
1439 ClipboardLock(clipboard->system);
1440 if (strcmp(format->formatName, type_HtmlFormat) == 0)
1441 dstFormatId = ClipboardGetFormatId(clipboard->system, mime_html);
1442 ClipboardUnlock(clipboard->system);
1443
1444 if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0)
1445 dstFormatId = format->localFormat;
1446
1447 return dstFormatId;
1448}
1449
1450static void get_src_format_info_for_local_request(xfClipboard* clipboard,
1451 const xfCliprdrFormat* format,
1452 UINT32* srcFormatId, BOOL* nullTerminated)
1453{
1454 *srcFormatId = 0;
1455 *nullTerminated = FALSE;
1456
1457 if (format->formatName)
1458 {
1459 ClipboardLock(clipboard->system);
1460 if (strcmp(format->formatName, type_HtmlFormat) == 0)
1461 {
1462 *srcFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat);
1463 *nullTerminated = TRUE;
1464 }
1465 else if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0)
1466 {
1467 *srcFormatId = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW);
1468 *nullTerminated = TRUE;
1469 }
1470 ClipboardUnlock(clipboard->system);
1471 }
1472 else
1473 {
1474 *srcFormatId = format->formatToRequest;
1475 switch (format->formatToRequest)
1476 {
1477 case CF_TEXT:
1478 case CF_OEMTEXT:
1479 case CF_UNICODETEXT:
1480 *nullTerminated = TRUE;
1481 break;
1482 case CF_DIB:
1483 *srcFormatId = CF_DIB;
1484 break;
1485 case CF_TIFF:
1486 *srcFormatId = CF_TIFF;
1487 break;
1488 default:
1489 break;
1490 }
1491 }
1492}
1493
1494static xfCachedData* convert_data_from_existing_raw_data(xfClipboard* clipboard,
1495 xfCachedData* cached_raw_data,
1496 UINT32 srcFormatId, BOOL nullTerminated,
1497 UINT32 dstFormatId)
1498{
1499 UINT32 dst_size = 0;
1500
1501 WINPR_ASSERT(clipboard);
1502 WINPR_ASSERT(cached_raw_data);
1503 WINPR_ASSERT(cached_raw_data->data);
1504
1505 ClipboardLock(clipboard->system);
1506 BOOL success = ClipboardSetData(clipboard->system, srcFormatId, cached_raw_data->data,
1507 cached_raw_data->data_length);
1508 if (!success)
1509 {
1510 WLog_Print(clipboard->log, WLOG_WARN,
1511 "Failed to set clipboard data (formatId: %u, data: %p, data_length: %u)",
1512 srcFormatId, WINPR_CXX_COMPAT_CAST(const void*, cached_raw_data->data),
1513 cached_raw_data->data_length);
1514 ClipboardUnlock(clipboard->system);
1515 return nullptr;
1516 }
1517
1518 BYTE* dst_data = ClipboardGetData(clipboard->system, dstFormatId, &dst_size);
1519 if (!dst_data)
1520 {
1521 WLog_Print(clipboard->log, WLOG_WARN, "Failed to get converted clipboard data");
1522 ClipboardUnlock(clipboard->system);
1523 return nullptr;
1524 }
1525 ClipboardUnlock(clipboard->system);
1526
1527 if (nullTerminated)
1528 {
1529 BYTE* nullTerminator = memchr(dst_data, '\0', dst_size);
1530 if (nullTerminator)
1531 {
1532 const intptr_t diff = nullTerminator - dst_data;
1533 WINPR_ASSERT(diff >= 0);
1534 WINPR_ASSERT(diff <= UINT32_MAX);
1535 dst_size = (UINT32)diff;
1536 }
1537 }
1538
1539 xfCachedData* cached_data = xf_cached_data_new(dst_data, dst_size);
1540 if (!cached_data)
1541 {
1542 WLog_Print(clipboard->log, WLOG_WARN, "Failed to allocate cache entry");
1543 free(dst_data);
1544 return nullptr;
1545 }
1546
1547 if (!HashTable_Insert(clipboard->cachedData, format_to_cache_slot(dstFormatId), cached_data))
1548 {
1549 WLog_Print(clipboard->log, WLOG_WARN, "Failed to cache clipboard data");
1550 xf_cached_data_free(cached_data);
1551 return nullptr;
1552 }
1553
1554 return cached_data;
1555}
1556
1557WINPR_ATTR_NODISCARD
1558static BOOL xf_cliprdr_pending_responses_ArrayList_ForEachFkt(void* data, size_t index, va_list ap)
1559{
1560 UINT32 formatId = 0;
1561 SelectionResponse* pendingResponse = (SelectionResponse*)data;
1562 UINT32 currentFormatId = va_arg(ap, UINT32);
1563 BOOL* res = va_arg(ap, BOOL*);
1564
1565 WINPR_UNUSED(index);
1566 WINPR_UNUSED(ap);
1567 WINPR_ASSERT(res);
1568
1569 formatId = pendingResponse->requestedFormat->formatToRequest;
1570
1571 if (formatId != currentFormatId)
1572 *res = TRUE;
1573 return TRUE;
1574}
1575
1576static void xf_cliprdr_provide_selection(xfClipboard* clipboard, XSelectionEvent* respond)
1577{
1578 WINPR_ASSERT(clipboard);
1579
1580 xfContext* xfc = clipboard->xfc;
1581 WINPR_ASSERT(xfc);
1582
1583 union
1584 {
1585 XEvent* ev;
1586 XSelectionEvent* sev;
1587 } conv;
1588
1589 conv.sev = respond;
1590 LogDynAndXSendEvent(clipboard->log, xfc->display, respond->requestor, 0, 0, conv.ev);
1591 LogDynAndXFlush(clipboard->log, xfc->display);
1592}
1593
1594static BOOL xf_cliprdr_process_selection_request(xfClipboard* clipboard,
1595 const XSelectionRequestEvent* xevent)
1596{
1597 int fmt = 0;
1598 Atom type = 0;
1599 UINT32 formatId = 0;
1600 XSelectionEvent* respond = nullptr;
1601 BYTE* data = nullptr;
1602 BOOL delayRespond = 0;
1603 BOOL rawTransfer = 0;
1604 unsigned long length = 0;
1605 unsigned long bytes_left = 0;
1606 xfContext* xfc = nullptr;
1607
1608 WINPR_ASSERT(clipboard);
1609 WINPR_ASSERT(xevent);
1610
1611 xfc = clipboard->xfc;
1612 WINPR_ASSERT(xfc);
1613
1614 if (xevent->owner != xfc->drawable)
1615 return FALSE;
1616
1617 delayRespond = FALSE;
1618
1619 if (!(respond = (XSelectionEvent*)calloc(1, sizeof(XSelectionEvent))))
1620 {
1621 WLog_Print(clipboard->log, WLOG_ERROR, "failed to allocate XEvent data");
1622 return FALSE;
1623 }
1624
1625 respond->property = None;
1626 respond->type = SelectionNotify;
1627 respond->display = xevent->display;
1628 respond->requestor = xevent->requestor;
1629 respond->selection = xevent->selection;
1630 respond->target = xevent->target;
1631 respond->time = xevent->time;
1632
1633 if (xevent->target == clipboard->targets[0]) /* TIMESTAMP */
1634 {
1635 /* Someone else requests the selection's timestamp */
1636 respond->property = xevent->property;
1637 xf_cliprdr_provide_timestamp(clipboard, respond);
1638 }
1639 else if (xevent->target == clipboard->targets[1]) /* TARGETS */
1640 {
1641 /* Someone else requests our available formats */
1642 respond->property = xevent->property;
1643 xf_cliprdr_provide_targets(clipboard, respond);
1644 }
1645 else
1646 {
1647 const CLIPRDR_FORMAT* format =
1648 xf_cliprdr_get_server_format_by_atom(clipboard, xevent->target);
1649 const xfCliprdrFormat* cformat =
1650 xf_cliprdr_get_client_format_by_atom(clipboard, xevent->target);
1651
1652 if (format && (xevent->requestor != xfc->drawable))
1653 {
1654 formatId = format->formatId;
1655 rawTransfer = FALSE;
1656 xfCachedData* cached_data = nullptr;
1657
1658 if (formatId == CF_RAW)
1659 {
1660 if (LogDynAndXGetWindowProperty(
1661 clipboard->log, xfc->display, xevent->requestor, clipboard->property_atom,
1662 0, 4, 0, XA_INTEGER, &type, &fmt, &length, &bytes_left, &data) != Success)
1663 {
1664 }
1665
1666 if (data)
1667 {
1668 rawTransfer = TRUE;
1669 CopyMemory(&formatId, data, 4);
1670 XFree(data);
1671 }
1672 }
1673
1674 const UINT32 dstFormatId = get_dst_format_id_for_local_request(clipboard, cformat);
1675 DEBUG_CLIPRDR("formatId: 0x%08" PRIx32 ", dstFormatId: 0x%08" PRIx32 "", formatId,
1676 dstFormatId);
1677
1678 wHashTable* table = clipboard->cachedData;
1679 if (rawTransfer)
1680 table = clipboard->cachedRawData;
1681
1682 HashTable_Lock(table);
1683 if (!rawTransfer)
1684 cached_data = HashTable_GetItemValue(table, format_to_cache_slot(dstFormatId));
1685 else
1686 cached_data = HashTable_GetItemValue(table, format_to_cache_slot(formatId));
1687 HashTable_Unlock(table);
1688
1689 DEBUG_CLIPRDR("hasCachedData: %u, rawTransfer: %d", cached_data ? 1u : 0u, rawTransfer);
1690
1691 if (!cached_data && !rawTransfer)
1692 {
1693 UINT32 srcFormatId = 0;
1694 BOOL nullTerminated = FALSE;
1695 xfCachedData* cached_raw_data = nullptr;
1696
1697 get_src_format_info_for_local_request(clipboard, cformat, &srcFormatId,
1698 &nullTerminated);
1699
1700 HashTable_Lock(clipboard->cachedRawData);
1701 cached_raw_data =
1702 HashTable_GetItemValue(clipboard->cachedRawData, (void*)(UINT_PTR)srcFormatId);
1703 HashTable_Unlock(clipboard->cachedRawData);
1704
1705 DEBUG_CLIPRDR("hasCachedRawData: %u, rawDataLength: %u", cached_raw_data ? 1u : 0u,
1706 cached_raw_data ? cached_raw_data->data_length : 0);
1707
1708 if (cached_raw_data && cached_raw_data->data_length != 0)
1709 cached_data = convert_data_from_existing_raw_data(
1710 clipboard, cached_raw_data, srcFormatId, nullTerminated, dstFormatId);
1711 }
1712
1713 DEBUG_CLIPRDR("hasCachedData: %u", cached_data ? 1u : 0u);
1714
1715 if (cached_data)
1716 {
1717 /* Cached clipboard data available. Send it now */
1718 respond->property = xevent->property;
1719
1720 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
1721 xf_cliprdr_provide_data(clipboard, respond, cached_data->data,
1722 cached_data->data_length);
1723 }
1724 else
1725 {
1726 SelectionResponse* selection_response = nullptr;
1727 WINPR_ASSERT(cformat);
1728
1729 if (!(selection_response =
1730 (SelectionResponse*)calloc(1, sizeof(SelectionResponse))))
1731 {
1732 respond->property = None;
1733 goto out;
1734 }
1735 respond->property = xevent->property;
1736
1737 selection_response->expectedResponse = respond;
1738 requested_format_replace(&selection_response->requestedFormat, formatId,
1739 dstFormatId, cformat->formatName);
1740 selection_response->data_raw_format = rawTransfer;
1741
1742 ArrayList_Lock(clipboard->pending_responses);
1743 ArrayList_Lock(clipboard->queued_responses);
1744 if (ArrayList_Count(clipboard->pending_responses) > 0)
1745 {
1746 BOOL shouldQueued = FALSE;
1747 BOOL success = FALSE;
1748 success = ArrayList_ForEach(clipboard->pending_responses,
1749 xf_cliprdr_pending_responses_ArrayList_ForEachFkt,
1750 formatId, &shouldQueued);
1751 if (!success || shouldQueued)
1752 {
1753 if (!ArrayList_Append(clipboard->queued_responses, selection_response))
1754 {
1755 requested_format_free(&selection_response->requestedFormat);
1756 free(selection_response);
1757 respond->property = None;
1758 goto out2;
1759 }
1760 }
1761 else
1762 {
1763 if (!ArrayList_Append(clipboard->pending_responses, selection_response))
1764 {
1765 requested_format_free(&selection_response->requestedFormat);
1766 free(selection_response);
1767 respond->property = None;
1768 goto out2;
1769 }
1770 }
1771 }
1772 else
1773 {
1774 if (!ArrayList_Append(clipboard->pending_responses, selection_response))
1775 {
1776 requested_format_free(&selection_response->requestedFormat);
1777 free(selection_response);
1778 respond->property = None;
1779 goto out2;
1780 }
1785 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership
1786 xf_cliprdr_send_data_request(clipboard, formatId, cformat);
1787 }
1788 delayRespond = TRUE;
1789 out2:
1790 ArrayList_Unlock(clipboard->queued_responses);
1791 ArrayList_Unlock(clipboard->pending_responses);
1792 }
1793 }
1794 }
1795
1796out:
1797 if (!delayRespond)
1798 {
1799 xf_cliprdr_provide_selection(clipboard, respond);
1800 free(respond);
1801 }
1802
1803 return TRUE;
1804}
1805
1806static BOOL xf_cliprdr_process_selection_clear(xfClipboard* clipboard,
1807 const XSelectionClearEvent* xevent)
1808{
1809 xfContext* xfc = nullptr;
1810
1811 WINPR_ASSERT(clipboard);
1812 WINPR_ASSERT(xevent);
1813
1814 xfc = clipboard->xfc;
1815 WINPR_ASSERT(xfc);
1816
1817 WINPR_UNUSED(xevent);
1818
1819 if (xf_cliprdr_is_self_owned(clipboard))
1820 return FALSE;
1821
1822 LogDynAndXDeleteProperty(clipboard->log, xfc->display, clipboard->root_window,
1823 clipboard->property_atom);
1824 return TRUE;
1825}
1826
1827static BOOL xf_cliprdr_process_property_notify(xfClipboard* clipboard, const XPropertyEvent* xevent)
1828{
1829 const xfCliprdrFormat* format = nullptr;
1830 xfContext* xfc = nullptr;
1831
1832 if (!clipboard)
1833 return TRUE;
1834
1835 xfc = clipboard->xfc;
1836 WINPR_ASSERT(xfc);
1837 WINPR_ASSERT(xevent);
1838
1839 if (xevent->atom == clipboard->timestamp_property_atom)
1840 {
1841 /* This is the response to the property change we did
1842 * in xf_cliprdr_prepare_to_set_selection_owner. Now
1843 * we can set ourselves as the selection owner. (See
1844 * comments in those functions below.) */
1845 xf_cliprdr_set_selection_owner(xfc, clipboard, xevent->time);
1846 return TRUE;
1847 }
1848
1849 if (xevent->atom != clipboard->property_atom)
1850 return FALSE; /* Not cliprdr-related */
1851
1852 if (xevent->window == clipboard->root_window)
1853 {
1854 xf_cliprdr_send_client_format_list(clipboard);
1855 }
1856 else if ((xevent->window == xfc->drawable) && (xevent->state == PropertyNewValue) &&
1857 clipboard->incr_starts)
1858 {
1859 format =
1860 xf_cliprdr_get_client_available_format_by_id(clipboard, clipboard->requestedFormatId);
1861
1862 if (format)
1863 xf_cliprdr_get_requested_data(clipboard, format->atom);
1864 }
1865
1866 return TRUE;
1867}
1868
1869void xf_cliprdr_handle_xevent(xfContext* xfc, const XEvent* event)
1870{
1871 xfClipboard* clipboard = nullptr;
1872
1873 if (!xfc || !event)
1874 return;
1875
1876 clipboard = xfc->clipboard;
1877
1878 if (!clipboard)
1879 return;
1880
1881#ifdef WITH_XFIXES
1882
1883 if (clipboard->xfixes_supported &&
1884 event->type == XFixesSelectionNotify + clipboard->xfixes_event_base)
1885 {
1886 const XFixesSelectionNotifyEvent* se = (const XFixesSelectionNotifyEvent*)event;
1887
1888 if (se->subtype == XFixesSetSelectionOwnerNotify)
1889 {
1890 if (se->selection != clipboard->clipboard_atom)
1891 return;
1892
1893 if (LogDynAndXGetSelectionOwner(clipboard->log, xfc->display, se->selection) ==
1894 xfc->drawable)
1895 return;
1896
1897 clipboard->owner = None;
1898 xf_cliprdr_check_owner(clipboard);
1899 }
1900
1901 return;
1902 }
1903
1904#endif
1905
1906 switch (event->type)
1907 {
1908 case SelectionNotify:
1909 log_selection_event(xfc, event);
1910 xf_cliprdr_process_selection_notify(clipboard, &event->xselection);
1911 break;
1912
1913 case SelectionRequest:
1914 log_selection_event(xfc, event);
1915 xf_cliprdr_process_selection_request(clipboard, &event->xselectionrequest);
1916 break;
1917
1918 case SelectionClear:
1919 log_selection_event(xfc, event);
1920 xf_cliprdr_process_selection_clear(clipboard, &event->xselectionclear);
1921 break;
1922
1923 case PropertyNotify:
1924 log_selection_event(xfc, event);
1925 xf_cliprdr_process_property_notify(clipboard, &event->xproperty);
1926 break;
1927
1928 case FocusIn:
1929 if (!clipboard->xfixes_supported)
1930 {
1931 xf_cliprdr_check_owner(clipboard);
1932 }
1933
1934 break;
1935 default:
1936 break;
1937 }
1938}
1939
1945static UINT xf_cliprdr_send_client_capabilities(xfClipboard* clipboard)
1946{
1947 CLIPRDR_CAPABILITIES capabilities = WINPR_C_ARRAY_INIT;
1948 CLIPRDR_GENERAL_CAPABILITY_SET generalCapabilitySet = WINPR_C_ARRAY_INIT;
1949
1950 WINPR_ASSERT(clipboard);
1951
1952 capabilities.cCapabilitiesSets = 1;
1953 capabilities.capabilitySets = (CLIPRDR_CAPABILITY_SET*)&(generalCapabilitySet);
1954 generalCapabilitySet.capabilitySetType = CB_CAPSTYPE_GENERAL;
1955 generalCapabilitySet.capabilitySetLength = 12;
1956 generalCapabilitySet.version = CB_CAPS_VERSION_2;
1957 generalCapabilitySet.generalFlags = CB_USE_LONG_FORMAT_NAMES;
1958
1959 WINPR_ASSERT(clipboard);
1960 generalCapabilitySet.generalFlags |= cliprdr_file_context_current_flags(clipboard->file);
1961
1962 if (!clipboard->context)
1963 return CHANNEL_RC_NOT_INITIALIZED;
1964 WINPR_ASSERT(clipboard->context->ClientCapabilities);
1965 return clipboard->context->ClientCapabilities(clipboard->context, &capabilities);
1966}
1967
1973static UINT xf_cliprdr_send_client_format_list(xfClipboard* clipboard)
1974{
1975 WINPR_ASSERT(clipboard);
1976
1977 xfContext* xfc = clipboard->xfc;
1978 WINPR_ASSERT(xfc);
1979
1980 UINT32 numFormats = 0;
1981 Atom* atoms = nullptr;
1982 size_t atomsCount = 0;
1983 CLIPRDR_FORMAT* formats =
1984 xf_cliprdr_get_client_formats(clipboard, &numFormats, &atoms, &atomsCount);
1985
1986 const UINT ret = xf_cliprdr_send_format_list(clipboard, formats, numFormats, atoms, atomsCount);
1987
1988 if (clipboard->owner && clipboard->owner != xfc->drawable)
1989 {
1990 /* Request the owner for TARGETS, and wait for SelectionNotify event */
1991 LogDynAndXConvertSelection(clipboard->log, xfc->display, clipboard->clipboard_atom,
1992 clipboard->targets[1], clipboard->property_atom, xfc->drawable,
1993 CurrentTime);
1994 }
1995
1996 xf_cliprdr_free_formats(formats, numFormats);
1997
1998 return ret;
1999}
2000
2006static UINT xf_cliprdr_send_client_format_list_response(xfClipboard* clipboard, BOOL status)
2007{
2008 CLIPRDR_FORMAT_LIST_RESPONSE formatListResponse = WINPR_C_ARRAY_INIT;
2009
2010 formatListResponse.common.msgType = CB_FORMAT_LIST_RESPONSE;
2011 formatListResponse.common.msgFlags = status ? CB_RESPONSE_OK : CB_RESPONSE_FAIL;
2012 formatListResponse.common.dataLen = 0;
2013
2014 WINPR_ASSERT(clipboard);
2015 if (!clipboard->context)
2016 return CHANNEL_RC_NOT_INITIALIZED;
2017 WINPR_ASSERT(clipboard->context->ClientFormatListResponse);
2018 return clipboard->context->ClientFormatListResponse(clipboard->context, &formatListResponse);
2019}
2020
2026static UINT xf_cliprdr_monitor_ready(CliprdrClientContext* context,
2027 const CLIPRDR_MONITOR_READY* monitorReady)
2028{
2029 WINPR_ASSERT(context);
2030 WINPR_ASSERT(monitorReady);
2031
2032 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2033 WINPR_ASSERT(clipboard);
2034
2035 WINPR_UNUSED(monitorReady);
2036
2037 const UINT ret = xf_cliprdr_send_client_capabilities(clipboard);
2038 if (ret != CHANNEL_RC_OK)
2039 return ret;
2040
2041 const UINT ret2 = xf_cliprdr_send_client_format_list(clipboard);
2042 if (ret2 != CHANNEL_RC_OK)
2043 return ret2;
2044
2045 clipboard->sync = TRUE;
2046 return CHANNEL_RC_OK;
2047}
2048
2054static UINT xf_cliprdr_server_capabilities(CliprdrClientContext* context,
2055 const CLIPRDR_CAPABILITIES* capabilities)
2056{
2057 WINPR_ASSERT(context);
2058 WINPR_ASSERT(capabilities);
2059
2060 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2061 WINPR_ASSERT(clipboard);
2062
2063 const BYTE* capsPtr = (const BYTE*)capabilities->capabilitySets;
2064 WINPR_ASSERT(capsPtr);
2065
2066 if (!cliprdr_file_context_remote_set_flags(clipboard->file, 0))
2067 return ERROR_INTERNAL_ERROR;
2068
2069 for (UINT32 i = 0; i < capabilities->cCapabilitiesSets; i++)
2070 {
2071 const CLIPRDR_CAPABILITY_SET* caps =
2072 WINPR_PACKED_ALIGN_CAST(const CLIPRDR_CAPABILITY_SET*, capsPtr);
2073
2074 if (caps->capabilitySetType == CB_CAPSTYPE_GENERAL)
2075 {
2076 const CLIPRDR_GENERAL_CAPABILITY_SET* generalCaps =
2077 WINPR_PACKED_ALIGN_CAST(const CLIPRDR_GENERAL_CAPABILITY_SET*, caps);
2078
2079 if (!cliprdr_file_context_remote_set_flags(clipboard->file, generalCaps->generalFlags))
2080 return ERROR_INTERNAL_ERROR;
2081 }
2082
2083 capsPtr += caps->capabilitySetLength;
2084 }
2085
2086 return CHANNEL_RC_OK;
2087}
2088
2089static void xf_cliprdr_prepare_to_set_selection_owner(xfContext* xfc, xfClipboard* clipboard)
2090{
2091 WINPR_ASSERT(xfc);
2092 WINPR_ASSERT(clipboard);
2093 /*
2094 * When you're writing to the selection in response to a
2095 * normal X event like a mouse click or keyboard action, you
2096 * get the selection timestamp by copying the time field out
2097 * of that X event. Here, we're doing it on our own
2098 * initiative, so we have to _request_ the X server time.
2099 *
2100 * There isn't a GetServerTime request in the X protocol, so I
2101 * work around it by setting a property on our own window, and
2102 * waiting for a PropertyNotify event to come back telling me
2103 * it's been done - which will have a timestamp we can use.
2104 */
2105
2106 /* We have to set the property to some value, but it doesn't
2107 * matter what. Set it to its own name, which we have here
2108 * anyway! */
2109 Atom value = clipboard->timestamp_property_atom;
2110
2111 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
2112 clipboard->timestamp_property_atom, XA_ATOM, 32, PropModeReplace,
2113 (const BYTE*)&value, 1);
2114 LogDynAndXFlush(clipboard->log, xfc->display);
2115}
2116
2117static void xf_cliprdr_set_selection_owner(xfContext* xfc, xfClipboard* clipboard, Time timestamp)
2118{
2119 WINPR_ASSERT(xfc);
2120 WINPR_ASSERT(clipboard);
2121 /*
2122 * Actually set ourselves up as the selection owner, now that
2123 * we have a timestamp to use.
2124 */
2125
2126 clipboard->selection_ownership_timestamp = timestamp;
2127 LogDynAndXSetSelectionOwner(clipboard->log, xfc->display, clipboard->clipboard_atom,
2128 xfc->drawable, timestamp);
2129 LogDynAndXFlush(clipboard->log, xfc->display);
2130}
2131
2137static UINT xf_cliprdr_server_format_list(CliprdrClientContext* context,
2138 const CLIPRDR_FORMAT_LIST* formatList)
2139{
2140 xfContext* xfc = nullptr;
2141 UINT ret = 0;
2142 xfClipboard* clipboard = nullptr;
2143
2144 WINPR_ASSERT(context);
2145 WINPR_ASSERT(formatList);
2146
2147 clipboard = cliprdr_file_context_get_context(context->custom);
2148 WINPR_ASSERT(clipboard);
2149
2150 xfc = clipboard->xfc;
2151 WINPR_ASSERT(xfc);
2152
2153 xf_lock_x11(xfc);
2154
2155 /* Clear the active SelectionRequest, as it is now invalid */
2156 ArrayList_Clear(clipboard->pending_responses);
2157 ArrayList_Clear(clipboard->queued_responses);
2158
2159 xf_cliprdr_clear_cached_data(clipboard);
2160
2161 xf_clipboard_free_server_formats(clipboard);
2162
2163 clipboard->numServerFormats = formatList->numFormats + 1; /* +1 for CF_RAW */
2164
2165 if (!(clipboard->serverFormats =
2166 (CLIPRDR_FORMAT*)calloc(clipboard->numServerFormats, sizeof(CLIPRDR_FORMAT))))
2167 {
2168 WLog_Print(clipboard->log, WLOG_ERROR,
2169 "failed to allocate %" PRIu32 " CLIPRDR_FORMAT structs",
2170 clipboard->numServerFormats);
2171 ret = CHANNEL_RC_NO_MEMORY;
2172 goto out;
2173 }
2174
2175 for (size_t i = 0; i < formatList->numFormats; i++)
2176 {
2177 const CLIPRDR_FORMAT* format = &formatList->formats[i];
2178 CLIPRDR_FORMAT* srvFormat = &clipboard->serverFormats[i];
2179
2180 srvFormat->formatId = format->formatId;
2181
2182 if (format->formatName)
2183 {
2184 srvFormat->formatName = _strdup(format->formatName);
2185
2186 if (!srvFormat->formatName)
2187 {
2188 for (UINT32 k = 0; k < i; k++)
2189 free(clipboard->serverFormats[k].formatName);
2190
2191 clipboard->numServerFormats = 0;
2192 free(clipboard->serverFormats);
2193 clipboard->serverFormats = nullptr;
2194 ret = CHANNEL_RC_NO_MEMORY;
2195 goto out;
2196 }
2197 }
2198 }
2199
2200 ClipboardLock(clipboard->system);
2201 ret = cliprdr_file_context_notify_new_server_format_list(clipboard->file);
2202 ClipboardUnlock(clipboard->system);
2203 if (ret)
2204 goto out;
2205
2206 /* CF_RAW is always implicitly supported by the server */
2207 {
2208 CLIPRDR_FORMAT* format = &clipboard->serverFormats[formatList->numFormats];
2209 format->formatId = CF_RAW;
2210 format->formatName = nullptr;
2211 }
2212 xf_cliprdr_provide_server_format_list(clipboard);
2213 clipboard->numTargets = 2;
2214
2215 for (size_t i = 0; i < formatList->numFormats; i++)
2216 {
2217 const CLIPRDR_FORMAT* format = &formatList->formats[i];
2218
2219 for (size_t j = 0; j < clipboard->numClientFormats; j++)
2220 {
2221 const xfCliprdrFormat* clientFormat = &clipboard->clientFormats[j];
2222 if (xf_cliprdr_formats_equal(format, clientFormat))
2223 {
2224 if ((clientFormat->formatName != nullptr) &&
2225 (strcmp(type_FileGroupDescriptorW, clientFormat->formatName) == 0))
2226 {
2227 if (!cliprdr_file_context_has_local_support(clipboard->file))
2228 continue;
2229 }
2230 xf_cliprdr_append_target(clipboard, clientFormat->atom);
2231 }
2232 }
2233 }
2234
2235 ret = xf_cliprdr_send_client_format_list_response(clipboard, TRUE);
2236 if (xfc->remote_app)
2237 xf_cliprdr_set_selection_owner(xfc, clipboard, CurrentTime);
2238 else
2239 xf_cliprdr_prepare_to_set_selection_owner(xfc, clipboard);
2240
2241out:
2242 xf_unlock_x11(xfc);
2243
2244 return ret;
2245}
2246
2252static UINT xf_cliprdr_server_format_list_response(
2253 WINPR_ATTR_UNUSED CliprdrClientContext* context,
2254 WINPR_ATTR_UNUSED const CLIPRDR_FORMAT_LIST_RESPONSE* formatListResponse)
2255{
2256 WINPR_ASSERT(context);
2257 WINPR_ASSERT(formatListResponse);
2258 // xfClipboard* clipboard = (xfClipboard*) context->custom;
2259 return CHANNEL_RC_OK;
2260}
2261
2267static UINT
2268xf_cliprdr_server_format_data_request(CliprdrClientContext* context,
2269 const CLIPRDR_FORMAT_DATA_REQUEST* formatDataRequest)
2270{
2271 const xfCliprdrFormat* format = nullptr;
2272
2273 WINPR_ASSERT(context);
2274 WINPR_ASSERT(formatDataRequest);
2275
2276 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2277 WINPR_ASSERT(clipboard);
2278
2279 xfContext* xfc = clipboard->xfc;
2280 WINPR_ASSERT(xfc);
2281
2282 const uint32_t formatId = formatDataRequest->requestedFormatId;
2283
2284 const UINT32 mask =
2285 freerdp_settings_get_uint32(context->rdpcontext->settings, FreeRDP_ClipboardFeatureMask);
2286 const UINT32 fileId = ClipboardRegisterFormat(clipboard->system, type_FileGroupDescriptorW);
2287 if (fileId == formatDataRequest->requestedFormatId)
2288 {
2289 if ((mask & CLIPRDR_FLAG_LOCAL_TO_REMOTE_FILES) == 0)
2290 return xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
2291 }
2292 else
2293 {
2294 if ((mask & CLIPRDR_FLAG_LOCAL_TO_REMOTE) == 0)
2295 return xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
2296 }
2297 const BOOL rawTransfer = xf_cliprdr_is_raw_transfer_available(clipboard);
2298
2299 if (rawTransfer)
2300 {
2301 format = xf_cliprdr_get_client_available_format_by_id(clipboard, CF_RAW);
2302 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
2303 clipboard->property_atom, XA_INTEGER, 32, PropModeReplace,
2304 (const BYTE*)&formatId, 1);
2305 }
2306 else
2307 format = xf_cliprdr_get_client_available_format_by_id(clipboard, formatId);
2308
2309 clipboard->requestedFormatId = rawTransfer ? CF_RAW : formatId;
2310 if (!format)
2311 return xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
2312
2313 DEBUG_CLIPRDR("requested format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 " [%s]} [%s]",
2314 format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest),
2315 format->localFormat,
2316 ClipboardGetFormatName(clipboard->system, format->localFormat),
2317 format->formatName);
2318 LogDynAndXConvertSelection(clipboard->log, xfc->display, clipboard->clipboard_atom,
2319 format->atom, clipboard->property_atom, xfc->drawable, CurrentTime);
2320 LogDynAndXFlush(clipboard->log, xfc->display);
2321 /* After this point, we expect a SelectionNotify event from the clipboard owner. */
2322 return CHANNEL_RC_OK;
2323}
2324
2330static UINT
2331xf_cliprdr_server_format_data_response(CliprdrClientContext* context,
2332 const CLIPRDR_FORMAT_DATA_RESPONSE* formatDataResponse)
2333{
2334 BOOL bSuccess = FALSE;
2335 BOOL bRawCached = FALSE;
2336 BOOL bFileContextUpdated = FALSE;
2337
2338 WINPR_ASSERT(context);
2339 WINPR_ASSERT(formatDataResponse);
2340
2341 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2342 WINPR_ASSERT(clipboard);
2343
2344 xfContext* xfc = clipboard->xfc;
2345 WINPR_ASSERT(xfc);
2346
2347 const UINT32 size = formatDataResponse->common.dataLen;
2348 const BYTE* data = formatDataResponse->requestedFormatData;
2349
2350 // Keep the same lock order as process_selection_request to prevent deadlock
2351 xf_lock_x11(xfc);
2352 ArrayList_Lock(clipboard->pending_responses);
2353 ArrayList_Lock(clipboard->queued_responses);
2354 if (formatDataResponse->common.msgFlags == CB_RESPONSE_FAIL)
2355 {
2356 WLog_Print(clipboard->log, WLOG_WARN,
2357 "Format Data Response PDU msgFlags is CB_RESPONSE_FAIL");
2358 while (ArrayList_Count(clipboard->pending_responses) > 0)
2359 {
2360 SelectionResponse* pending = ArrayList_GetItem(clipboard->pending_responses, 0);
2361
2362 pending->expectedResponse->property = None;
2363 xf_cliprdr_provide_selection(clipboard, pending->expectedResponse);
2364
2365 ArrayList_Remove(clipboard->pending_responses, pending);
2366 }
2367 WINPR_ASSERT(ArrayList_Count(clipboard->pending_responses) == 0);
2368 }
2369
2370 while (ArrayList_Count(clipboard->pending_responses) > 0)
2371 {
2372 BYTE* pDstData = nullptr;
2373 UINT32 DstSize = 0;
2374 UINT32 SrcSize = 0;
2375 UINT32 srcFormatId = 0;
2376 UINT32 dstFormatId = 0;
2377 BOOL nullTerminated = FALSE;
2378 xfCachedData* cached_data = nullptr;
2379 xfCachedData* hit_cached_data = nullptr;
2380
2381 SelectionResponse* pending = ArrayList_GetItem(clipboard->pending_responses, 0);
2382 const RequestedFormat* format = pending->requestedFormat;
2383 if (pending->data_raw_format)
2384 {
2385 srcFormatId = CF_RAW;
2386 dstFormatId = CF_RAW;
2387 }
2388 else if (!format)
2389 {
2390 pending->expectedResponse->property = None;
2391 goto out;
2392 }
2393 else if (format->formatName)
2394 {
2395 dstFormatId = format->localFormat;
2396
2397 ClipboardLock(clipboard->system);
2398 if (strcmp(format->formatName, type_HtmlFormat) == 0)
2399 {
2400 srcFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat);
2401 dstFormatId = ClipboardGetFormatId(clipboard->system, mime_html);
2402 nullTerminated = TRUE;
2403 }
2404
2405 if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0)
2406 {
2407 if (!bFileContextUpdated)
2408 {
2409 if (!cliprdr_file_context_update_server_data(clipboard->file, clipboard->system,
2410 data, size))
2411 WLog_Print(clipboard->log, WLOG_WARN, "failed to update file descriptors");
2412 else
2413 bFileContextUpdated = TRUE;
2414 }
2415
2416 srcFormatId = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW);
2417 const xfCliprdrFormat* dstTargetFormat = xf_cliprdr_get_client_format_by_atom(
2418 clipboard, pending->expectedResponse->target);
2419 if (!dstTargetFormat)
2420 {
2421 dstFormatId = ClipboardGetFormatId(clipboard->system, mime_uri_list);
2422 }
2423 else
2424 {
2425 dstFormatId = dstTargetFormat->localFormat;
2426 }
2427
2428 nullTerminated = TRUE;
2429 }
2430 ClipboardUnlock(clipboard->system);
2431 }
2432 else
2433 {
2434 srcFormatId = format->formatToRequest;
2435 dstFormatId = format->localFormat;
2436 switch (format->formatToRequest)
2437 {
2438 case CF_TEXT:
2439 nullTerminated = TRUE;
2440 break;
2441
2442 case CF_OEMTEXT:
2443 nullTerminated = TRUE;
2444 break;
2445
2446 case CF_UNICODETEXT:
2447 nullTerminated = TRUE;
2448 break;
2449
2450 case CF_DIB:
2451 srcFormatId = CF_DIB;
2452 break;
2453
2454 case CF_TIFF:
2455 srcFormatId = CF_TIFF;
2456 break;
2457
2458 default:
2459 break;
2460 }
2461 }
2462
2463 DEBUG_CLIPRDR("requested format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 " [%s]} [%s]",
2464 format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest),
2465 format->localFormat,
2466 ClipboardGetFormatName(clipboard->system, format->localFormat),
2467 format->formatName);
2468 SrcSize = size;
2469
2470 DEBUG_CLIPRDR("srcFormatId: 0x%08" PRIx32 ", dstFormatId: 0x%08" PRIx32 "", srcFormatId,
2471 dstFormatId);
2472
2473 if (SrcSize != 0 && !bRawCached)
2474 {
2475 /* We have to copy the original data again, as pSrcData is now owned
2476 * by clipboard->system. Memory allocation failure is not fatal here
2477 * as this is only a cached value. */
2478 {
2479 // clipboard->cachedData owns cached_data
2480 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc
2481 xfCachedData* cached_raw_data = xf_cached_data_new_copy(data, size);
2482 if (!cached_raw_data)
2483 WLog_Print(clipboard->log, WLOG_WARN, "Failed to allocate cache entry");
2484 else
2485 {
2486 if (!(bRawCached =
2487 HashTable_Insert(clipboard->cachedRawData,
2488 (void*)(UINT_PTR)srcFormatId, cached_raw_data)))
2489 {
2490 WLog_Print(clipboard->log, WLOG_WARN, "Failed to cache clipboard data");
2491 xf_cached_data_free(cached_raw_data);
2492 }
2493 }
2494 }
2495 }
2496
2497 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership
2498 if (SrcSize == 0)
2499 {
2500 WLog_Print(clipboard->log, WLOG_DEBUG, "skipping, empty data detected!");
2501 goto out;
2502 }
2503
2504 if (!bSuccess)
2505 {
2506 ClipboardLock(clipboard->system);
2507 bSuccess = ClipboardSetData(clipboard->system, srcFormatId, data, SrcSize);
2508 ClipboardUnlock(clipboard->system);
2509 }
2510
2511 if (!bSuccess)
2512 {
2513 WLog_Print(clipboard->log, WLOG_DEBUG, "skipping, ClipboardSetData failed!");
2514 goto out;
2515 }
2516
2517 wHashTable* table = clipboard->cachedData;
2518 if (pending->data_raw_format)
2519 table = clipboard->cachedRawData;
2520
2521 HashTable_Lock(table);
2522
2523 if (!pending->data_raw_format)
2524 hit_cached_data = HashTable_GetItemValue(table, format_to_cache_slot(dstFormatId));
2525 else
2526 hit_cached_data = HashTable_GetItemValue(table, format_to_cache_slot(srcFormatId));
2527
2528 HashTable_Unlock(table);
2529
2530 DEBUG_CLIPRDR("hasCachedData: %u, pending->data_raw_format: %d", hit_cached_data ? 1u : 0u,
2531 pending->data_raw_format);
2532
2533 ClipboardLock(clipboard->system);
2534 if (hit_cached_data)
2535 {
2536 pDstData = hit_cached_data->data;
2537 DstSize = hit_cached_data->data_length;
2538 }
2539 else
2540 {
2541 pDstData = (BYTE*)ClipboardGetData(clipboard->system, dstFormatId, &DstSize);
2542 }
2543
2544 if (!pDstData)
2545 {
2546 WLog_Print(clipboard->log, WLOG_WARN,
2547 "failed to get clipboard data in format %s [source format %s]",
2548 ClipboardGetFormatName(clipboard->system, dstFormatId),
2549 ClipboardGetFormatName(clipboard->system, srcFormatId));
2550 }
2551 ClipboardUnlock(clipboard->system);
2552
2553 if (!pDstData)
2554 {
2555 pending->expectedResponse->property = None;
2556 goto out;
2557 }
2558
2559 if (nullTerminated && pDstData)
2560 {
2561 BYTE* nullTerminator = memchr(pDstData, '\0', DstSize);
2562 if (nullTerminator)
2563 {
2564 const intptr_t diff = nullTerminator - pDstData;
2565 WINPR_ASSERT(diff >= 0);
2566 WINPR_ASSERT(diff <= UINT32_MAX);
2567 DstSize = (UINT32)diff;
2568 }
2569 }
2570
2571 // clipboard->cachedRawData owns cached_raw_data
2572 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
2573 xf_cliprdr_provide_data(clipboard, pending->expectedResponse, pDstData, DstSize);
2574
2575 if (!hit_cached_data && pDstData)
2576 {
2577 cached_data = xf_cached_data_new(pDstData, DstSize);
2578 if (!cached_data)
2579 {
2580
2581 free(pDstData);
2582 WLog_Print(clipboard->log, WLOG_WARN, "Failed to allocate cache entry");
2583 }
2584 else
2585 {
2586 HashTable_Lock(clipboard->cachedData);
2587 if (!HashTable_Insert(clipboard->cachedData, format_to_cache_slot(dstFormatId),
2588 cached_data))
2589 {
2590 WLog_Print(clipboard->log, WLOG_WARN, "Failed to cache clipboard data");
2591 xf_cached_data_free(cached_data);
2592 }
2593 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership
2594 HashTable_Unlock(clipboard->cachedData);
2595 }
2596 }
2597
2598 out:
2599 xf_cliprdr_provide_selection(clipboard, pending->expectedResponse);
2600
2601 ArrayList_Remove(clipboard->pending_responses, pending);
2602 }
2603
2604 // Processing data request for next formatId
2605 WINPR_ASSERT(ArrayList_Count(clipboard->pending_responses) == 0);
2606
2607 SelectionResponse* next = ArrayList_GetItem(clipboard->queued_responses, 0);
2608 if (next)
2609 {
2610 UINT32 nextFormatId = next->requestedFormat->formatToRequest;
2611 const xfCliprdrFormat* cformat =
2612 xf_cliprdr_get_client_format_by_atom(clipboard, next->expectedResponse->target);
2613
2614 size_t index = 0;
2615 while ((next = ArrayList_GetItem(clipboard->queued_responses, index)) != nullptr)
2616 {
2617 if (next->requestedFormat->formatToRequest == nextFormatId)
2618 {
2619 /* First set item to nullptr, then remove/free the element. Avoids double free */
2620 if (!ArrayList_SetItem(clipboard->queued_responses, index, nullptr))
2621 goto fail;
2622 ArrayList_RemoveAt(clipboard->queued_responses, index);
2623 if (!ArrayList_Append(clipboard->pending_responses, next))
2624 {
2625 selection_response_free(next);
2626 }
2627 }
2628 else
2629 index++;
2630 }
2631
2632 fail:
2633 xf_cliprdr_send_data_request(clipboard, nextFormatId, cformat);
2634 }
2635
2636 ArrayList_Unlock(clipboard->queued_responses);
2637 ArrayList_Unlock(clipboard->pending_responses);
2638 xf_unlock_x11(xfc);
2639
2640 return CHANNEL_RC_OK;
2641}
2642
2643static BOOL xf_cliprdr_is_valid_unix_filename(LPCWSTR filename)
2644{
2645 if (!filename)
2646 return FALSE;
2647
2648 if (filename[0] == L'\0')
2649 return FALSE;
2650
2651 /* Reserved characters */
2652 for (const WCHAR* c = filename; *c; ++c)
2653 {
2654 if (*c == L'/')
2655 return FALSE;
2656 }
2657
2658 return TRUE;
2659}
2660
2661xfClipboard* xf_clipboard_new(xfContext* xfc, BOOL relieveFilenameRestriction)
2662{
2663 int n = 0;
2664 rdpChannels* channels = nullptr;
2665 const char* selectionAtom = nullptr;
2666 xfCliprdrFormat* clientFormat = nullptr;
2667 wObject* obj = nullptr;
2668
2669 WINPR_ASSERT(xfc);
2670 WINPR_ASSERT(xfc->common.context.settings);
2671
2672 xfClipboard* clipboard = (xfClipboard*)calloc(1, sizeof(xfClipboard));
2673 if (!clipboard)
2674 return nullptr;
2675
2676 clipboard->log = WLog_Get(TAG);
2677 if (!clipboard->log)
2678 goto fail;
2679
2680 clipboard->file = cliprdr_file_context_new(clipboard);
2681 if (!clipboard->file)
2682 goto fail;
2683
2684 xfc->clipboard = clipboard;
2685 clipboard->xfc = xfc;
2686 channels = xfc->common.context.channels;
2687 clipboard->channels = channels;
2688 clipboard->system = ClipboardCreate();
2689 clipboard->requestedFormatId = UINT32_MAX;
2690 clipboard->root_window = DefaultRootWindow(xfc->display);
2691
2692 selectionAtom =
2693 freerdp_settings_get_string(xfc->common.context.settings, FreeRDP_ClipboardUseSelection);
2694 if (!selectionAtom)
2695 selectionAtom = "CLIPBOARD";
2696
2697 clipboard->clipboard_atom =
2698 Logging_XInternAtom(clipboard->log, xfc->display, selectionAtom, FALSE);
2699
2700 if (clipboard->clipboard_atom == None)
2701 {
2702 WLog_Print(clipboard->log, WLOG_ERROR, "unable to get %s atom", selectionAtom);
2703 goto fail;
2704 }
2705
2706 clipboard->timestamp_property_atom =
2707 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_TIMESTAMP_PROPERTY", FALSE);
2708 clipboard->property_atom =
2709 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR", FALSE);
2710 clipboard->raw_transfer_atom =
2711 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR_RAW", FALSE);
2712 clipboard->raw_format_list_atom =
2713 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR_FORMATS", FALSE);
2714 xf_cliprdr_set_raw_transfer_enabled(clipboard, TRUE);
2715 LogDynAndXSelectInput(clipboard->log, xfc->display, clipboard->root_window, PropertyChangeMask);
2716#ifdef WITH_XFIXES
2717
2718 if (XFixesQueryExtension(xfc->display, &clipboard->xfixes_event_base,
2719 &clipboard->xfixes_error_base))
2720 {
2721 int xfmajor = 0;
2722 int xfminor = 0;
2723
2724 if (XFixesQueryVersion(xfc->display, &xfmajor, &xfminor))
2725 {
2726 XFixesSelectSelectionInput(xfc->display, clipboard->root_window,
2727 clipboard->clipboard_atom,
2728 XFixesSetSelectionOwnerNotifyMask);
2729 clipboard->xfixes_supported = TRUE;
2730 }
2731 else
2732 {
2733 WLog_Print(clipboard->log, WLOG_ERROR, "Error querying X Fixes extension version");
2734 }
2735 }
2736 else
2737 {
2738 WLog_Print(clipboard->log, WLOG_ERROR, "Error loading X Fixes extension");
2739 }
2740
2741#else
2742 WLog_ERR(
2743 TAG,
2744 "Warning: Using clipboard redirection without XFIXES extension is strongly discouraged!");
2745#endif
2746 clientFormat = &clipboard->clientFormats[n++];
2747 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_RAW", False);
2748 clientFormat->localFormat = clientFormat->formatToRequest = CF_RAW;
2749
2750 clientFormat = &clipboard->clientFormats[n++];
2751 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, "UTF8_STRING", False);
2752 clientFormat->formatToRequest = CF_UNICODETEXT;
2753 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_text_utf8);
2754
2755 clientFormat = &clipboard->clientFormats[n++];
2756 clientFormat->atom = XA_STRING;
2757 clientFormat->formatToRequest = CF_TEXT;
2758 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_text_plain);
2759
2760 clientFormat = &clipboard->clientFormats[n++];
2761 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_tiff, False);
2762 clientFormat->formatToRequest = clientFormat->localFormat = CF_TIFF;
2763
2764 for (size_t x = 0; x < ARRAYSIZE(mime_bitmap); x++)
2765 {
2766 const char* mime_bmp = mime_bitmap[x];
2767 const DWORD format = ClipboardGetFormatId(xfc->clipboard->system, mime_bmp);
2768 if (format == 0)
2769 {
2770 WLog_Print(clipboard->log, WLOG_DEBUG,
2771 "skipping local bitmap format %s [NOT SUPPORTED]", mime_bmp);
2772 continue;
2773 }
2774
2775 WLog_Print(clipboard->log, WLOG_DEBUG, "register local bitmap format %s [0x%08" PRIx32 "]",
2776 mime_bmp, format);
2777 clientFormat = &clipboard->clientFormats[n++];
2778 clientFormat->localFormat = format;
2779 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_bmp, False);
2780 clientFormat->formatToRequest = CF_DIB;
2781 clientFormat->isImage = TRUE;
2782 }
2783
2784 for (size_t x = 0; x < ARRAYSIZE(mime_images); x++)
2785 {
2786 const char* mime_bmp = mime_images[x];
2787 const DWORD format = ClipboardGetFormatId(xfc->clipboard->system, mime_bmp);
2788 if (format == 0)
2789 {
2790 WLog_Print(clipboard->log, WLOG_DEBUG,
2791 "skipping local bitmap format %s [NOT SUPPORTED]", mime_bmp);
2792 continue;
2793 }
2794
2795 WLog_Print(clipboard->log, WLOG_DEBUG, "register local bitmap format %s [0x%08" PRIx32 "]",
2796 mime_bmp, format);
2797 clientFormat = &clipboard->clientFormats[n++];
2798 clientFormat->localFormat = format;
2799 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_bmp, False);
2800 clientFormat->formatToRequest = CF_DIB;
2801 clientFormat->isImage = TRUE;
2802 }
2803
2804 clientFormat = &clipboard->clientFormats[n++];
2805 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_html, False);
2806 clientFormat->formatToRequest = ClipboardGetFormatId(xfc->clipboard->system, type_HtmlFormat);
2807 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_html);
2808 clientFormat->formatName = _strdup(type_HtmlFormat);
2809
2810 if (!clientFormat->formatName)
2811 goto fail;
2812
2813 clientFormat = &clipboard->clientFormats[n++];
2814
2815 /*
2816 * Existence of registered format IDs for file formats does not guarantee that they are
2817 * in fact supported by wClipboard (as further initialization may have failed after format
2818 * registration). However, they are definitely not supported if there are no registered
2819 * formats. In this case we should not list file formats in TARGETS.
2820 */
2821 {
2822 const UINT32 fgid = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW);
2823 {
2824 const UINT32 uid = ClipboardGetFormatId(clipboard->system, mime_uri_list);
2825 if (uid)
2826 {
2827 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2828 goto fail;
2829 clientFormat->atom =
2830 Logging_XInternAtom(clipboard->log, xfc->display, mime_uri_list, False);
2831 clientFormat->localFormat = uid;
2832 clientFormat->formatToRequest = fgid;
2833 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2834
2835 if (!clientFormat->formatName)
2836 goto fail;
2837
2838 clientFormat = &clipboard->clientFormats[n++];
2839 }
2840 }
2841
2842 {
2843 const UINT32 gid = ClipboardGetFormatId(clipboard->system, mime_gnome_copied_files);
2844 if (gid != 0)
2845 {
2846 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2847 goto fail;
2848 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display,
2849 mime_gnome_copied_files, False);
2850 clientFormat->localFormat = gid;
2851 clientFormat->formatToRequest = fgid;
2852 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2853
2854 if (!clientFormat->formatName)
2855 goto fail;
2856
2857 clientFormat = &clipboard->clientFormats[n++];
2858 }
2859 }
2860
2861 {
2862 const UINT32 mid = ClipboardGetFormatId(clipboard->system, mime_mate_copied_files);
2863 if (mid != 0)
2864 {
2865 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2866 goto fail;
2867 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display,
2868 mime_mate_copied_files, False);
2869 clientFormat->localFormat = mid;
2870 clientFormat->formatToRequest = fgid;
2871 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2872
2873 if (!clientFormat->formatName)
2874 goto fail;
2875 }
2876 }
2877 }
2878
2879 clipboard->numClientFormats = WINPR_ASSERTING_INT_CAST(uint32_t, n);
2880 clipboard->targets[0] = Logging_XInternAtom(clipboard->log, xfc->display, "TIMESTAMP", FALSE);
2881 clipboard->targets[1] = Logging_XInternAtom(clipboard->log, xfc->display, "TARGETS", FALSE);
2882 clipboard->numTargets = 2;
2883 clipboard->incr_atom = Logging_XInternAtom(clipboard->log, xfc->display, "INCR", FALSE);
2884
2885 if (relieveFilenameRestriction)
2886 {
2887 WLog_Print(clipboard->log, WLOG_DEBUG, "Relieving CLIPRDR filename restriction");
2888 ClipboardGetDelegate(clipboard->system)->IsFileNameComponentValid =
2889 xf_cliprdr_is_valid_unix_filename;
2890 }
2891
2892 clipboard->cachedData = HashTable_New(TRUE);
2893 if (!clipboard->cachedData)
2894 goto fail;
2895
2896 obj = HashTable_ValueObject(clipboard->cachedData);
2897 obj->fnObjectFree = xf_cached_data_free;
2898
2899 clipboard->cachedRawData = HashTable_New(TRUE);
2900 if (!clipboard->cachedRawData)
2901 goto fail;
2902
2903 obj = HashTable_ValueObject(clipboard->cachedRawData);
2904 obj->fnObjectFree = xf_cached_data_free;
2905
2906 clipboard->pending_responses = ArrayList_New(TRUE);
2907 if (!clipboard->pending_responses)
2908 goto fail;
2909 obj = ArrayList_Object(clipboard->pending_responses);
2910 obj->fnObjectFree = selection_response_free;
2911
2912 clipboard->queued_responses = ArrayList_New(TRUE);
2913 if (!clipboard->queued_responses)
2914 goto fail;
2915 obj = ArrayList_Object(clipboard->queued_responses);
2916 obj->fnObjectFree = selection_response_free;
2917
2918 return clipboard;
2919
2920fail:
2921 WINPR_PRAGMA_DIAG_PUSH
2922 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
2923 xf_clipboard_free(clipboard);
2924 WINPR_PRAGMA_DIAG_POP
2925 return nullptr;
2926}
2927
2928void xf_clipboard_free(xfClipboard* clipboard)
2929{
2930 if (!clipboard)
2931 return;
2932
2933 xf_clipboard_free_server_formats(clipboard);
2934
2935 for (UINT32 i = 0; i < clipboard->numClientFormats; i++)
2936 {
2937 xfCliprdrFormat* format = &clipboard->clientFormats[i];
2938 free(format->formatName);
2939 }
2940
2941 cliprdr_file_context_free(clipboard->file);
2942
2943 XFree(clipboard->clientAvailableFormatAtoms);
2944
2945 ClipboardDestroy(clipboard->system);
2946 HashTable_Free(clipboard->cachedRawData);
2947 HashTable_Free(clipboard->cachedData);
2948 ArrayList_Free(clipboard->pending_responses);
2949 ArrayList_Free(clipboard->queued_responses);
2950 free(clipboard->incr_data);
2951 free(clipboard);
2952}
2953
2954void xf_cliprdr_init(xfContext* xfc, CliprdrClientContext* cliprdr)
2955{
2956 WINPR_ASSERT(xfc);
2957 WINPR_ASSERT(cliprdr);
2958
2959 xfc->cliprdr = cliprdr;
2960 xfc->clipboard->context = cliprdr;
2961
2962 cliprdr->MonitorReady = xf_cliprdr_monitor_ready;
2963 cliprdr->ServerCapabilities = xf_cliprdr_server_capabilities;
2964 cliprdr->ServerFormatList = xf_cliprdr_server_format_list;
2965 cliprdr->ServerFormatListResponse = xf_cliprdr_server_format_list_response;
2966 cliprdr->ServerFormatDataRequest = xf_cliprdr_server_format_data_request;
2967 cliprdr->ServerFormatDataResponse = xf_cliprdr_server_format_data_response;
2968
2969 cliprdr_file_context_init(xfc->clipboard->file, cliprdr);
2970}
2971
2972void xf_cliprdr_uninit(xfContext* xfc, CliprdrClientContext* cliprdr)
2973{
2974 WINPR_ASSERT(xfc);
2975
2976 xfc->cliprdr = nullptr;
2977
2978 if (xfc->clipboard)
2979 {
2980 ClipboardLock(xfc->clipboard->system);
2981 cliprdr_file_context_uninit(xfc->clipboard->file, cliprdr);
2982 ClipboardUnlock(xfc->clipboard->system);
2983 xfc->clipboard->context = nullptr;
2984 }
2985}
WINPR_ATTR_NODISCARD FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.
WINPR_ATTR_NODISCARD FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
This struct contains function pointer to initialize/free objects.
Definition collections.h:52
OBJECT_FREE_FN fnObjectFree
Definition collections.h:59