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