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->clientAvailableFormatAtomsCount; 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
730WINPR_ATTR_NODISCARD
731static CLIPRDR_FORMAT* xf_cliprdr_get_formats_from_targets(xfClipboard* clipboard,
732 UINT32* numFormats, Atom** atoms,
733 size_t* atomsCount)
734{
735 Atom atom = None;
736 BYTE* data = nullptr;
737 int format_property = 0;
738 unsigned long proplength = 0;
739 unsigned long bytes_left = 0;
740 CLIPRDR_FORMAT* formats = nullptr;
741
742 WINPR_ASSERT(clipboard);
743 WINPR_ASSERT(numFormats);
744 WINPR_ASSERT(atoms);
745 WINPR_ASSERT(atomsCount);
746
747 xfContext* xfc = clipboard->xfc;
748 WINPR_ASSERT(xfc);
749
750 *numFormats = 0;
751 *atomsCount = 0;
752 {
753 XFree(*atoms);
754 *atoms = nullptr;
755 }
756
757 LogDynAndXGetWindowProperty(clipboard->log, xfc->display, xfc->drawable,
758 clipboard->property_atom, 0, 200, 0, XA_ATOM, &atom,
759 &format_property, &proplength, &bytes_left, &data);
760
761 if (proplength > 0)
762 {
763 unsigned long length = proplength + 1;
764 if (!data)
765 {
766 WLog_Print(clipboard->log, WLOG_ERROR,
767 "XGetWindowProperty set length = %lu but data is nullptr", length);
768 goto out;
769 }
770
771 if (!(formats = (CLIPRDR_FORMAT*)calloc(length, sizeof(CLIPRDR_FORMAT))))
772 {
773 WLog_Print(clipboard->log, WLOG_ERROR, "failed to allocate %lu CLIPRDR_FORMAT structs",
774 length);
775 goto out;
776 }
777 }
778
779 {
780 BOOL isImage = FALSE;
781 BOOL hasHtml = FALSE;
782 const uint32_t htmlFormatId = ClipboardRegisterFormat(clipboard->system, type_HtmlFormat);
783 for (unsigned long i = 0; i < proplength; i++)
784 {
785 Atom tatom = WINPR_PACKED_ALIGN_CAST(Atom*, data)[i];
786 const xfCliprdrFormat* format = xf_cliprdr_get_client_format_by_atom(clipboard, tatom);
787
788 if (xf_cliprdr_should_add_format(formats, *numFormats, format))
789 {
790 CLIPRDR_FORMAT* cformat = &formats[*numFormats];
791 cformat->formatId = format->formatToRequest;
792
793 /* We do not want to double register a format, so check if HTML was already
794 * registered.
795 */
796 if (cformat->formatId == htmlFormatId)
797 hasHtml = TRUE;
798
799 /* These are standard image types that will always be registered regardless of
800 * actual image format. */
801 if (cformat->formatId == CF_TIFF)
802 isImage = TRUE;
803 else if (cformat->formatId == CF_DIB)
804 isImage = TRUE;
805 else if (cformat->formatId == CF_DIBV5)
806 isImage = TRUE;
807
808 if (format->formatName)
809 {
810 cformat->formatName = _strdup(format->formatName);
811 WINPR_ASSERT(cformat->formatName);
812 }
813 else
814 cformat->formatName = nullptr;
815
816 *numFormats += 1;
817 }
818 }
819
820 clipboard->isImageContent = isImage;
821 if (isImage && !hasHtml)
822 {
823 CLIPRDR_FORMAT* cformat = &formats[*numFormats];
824 cformat->formatId = htmlFormatId;
825 cformat->formatName = _strdup(type_HtmlFormat);
826
827 *numFormats += 1;
828 }
829 }
830out:
831
832 if (data && !atoms)
833 XFree(data);
834 else if (atoms && data)
835 {
836 *atoms = WINPR_PACKED_ALIGN_CAST(Atom*, data);
837 *atomsCount = proplength;
838 }
839
840 return formats;
841}
842
843WINPR_ATTR_NODISCARD
844static CLIPRDR_FORMAT* xf_cliprdr_get_client_formats(xfClipboard* clipboard, UINT32* numFormats,
845 Atom** atoms, size_t* atomsCount)
846{
847 CLIPRDR_FORMAT* formats = nullptr;
848
849 WINPR_ASSERT(clipboard);
850 WINPR_ASSERT(numFormats);
851 WINPR_ASSERT(atoms);
852 WINPR_ASSERT(atomsCount);
853
854 *numFormats = 0;
855 *atomsCount = 0;
856 {
857 XFree(*atoms);
858 *atoms = nullptr;
859 }
860
861 if (xf_cliprdr_is_raw_transfer_available(clipboard))
862 formats = xf_cliprdr_get_raw_server_formats(clipboard, numFormats);
863
864 if (*numFormats == 0)
865 {
866 xf_cliprdr_free_formats(formats, *numFormats);
867 formats = xf_cliprdr_get_formats_from_targets(clipboard, numFormats, atoms, atomsCount);
868 }
869
870 return formats;
871}
872
873static void xf_cliprdr_provide_server_format_list(xfClipboard* clipboard)
874{
875 wStream* formats = nullptr;
876 xfContext* xfc = nullptr;
877
878 WINPR_ASSERT(clipboard);
879
880 xfc = clipboard->xfc;
881 WINPR_ASSERT(xfc);
882
883 formats = xf_cliprdr_serialize_server_format_list(clipboard);
884
885 if (formats)
886 {
887 const size_t len = Stream_Length(formats);
888 WINPR_ASSERT(len <= INT32_MAX);
889 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
890 clipboard->raw_format_list_atom, clipboard->raw_format_list_atom,
891 8, PropModeReplace, Stream_Buffer(formats), (int)len);
892 }
893 else
894 {
895 LogDynAndXDeleteProperty(clipboard->log, xfc->display, xfc->drawable,
896 clipboard->raw_format_list_atom);
897 }
898
899 Stream_Free(formats, TRUE);
900}
901
902WINPR_ATTR_MALLOC(free, 1)
903static char* atomsToStringList(wLog* log, Display* display, const Atom* atoms, size_t count)
904{
905 WINPR_ASSERT(atoms || (count == 0));
906
907 char* str = calloc(1, sizeof(char));
908 if (!str)
909 return str;
910 size_t len = 0;
911 for (size_t x = 0; x < count; x++)
912 {
913 Atom atom = atoms[x];
914 char* name = Safe_XGetAtomName(log, display, atom);
915 if (name)
916 {
917 char* tmp = nullptr;
918 if (len > 0)
919 winpr_asprintf(&tmp, &len, "%s,%s", str, name);
920 else
921 {
922 tmp = name;
923 name = nullptr;
924 }
925 free(str);
926 str = tmp;
927 }
928 winpr_str_append(name, str, len, ",");
929 free(name);
930 }
931 return str;
932}
933
934static UINT xf_cliprdr_send_format_list(xfClipboard* clipboard, const CLIPRDR_FORMAT* formats,
935 UINT32 numFormats, Atom* atoms, size_t atomsCount)
936{
937 union
938 {
939 const CLIPRDR_FORMAT* cpv;
940 CLIPRDR_FORMAT* pv;
941 } cnv = { .cpv = formats };
942 const CLIPRDR_FORMAT_LIST formatList = { .common.msgFlags = 0,
943 .numFormats = numFormats,
944 .formats = cnv.pv,
945 .common.msgType = CB_FORMAT_LIST };
946 UINT ret = 0;
947
948 WINPR_ASSERT(clipboard);
949 WINPR_ASSERT(formats || (numFormats == 0));
950 WINPR_ASSERT(atoms || (atomsCount == 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 = WINPR_PACKED_ALIGN_CAST(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 =
2057 WINPR_PACKED_ALIGN_CAST(const CLIPRDR_CAPABILITY_SET*, capsPtr);
2058
2059 if (caps->capabilitySetType == CB_CAPSTYPE_GENERAL)
2060 {
2061 const CLIPRDR_GENERAL_CAPABILITY_SET* generalCaps =
2062 WINPR_PACKED_ALIGN_CAST(const CLIPRDR_GENERAL_CAPABILITY_SET*, caps);
2063
2064 if (!cliprdr_file_context_remote_set_flags(clipboard->file, generalCaps->generalFlags))
2065 return ERROR_INTERNAL_ERROR;
2066 }
2067
2068 capsPtr += caps->capabilitySetLength;
2069 }
2070
2071 return CHANNEL_RC_OK;
2072}
2073
2074static void xf_cliprdr_prepare_to_set_selection_owner(xfContext* xfc, xfClipboard* clipboard)
2075{
2076 WINPR_ASSERT(xfc);
2077 WINPR_ASSERT(clipboard);
2078 /*
2079 * When you're writing to the selection in response to a
2080 * normal X event like a mouse click or keyboard action, you
2081 * get the selection timestamp by copying the time field out
2082 * of that X event. Here, we're doing it on our own
2083 * initiative, so we have to _request_ the X server time.
2084 *
2085 * There isn't a GetServerTime request in the X protocol, so I
2086 * work around it by setting a property on our own window, and
2087 * waiting for a PropertyNotify event to come back telling me
2088 * it's been done - which will have a timestamp we can use.
2089 */
2090
2091 /* We have to set the property to some value, but it doesn't
2092 * matter what. Set it to its own name, which we have here
2093 * anyway! */
2094 Atom value = clipboard->timestamp_property_atom;
2095
2096 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
2097 clipboard->timestamp_property_atom, XA_ATOM, 32, PropModeReplace,
2098 (const BYTE*)&value, 1);
2099 LogDynAndXFlush(clipboard->log, xfc->display);
2100}
2101
2102static void xf_cliprdr_set_selection_owner(xfContext* xfc, xfClipboard* clipboard, Time timestamp)
2103{
2104 WINPR_ASSERT(xfc);
2105 WINPR_ASSERT(clipboard);
2106 /*
2107 * Actually set ourselves up as the selection owner, now that
2108 * we have a timestamp to use.
2109 */
2110
2111 clipboard->selection_ownership_timestamp = timestamp;
2112 LogDynAndXSetSelectionOwner(clipboard->log, xfc->display, clipboard->clipboard_atom,
2113 xfc->drawable, timestamp);
2114 LogDynAndXFlush(clipboard->log, xfc->display);
2115}
2116
2122static UINT xf_cliprdr_server_format_list(CliprdrClientContext* context,
2123 const CLIPRDR_FORMAT_LIST* formatList)
2124{
2125 xfContext* xfc = nullptr;
2126 UINT ret = 0;
2127 xfClipboard* clipboard = nullptr;
2128
2129 WINPR_ASSERT(context);
2130 WINPR_ASSERT(formatList);
2131
2132 clipboard = cliprdr_file_context_get_context(context->custom);
2133 WINPR_ASSERT(clipboard);
2134
2135 xfc = clipboard->xfc;
2136 WINPR_ASSERT(xfc);
2137
2138 xf_lock_x11(xfc);
2139
2140 /* Clear the active SelectionRequest, as it is now invalid */
2141 ArrayList_Clear(clipboard->pending_responses);
2142 ArrayList_Clear(clipboard->queued_responses);
2143
2144 xf_cliprdr_clear_cached_data(clipboard);
2145
2146 xf_clipboard_free_server_formats(clipboard);
2147
2148 clipboard->numServerFormats = formatList->numFormats + 1; /* +1 for CF_RAW */
2149
2150 if (!(clipboard->serverFormats =
2151 (CLIPRDR_FORMAT*)calloc(clipboard->numServerFormats, sizeof(CLIPRDR_FORMAT))))
2152 {
2153 WLog_Print(clipboard->log, WLOG_ERROR,
2154 "failed to allocate %" PRIu32 " CLIPRDR_FORMAT structs",
2155 clipboard->numServerFormats);
2156 ret = CHANNEL_RC_NO_MEMORY;
2157 goto out;
2158 }
2159
2160 for (size_t i = 0; i < formatList->numFormats; i++)
2161 {
2162 const CLIPRDR_FORMAT* format = &formatList->formats[i];
2163 CLIPRDR_FORMAT* srvFormat = &clipboard->serverFormats[i];
2164
2165 srvFormat->formatId = format->formatId;
2166
2167 if (format->formatName)
2168 {
2169 srvFormat->formatName = _strdup(format->formatName);
2170
2171 if (!srvFormat->formatName)
2172 {
2173 for (UINT32 k = 0; k < i; k++)
2174 free(clipboard->serverFormats[k].formatName);
2175
2176 clipboard->numServerFormats = 0;
2177 free(clipboard->serverFormats);
2178 clipboard->serverFormats = nullptr;
2179 ret = CHANNEL_RC_NO_MEMORY;
2180 goto out;
2181 }
2182 }
2183 }
2184
2185 ClipboardLock(clipboard->system);
2186 ret = cliprdr_file_context_notify_new_server_format_list(clipboard->file);
2187 ClipboardUnlock(clipboard->system);
2188 if (ret)
2189 goto out;
2190
2191 /* CF_RAW is always implicitly supported by the server */
2192 {
2193 CLIPRDR_FORMAT* format = &clipboard->serverFormats[formatList->numFormats];
2194 format->formatId = CF_RAW;
2195 format->formatName = nullptr;
2196 }
2197 xf_cliprdr_provide_server_format_list(clipboard);
2198 clipboard->numTargets = 2;
2199
2200 for (size_t i = 0; i < formatList->numFormats; i++)
2201 {
2202 const CLIPRDR_FORMAT* format = &formatList->formats[i];
2203
2204 for (size_t j = 0; j < clipboard->numClientFormats; j++)
2205 {
2206 const xfCliprdrFormat* clientFormat = &clipboard->clientFormats[j];
2207 if (xf_cliprdr_formats_equal(format, clientFormat))
2208 {
2209 if ((clientFormat->formatName != nullptr) &&
2210 (strcmp(type_FileGroupDescriptorW, clientFormat->formatName) == 0))
2211 {
2212 if (!cliprdr_file_context_has_local_support(clipboard->file))
2213 continue;
2214 }
2215 xf_cliprdr_append_target(clipboard, clientFormat->atom);
2216 }
2217 }
2218 }
2219
2220 ret = xf_cliprdr_send_client_format_list_response(clipboard, TRUE);
2221 if (xfc->remote_app)
2222 xf_cliprdr_set_selection_owner(xfc, clipboard, CurrentTime);
2223 else
2224 xf_cliprdr_prepare_to_set_selection_owner(xfc, clipboard);
2225
2226out:
2227 xf_unlock_x11(xfc);
2228
2229 return ret;
2230}
2231
2237static UINT xf_cliprdr_server_format_list_response(
2238 WINPR_ATTR_UNUSED CliprdrClientContext* context,
2239 WINPR_ATTR_UNUSED const CLIPRDR_FORMAT_LIST_RESPONSE* formatListResponse)
2240{
2241 WINPR_ASSERT(context);
2242 WINPR_ASSERT(formatListResponse);
2243 // xfClipboard* clipboard = (xfClipboard*) context->custom;
2244 return CHANNEL_RC_OK;
2245}
2246
2252static UINT
2253xf_cliprdr_server_format_data_request(CliprdrClientContext* context,
2254 const CLIPRDR_FORMAT_DATA_REQUEST* formatDataRequest)
2255{
2256 const xfCliprdrFormat* format = nullptr;
2257
2258 WINPR_ASSERT(context);
2259 WINPR_ASSERT(formatDataRequest);
2260
2261 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2262 WINPR_ASSERT(clipboard);
2263
2264 xfContext* xfc = clipboard->xfc;
2265 WINPR_ASSERT(xfc);
2266
2267 const uint32_t formatId = formatDataRequest->requestedFormatId;
2268
2269 const BOOL rawTransfer = xf_cliprdr_is_raw_transfer_available(clipboard);
2270
2271 if (rawTransfer)
2272 {
2273 format = xf_cliprdr_get_client_available_format_by_id(clipboard, CF_RAW);
2274 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
2275 clipboard->property_atom, XA_INTEGER, 32, PropModeReplace,
2276 (const BYTE*)&formatId, 1);
2277 }
2278 else
2279 format = xf_cliprdr_get_client_available_format_by_id(clipboard, formatId);
2280
2281 clipboard->requestedFormatId = rawTransfer ? CF_RAW : formatId;
2282 if (!format)
2283 return xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
2284
2285 DEBUG_CLIPRDR("requested format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 " [%s]} [%s]",
2286 format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest),
2287 format->localFormat,
2288 ClipboardGetFormatName(clipboard->system, format->localFormat),
2289 format->formatName);
2290 LogDynAndXConvertSelection(clipboard->log, xfc->display, clipboard->clipboard_atom,
2291 format->atom, clipboard->property_atom, xfc->drawable, CurrentTime);
2292 LogDynAndXFlush(clipboard->log, xfc->display);
2293 /* After this point, we expect a SelectionNotify event from the clipboard owner. */
2294 return CHANNEL_RC_OK;
2295}
2296
2302static UINT
2303xf_cliprdr_server_format_data_response(CliprdrClientContext* context,
2304 const CLIPRDR_FORMAT_DATA_RESPONSE* formatDataResponse)
2305{
2306 BOOL bSuccess = FALSE;
2307 BOOL bRawCached = FALSE;
2308 BOOL bFileContextUpdated = FALSE;
2309
2310 WINPR_ASSERT(context);
2311 WINPR_ASSERT(formatDataResponse);
2312
2313 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2314 WINPR_ASSERT(clipboard);
2315
2316 xfContext* xfc = clipboard->xfc;
2317 WINPR_ASSERT(xfc);
2318
2319 const UINT32 size = formatDataResponse->common.dataLen;
2320 const BYTE* data = formatDataResponse->requestedFormatData;
2321
2322 // Keep the same lock order as process_selection_request to prevent deadlock
2323 xf_lock_x11(xfc);
2324 ArrayList_Lock(clipboard->pending_responses);
2325 ArrayList_Lock(clipboard->queued_responses);
2326 if (formatDataResponse->common.msgFlags == CB_RESPONSE_FAIL)
2327 {
2328 WLog_Print(clipboard->log, WLOG_WARN,
2329 "Format Data Response PDU msgFlags is CB_RESPONSE_FAIL");
2330 while (ArrayList_Count(clipboard->pending_responses) > 0)
2331 {
2332 SelectionResponse* pending = ArrayList_GetItem(clipboard->pending_responses, 0);
2333
2334 pending->expectedResponse->property = None;
2335 xf_cliprdr_provide_selection(clipboard, pending->expectedResponse);
2336
2337 ArrayList_Remove(clipboard->pending_responses, pending);
2338 }
2339 WINPR_ASSERT(ArrayList_Count(clipboard->pending_responses) == 0);
2340 }
2341
2342 while (ArrayList_Count(clipboard->pending_responses) > 0)
2343 {
2344 BYTE* pDstData = nullptr;
2345 UINT32 DstSize = 0;
2346 UINT32 SrcSize = 0;
2347 UINT32 srcFormatId = 0;
2348 UINT32 dstFormatId = 0;
2349 BOOL nullTerminated = FALSE;
2350 xfCachedData* cached_data = nullptr;
2351 xfCachedData* hit_cached_data = nullptr;
2352
2353 SelectionResponse* pending = ArrayList_GetItem(clipboard->pending_responses, 0);
2354 const RequestedFormat* format = pending->requestedFormat;
2355 if (pending->data_raw_format)
2356 {
2357 srcFormatId = CF_RAW;
2358 dstFormatId = CF_RAW;
2359 }
2360 else if (!format)
2361 {
2362 pending->expectedResponse->property = None;
2363 goto out;
2364 }
2365 else if (format->formatName)
2366 {
2367 dstFormatId = format->localFormat;
2368
2369 ClipboardLock(clipboard->system);
2370 if (strcmp(format->formatName, type_HtmlFormat) == 0)
2371 {
2372 srcFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat);
2373 dstFormatId = ClipboardGetFormatId(clipboard->system, mime_html);
2374 nullTerminated = TRUE;
2375 }
2376
2377 if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0)
2378 {
2379 if (!bFileContextUpdated)
2380 {
2381 if (!cliprdr_file_context_update_server_data(clipboard->file, clipboard->system,
2382 data, size))
2383 WLog_Print(clipboard->log, WLOG_WARN, "failed to update file descriptors");
2384 else
2385 bFileContextUpdated = TRUE;
2386 }
2387
2388 srcFormatId = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW);
2389 const xfCliprdrFormat* dstTargetFormat = xf_cliprdr_get_client_format_by_atom(
2390 clipboard, pending->expectedResponse->target);
2391 if (!dstTargetFormat)
2392 {
2393 dstFormatId = ClipboardGetFormatId(clipboard->system, mime_uri_list);
2394 }
2395 else
2396 {
2397 dstFormatId = dstTargetFormat->localFormat;
2398 }
2399
2400 nullTerminated = TRUE;
2401 }
2402 ClipboardUnlock(clipboard->system);
2403 }
2404 else
2405 {
2406 srcFormatId = format->formatToRequest;
2407 dstFormatId = format->localFormat;
2408 switch (format->formatToRequest)
2409 {
2410 case CF_TEXT:
2411 nullTerminated = TRUE;
2412 break;
2413
2414 case CF_OEMTEXT:
2415 nullTerminated = TRUE;
2416 break;
2417
2418 case CF_UNICODETEXT:
2419 nullTerminated = TRUE;
2420 break;
2421
2422 case CF_DIB:
2423 srcFormatId = CF_DIB;
2424 break;
2425
2426 case CF_TIFF:
2427 srcFormatId = CF_TIFF;
2428 break;
2429
2430 default:
2431 break;
2432 }
2433 }
2434
2435 DEBUG_CLIPRDR("requested format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 " [%s]} [%s]",
2436 format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest),
2437 format->localFormat,
2438 ClipboardGetFormatName(clipboard->system, format->localFormat),
2439 format->formatName);
2440 SrcSize = size;
2441
2442 DEBUG_CLIPRDR("srcFormatId: 0x%08" PRIx32 ", dstFormatId: 0x%08" PRIx32 "", srcFormatId,
2443 dstFormatId);
2444
2445 if (SrcSize != 0 && !bRawCached)
2446 {
2447 /* We have to copy the original data again, as pSrcData is now owned
2448 * by clipboard->system. Memory allocation failure is not fatal here
2449 * as this is only a cached value. */
2450 {
2451 // clipboard->cachedData owns cached_data
2452 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc
2453 xfCachedData* cached_raw_data = xf_cached_data_new_copy(data, size);
2454 if (!cached_raw_data)
2455 WLog_Print(clipboard->log, WLOG_WARN, "Failed to allocate cache entry");
2456 else
2457 {
2458 if (!(bRawCached =
2459 HashTable_Insert(clipboard->cachedRawData,
2460 (void*)(UINT_PTR)srcFormatId, cached_raw_data)))
2461 {
2462 WLog_Print(clipboard->log, WLOG_WARN, "Failed to cache clipboard data");
2463 xf_cached_data_free(cached_raw_data);
2464 }
2465 }
2466 }
2467 }
2468
2469 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership
2470 if (SrcSize == 0)
2471 {
2472 WLog_Print(clipboard->log, WLOG_DEBUG, "skipping, empty data detected!");
2473 goto out;
2474 }
2475
2476 if (!bSuccess)
2477 {
2478 ClipboardLock(clipboard->system);
2479 bSuccess = ClipboardSetData(clipboard->system, srcFormatId, data, SrcSize);
2480 ClipboardUnlock(clipboard->system);
2481 }
2482
2483 if (!bSuccess)
2484 {
2485 WLog_Print(clipboard->log, WLOG_DEBUG, "skipping, ClipboardSetData failed!");
2486 goto out;
2487 }
2488
2489 wHashTable* table = clipboard->cachedData;
2490 if (pending->data_raw_format)
2491 table = clipboard->cachedRawData;
2492
2493 HashTable_Lock(table);
2494
2495 if (!pending->data_raw_format)
2496 hit_cached_data = HashTable_GetItemValue(table, format_to_cache_slot(dstFormatId));
2497 else
2498 hit_cached_data = HashTable_GetItemValue(table, format_to_cache_slot(srcFormatId));
2499
2500 HashTable_Unlock(table);
2501
2502 DEBUG_CLIPRDR("hasCachedData: %u, pending->data_raw_format: %d", hit_cached_data ? 1u : 0u,
2503 pending->data_raw_format);
2504
2505 ClipboardLock(clipboard->system);
2506 if (hit_cached_data)
2507 {
2508 pDstData = hit_cached_data->data;
2509 DstSize = hit_cached_data->data_length;
2510 }
2511 else
2512 {
2513 pDstData = (BYTE*)ClipboardGetData(clipboard->system, dstFormatId, &DstSize);
2514 }
2515
2516 if (!pDstData)
2517 {
2518 WLog_Print(clipboard->log, WLOG_WARN,
2519 "failed to get clipboard data in format %s [source format %s]",
2520 ClipboardGetFormatName(clipboard->system, dstFormatId),
2521 ClipboardGetFormatName(clipboard->system, srcFormatId));
2522 }
2523 ClipboardUnlock(clipboard->system);
2524
2525 if (!pDstData)
2526 {
2527 pending->expectedResponse->property = None;
2528 goto out;
2529 }
2530
2531 if (nullTerminated && pDstData)
2532 {
2533 BYTE* nullTerminator = memchr(pDstData, '\0', DstSize);
2534 if (nullTerminator)
2535 {
2536 const intptr_t diff = nullTerminator - pDstData;
2537 WINPR_ASSERT(diff >= 0);
2538 WINPR_ASSERT(diff <= UINT32_MAX);
2539 DstSize = (UINT32)diff;
2540 }
2541 }
2542
2543 // clipboard->cachedRawData owns cached_raw_data
2544 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
2545 xf_cliprdr_provide_data(clipboard, pending->expectedResponse, pDstData, DstSize);
2546
2547 if (!hit_cached_data && pDstData)
2548 {
2549 cached_data = xf_cached_data_new(pDstData, DstSize);
2550 if (!cached_data)
2551 {
2552
2553 free(pDstData);
2554 WLog_Print(clipboard->log, WLOG_WARN, "Failed to allocate cache entry");
2555 }
2556 else
2557 {
2558 HashTable_Lock(clipboard->cachedData);
2559 if (!HashTable_Insert(clipboard->cachedData, format_to_cache_slot(dstFormatId),
2560 cached_data))
2561 {
2562 WLog_Print(clipboard->log, WLOG_WARN, "Failed to cache clipboard data");
2563 xf_cached_data_free(cached_data);
2564 }
2565 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership
2566 HashTable_Unlock(clipboard->cachedData);
2567 }
2568 }
2569
2570 out:
2571 xf_cliprdr_provide_selection(clipboard, pending->expectedResponse);
2572
2573 ArrayList_Remove(clipboard->pending_responses, pending);
2574 }
2575
2576 // Processing data request for next formatId
2577 WINPR_ASSERT(ArrayList_Count(clipboard->pending_responses) == 0);
2578
2579 SelectionResponse* next = ArrayList_GetItem(clipboard->queued_responses, 0);
2580 if (next)
2581 {
2582 UINT32 nextFormatId = next->requestedFormat->formatToRequest;
2583 const xfCliprdrFormat* cformat =
2584 xf_cliprdr_get_client_format_by_atom(clipboard, next->expectedResponse->target);
2585
2586 size_t index = 0;
2587 while ((next = ArrayList_GetItem(clipboard->queued_responses, index)) != nullptr)
2588 {
2589 if (next->requestedFormat->formatToRequest == nextFormatId)
2590 {
2591 /* First set item to nullptr, then remove/free the element. Avoids double free */
2592 if (!ArrayList_SetItem(clipboard->queued_responses, index, nullptr))
2593 goto fail;
2594 ArrayList_RemoveAt(clipboard->queued_responses, index);
2595 if (!ArrayList_Append(clipboard->pending_responses, next))
2596 {
2597 selection_response_free(next);
2598 }
2599 }
2600 else
2601 index++;
2602 }
2603
2604 fail:
2605 xf_cliprdr_send_data_request(clipboard, nextFormatId, cformat);
2606 }
2607
2608 ArrayList_Unlock(clipboard->queued_responses);
2609 ArrayList_Unlock(clipboard->pending_responses);
2610 xf_unlock_x11(xfc);
2611
2612 return CHANNEL_RC_OK;
2613}
2614
2615static BOOL xf_cliprdr_is_valid_unix_filename(LPCWSTR filename)
2616{
2617 if (!filename)
2618 return FALSE;
2619
2620 if (filename[0] == L'\0')
2621 return FALSE;
2622
2623 /* Reserved characters */
2624 for (const WCHAR* c = filename; *c; ++c)
2625 {
2626 if (*c == L'/')
2627 return FALSE;
2628 }
2629
2630 return TRUE;
2631}
2632
2633xfClipboard* xf_clipboard_new(xfContext* xfc, BOOL relieveFilenameRestriction)
2634{
2635 int n = 0;
2636 rdpChannels* channels = nullptr;
2637 const char* selectionAtom = nullptr;
2638 xfCliprdrFormat* clientFormat = nullptr;
2639 wObject* obj = nullptr;
2640
2641 WINPR_ASSERT(xfc);
2642 WINPR_ASSERT(xfc->common.context.settings);
2643
2644 xfClipboard* clipboard = (xfClipboard*)calloc(1, sizeof(xfClipboard));
2645 if (!clipboard)
2646 return nullptr;
2647
2648 clipboard->log = WLog_Get(TAG);
2649 if (!clipboard->log)
2650 goto fail;
2651
2652 clipboard->file = cliprdr_file_context_new(clipboard);
2653 if (!clipboard->file)
2654 goto fail;
2655
2656 xfc->clipboard = clipboard;
2657 clipboard->xfc = xfc;
2658 channels = xfc->common.context.channels;
2659 clipboard->channels = channels;
2660 clipboard->system = ClipboardCreate();
2661 clipboard->requestedFormatId = UINT32_MAX;
2662 clipboard->root_window = DefaultRootWindow(xfc->display);
2663
2664 selectionAtom =
2665 freerdp_settings_get_string(xfc->common.context.settings, FreeRDP_ClipboardUseSelection);
2666 if (!selectionAtom)
2667 selectionAtom = "CLIPBOARD";
2668
2669 clipboard->clipboard_atom =
2670 Logging_XInternAtom(clipboard->log, xfc->display, selectionAtom, FALSE);
2671
2672 if (clipboard->clipboard_atom == None)
2673 {
2674 WLog_Print(clipboard->log, WLOG_ERROR, "unable to get %s atom", selectionAtom);
2675 goto fail;
2676 }
2677
2678 clipboard->timestamp_property_atom =
2679 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_TIMESTAMP_PROPERTY", FALSE);
2680 clipboard->property_atom =
2681 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR", FALSE);
2682 clipboard->raw_transfer_atom =
2683 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR_RAW", FALSE);
2684 clipboard->raw_format_list_atom =
2685 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR_FORMATS", FALSE);
2686 xf_cliprdr_set_raw_transfer_enabled(clipboard, TRUE);
2687 LogDynAndXSelectInput(clipboard->log, xfc->display, clipboard->root_window, PropertyChangeMask);
2688#ifdef WITH_XFIXES
2689
2690 if (XFixesQueryExtension(xfc->display, &clipboard->xfixes_event_base,
2691 &clipboard->xfixes_error_base))
2692 {
2693 int xfmajor = 0;
2694 int xfminor = 0;
2695
2696 if (XFixesQueryVersion(xfc->display, &xfmajor, &xfminor))
2697 {
2698 XFixesSelectSelectionInput(xfc->display, clipboard->root_window,
2699 clipboard->clipboard_atom,
2700 XFixesSetSelectionOwnerNotifyMask);
2701 clipboard->xfixes_supported = TRUE;
2702 }
2703 else
2704 {
2705 WLog_Print(clipboard->log, WLOG_ERROR, "Error querying X Fixes extension version");
2706 }
2707 }
2708 else
2709 {
2710 WLog_Print(clipboard->log, WLOG_ERROR, "Error loading X Fixes extension");
2711 }
2712
2713#else
2714 WLog_ERR(
2715 TAG,
2716 "Warning: Using clipboard redirection without XFIXES extension is strongly discouraged!");
2717#endif
2718 clientFormat = &clipboard->clientFormats[n++];
2719 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_RAW", False);
2720 clientFormat->localFormat = clientFormat->formatToRequest = CF_RAW;
2721
2722 clientFormat = &clipboard->clientFormats[n++];
2723 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, "UTF8_STRING", False);
2724 clientFormat->formatToRequest = CF_UNICODETEXT;
2725 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_text_plain);
2726
2727 clientFormat = &clipboard->clientFormats[n++];
2728 clientFormat->atom = XA_STRING;
2729 clientFormat->formatToRequest = CF_TEXT;
2730 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_text_plain);
2731
2732 clientFormat = &clipboard->clientFormats[n++];
2733 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_tiff, False);
2734 clientFormat->formatToRequest = clientFormat->localFormat = CF_TIFF;
2735
2736 for (size_t x = 0; x < ARRAYSIZE(mime_bitmap); x++)
2737 {
2738 const char* mime_bmp = mime_bitmap[x];
2739 const DWORD format = ClipboardGetFormatId(xfc->clipboard->system, mime_bmp);
2740 if (format == 0)
2741 {
2742 WLog_Print(clipboard->log, WLOG_DEBUG,
2743 "skipping local bitmap format %s [NOT SUPPORTED]", mime_bmp);
2744 continue;
2745 }
2746
2747 WLog_Print(clipboard->log, WLOG_DEBUG, "register local bitmap format %s [0x%08" PRIx32 "]",
2748 mime_bmp, format);
2749 clientFormat = &clipboard->clientFormats[n++];
2750 clientFormat->localFormat = format;
2751 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_bmp, False);
2752 clientFormat->formatToRequest = CF_DIB;
2753 clientFormat->isImage = TRUE;
2754 }
2755
2756 for (size_t x = 0; x < ARRAYSIZE(mime_images); x++)
2757 {
2758 const char* mime_bmp = mime_images[x];
2759 const DWORD format = ClipboardGetFormatId(xfc->clipboard->system, mime_bmp);
2760 if (format == 0)
2761 {
2762 WLog_Print(clipboard->log, WLOG_DEBUG,
2763 "skipping local bitmap format %s [NOT SUPPORTED]", mime_bmp);
2764 continue;
2765 }
2766
2767 WLog_Print(clipboard->log, WLOG_DEBUG, "register local bitmap format %s [0x%08" PRIx32 "]",
2768 mime_bmp, format);
2769 clientFormat = &clipboard->clientFormats[n++];
2770 clientFormat->localFormat = format;
2771 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_bmp, False);
2772 clientFormat->formatToRequest = CF_DIB;
2773 clientFormat->isImage = TRUE;
2774 }
2775
2776 clientFormat = &clipboard->clientFormats[n++];
2777 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_html, False);
2778 clientFormat->formatToRequest = ClipboardGetFormatId(xfc->clipboard->system, type_HtmlFormat);
2779 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_html);
2780 clientFormat->formatName = _strdup(type_HtmlFormat);
2781
2782 if (!clientFormat->formatName)
2783 goto fail;
2784
2785 clientFormat = &clipboard->clientFormats[n++];
2786
2787 /*
2788 * Existence of registered format IDs for file formats does not guarantee that they are
2789 * in fact supported by wClipboard (as further initialization may have failed after format
2790 * registration). However, they are definitely not supported if there are no registered
2791 * formats. In this case we should not list file formats in TARGETS.
2792 */
2793 {
2794 const UINT32 fgid = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW);
2795 {
2796 const UINT32 uid = ClipboardGetFormatId(clipboard->system, mime_uri_list);
2797 if (uid)
2798 {
2799 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2800 goto fail;
2801 clientFormat->atom =
2802 Logging_XInternAtom(clipboard->log, xfc->display, mime_uri_list, False);
2803 clientFormat->localFormat = uid;
2804 clientFormat->formatToRequest = fgid;
2805 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2806
2807 if (!clientFormat->formatName)
2808 goto fail;
2809
2810 clientFormat = &clipboard->clientFormats[n++];
2811 }
2812 }
2813
2814 {
2815 const UINT32 gid = ClipboardGetFormatId(clipboard->system, mime_gnome_copied_files);
2816 if (gid != 0)
2817 {
2818 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2819 goto fail;
2820 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display,
2821 mime_gnome_copied_files, False);
2822 clientFormat->localFormat = gid;
2823 clientFormat->formatToRequest = fgid;
2824 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2825
2826 if (!clientFormat->formatName)
2827 goto fail;
2828
2829 clientFormat = &clipboard->clientFormats[n++];
2830 }
2831 }
2832
2833 {
2834 const UINT32 mid = ClipboardGetFormatId(clipboard->system, mime_mate_copied_files);
2835 if (mid != 0)
2836 {
2837 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2838 goto fail;
2839 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display,
2840 mime_mate_copied_files, False);
2841 clientFormat->localFormat = mid;
2842 clientFormat->formatToRequest = fgid;
2843 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2844
2845 if (!clientFormat->formatName)
2846 goto fail;
2847 }
2848 }
2849 }
2850
2851 clipboard->numClientFormats = WINPR_ASSERTING_INT_CAST(uint32_t, n);
2852 clipboard->targets[0] = Logging_XInternAtom(clipboard->log, xfc->display, "TIMESTAMP", FALSE);
2853 clipboard->targets[1] = Logging_XInternAtom(clipboard->log, xfc->display, "TARGETS", FALSE);
2854 clipboard->numTargets = 2;
2855 clipboard->incr_atom = Logging_XInternAtom(clipboard->log, xfc->display, "INCR", FALSE);
2856
2857 if (relieveFilenameRestriction)
2858 {
2859 WLog_Print(clipboard->log, WLOG_DEBUG, "Relieving CLIPRDR filename restriction");
2860 ClipboardGetDelegate(clipboard->system)->IsFileNameComponentValid =
2861 xf_cliprdr_is_valid_unix_filename;
2862 }
2863
2864 clipboard->cachedData = HashTable_New(TRUE);
2865 if (!clipboard->cachedData)
2866 goto fail;
2867
2868 obj = HashTable_ValueObject(clipboard->cachedData);
2869 obj->fnObjectFree = xf_cached_data_free;
2870
2871 clipboard->cachedRawData = HashTable_New(TRUE);
2872 if (!clipboard->cachedRawData)
2873 goto fail;
2874
2875 obj = HashTable_ValueObject(clipboard->cachedRawData);
2876 obj->fnObjectFree = xf_cached_data_free;
2877
2878 clipboard->pending_responses = ArrayList_New(TRUE);
2879 if (!clipboard->pending_responses)
2880 goto fail;
2881 obj = ArrayList_Object(clipboard->pending_responses);
2882 obj->fnObjectFree = selection_response_free;
2883
2884 clipboard->queued_responses = ArrayList_New(TRUE);
2885 if (!clipboard->queued_responses)
2886 goto fail;
2887 obj = ArrayList_Object(clipboard->queued_responses);
2888 obj->fnObjectFree = selection_response_free;
2889
2890 return clipboard;
2891
2892fail:
2893 WINPR_PRAGMA_DIAG_PUSH
2894 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
2895 xf_clipboard_free(clipboard);
2896 WINPR_PRAGMA_DIAG_POP
2897 return nullptr;
2898}
2899
2900void xf_clipboard_free(xfClipboard* clipboard)
2901{
2902 if (!clipboard)
2903 return;
2904
2905 xf_clipboard_free_server_formats(clipboard);
2906
2907 for (UINT32 i = 0; i < clipboard->numClientFormats; i++)
2908 {
2909 xfCliprdrFormat* format = &clipboard->clientFormats[i];
2910 free(format->formatName);
2911 }
2912
2913 cliprdr_file_context_free(clipboard->file);
2914
2915 XFree(clipboard->clientAvailableFormatAtoms);
2916
2917 ClipboardDestroy(clipboard->system);
2918 HashTable_Free(clipboard->cachedRawData);
2919 HashTable_Free(clipboard->cachedData);
2920 ArrayList_Free(clipboard->pending_responses);
2921 ArrayList_Free(clipboard->queued_responses);
2922 free(clipboard->incr_data);
2923 free(clipboard);
2924}
2925
2926void xf_cliprdr_init(xfContext* xfc, CliprdrClientContext* cliprdr)
2927{
2928 WINPR_ASSERT(xfc);
2929 WINPR_ASSERT(cliprdr);
2930
2931 xfc->cliprdr = cliprdr;
2932 xfc->clipboard->context = cliprdr;
2933
2934 cliprdr->MonitorReady = xf_cliprdr_monitor_ready;
2935 cliprdr->ServerCapabilities = xf_cliprdr_server_capabilities;
2936 cliprdr->ServerFormatList = xf_cliprdr_server_format_list;
2937 cliprdr->ServerFormatListResponse = xf_cliprdr_server_format_list_response;
2938 cliprdr->ServerFormatDataRequest = xf_cliprdr_server_format_data_request;
2939 cliprdr->ServerFormatDataResponse = xf_cliprdr_server_format_data_response;
2940
2941 cliprdr_file_context_init(xfc->clipboard->file, cliprdr);
2942}
2943
2944void xf_cliprdr_uninit(xfContext* xfc, CliprdrClientContext* cliprdr)
2945{
2946 WINPR_ASSERT(xfc);
2947
2948 xfc->cliprdr = nullptr;
2949
2950 if (xfc->clipboard)
2951 {
2952 ClipboardLock(xfc->clipboard->system);
2953 cliprdr_file_context_uninit(xfc->clipboard->file, cliprdr);
2954 ClipboardUnlock(xfc->clipboard->system);
2955 xfc->clipboard->context = nullptr;
2956 }
2957}
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