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