FreeRDP
Loading...
Searching...
No Matches
xf_cliprdr.c
1
21
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 /* We have to read incremental updates */
1187 if ((type == clipboard->incr_atom) && !clipboard->incr_starts)
1188 {
1189 xf_cliprdr_stop_incr(clipboard);
1190 clipboard->incr_starts = TRUE;
1191 has_data = TRUE; /* data will follow in PropertyNotify event */
1192 }
1193 /* No data, empty return */
1194 else if ((total_bytes <= 0) && !clipboard->incr_starts)
1195 {
1196 xf_cliprdr_stop_incr(clipboard);
1197 }
1198 else
1199 {
1200 BYTE* incremental_data = nullptr;
1201 unsigned long incremental_len = 0;
1202
1203 /* Incremental updates completed, pass data */
1204 len = clipboard->incr_data_length;
1205 if (total_bytes <= 0)
1206 {
1207 xf_cliprdr_stop_incr(clipboard);
1208 has_data = TRUE;
1209 }
1210 /* Read incremental data batch */
1211 else if (LogDynAndXGetWindowProperty(
1212 clipboard->log, xfc->display, xfc->drawable, clipboard->property_atom, 0,
1213 WINPR_ASSERTING_INT_CAST(int32_t, total_bytes), False, target, &type,
1214 &format_property, &incremental_len, &length, &incremental_data) == Success)
1215 {
1216 has_data = append(clipboard, incremental_data, incremental_len);
1217 len = clipboard->incr_data_length;
1218 }
1219
1220 if (incremental_data)
1221 XFree(incremental_data);
1222 }
1223
1224 LogDynAndXDeleteProperty(clipboard->log, xfc->display, xfc->drawable, clipboard->property_atom);
1225 xf_cliprdr_process_requested_data(clipboard, has_data, clipboard->incr_data, len);
1226
1227 return TRUE;
1228}
1229
1230static void xf_cliprdr_append_target(xfClipboard* clipboard, Atom target)
1231{
1232 WINPR_ASSERT(clipboard);
1233
1234 if (clipboard->numTargets >= ARRAYSIZE(clipboard->targets))
1235 return;
1236
1237 for (size_t i = 0; i < clipboard->numTargets; i++)
1238 {
1239 if (clipboard->targets[i] == target)
1240 return;
1241 }
1242
1243 clipboard->targets[clipboard->numTargets++] = target;
1244}
1245
1246static void xf_cliprdr_provide_targets(xfClipboard* clipboard, const XSelectionEvent* respond)
1247{
1248 xfContext* xfc = nullptr;
1249
1250 WINPR_ASSERT(clipboard);
1251
1252 xfc = clipboard->xfc;
1253 WINPR_ASSERT(xfc);
1254
1255 if (respond->property != None)
1256 {
1257 WINPR_ASSERT(clipboard->numTargets <= INT32_MAX);
1258 LogDynAndXChangeProperty(clipboard->log, xfc->display, respond->requestor,
1259 respond->property, XA_ATOM, 32, PropModeReplace,
1260 (const BYTE*)clipboard->targets, (int)clipboard->numTargets);
1261 }
1262}
1263
1264static void xf_cliprdr_provide_timestamp(xfClipboard* clipboard, const XSelectionEvent* respond)
1265{
1266 xfContext* xfc = nullptr;
1267
1268 WINPR_ASSERT(clipboard);
1269
1270 xfc = clipboard->xfc;
1271 WINPR_ASSERT(xfc);
1272
1273 if (respond->property != None)
1274 {
1275 LogDynAndXChangeProperty(clipboard->log, xfc->display, respond->requestor,
1276 respond->property, XA_INTEGER, 32, PropModeReplace,
1277 (const BYTE*)&clipboard->selection_ownership_timestamp, 1);
1278 }
1279}
1280
1281#define xf_cliprdr_provide_data(clipboard, respond, data, size) \
1282 xf_cliprdr_provide_data_((clipboard), (respond), (data), (size), __FILE__, __func__, __LINE__)
1283static void xf_cliprdr_provide_data_(xfClipboard* clipboard, const XSelectionEvent* respond,
1284 const BYTE* data, UINT32 size, const char* file,
1285 const char* fkt, size_t line)
1286{
1287 WINPR_ASSERT(clipboard);
1288
1289 xfContext* xfc = clipboard->xfc;
1290 WINPR_ASSERT(xfc);
1291
1292 if (respond->property != None)
1293 {
1294 LogDynAndXChangeProperty_ex(clipboard->log, file, fkt, line, xfc->display,
1295 respond->requestor, respond->property, respond->target, 8,
1296 PropModeReplace, data, WINPR_ASSERTING_INT_CAST(int32_t, size));
1297 }
1298}
1299
1300static void log_selection_event(xfContext* xfc, const XEvent* event)
1301{
1302 const DWORD level = WLOG_TRACE;
1303 static wLog* _log_cached_ptr = nullptr;
1304 if (!_log_cached_ptr)
1305 _log_cached_ptr = WLog_Get(TAG);
1306 if (WLog_IsLevelActive(_log_cached_ptr, level))
1307 {
1308
1309 switch (event->type)
1310 {
1311 case SelectionClear:
1312 {
1313 const XSelectionClearEvent* xevent = &event->xselectionclear;
1314 char* selection =
1315 Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection);
1316 WLog_Print(_log_cached_ptr, level, "got event %s [selection %s]",
1317 x11_event_string(event->type), selection);
1318 XFree(selection);
1319 }
1320 break;
1321 case SelectionNotify:
1322 {
1323 const XSelectionEvent* xevent = &event->xselection;
1324 char* selection =
1325 Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection);
1326 char* target = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->target);
1327 char* property = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->property);
1328 WLog_Print(_log_cached_ptr, level,
1329 "got event %s [selection %s, target %s, property %s]",
1330 x11_event_string(event->type), selection, target, property);
1331 XFree(selection);
1332 XFree(target);
1333 XFree(property);
1334 }
1335 break;
1336 case SelectionRequest:
1337 {
1338 const XSelectionRequestEvent* xevent = &event->xselectionrequest;
1339 char* selection =
1340 Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->selection);
1341 char* target = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->target);
1342 char* property = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->property);
1343 WLog_Print(_log_cached_ptr, level,
1344 "got event %s [selection %s, target %s, property %s]",
1345 x11_event_string(event->type), selection, target, property);
1346 XFree(selection);
1347 XFree(target);
1348 XFree(property);
1349 }
1350 break;
1351 case PropertyNotify:
1352 {
1353 const XPropertyEvent* xevent = &event->xproperty;
1354 char* atom = Safe_XGetAtomName(_log_cached_ptr, xfc->display, xevent->atom);
1355 WLog_Print(_log_cached_ptr, level, "got event %s [atom %s]",
1356 x11_event_string(event->type), atom);
1357 XFree(atom);
1358 }
1359 break;
1360 default:
1361 break;
1362 }
1363 }
1364}
1365
1366static BOOL xf_cliprdr_process_selection_notify(xfClipboard* clipboard,
1367 const XSelectionEvent* xevent)
1368{
1369 WINPR_ASSERT(clipboard);
1370 WINPR_ASSERT(xevent);
1371
1372 if (xevent->target == clipboard->targets[1])
1373 {
1374 if (xevent->property == None)
1375 {
1376 /* The owner refused to list its targets. Do not ask again from here:
1377 * xf_cliprdr_send_client_format_list would issue a new TARGETS request,
1378 * and an owner that keeps refusing (Xwayland can) turns that into a
1379 * busy loop that also sends the server a format list on every turn,
1380 * built from the stale TARGETS of the previous owner. Wait for the
1381 * next owner change.
1382 *
1383 * Do not announce an empty format list here: Xwayland refuses while
1384 * it is still handing the selection over (e.g. on focus change), so
1385 * the server would get "empty" squeezed between two real lists, and
1386 * Windows rdpclip then stops requesting data on paste. */
1387 WLog_Print(clipboard->log, WLOG_DEBUG,
1388 "TARGETS refused by owner, waiting for next owner change");
1389 }
1390 else
1391 {
1392 xf_cliprdr_get_requested_targets(clipboard);
1393 }
1394
1395 return TRUE;
1396 }
1397 else
1398 {
1399 return xf_cliprdr_get_requested_data(clipboard, xevent->target);
1400 }
1401}
1402
1403void xf_cliprdr_clear_cached_data(xfClipboard* clipboard)
1404{
1405 WINPR_ASSERT(clipboard);
1406
1407 WLog_Print(clipboard->log, WLOG_DEBUG, "Clearing cached clipboard data");
1408 ClipboardLock(clipboard->system);
1409 ClipboardEmpty(clipboard->system);
1410
1411 HashTable_Clear(clipboard->cachedData);
1412 HashTable_Clear(clipboard->cachedRawData);
1413
1414 XFree(clipboard->clientAvailableFormatAtoms);
1415 clipboard->clientAvailableFormatAtoms = nullptr;
1416 clipboard->clientAvailableFormatAtomsCount = 0;
1417
1418 cliprdr_file_context_clear(clipboard->file);
1419
1420 xf_cliprdr_stop_incr(clipboard);
1421 ClipboardUnlock(clipboard->system);
1422}
1423
1424static void* format_to_cache_slot(UINT32 format)
1425{
1426 union
1427 {
1428 uintptr_t uptr;
1429 void* vptr;
1430 } cnv;
1431 cnv.uptr = 0x100000000ULL + format;
1432 return cnv.vptr;
1433}
1434
1435static UINT32 get_dst_format_id_for_local_request(xfClipboard* clipboard,
1436 const xfCliprdrFormat* format)
1437{
1438 UINT32 dstFormatId = 0;
1439
1440 WINPR_ASSERT(format);
1441
1442 if (!format->formatName)
1443 return format->localFormat;
1444
1445 ClipboardLock(clipboard->system);
1446 if (strcmp(format->formatName, type_HtmlFormat) == 0)
1447 dstFormatId = ClipboardGetFormatId(clipboard->system, mime_html);
1448 ClipboardUnlock(clipboard->system);
1449
1450 if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0)
1451 dstFormatId = format->localFormat;
1452
1453 return dstFormatId;
1454}
1455
1456static void get_src_format_info_for_local_request(xfClipboard* clipboard,
1457 const xfCliprdrFormat* format,
1458 UINT32* srcFormatId, BOOL* nullTerminated)
1459{
1460 *srcFormatId = 0;
1461 *nullTerminated = FALSE;
1462
1463 if (format->formatName)
1464 {
1465 ClipboardLock(clipboard->system);
1466 if (strcmp(format->formatName, type_HtmlFormat) == 0)
1467 {
1468 *srcFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat);
1469 *nullTerminated = TRUE;
1470 }
1471 else if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0)
1472 {
1473 *srcFormatId = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW);
1474 *nullTerminated = TRUE;
1475 }
1476 ClipboardUnlock(clipboard->system);
1477 }
1478 else
1479 {
1480 *srcFormatId = format->formatToRequest;
1481 switch (format->formatToRequest)
1482 {
1483 case CF_TEXT:
1484 case CF_OEMTEXT:
1485 case CF_UNICODETEXT:
1486 *nullTerminated = TRUE;
1487 break;
1488 case CF_DIB:
1489 *srcFormatId = CF_DIB;
1490 break;
1491 case CF_TIFF:
1492 *srcFormatId = CF_TIFF;
1493 break;
1494 default:
1495 break;
1496 }
1497 }
1498}
1499
1500static xfCachedData* convert_data_from_existing_raw_data(xfClipboard* clipboard,
1501 xfCachedData* cached_raw_data,
1502 UINT32 srcFormatId, BOOL nullTerminated,
1503 UINT32 dstFormatId)
1504{
1505 UINT32 dst_size = 0;
1506
1507 WINPR_ASSERT(clipboard);
1508 WINPR_ASSERT(cached_raw_data);
1509 WINPR_ASSERT(cached_raw_data->data);
1510
1511 ClipboardLock(clipboard->system);
1512 BOOL success = ClipboardSetData(clipboard->system, srcFormatId, cached_raw_data->data,
1513 cached_raw_data->data_length);
1514 if (!success)
1515 {
1516 WLog_Print(clipboard->log, WLOG_WARN,
1517 "Failed to set clipboard data (formatId: %u, data: %p, data_length: %u)",
1518 srcFormatId, WINPR_CXX_COMPAT_CAST(const void*, cached_raw_data->data),
1519 cached_raw_data->data_length);
1520 ClipboardUnlock(clipboard->system);
1521 return nullptr;
1522 }
1523
1524 BYTE* dst_data = ClipboardGetData(clipboard->system, dstFormatId, &dst_size);
1525 if (!dst_data)
1526 {
1527 WLog_Print(clipboard->log, WLOG_WARN, "Failed to get converted clipboard data");
1528 ClipboardUnlock(clipboard->system);
1529 return nullptr;
1530 }
1531 ClipboardUnlock(clipboard->system);
1532
1533 if (nullTerminated)
1534 {
1535 BYTE* nullTerminator = memchr(dst_data, '\0', dst_size);
1536 if (nullTerminator)
1537 {
1538 const intptr_t diff = nullTerminator - dst_data;
1539 WINPR_ASSERT(diff >= 0);
1540 WINPR_ASSERT(diff <= UINT32_MAX);
1541 dst_size = (UINT32)diff;
1542 }
1543 }
1544
1545 xfCachedData* cached_data = xf_cached_data_new(dst_data, dst_size);
1546 if (!cached_data)
1547 {
1548 WLog_Print(clipboard->log, WLOG_WARN, "Failed to allocate cache entry");
1549 free(dst_data);
1550 return nullptr;
1551 }
1552
1553 if (!HashTable_Insert(clipboard->cachedData, format_to_cache_slot(dstFormatId), cached_data))
1554 {
1555 WLog_Print(clipboard->log, WLOG_WARN, "Failed to cache clipboard data");
1556 xf_cached_data_free(cached_data);
1557 return nullptr;
1558 }
1559
1560 return cached_data;
1561}
1562
1563WINPR_ATTR_NODISCARD
1564static BOOL xf_cliprdr_pending_responses_ArrayList_ForEachFkt(void* data, size_t index, va_list ap)
1565{
1566 UINT32 formatId = 0;
1567 SelectionResponse* pendingResponse = (SelectionResponse*)data;
1568 UINT32 currentFormatId = va_arg(ap, UINT32);
1569 BOOL* res = va_arg(ap, BOOL*);
1570
1571 WINPR_UNUSED(index);
1572 WINPR_UNUSED(ap);
1573 WINPR_ASSERT(res);
1574
1575 formatId = pendingResponse->requestedFormat->formatToRequest;
1576
1577 if (formatId != currentFormatId)
1578 *res = TRUE;
1579 return TRUE;
1580}
1581
1582static void xf_cliprdr_provide_selection(xfClipboard* clipboard, XSelectionEvent* respond)
1583{
1584 WINPR_ASSERT(clipboard);
1585
1586 xfContext* xfc = clipboard->xfc;
1587 WINPR_ASSERT(xfc);
1588
1589 union
1590 {
1591 XEvent* ev;
1592 XSelectionEvent* sev;
1593 } conv;
1594
1595 conv.sev = respond;
1596 LogDynAndXSendEvent(clipboard->log, xfc->display, respond->requestor, 0, 0, conv.ev);
1597 LogDynAndXFlush(clipboard->log, xfc->display);
1598}
1599
1600static BOOL xf_cliprdr_process_selection_request(xfClipboard* clipboard,
1601 const XSelectionRequestEvent* xevent)
1602{
1603 int fmt = 0;
1604 Atom type = 0;
1605 UINT32 formatId = 0;
1606 XSelectionEvent* respond = nullptr;
1607 BYTE* data = nullptr;
1608 BOOL delayRespond = 0;
1609 BOOL rawTransfer = 0;
1610 unsigned long length = 0;
1611 unsigned long bytes_left = 0;
1612 xfContext* xfc = nullptr;
1613
1614 WINPR_ASSERT(clipboard);
1615 WINPR_ASSERT(xevent);
1616
1617 xfc = clipboard->xfc;
1618 WINPR_ASSERT(xfc);
1619
1620 if (xevent->owner != xfc->drawable)
1621 return FALSE;
1622
1623 delayRespond = FALSE;
1624
1625 if (!(respond = (XSelectionEvent*)calloc(1, sizeof(XSelectionEvent))))
1626 {
1627 WLog_Print(clipboard->log, WLOG_ERROR, "failed to allocate XEvent data");
1628 return FALSE;
1629 }
1630
1631 respond->property = None;
1632 respond->type = SelectionNotify;
1633 respond->display = xevent->display;
1634 respond->requestor = xevent->requestor;
1635 respond->selection = xevent->selection;
1636 respond->target = xevent->target;
1637 respond->time = xevent->time;
1638
1639 if (xevent->target == clipboard->targets[0]) /* TIMESTAMP */
1640 {
1641 /* Someone else requests the selection's timestamp */
1642 respond->property = xevent->property;
1643 xf_cliprdr_provide_timestamp(clipboard, respond);
1644 }
1645 else if (xevent->target == clipboard->targets[1]) /* TARGETS */
1646 {
1647 /* Someone else requests our available formats */
1648 respond->property = xevent->property;
1649 xf_cliprdr_provide_targets(clipboard, respond);
1650 }
1651 else
1652 {
1653 const CLIPRDR_FORMAT* format =
1654 xf_cliprdr_get_server_format_by_atom(clipboard, xevent->target);
1655 const xfCliprdrFormat* cformat =
1656 xf_cliprdr_get_client_format_by_atom(clipboard, xevent->target);
1657
1658 if (format && (xevent->requestor != xfc->drawable))
1659 {
1660 formatId = format->formatId;
1661 rawTransfer = FALSE;
1662 xfCachedData* cached_data = nullptr;
1663
1664 if (formatId == CF_RAW)
1665 {
1666 if (LogDynAndXGetWindowProperty(
1667 clipboard->log, xfc->display, xevent->requestor, clipboard->property_atom,
1668 0, 4, 0, XA_INTEGER, &type, &fmt, &length, &bytes_left, &data) != Success)
1669 {
1670 }
1671
1672 if (data)
1673 {
1674 rawTransfer = TRUE;
1675 CopyMemory(&formatId, data, 4);
1676 XFree(data);
1677 }
1678 }
1679
1680 const UINT32 dstFormatId = get_dst_format_id_for_local_request(clipboard, cformat);
1681 DEBUG_CLIPRDR("formatId: 0x%08" PRIx32 ", dstFormatId: 0x%08" PRIx32 "", formatId,
1682 dstFormatId);
1683
1684 wHashTable* table = clipboard->cachedData;
1685 if (rawTransfer)
1686 table = clipboard->cachedRawData;
1687
1688 HashTable_Lock(table);
1689 if (!rawTransfer)
1690 cached_data = HashTable_GetItemValue(table, format_to_cache_slot(dstFormatId));
1691 else
1692 cached_data = HashTable_GetItemValue(table, format_to_cache_slot(formatId));
1693 HashTable_Unlock(table);
1694
1695 DEBUG_CLIPRDR("hasCachedData: %u, rawTransfer: %d", cached_data ? 1u : 0u, rawTransfer);
1696
1697 if (!cached_data && !rawTransfer)
1698 {
1699 UINT32 srcFormatId = 0;
1700 BOOL nullTerminated = FALSE;
1701 xfCachedData* cached_raw_data = nullptr;
1702
1703 get_src_format_info_for_local_request(clipboard, cformat, &srcFormatId,
1704 &nullTerminated);
1705
1706 HashTable_Lock(clipboard->cachedRawData);
1707 cached_raw_data =
1708 HashTable_GetItemValue(clipboard->cachedRawData, (void*)(UINT_PTR)srcFormatId);
1709 HashTable_Unlock(clipboard->cachedRawData);
1710
1711 DEBUG_CLIPRDR("hasCachedRawData: %u, rawDataLength: %u", cached_raw_data ? 1u : 0u,
1712 cached_raw_data ? cached_raw_data->data_length : 0);
1713
1714 if (cached_raw_data && cached_raw_data->data_length != 0)
1715 cached_data = convert_data_from_existing_raw_data(
1716 clipboard, cached_raw_data, srcFormatId, nullTerminated, dstFormatId);
1717 }
1718
1719 DEBUG_CLIPRDR("hasCachedData: %u", cached_data ? 1u : 0u);
1720
1721 if (cached_data)
1722 {
1723 /* Cached clipboard data available. Send it now */
1724 respond->property = xevent->property;
1725
1726 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
1727 xf_cliprdr_provide_data(clipboard, respond, cached_data->data,
1728 cached_data->data_length);
1729 }
1730 else
1731 {
1732 SelectionResponse* selection_response = nullptr;
1733 WINPR_ASSERT(cformat);
1734
1735 if (!(selection_response =
1736 (SelectionResponse*)calloc(1, sizeof(SelectionResponse))))
1737 {
1738 respond->property = None;
1739 goto out;
1740 }
1741 respond->property = xevent->property;
1742
1743 selection_response->expectedResponse = respond;
1744 requested_format_replace(&selection_response->requestedFormat, formatId,
1745 dstFormatId, cformat->formatName);
1746 selection_response->data_raw_format = rawTransfer;
1747
1748 ArrayList_Lock(clipboard->pending_responses);
1749 ArrayList_Lock(clipboard->queued_responses);
1750 if (ArrayList_Count(clipboard->pending_responses) > 0)
1751 {
1752 BOOL shouldQueued = FALSE;
1753 BOOL success = FALSE;
1754 success = ArrayList_ForEach(clipboard->pending_responses,
1755 xf_cliprdr_pending_responses_ArrayList_ForEachFkt,
1756 formatId, &shouldQueued);
1757 if (!success || shouldQueued)
1758 {
1759 if (!ArrayList_Append(clipboard->queued_responses, selection_response))
1760 {
1761 requested_format_free(&selection_response->requestedFormat);
1762 free(selection_response);
1763 respond->property = None;
1764 goto out2;
1765 }
1766 }
1767 else
1768 {
1769 if (!ArrayList_Append(clipboard->pending_responses, selection_response))
1770 {
1771 requested_format_free(&selection_response->requestedFormat);
1772 free(selection_response);
1773 respond->property = None;
1774 goto out2;
1775 }
1776 }
1777 }
1778 else
1779 {
1780 if (!ArrayList_Append(clipboard->pending_responses, selection_response))
1781 {
1782 requested_format_free(&selection_response->requestedFormat);
1783 free(selection_response);
1784 respond->property = None;
1785 goto out2;
1786 }
1791 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership
1792 xf_cliprdr_send_data_request(clipboard, formatId, cformat);
1793 }
1794 delayRespond = TRUE;
1795 out2:
1796 ArrayList_Unlock(clipboard->queued_responses);
1797 ArrayList_Unlock(clipboard->pending_responses);
1798 }
1799 }
1800 }
1801
1802out:
1803 if (!delayRespond)
1804 {
1805 xf_cliprdr_provide_selection(clipboard, respond);
1806 free(respond);
1807 }
1808
1809 return TRUE;
1810}
1811
1812static BOOL xf_cliprdr_process_selection_clear(xfClipboard* clipboard,
1813 const XSelectionClearEvent* xevent)
1814{
1815 xfContext* xfc = nullptr;
1816
1817 WINPR_ASSERT(clipboard);
1818 WINPR_ASSERT(xevent);
1819
1820 xfc = clipboard->xfc;
1821 WINPR_ASSERT(xfc);
1822
1823 WINPR_UNUSED(xevent);
1824
1825 if (xf_cliprdr_is_self_owned(clipboard))
1826 return FALSE;
1827
1828 LogDynAndXDeleteProperty(clipboard->log, xfc->display, clipboard->root_window,
1829 clipboard->property_atom);
1830 return TRUE;
1831}
1832
1833static BOOL xf_cliprdr_process_property_notify(xfClipboard* clipboard, const XPropertyEvent* xevent)
1834{
1835 const xfCliprdrFormat* format = nullptr;
1836 xfContext* xfc = nullptr;
1837
1838 if (!clipboard)
1839 return TRUE;
1840
1841 xfc = clipboard->xfc;
1842 WINPR_ASSERT(xfc);
1843 WINPR_ASSERT(xevent);
1844
1845 if (xevent->atom == clipboard->timestamp_property_atom)
1846 {
1847 /* This is the response to the property change we did
1848 * in xf_cliprdr_prepare_to_set_selection_owner. Now
1849 * we can set ourselves as the selection owner. (See
1850 * comments in those functions below.) */
1851 xf_cliprdr_set_selection_owner(xfc, clipboard, xevent->time);
1852 return TRUE;
1853 }
1854
1855 if (xevent->atom != clipboard->property_atom)
1856 return FALSE; /* Not cliprdr-related */
1857
1858 if (xevent->window == clipboard->root_window)
1859 {
1860 xf_cliprdr_send_client_format_list(clipboard);
1861 }
1862 else if ((xevent->window == xfc->drawable) && (xevent->state == PropertyNewValue) &&
1863 clipboard->incr_starts)
1864 {
1865 format =
1866 xf_cliprdr_get_client_available_format_by_id(clipboard, clipboard->requestedFormatId);
1867
1868 if (format)
1869 xf_cliprdr_get_requested_data(clipboard, format->atom);
1870 }
1871
1872 return TRUE;
1873}
1874
1875void xf_cliprdr_handle_xevent(xfContext* xfc, const XEvent* event)
1876{
1877 xfClipboard* clipboard = nullptr;
1878
1879 if (!xfc || !event)
1880 return;
1881
1882 clipboard = xfc->clipboard;
1883
1884 if (!clipboard)
1885 return;
1886
1887#ifdef WITH_XFIXES
1888
1889 if (clipboard->xfixes_supported &&
1890 event->type == XFixesSelectionNotify + clipboard->xfixes_event_base)
1891 {
1892 const XFixesSelectionNotifyEvent* se = (const XFixesSelectionNotifyEvent*)event;
1893
1894 if (se->subtype == XFixesSetSelectionOwnerNotify)
1895 {
1896 if (se->selection != clipboard->clipboard_atom)
1897 return;
1898
1899 if (LogDynAndXGetSelectionOwner(clipboard->log, xfc->display, se->selection) ==
1900 xfc->drawable)
1901 return;
1902
1903 clipboard->owner = None;
1904 xf_cliprdr_check_owner(clipboard);
1905 }
1906
1907 return;
1908 }
1909
1910#endif
1911
1912 switch (event->type)
1913 {
1914 case SelectionNotify:
1915 log_selection_event(xfc, event);
1916 xf_cliprdr_process_selection_notify(clipboard, &event->xselection);
1917 break;
1918
1919 case SelectionRequest:
1920 log_selection_event(xfc, event);
1921 xf_cliprdr_process_selection_request(clipboard, &event->xselectionrequest);
1922 break;
1923
1924 case SelectionClear:
1925 log_selection_event(xfc, event);
1926 xf_cliprdr_process_selection_clear(clipboard, &event->xselectionclear);
1927 break;
1928
1929 case PropertyNotify:
1930 log_selection_event(xfc, event);
1931 xf_cliprdr_process_property_notify(clipboard, &event->xproperty);
1932 break;
1933
1934 case FocusIn:
1935 if (!clipboard->xfixes_supported)
1936 {
1937 xf_cliprdr_check_owner(clipboard);
1938 }
1939
1940 break;
1941 default:
1942 break;
1943 }
1944}
1945
1951static UINT xf_cliprdr_send_client_capabilities(xfClipboard* clipboard)
1952{
1953 CLIPRDR_CAPABILITIES capabilities = WINPR_C_ARRAY_INIT;
1954 CLIPRDR_GENERAL_CAPABILITY_SET generalCapabilitySet = WINPR_C_ARRAY_INIT;
1955
1956 WINPR_ASSERT(clipboard);
1957
1958 capabilities.cCapabilitiesSets = 1;
1959 capabilities.capabilitySets = (CLIPRDR_CAPABILITY_SET*)&(generalCapabilitySet);
1960 generalCapabilitySet.capabilitySetType = CB_CAPSTYPE_GENERAL;
1961 generalCapabilitySet.capabilitySetLength = 12;
1962 generalCapabilitySet.version = CB_CAPS_VERSION_2;
1963 generalCapabilitySet.generalFlags = CB_USE_LONG_FORMAT_NAMES;
1964
1965 WINPR_ASSERT(clipboard);
1966 generalCapabilitySet.generalFlags |= cliprdr_file_context_current_flags(clipboard->file);
1967
1968 if (!clipboard->context)
1969 return CHANNEL_RC_NOT_INITIALIZED;
1970 WINPR_ASSERT(clipboard->context->ClientCapabilities);
1971 return clipboard->context->ClientCapabilities(clipboard->context, &capabilities);
1972}
1973
1979static UINT xf_cliprdr_send_client_format_list(xfClipboard* clipboard)
1980{
1981 WINPR_ASSERT(clipboard);
1982
1983 xfContext* xfc = clipboard->xfc;
1984 WINPR_ASSERT(xfc);
1985
1986 if (clipboard->owner && clipboard->owner != xfc->drawable)
1987 {
1988 /* Request the owner for TARGETS, and wait for SelectionNotify event.
1989 * The format list is sent from there: what is in property_atom now are
1990 * the TARGETS of the previous owner, announcing them would be stale. */
1991 LogDynAndXDeleteProperty(clipboard->log, xfc->display, xfc->drawable,
1992 clipboard->property_atom);
1993 LogDynAndXConvertSelection(clipboard->log, xfc->display, clipboard->clipboard_atom,
1994 clipboard->targets[1], clipboard->property_atom, xfc->drawable,
1995 CurrentTime);
1996 return CHANNEL_RC_OK;
1997 }
1998
1999 UINT32 numFormats = 0;
2000 Atom* atoms = nullptr;
2001 size_t atomsCount = 0;
2002 CLIPRDR_FORMAT* formats = nullptr;
2003
2004 /* No owner: the clipboard is empty, whatever property_atom still holds. */
2005 if (clipboard->owner)
2006 formats = xf_cliprdr_get_client_formats(clipboard, &numFormats, &atoms, &atomsCount);
2007
2008 const UINT ret = xf_cliprdr_send_format_list(clipboard, formats, numFormats, atoms, atomsCount);
2009
2010 xf_cliprdr_free_formats(formats, numFormats);
2011
2012 return ret;
2013}
2014
2020static UINT xf_cliprdr_send_client_format_list_response(xfClipboard* clipboard, BOOL status)
2021{
2022 CLIPRDR_FORMAT_LIST_RESPONSE formatListResponse = WINPR_C_ARRAY_INIT;
2023
2024 formatListResponse.common.msgType = CB_FORMAT_LIST_RESPONSE;
2025 formatListResponse.common.msgFlags = status ? CB_RESPONSE_OK : CB_RESPONSE_FAIL;
2026 formatListResponse.common.dataLen = 0;
2027
2028 WINPR_ASSERT(clipboard);
2029 if (!clipboard->context)
2030 return CHANNEL_RC_NOT_INITIALIZED;
2031 WINPR_ASSERT(clipboard->context->ClientFormatListResponse);
2032 return clipboard->context->ClientFormatListResponse(clipboard->context, &formatListResponse);
2033}
2034
2040static UINT xf_cliprdr_monitor_ready(CliprdrClientContext* context,
2041 const CLIPRDR_MONITOR_READY* monitorReady)
2042{
2043 WINPR_ASSERT(context);
2044 WINPR_ASSERT(monitorReady);
2045
2046 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2047 WINPR_ASSERT(clipboard);
2048
2049 WINPR_UNUSED(monitorReady);
2050
2051 const UINT ret = xf_cliprdr_send_client_capabilities(clipboard);
2052 if (ret != CHANNEL_RC_OK)
2053 return ret;
2054
2055 const UINT ret2 = xf_cliprdr_send_client_format_list(clipboard);
2056 if (ret2 != CHANNEL_RC_OK)
2057 return ret2;
2058
2059 clipboard->sync = TRUE;
2060 return CHANNEL_RC_OK;
2061}
2062
2068static UINT xf_cliprdr_server_capabilities(CliprdrClientContext* context,
2069 const CLIPRDR_CAPABILITIES* capabilities)
2070{
2071 WINPR_ASSERT(context);
2072 WINPR_ASSERT(capabilities);
2073
2074 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2075 WINPR_ASSERT(clipboard);
2076
2077 const BYTE* capsPtr = (const BYTE*)capabilities->capabilitySets;
2078 WINPR_ASSERT(capsPtr);
2079
2080 if (!cliprdr_file_context_remote_set_flags(clipboard->file, 0))
2081 return ERROR_INTERNAL_ERROR;
2082
2083 for (UINT32 i = 0; i < capabilities->cCapabilitiesSets; i++)
2084 {
2085 const CLIPRDR_CAPABILITY_SET* caps =
2086 WINPR_PACKED_ALIGN_CAST(const CLIPRDR_CAPABILITY_SET*, capsPtr);
2087
2088 if (caps->capabilitySetType == CB_CAPSTYPE_GENERAL)
2089 {
2090 const CLIPRDR_GENERAL_CAPABILITY_SET* generalCaps =
2091 WINPR_PACKED_ALIGN_CAST(const CLIPRDR_GENERAL_CAPABILITY_SET*, caps);
2092
2093 if (!cliprdr_file_context_remote_set_flags(clipboard->file, generalCaps->generalFlags))
2094 return ERROR_INTERNAL_ERROR;
2095 }
2096
2097 capsPtr += caps->capabilitySetLength;
2098 }
2099
2100 return CHANNEL_RC_OK;
2101}
2102
2103static void xf_cliprdr_prepare_to_set_selection_owner(xfContext* xfc, xfClipboard* clipboard)
2104{
2105 WINPR_ASSERT(xfc);
2106 WINPR_ASSERT(clipboard);
2107 /*
2108 * When you're writing to the selection in response to a
2109 * normal X event like a mouse click or keyboard action, you
2110 * get the selection timestamp by copying the time field out
2111 * of that X event. Here, we're doing it on our own
2112 * initiative, so we have to _request_ the X server time.
2113 *
2114 * There isn't a GetServerTime request in the X protocol, so I
2115 * work around it by setting a property on our own window, and
2116 * waiting for a PropertyNotify event to come back telling me
2117 * it's been done - which will have a timestamp we can use.
2118 */
2119
2120 /* We have to set the property to some value, but it doesn't
2121 * matter what. Set it to its own name, which we have here
2122 * anyway! */
2123 Atom value = clipboard->timestamp_property_atom;
2124
2125 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
2126 clipboard->timestamp_property_atom, XA_ATOM, 32, PropModeReplace,
2127 (const BYTE*)&value, 1);
2128 LogDynAndXFlush(clipboard->log, xfc->display);
2129}
2130
2131static void xf_cliprdr_set_selection_owner(xfContext* xfc, xfClipboard* clipboard, Time timestamp)
2132{
2133 WINPR_ASSERT(xfc);
2134 WINPR_ASSERT(clipboard);
2135 /*
2136 * Actually set ourselves up as the selection owner, now that
2137 * we have a timestamp to use.
2138 */
2139
2140 clipboard->selection_ownership_timestamp = timestamp;
2141 LogDynAndXSetSelectionOwner(clipboard->log, xfc->display, clipboard->clipboard_atom,
2142 xfc->drawable, timestamp);
2143 LogDynAndXFlush(clipboard->log, xfc->display);
2144}
2145
2151static UINT xf_cliprdr_server_format_list(CliprdrClientContext* context,
2152 const CLIPRDR_FORMAT_LIST* formatList)
2153{
2154 xfContext* xfc = nullptr;
2155 UINT ret = 0;
2156 xfClipboard* clipboard = nullptr;
2157
2158 WINPR_ASSERT(context);
2159 WINPR_ASSERT(formatList);
2160
2161 clipboard = cliprdr_file_context_get_context(context->custom);
2162 WINPR_ASSERT(clipboard);
2163
2164 xfc = clipboard->xfc;
2165 WINPR_ASSERT(xfc);
2166
2167 xf_lock_x11(xfc);
2168
2169 /* Clear the active SelectionRequest, as it is now invalid */
2170 ArrayList_Clear(clipboard->pending_responses);
2171 ArrayList_Clear(clipboard->queued_responses);
2172
2173 xf_cliprdr_clear_cached_data(clipboard);
2174
2175 xf_clipboard_free_server_formats(clipboard);
2176
2177 clipboard->numServerFormats = formatList->numFormats + 1; /* +1 for CF_RAW */
2178
2179 if (!(clipboard->serverFormats =
2180 (CLIPRDR_FORMAT*)calloc(clipboard->numServerFormats, sizeof(CLIPRDR_FORMAT))))
2181 {
2182 WLog_Print(clipboard->log, WLOG_ERROR,
2183 "failed to allocate %" PRIu32 " CLIPRDR_FORMAT structs",
2184 clipboard->numServerFormats);
2185 ret = CHANNEL_RC_NO_MEMORY;
2186 goto out;
2187 }
2188
2189 for (size_t i = 0; i < formatList->numFormats; i++)
2190 {
2191 const CLIPRDR_FORMAT* format = &formatList->formats[i];
2192 CLIPRDR_FORMAT* srvFormat = &clipboard->serverFormats[i];
2193
2194 srvFormat->formatId = format->formatId;
2195
2196 if (format->formatName)
2197 {
2198 srvFormat->formatName = _strdup(format->formatName);
2199
2200 if (!srvFormat->formatName)
2201 {
2202 for (UINT32 k = 0; k < i; k++)
2203 free(clipboard->serverFormats[k].formatName);
2204
2205 clipboard->numServerFormats = 0;
2206 free(clipboard->serverFormats);
2207 clipboard->serverFormats = nullptr;
2208 ret = CHANNEL_RC_NO_MEMORY;
2209 goto out;
2210 }
2211 }
2212 }
2213
2214 ClipboardLock(clipboard->system);
2215 ret = cliprdr_file_context_notify_new_server_format_list(clipboard->file);
2216 ClipboardUnlock(clipboard->system);
2217 if (ret)
2218 goto out;
2219
2220 /* CF_RAW is always implicitly supported by the server */
2221 {
2222 CLIPRDR_FORMAT* format = &clipboard->serverFormats[formatList->numFormats];
2223 format->formatId = CF_RAW;
2224 format->formatName = nullptr;
2225 }
2226 xf_cliprdr_provide_server_format_list(clipboard);
2227 clipboard->numTargets = 2;
2228
2229 for (size_t i = 0; i < formatList->numFormats; i++)
2230 {
2231 const CLIPRDR_FORMAT* format = &formatList->formats[i];
2232
2233 for (size_t j = 0; j < clipboard->numClientFormats; j++)
2234 {
2235 const xfCliprdrFormat* clientFormat = &clipboard->clientFormats[j];
2236 if (xf_cliprdr_formats_equal(format, clientFormat))
2237 {
2238 if ((clientFormat->formatName != nullptr) &&
2239 (strcmp(type_FileGroupDescriptorW, clientFormat->formatName) == 0))
2240 {
2241 if (!cliprdr_file_context_has_local_support(clipboard->file))
2242 continue;
2243 }
2244 xf_cliprdr_append_target(clipboard, clientFormat->atom);
2245 }
2246 }
2247 }
2248
2249 ret = xf_cliprdr_send_client_format_list_response(clipboard, TRUE);
2250 if (xfc->remote_app)
2251 xf_cliprdr_set_selection_owner(xfc, clipboard, CurrentTime);
2252 else
2253 xf_cliprdr_prepare_to_set_selection_owner(xfc, clipboard);
2254
2255out:
2256 xf_unlock_x11(xfc);
2257
2258 return ret;
2259}
2260
2266static UINT xf_cliprdr_server_format_list_response(
2267 WINPR_ATTR_UNUSED CliprdrClientContext* context,
2268 WINPR_ATTR_UNUSED const CLIPRDR_FORMAT_LIST_RESPONSE* formatListResponse)
2269{
2270 WINPR_ASSERT(context);
2271 WINPR_ASSERT(formatListResponse);
2272 // xfClipboard* clipboard = (xfClipboard*) context->custom;
2273 return CHANNEL_RC_OK;
2274}
2275
2281static UINT
2282xf_cliprdr_server_format_data_request(CliprdrClientContext* context,
2283 const CLIPRDR_FORMAT_DATA_REQUEST* formatDataRequest)
2284{
2285 const xfCliprdrFormat* format = nullptr;
2286
2287 WINPR_ASSERT(context);
2288 WINPR_ASSERT(formatDataRequest);
2289
2290 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2291 WINPR_ASSERT(clipboard);
2292
2293 xfContext* xfc = clipboard->xfc;
2294 WINPR_ASSERT(xfc);
2295
2296 const uint32_t formatId = formatDataRequest->requestedFormatId;
2297
2298 const UINT32 mask =
2299 freerdp_settings_get_uint32(context->rdpcontext->settings, FreeRDP_ClipboardFeatureMask);
2300 const UINT32 fileId = ClipboardRegisterFormat(clipboard->system, type_FileGroupDescriptorW);
2301 if (fileId == formatDataRequest->requestedFormatId)
2302 {
2303 if ((mask & CLIPRDR_FLAG_LOCAL_TO_REMOTE_FILES) == 0)
2304 return xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
2305 }
2306 else
2307 {
2308 if ((mask & CLIPRDR_FLAG_LOCAL_TO_REMOTE) == 0)
2309 return xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
2310 }
2311 const BOOL rawTransfer = xf_cliprdr_is_raw_transfer_available(clipboard);
2312
2313 if (rawTransfer)
2314 {
2315 format = xf_cliprdr_get_client_available_format_by_id(clipboard, CF_RAW);
2316 LogDynAndXChangeProperty(clipboard->log, xfc->display, xfc->drawable,
2317 clipboard->property_atom, XA_INTEGER, 32, PropModeReplace,
2318 (const BYTE*)&formatId, 1);
2319 }
2320 else
2321 format = xf_cliprdr_get_client_available_format_by_id(clipboard, formatId);
2322
2323 clipboard->requestedFormatId = rawTransfer ? CF_RAW : formatId;
2324 if (!format)
2325 return xf_cliprdr_send_data_response(clipboard, format, nullptr, 0);
2326
2327 DEBUG_CLIPRDR("requested format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 " [%s]} [%s]",
2328 format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest),
2329 format->localFormat,
2330 ClipboardGetFormatName(clipboard->system, format->localFormat),
2331 format->formatName);
2332 LogDynAndXConvertSelection(clipboard->log, xfc->display, clipboard->clipboard_atom,
2333 format->atom, clipboard->property_atom, xfc->drawable, CurrentTime);
2334 LogDynAndXFlush(clipboard->log, xfc->display);
2335 /* After this point, we expect a SelectionNotify event from the clipboard owner. */
2336 return CHANNEL_RC_OK;
2337}
2338
2344static UINT
2345xf_cliprdr_server_format_data_response(CliprdrClientContext* context,
2346 const CLIPRDR_FORMAT_DATA_RESPONSE* formatDataResponse)
2347{
2348 BOOL bSuccess = FALSE;
2349 BOOL bRawCached = FALSE;
2350 BOOL bFileContextUpdated = FALSE;
2351
2352 WINPR_ASSERT(context);
2353 WINPR_ASSERT(formatDataResponse);
2354
2355 xfClipboard* clipboard = cliprdr_file_context_get_context(context->custom);
2356 WINPR_ASSERT(clipboard);
2357
2358 xfContext* xfc = clipboard->xfc;
2359 WINPR_ASSERT(xfc);
2360
2361 const UINT32 size = formatDataResponse->common.dataLen;
2362 const BYTE* data = formatDataResponse->requestedFormatData;
2363
2364 // Keep the same lock order as process_selection_request to prevent deadlock
2365 xf_lock_x11(xfc);
2366 ArrayList_Lock(clipboard->pending_responses);
2367 ArrayList_Lock(clipboard->queued_responses);
2368 if (formatDataResponse->common.msgFlags == CB_RESPONSE_FAIL)
2369 {
2370 WLog_Print(clipboard->log, WLOG_WARN,
2371 "Format Data Response PDU msgFlags is CB_RESPONSE_FAIL");
2372 while (ArrayList_Count(clipboard->pending_responses) > 0)
2373 {
2374 SelectionResponse* pending = ArrayList_GetItem(clipboard->pending_responses, 0);
2375
2376 pending->expectedResponse->property = None;
2377 xf_cliprdr_provide_selection(clipboard, pending->expectedResponse);
2378
2379 ArrayList_Remove(clipboard->pending_responses, pending);
2380 }
2381 WINPR_ASSERT(ArrayList_Count(clipboard->pending_responses) == 0);
2382 }
2383
2384 while (ArrayList_Count(clipboard->pending_responses) > 0)
2385 {
2386 BYTE* pDstData = nullptr;
2387 UINT32 DstSize = 0;
2388 UINT32 SrcSize = 0;
2389 UINT32 srcFormatId = 0;
2390 UINT32 dstFormatId = 0;
2391 BOOL nullTerminated = FALSE;
2392 xfCachedData* cached_data = nullptr;
2393 xfCachedData* hit_cached_data = nullptr;
2394
2395 SelectionResponse* pending = ArrayList_GetItem(clipboard->pending_responses, 0);
2396 const RequestedFormat* format = pending->requestedFormat;
2397 if (pending->data_raw_format)
2398 {
2399 srcFormatId = CF_RAW;
2400 dstFormatId = CF_RAW;
2401 }
2402 else if (!format)
2403 {
2404 pending->expectedResponse->property = None;
2405 goto out;
2406 }
2407 else if (format->formatName)
2408 {
2409 dstFormatId = format->localFormat;
2410
2411 ClipboardLock(clipboard->system);
2412 if (strcmp(format->formatName, type_HtmlFormat) == 0)
2413 {
2414 srcFormatId = ClipboardGetFormatId(clipboard->system, type_HtmlFormat);
2415 dstFormatId = ClipboardGetFormatId(clipboard->system, mime_html);
2416 nullTerminated = TRUE;
2417 }
2418
2419 if (strcmp(format->formatName, type_FileGroupDescriptorW) == 0)
2420 {
2421 if (!bFileContextUpdated)
2422 {
2423 if (!cliprdr_file_context_update_server_data(clipboard->file, clipboard->system,
2424 data, size))
2425 WLog_Print(clipboard->log, WLOG_WARN, "failed to update file descriptors");
2426 else
2427 bFileContextUpdated = TRUE;
2428 }
2429
2430 srcFormatId = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW);
2431 const xfCliprdrFormat* dstTargetFormat = xf_cliprdr_get_client_format_by_atom(
2432 clipboard, pending->expectedResponse->target);
2433 if (!dstTargetFormat)
2434 {
2435 dstFormatId = ClipboardGetFormatId(clipboard->system, mime_uri_list);
2436 }
2437 else
2438 {
2439 dstFormatId = dstTargetFormat->localFormat;
2440 }
2441
2442 nullTerminated = TRUE;
2443 }
2444 ClipboardUnlock(clipboard->system);
2445 }
2446 else
2447 {
2448 srcFormatId = format->formatToRequest;
2449 dstFormatId = format->localFormat;
2450 switch (format->formatToRequest)
2451 {
2452 case CF_TEXT:
2453 nullTerminated = TRUE;
2454 break;
2455
2456 case CF_OEMTEXT:
2457 nullTerminated = TRUE;
2458 break;
2459
2460 case CF_UNICODETEXT:
2461 nullTerminated = TRUE;
2462 break;
2463
2464 case CF_DIB:
2465 srcFormatId = CF_DIB;
2466 break;
2467
2468 case CF_TIFF:
2469 srcFormatId = CF_TIFF;
2470 break;
2471
2472 default:
2473 break;
2474 }
2475 }
2476
2477 DEBUG_CLIPRDR("requested format 0x%08" PRIx32 " [%s] {local 0x%08" PRIx32 " [%s]} [%s]",
2478 format->formatToRequest, ClipboardGetFormatIdString(format->formatToRequest),
2479 format->localFormat,
2480 ClipboardGetFormatName(clipboard->system, format->localFormat),
2481 format->formatName);
2482 SrcSize = size;
2483
2484 DEBUG_CLIPRDR("srcFormatId: 0x%08" PRIx32 ", dstFormatId: 0x%08" PRIx32 "", srcFormatId,
2485 dstFormatId);
2486
2487 if (SrcSize != 0 && !bRawCached)
2488 {
2489 /* We have to copy the original data again, as pSrcData is now owned
2490 * by clipboard->system. Memory allocation failure is not fatal here
2491 * as this is only a cached value. */
2492 {
2493 // clipboard->cachedData owns cached_data
2494 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc
2495 xfCachedData* cached_raw_data = xf_cached_data_new_copy(data, size);
2496 if (!cached_raw_data)
2497 WLog_Print(clipboard->log, WLOG_WARN, "Failed to allocate cache entry");
2498 else
2499 {
2500 if (!(bRawCached =
2501 HashTable_Insert(clipboard->cachedRawData,
2502 (void*)(UINT_PTR)srcFormatId, cached_raw_data)))
2503 {
2504 WLog_Print(clipboard->log, WLOG_WARN, "Failed to cache clipboard data");
2505 xf_cached_data_free(cached_raw_data);
2506 }
2507 }
2508 }
2509 }
2510
2511 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership
2512 if (SrcSize == 0)
2513 {
2514 WLog_Print(clipboard->log, WLOG_DEBUG, "skipping, empty data detected!");
2515 goto out;
2516 }
2517
2518 if (!bSuccess)
2519 {
2520 ClipboardLock(clipboard->system);
2521 bSuccess = ClipboardSetData(clipboard->system, srcFormatId, data, SrcSize);
2522 ClipboardUnlock(clipboard->system);
2523 }
2524
2525 if (!bSuccess)
2526 {
2527 WLog_Print(clipboard->log, WLOG_DEBUG, "skipping, ClipboardSetData failed!");
2528 goto out;
2529 }
2530
2531 wHashTable* table = clipboard->cachedData;
2532 if (pending->data_raw_format)
2533 table = clipboard->cachedRawData;
2534
2535 HashTable_Lock(table);
2536
2537 if (!pending->data_raw_format)
2538 hit_cached_data = HashTable_GetItemValue(table, format_to_cache_slot(dstFormatId));
2539 else
2540 hit_cached_data = HashTable_GetItemValue(table, format_to_cache_slot(srcFormatId));
2541
2542 HashTable_Unlock(table);
2543
2544 DEBUG_CLIPRDR("hasCachedData: %u, pending->data_raw_format: %d", hit_cached_data ? 1u : 0u,
2545 pending->data_raw_format);
2546
2547 ClipboardLock(clipboard->system);
2548 if (hit_cached_data)
2549 {
2550 pDstData = hit_cached_data->data;
2551 DstSize = hit_cached_data->data_length;
2552 }
2553 else
2554 {
2555 pDstData = (BYTE*)ClipboardGetData(clipboard->system, dstFormatId, &DstSize);
2556 }
2557
2558 if (!pDstData)
2559 {
2560 WLog_Print(clipboard->log, WLOG_WARN,
2561 "failed to get clipboard data in format %s [source format %s]",
2562 ClipboardGetFormatName(clipboard->system, dstFormatId),
2563 ClipboardGetFormatName(clipboard->system, srcFormatId));
2564 }
2565 ClipboardUnlock(clipboard->system);
2566
2567 if (!pDstData)
2568 {
2569 pending->expectedResponse->property = None;
2570 goto out;
2571 }
2572
2573 if (nullTerminated && pDstData)
2574 {
2575 BYTE* nullTerminator = memchr(pDstData, '\0', DstSize);
2576 if (nullTerminator)
2577 {
2578 const intptr_t diff = nullTerminator - pDstData;
2579 WINPR_ASSERT(diff >= 0);
2580 WINPR_ASSERT(diff <= UINT32_MAX);
2581 DstSize = (UINT32)diff;
2582 }
2583 }
2584
2585 // clipboard->cachedRawData owns cached_raw_data
2586 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
2587 xf_cliprdr_provide_data(clipboard, pending->expectedResponse, pDstData, DstSize);
2588
2589 if (!hit_cached_data && pDstData)
2590 {
2591 cached_data = xf_cached_data_new(pDstData, DstSize);
2592 if (!cached_data)
2593 {
2594
2595 free(pDstData);
2596 WLog_Print(clipboard->log, WLOG_WARN, "Failed to allocate cache entry");
2597 }
2598 else
2599 {
2600 HashTable_Lock(clipboard->cachedData);
2601 if (!HashTable_Insert(clipboard->cachedData, format_to_cache_slot(dstFormatId),
2602 cached_data))
2603 {
2604 WLog_Print(clipboard->log, WLOG_WARN, "Failed to cache clipboard data");
2605 xf_cached_data_free(cached_data);
2606 }
2607 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert takes ownership
2608 HashTable_Unlock(clipboard->cachedData);
2609 }
2610 }
2611
2612 out:
2613 xf_cliprdr_provide_selection(clipboard, pending->expectedResponse);
2614
2615 ArrayList_Remove(clipboard->pending_responses, pending);
2616 }
2617
2618 // Processing data request for next formatId
2619 WINPR_ASSERT(ArrayList_Count(clipboard->pending_responses) == 0);
2620
2621 SelectionResponse* next = ArrayList_GetItem(clipboard->queued_responses, 0);
2622 if (next)
2623 {
2624 UINT32 nextFormatId = next->requestedFormat->formatToRequest;
2625 const xfCliprdrFormat* cformat =
2626 xf_cliprdr_get_client_format_by_atom(clipboard, next->expectedResponse->target);
2627
2628 size_t index = 0;
2629 while ((next = ArrayList_GetItem(clipboard->queued_responses, index)) != nullptr)
2630 {
2631 if (next->requestedFormat->formatToRequest == nextFormatId)
2632 {
2633 /* First set item to nullptr, then remove/free the element. Avoids double free */
2634 if (!ArrayList_SetItem(clipboard->queued_responses, index, nullptr))
2635 goto fail;
2636 ArrayList_RemoveAt(clipboard->queued_responses, index);
2637 if (!ArrayList_Append(clipboard->pending_responses, next))
2638 {
2639 selection_response_free(next);
2640 }
2641 }
2642 else
2643 index++;
2644 }
2645
2646 fail:
2647 xf_cliprdr_send_data_request(clipboard, nextFormatId, cformat);
2648 }
2649
2650 ArrayList_Unlock(clipboard->queued_responses);
2651 ArrayList_Unlock(clipboard->pending_responses);
2652 xf_unlock_x11(xfc);
2653
2654 return CHANNEL_RC_OK;
2655}
2656
2657static BOOL xf_cliprdr_is_valid_unix_filename(LPCWSTR filename)
2658{
2659 if (!filename)
2660 return FALSE;
2661
2662 if (filename[0] == L'\0')
2663 return FALSE;
2664
2665 /* Reserved characters */
2666 for (const WCHAR* c = filename; *c; ++c)
2667 {
2668 if (*c == L'/')
2669 return FALSE;
2670 }
2671
2672 return TRUE;
2673}
2674
2675xfClipboard* xf_clipboard_new(xfContext* xfc, BOOL relieveFilenameRestriction)
2676{
2677 int n = 0;
2678 rdpChannels* channels = nullptr;
2679 const char* selectionAtom = nullptr;
2680 xfCliprdrFormat* clientFormat = nullptr;
2681 wObject* obj = nullptr;
2682
2683 WINPR_ASSERT(xfc);
2684 WINPR_ASSERT(xfc->common.context.settings);
2685
2686 xfClipboard* clipboard = (xfClipboard*)calloc(1, sizeof(xfClipboard));
2687 if (!clipboard)
2688 return nullptr;
2689
2690 clipboard->log = WLog_Get(TAG);
2691 if (!clipboard->log)
2692 goto fail;
2693
2694 clipboard->file = cliprdr_file_context_new(clipboard);
2695 if (!clipboard->file)
2696 goto fail;
2697
2698 xfc->clipboard = clipboard;
2699 clipboard->xfc = xfc;
2700 channels = xfc->common.context.channels;
2701 clipboard->channels = channels;
2702 clipboard->system = ClipboardCreate();
2703 clipboard->requestedFormatId = UINT32_MAX;
2704 clipboard->root_window = DefaultRootWindow(xfc->display);
2705
2706 selectionAtom =
2707 freerdp_settings_get_string(xfc->common.context.settings, FreeRDP_ClipboardUseSelection);
2708 if (!selectionAtom)
2709 selectionAtom = "CLIPBOARD";
2710
2711 clipboard->clipboard_atom =
2712 Logging_XInternAtom(clipboard->log, xfc->display, selectionAtom, FALSE);
2713
2714 if (clipboard->clipboard_atom == None)
2715 {
2716 WLog_Print(clipboard->log, WLOG_ERROR, "unable to get %s atom", selectionAtom);
2717 goto fail;
2718 }
2719
2720 clipboard->timestamp_property_atom =
2721 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_TIMESTAMP_PROPERTY", FALSE);
2722 clipboard->property_atom =
2723 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR", FALSE);
2724 clipboard->raw_transfer_atom =
2725 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR_RAW", FALSE);
2726 clipboard->raw_format_list_atom =
2727 Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_CLIPRDR_FORMATS", FALSE);
2728 xf_cliprdr_set_raw_transfer_enabled(clipboard, TRUE);
2729 LogDynAndXSelectInput(clipboard->log, xfc->display, clipboard->root_window, PropertyChangeMask);
2730#ifdef WITH_XFIXES
2731
2732 if (XFixesQueryExtension(xfc->display, &clipboard->xfixes_event_base,
2733 &clipboard->xfixes_error_base))
2734 {
2735 int xfmajor = 0;
2736 int xfminor = 0;
2737
2738 if (XFixesQueryVersion(xfc->display, &xfmajor, &xfminor))
2739 {
2740 XFixesSelectSelectionInput(xfc->display, clipboard->root_window,
2741 clipboard->clipboard_atom,
2742 XFixesSetSelectionOwnerNotifyMask);
2743 clipboard->xfixes_supported = TRUE;
2744 }
2745 else
2746 {
2747 WLog_Print(clipboard->log, WLOG_ERROR, "Error querying X Fixes extension version");
2748 }
2749 }
2750 else
2751 {
2752 WLog_Print(clipboard->log, WLOG_ERROR, "Error loading X Fixes extension");
2753 }
2754
2755#else
2756 WLog_ERR(
2757 TAG,
2758 "Warning: Using clipboard redirection without XFIXES extension is strongly discouraged!");
2759#endif
2760 clientFormat = &clipboard->clientFormats[n++];
2761 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, "_FREERDP_RAW", False);
2762 clientFormat->localFormat = clientFormat->formatToRequest = CF_RAW;
2763
2764 clientFormat = &clipboard->clientFormats[n++];
2765 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, "UTF8_STRING", False);
2766 clientFormat->formatToRequest = CF_UNICODETEXT;
2767 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_text_utf8);
2768
2769 clientFormat = &clipboard->clientFormats[n++];
2770 clientFormat->atom = XA_STRING;
2771 clientFormat->formatToRequest = CF_TEXT;
2772 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_text_plain);
2773
2774 clientFormat = &clipboard->clientFormats[n++];
2775 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_tiff, False);
2776 clientFormat->formatToRequest = clientFormat->localFormat = CF_TIFF;
2777
2778 for (size_t x = 0; x < ARRAYSIZE(mime_bitmap); x++)
2779 {
2780 const char* mime_bmp = mime_bitmap[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 for (size_t x = 0; x < ARRAYSIZE(mime_images); x++)
2799 {
2800 const char* mime_bmp = mime_images[x];
2801 const DWORD format = ClipboardGetFormatId(xfc->clipboard->system, mime_bmp);
2802 if (format == 0)
2803 {
2804 WLog_Print(clipboard->log, WLOG_DEBUG,
2805 "skipping local bitmap format %s [NOT SUPPORTED]", mime_bmp);
2806 continue;
2807 }
2808
2809 WLog_Print(clipboard->log, WLOG_DEBUG, "register local bitmap format %s [0x%08" PRIx32 "]",
2810 mime_bmp, format);
2811 clientFormat = &clipboard->clientFormats[n++];
2812 clientFormat->localFormat = format;
2813 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_bmp, False);
2814 clientFormat->formatToRequest = CF_DIB;
2815 clientFormat->isImage = TRUE;
2816 }
2817
2818 clientFormat = &clipboard->clientFormats[n++];
2819 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display, mime_html, False);
2820 clientFormat->formatToRequest = ClipboardGetFormatId(xfc->clipboard->system, type_HtmlFormat);
2821 clientFormat->localFormat = ClipboardGetFormatId(xfc->clipboard->system, mime_html);
2822 clientFormat->formatName = _strdup(type_HtmlFormat);
2823
2824 if (!clientFormat->formatName)
2825 goto fail;
2826
2827 clientFormat = &clipboard->clientFormats[n++];
2828
2829 /*
2830 * Existence of registered format IDs for file formats does not guarantee that they are
2831 * in fact supported by wClipboard (as further initialization may have failed after format
2832 * registration). However, they are definitely not supported if there are no registered
2833 * formats. In this case we should not list file formats in TARGETS.
2834 */
2835 {
2836 const UINT32 fgid = ClipboardGetFormatId(clipboard->system, type_FileGroupDescriptorW);
2837 {
2838 const UINT32 uid = ClipboardGetFormatId(clipboard->system, mime_uri_list);
2839 if (uid)
2840 {
2841 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2842 goto fail;
2843 clientFormat->atom =
2844 Logging_XInternAtom(clipboard->log, xfc->display, mime_uri_list, False);
2845 clientFormat->localFormat = uid;
2846 clientFormat->formatToRequest = fgid;
2847 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2848
2849 if (!clientFormat->formatName)
2850 goto fail;
2851
2852 clientFormat = &clipboard->clientFormats[n++];
2853 }
2854 }
2855
2856 {
2857 const UINT32 gid = ClipboardGetFormatId(clipboard->system, mime_gnome_copied_files);
2858 if (gid != 0)
2859 {
2860 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2861 goto fail;
2862 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display,
2863 mime_gnome_copied_files, False);
2864 clientFormat->localFormat = gid;
2865 clientFormat->formatToRequest = fgid;
2866 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2867
2868 if (!clientFormat->formatName)
2869 goto fail;
2870
2871 clientFormat = &clipboard->clientFormats[n++];
2872 }
2873 }
2874
2875 {
2876 const UINT32 mid = ClipboardGetFormatId(clipboard->system, mime_mate_copied_files);
2877 if (mid != 0)
2878 {
2879 if (!cliprdr_file_context_set_locally_available(clipboard->file, TRUE))
2880 goto fail;
2881 clientFormat->atom = Logging_XInternAtom(clipboard->log, xfc->display,
2882 mime_mate_copied_files, False);
2883 clientFormat->localFormat = mid;
2884 clientFormat->formatToRequest = fgid;
2885 clientFormat->formatName = _strdup(type_FileGroupDescriptorW);
2886
2887 if (!clientFormat->formatName)
2888 goto fail;
2889 }
2890 }
2891 }
2892
2893 clipboard->numClientFormats = WINPR_ASSERTING_INT_CAST(uint32_t, n);
2894 clipboard->targets[0] = Logging_XInternAtom(clipboard->log, xfc->display, "TIMESTAMP", FALSE);
2895 clipboard->targets[1] = Logging_XInternAtom(clipboard->log, xfc->display, "TARGETS", FALSE);
2896 clipboard->numTargets = 2;
2897 clipboard->incr_atom = Logging_XInternAtom(clipboard->log, xfc->display, "INCR", FALSE);
2898
2899 if (relieveFilenameRestriction)
2900 {
2901 WLog_Print(clipboard->log, WLOG_DEBUG, "Relieving CLIPRDR filename restriction");
2902 ClipboardGetDelegate(clipboard->system)->IsFileNameComponentValid =
2903 xf_cliprdr_is_valid_unix_filename;
2904 }
2905
2906 clipboard->cachedData = HashTable_New(TRUE);
2907 if (!clipboard->cachedData)
2908 goto fail;
2909
2910 obj = HashTable_ValueObject(clipboard->cachedData);
2911 obj->fnObjectFree = xf_cached_data_free;
2912
2913 clipboard->cachedRawData = HashTable_New(TRUE);
2914 if (!clipboard->cachedRawData)
2915 goto fail;
2916
2917 obj = HashTable_ValueObject(clipboard->cachedRawData);
2918 obj->fnObjectFree = xf_cached_data_free;
2919
2920 clipboard->pending_responses = ArrayList_New(TRUE);
2921 if (!clipboard->pending_responses)
2922 goto fail;
2923 obj = ArrayList_Object(clipboard->pending_responses);
2924 obj->fnObjectFree = selection_response_free;
2925
2926 clipboard->queued_responses = ArrayList_New(TRUE);
2927 if (!clipboard->queued_responses)
2928 goto fail;
2929 obj = ArrayList_Object(clipboard->queued_responses);
2930 obj->fnObjectFree = selection_response_free;
2931
2932 return clipboard;
2933
2934fail:
2935 WINPR_PRAGMA_DIAG_PUSH
2936 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
2937 xf_clipboard_free(clipboard);
2938 WINPR_PRAGMA_DIAG_POP
2939 return nullptr;
2940}
2941
2942void xf_clipboard_free(xfClipboard* clipboard)
2943{
2944 if (!clipboard)
2945 return;
2946
2947 xf_clipboard_free_server_formats(clipboard);
2948
2949 for (UINT32 i = 0; i < clipboard->numClientFormats; i++)
2950 {
2951 xfCliprdrFormat* format = &clipboard->clientFormats[i];
2952 free(format->formatName);
2953 }
2954
2955 cliprdr_file_context_free(clipboard->file);
2956
2957 XFree(clipboard->clientAvailableFormatAtoms);
2958
2959 ClipboardDestroy(clipboard->system);
2960 HashTable_Free(clipboard->cachedRawData);
2961 HashTable_Free(clipboard->cachedData);
2962 ArrayList_Free(clipboard->pending_responses);
2963 ArrayList_Free(clipboard->queued_responses);
2964 free(clipboard->incr_data);
2965 free(clipboard);
2966}
2967
2968void xf_cliprdr_init(xfContext* xfc, CliprdrClientContext* cliprdr)
2969{
2970 WINPR_ASSERT(xfc);
2971 WINPR_ASSERT(cliprdr);
2972
2973 xfc->cliprdr = cliprdr;
2974 xfc->clipboard->context = cliprdr;
2975
2976 cliprdr->MonitorReady = xf_cliprdr_monitor_ready;
2977 cliprdr->ServerCapabilities = xf_cliprdr_server_capabilities;
2978 cliprdr->ServerFormatList = xf_cliprdr_server_format_list;
2979 cliprdr->ServerFormatListResponse = xf_cliprdr_server_format_list_response;
2980 cliprdr->ServerFormatDataRequest = xf_cliprdr_server_format_data_request;
2981 cliprdr->ServerFormatDataResponse = xf_cliprdr_server_format_data_response;
2982
2983 cliprdr_file_context_init(xfc->clipboard->file, cliprdr);
2984}
2985
2986void xf_cliprdr_uninit(xfContext* xfc, CliprdrClientContext* cliprdr)
2987{
2988 WINPR_ASSERT(xfc);
2989
2990 xfc->cliprdr = nullptr;
2991
2992 if (xfc->clipboard)
2993 {
2994 ClipboardLock(xfc->clipboard->system);
2995 cliprdr_file_context_uninit(xfc->clipboard->file, cliprdr);
2996 ClipboardUnlock(xfc->clipboard->system);
2997 xfc->clipboard->context = nullptr;
2998 }
2999}
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