FreeRDP
Loading...
Searching...
No Matches
sdl_clip.cpp
1
20
21#include <memory>
22#include <string>
23#include <sstream>
24#include <mutex>
25#include <iterator>
26#include <algorithm>
27#include <utility>
28#include <cstring>
29
30#include <winpr/wlog.h>
31#include <winpr/image.h>
32
33#include <string_view>
34#include "sdl_clip.hpp"
35#include "sdl_context.hpp"
36
37#if defined(__EMSCRIPTEN__)
38#include <mutex>
39class sdlClip;
40/* The clipboard the page talks to. s_web_lock keeps uninit() from tearing it down while an
41 * offer from the page is being sent. */
42static std::mutex s_web_lock;
43static sdlClip* s_web_clip = nullptr;
44#include <emscripten.h>
45#include <emscripten/proxying.h>
46#include <emscripten/threading.h>
47#include <winpr/string.h>
48#include <pthread.h>
49#endif
50
51#define TAG CLIENT_TAG("sdl.cliprdr")
52
53#define mime_text_plain "text/plain"
54const char mime_text_utf8[] = "text/plain;charset=utf-8";
55
56static const char* first_announcement[] = {
57 "sdl-clipboard-monitor-ready-4b8c7d9b-6d5c-4dcc-add1-21573ca564b0"
58};
59
60[[nodiscard]] static const std::vector<const char*>& s_mime_text()
61{
62 static std::vector<const char*> values;
63 if (values.empty())
64 {
65 values = std::vector<const char*>(
66 { mime_text_utf8, "UTF8_STRING", mime_text_plain, "TEXT", "STRING" });
67 }
68 return values;
69}
70
71static const char s_mime_jxl[] = "image/jxl";
72static const char s_mime_avif[] = "image/avif";
73static const char s_mime_png[] = "image/png";
74static const char s_mime_webp[] = "image/webp";
75static const char s_mime_jpg[] = "image/jpeg";
76
77static const char s_mime_tiff[] = "image/tiff";
78static const char s_mime_uri_list[] = "text/uri-list";
79/* SDL reports the native pasteboard types on macOS, Finder files have no MIME type */
80static const char s_type_file_url[] = "public.file-url";
81static const char s_mime_html[] = "text/html";
82
83#define BMP_MIME_LIST "image/bmp", "image/x-bmp", "image/x-MS-bmp", "image/x-win-bitmap"
84
85[[nodiscard]] static const std::vector<const char*>& s_mime_bitmap()
86{
87 static std::vector<const char*> values;
88 if (values.empty())
89 {
90 values = std::vector<const char*>({ BMP_MIME_LIST });
91 }
92 return values;
93}
94
95[[nodiscard]] static const std::vector<const char*>& s_mime_image()
96{
97 static std::vector<const char*> values;
98 if (values.empty())
99 {
100 if (winpr_image_format_is_supported(WINPR_IMAGE_WEBP))
101 values.push_back(s_mime_webp);
102
103 if (winpr_image_format_is_supported(WINPR_IMAGE_PNG))
104 values.push_back(s_mime_png);
105
106 if (winpr_image_format_is_supported(WINPR_IMAGE_JPEG))
107 values.push_back(s_mime_jpg);
108
109 auto bmp = std::vector<const char*>({ BMP_MIME_LIST });
110 values.insert(values.end(), bmp.begin(), bmp.end());
111 }
112 return values;
113}
114
115/* Local image types winpr can turn into a CF_DIB, in order of preference: BMP only needs its
116 * file header stripped, the others need the matching winpr image support compiled in. */
117[[nodiscard]] static const std::vector<const char*>& s_mime_dib_sources()
118{
119 static const std::vector<const char*> values = []()
120 {
121 std::vector<const char*> v({ BMP_MIME_LIST });
122 if (winpr_image_format_is_supported(WINPR_IMAGE_PNG))
123 v.push_back(s_mime_png);
124 if (winpr_image_format_is_supported(WINPR_IMAGE_WEBP))
125 v.push_back(s_mime_webp);
126 if (winpr_image_format_is_supported(WINPR_IMAGE_JPEG))
127 v.push_back(s_mime_jpg);
128 return v;
129 }();
130 return values;
131}
132
133/* Local image types an "HTML Format" request may be answered from */
134[[nodiscard]] static const std::vector<const char*>& s_mime_html_image_sources()
135{
136 static const std::vector<const char*> values({ s_mime_jpg, s_mime_png, s_mime_webp, s_mime_avif,
137 s_mime_jxl, s_mime_tiff, BMP_MIME_LIST });
138 return values;
139}
140
141/* The mime types SDL has cached for the current clipboard owner. Unlike SDL_HasClipboardData
142 * this does no clipboard I/O: on X11, SDL_HasClipboardData transfers the data, and calls our
143 * own ClipDataCb when we are the owner. */
144[[nodiscard]] static std::vector<std::string> localMimeTypes()
145{
146 std::vector<std::string> list;
147 size_t count = 0;
148 auto mimes = SDL_GetClipboardMimeTypes(&count);
149 for (size_t x = 0; mimes && (x < count); x++)
150 {
151 if (mimes[x])
152 list.emplace_back(mimes[x]);
153 }
154 SDL_free(static_cast<void*>(mimes));
155 return list;
156}
157
158[[nodiscard]] static bool hasMime(const std::vector<std::string>& list, const char* mime)
159{
160 return std::find(list.begin(), list.end(), mime) != list.end();
161}
162
163[[nodiscard]] static const char* firstOffered(const std::vector<std::string>& offered,
164 const std::vector<const char*>& candidates)
165{
166 for (const auto& m : candidates)
167 {
168 if (hasMime(offered, m))
169 return m;
170 }
171 return nullptr;
172}
173
174/* WinPR synthesizes text with its terminating '\0' included in the size, as the RDP
175 * wire formats require. Local applications expect the bare string, so cut it at the
176 * first '\0' (as the X11 client does). */
177[[nodiscard]] static uint32_t textLength(const void* data, uint32_t size)
178{
179 const auto end = memchr(data, '\0', size);
180 if (!end)
181 return size;
182 return WINPR_ASSERTING_INT_CAST(uint32_t,
183 static_cast<const char*>(end) - static_cast<const char*>(data));
184}
185
186static const char s_mime_gnome_copied_files[] = "x-special/gnome-copied-files";
187static const char s_mime_mate_copied_files[] = "x-special/mate-copied-files";
188
189static const char s_mime_freerdp_update[] = "x-special/freerdp-clipboard-update";
190
191static const char* s_type_HtmlFormat = "HTML Format";
192static const char* s_type_FileGroupDescriptorW = "FileGroupDescriptorW";
193
194class ClipboardLockGuard
195{
196 public:
197 explicit ClipboardLockGuard(wClipboard* clipboard) : _clipboard(clipboard)
198 {
199 ClipboardLock(_clipboard);
200 }
201 ClipboardLockGuard(const ClipboardLockGuard& other) = delete;
202 ClipboardLockGuard(ClipboardLockGuard&& other) = delete;
203
204 ClipboardLockGuard& operator=(const ClipboardLockGuard& rhs) = delete;
205 ClipboardLockGuard& operator=(ClipboardLockGuard&& rhs) = delete;
206
207 ~ClipboardLockGuard()
208 {
209 ClipboardUnlock(_clipboard);
210 }
211
212 private:
213 wClipboard* _clipboard;
214};
215
216static bool operator<(const CLIPRDR_FORMAT& lhs, const CLIPRDR_FORMAT& rhs)
217{
218 return (lhs.formatId < rhs.formatId);
219}
220
221static bool operator==(const CLIPRDR_FORMAT& lhs, const CLIPRDR_FORMAT& rhs)
222{
223 return (lhs.formatId == rhs.formatId);
224}
225
226sdlClip::sdlClip(SdlContext* sdl)
227 : _sdl(sdl), _file(cliprdr_file_context_new(this)), _log(WLog_Get(TAG)),
228 _system(ClipboardCreate()), _event(CreateEventA(nullptr, TRUE, FALSE, nullptr)),
229 _uuid(sdl::utils::generate_uuid_v4())
230{
231 WINPR_ASSERT(sdl);
232
233 std::stringstream ss;
234 ss << s_mime_freerdp_update << "-" << _uuid;
235 _mime_uuid = ss.str();
236
237 std::ignore = cliprdr_file_context_set_locally_available(_file, TRUE);
238}
239
240sdlClip::~sdlClip()
241{
242#if defined(__EMSCRIPTEN__)
243 {
244 std::scoped_lock web(s_web_lock);
245 if (s_web_clip == this)
246 s_web_clip = nullptr;
247 }
248#endif
249 cliprdr_file_context_free(_file);
250 ClipboardDestroy(_system);
251 std::ignore = CloseHandle(_event);
252}
253
254bool sdlClip::init(CliprdrClientContext* clip)
255{
256 WINPR_ASSERT(clip);
257 ClipboardLockGuard systemlock(_system);
258 std::scoped_lock lock(_lock);
259 _ctx = clip;
260 clip->custom = this;
261 _ctx->MonitorReady = sdlClip::MonitorReady;
262 _ctx->ServerCapabilities = sdlClip::ReceiveServerCapabilities;
263 _ctx->ServerFormatList = sdlClip::ReceiveServerFormatList;
264 _ctx->ServerFormatListResponse = sdlClip::ReceiveFormatListResponse;
265 _ctx->ServerFormatDataRequest = sdlClip::ReceiveFormatDataRequest;
266 _ctx->ServerFormatDataResponse = sdlClip::ReceiveFormatDataResponse;
267#if defined(__EMSCRIPTEN__)
268 {
269 std::scoped_lock web(s_web_lock);
270 s_web_clip = this;
271 }
272#endif
273
274 return cliprdr_file_context_init(_file, _ctx);
275}
276
277bool sdlClip::uninit(CliprdrClientContext* clip)
278{
279 WINPR_ASSERT(clip);
280#if defined(__EMSCRIPTEN__)
281 {
282 std::scoped_lock web(s_web_lock);
283 if (s_web_clip == this)
284 s_web_clip = nullptr;
285 }
286#endif
287 ClipboardLockGuard systemlock(_system);
288 std::scoped_lock lock(_lock);
289 /* The object outlives the channel: after a reconnect or redirect the new channel must see
290 * its Monitor Ready before we announce the local clipboard ([MS-RDPECLIP] 1.3.2.1). */
291 _sync = false;
292 if (!cliprdr_file_context_uninit(_file, _ctx))
293 return false;
294 _ctx = nullptr;
295 clip->custom = nullptr;
296 _server_requests.clear();
297 return true;
298}
299
300bool sdlClip::contains(const char** mime_types, Sint32 count)
301{
302 for (Sint32 x = 0; x < count; x++)
303 {
304 const auto mime = mime_types[x];
305 if (mime && (strcmp(_mime_uuid.c_str(), mime) == 0))
306 return true;
307 }
308 return false;
309}
310
311bool sdlClip::ownsClipboard() const
312{
313 return hasMime(localMimeTypes(), _mime_uuid.c_str());
314}
315
316bool sdlClip::handleEvent(const SDL_ClipboardEvent& ev)
317{
318 std::unique_ptr<char*, decltype(&SDL_free)> current(nullptr, SDL_free);
319 const char** mime_types = ev.mime_types;
320 size_t nformats = WINPR_ASSERTING_INT_CAST(size_t, ev.num_mime_types);
321 bool connected = false;
322 {
323 std::scoped_lock lock(_lock);
324 connected = (_ctx != nullptr);
325 }
326 if (connected && _ctx && _sync && ev.owner && (ev.num_mime_types == 1))
327 {
328 if (strcmp(first_announcement[0], ev.mime_types[0]) == 0)
329 {
330 current.reset(SDL_GetClipboardMimeTypes(&nformats));
331 mime_types = const_cast<const char**>(current.get());
332 if (!mime_types)
333 nformats = 0;
334 }
335 }
336 else if (!connected || !_ctx || !_sync || ev.owner)
337 {
338 _last_timestamp = ev.timestamp;
339
340 /* The channel thread replaces _current_mimetypes on every server format list, so take
341 * them under the lock instead of trusting pointers carried in the event. */
342 std::vector<std::string> mimes;
343 {
344 ClipboardLockGuard systemlock(_system);
345 std::scoped_lock lock(_lock);
346 mimes.swap(_current_mimetypes);
347 if (!mimes.empty())
348 _cache_data.clear();
349 }
350 if (mimes.empty())
351 return true;
352
353 std::vector<const char*> cmimes;
354 cmimes.reserve(mimes.size());
355 for (const auto& m : mimes)
356 cmimes.push_back(m.c_str());
357
358 /* Server files need native clipboard items on some platforms (macOS), which only the
359 * file context can offer. It requests the data with ClipDataCb like SDL does. */
360 if (cliprdr_file_context_set_local_clipboard_data(_file, sdlClip::ClipDataCb, this,
361 cmimes.data(), cmimes.size()))
362 return true;
363
364 /* SDL copies the mime type strings */
365 return SDL_SetClipboardData(sdlClip::ClipDataCb, sdlClip::ClipCleanCb, this, cmimes.data(),
366 cmimes.size());
367 }
368
369 if (ev.timestamp == _last_timestamp)
370 return true;
371
372 if (contains(mime_types, WINPR_ASSERTING_INT_CAST(Sint32, nformats)))
373 return true;
374
375 /* SDL holds this session's server data right now, so this update was queued before our
376 * later SDL_SetClipboardData took effect: typically the selection a compositor re-sends on
377 * focus-in, racing a server format list. Announcing it would replace the fresh server
378 * clipboard with the stale local one (and the server would then ask us for data we no
379 * longer own). A genuine local change cancels our data before its update is queued. */
380 if (ownsClipboard())
381 {
382 WLog_Print(_log, WLOG_DEBUG, "ignoring stale local clipboard update");
383 return true;
384 }
385
386 {
387 ClipboardLockGuard systemlock(_system);
388 std::scoped_lock lock(_lock);
389 clearServerFormats();
390 }
391
392 const std::string mime_html = s_mime_html;
393
394 const std::vector<std::string> mime_bitmap = { BMP_MIME_LIST };
395 const std::string mime_webp = s_mime_webp;
396 const std::string mime_png = s_mime_png;
397 const std::string mime_jpeg = s_mime_jpg;
398 const std::string mime_tiff = s_mime_tiff;
399 const std::vector<std::string> mime_images = { mime_webp, mime_png, mime_jpeg,
400 mime_tiff, s_mime_avif, s_mime_jxl };
401
402 std::vector<std::string> clientFormatNames;
403 std::vector<CLIPRDR_FORMAT> clientFormats;
404
405 const char** clipboard_mime_formats = mime_types;
406
407 WLog_Print(_log, WLOG_TRACE, "SDL has %" PRIuz " formats", nformats);
408
409 bool textPushed = false;
410 bool imgPushed = false;
411 bool filePushed = false;
412
413 for (size_t i = 0; i < nformats; i++)
414 {
415 std::string local_mime = clipboard_mime_formats[i];
416 WLog_Print(_log, WLOG_TRACE, " - %s", local_mime.c_str());
417
418 if (std::find(s_mime_text().begin(), s_mime_text().end(), local_mime) !=
419 s_mime_text().end())
420 {
421 /* text formats */
422 if (!textPushed)
423 {
424 clientFormats.push_back({ CF_TEXT, nullptr });
425 clientFormats.push_back({ CF_OEMTEXT, nullptr });
426 clientFormats.push_back({ CF_UNICODETEXT, nullptr });
427 textPushed = true;
428 }
429 }
430 else if (local_mime == mime_html)
431 /* html */
432 clientFormatNames.emplace_back(s_type_HtmlFormat);
433 else if ((std::find(mime_bitmap.begin(), mime_bitmap.end(), local_mime) !=
434 mime_bitmap.end()) ||
435 (std::find(mime_images.begin(), mime_images.end(), local_mime) !=
436 mime_images.end()))
437 {
438 /* image formats */
439 if (!imgPushed)
440 {
441 clientFormats.push_back({ CF_DIB, nullptr });
442#if defined(WINPR_UTILS_IMAGE_DIBv5)
443 clientFormats.push_back({ CF_DIBV5, nullptr });
444#endif
445
446 if (winpr_image_format_is_supported(WINPR_IMAGE_BITMAP))
447 {
448 for (auto& bmp : mime_bitmap)
449 clientFormatNames.emplace_back(bmp);
450 }
451
452 if (winpr_image_format_is_supported(WINPR_IMAGE_JPEG))
453 clientFormatNames.emplace_back(mime_jpeg);
454 if (winpr_image_format_is_supported(WINPR_IMAGE_WEBP))
455 clientFormatNames.emplace_back(mime_webp);
456 if (winpr_image_format_is_supported(WINPR_IMAGE_PNG))
457 clientFormatNames.emplace_back(mime_png);
458
459 clientFormatNames.emplace_back(s_type_HtmlFormat);
460 imgPushed = true;
461 }
462 clientFormatNames.emplace_back(local_mime);
463 }
464 else if (mime_is_file(local_mime) || (local_mime == s_type_file_url))
465 {
466 if (!filePushed)
467 {
468 clientFormatNames.emplace_back(s_type_FileGroupDescriptorW);
469 filePushed = true;
470 }
471 }
472 }
473
474 std::sort(clientFormatNames.begin(), clientFormatNames.end());
475 clientFormatNames.erase(std::unique(clientFormatNames.begin(), clientFormatNames.end()),
476 clientFormatNames.end());
477
478 for (auto& name : clientFormatNames)
479 {
480 clientFormats.push_back({ ClipboardRegisterFormat(_system, name.c_str()), name.data() });
481 }
482
483 std::sort(clientFormats.begin(), clientFormats.end(),
484 [](const auto& a, const auto& b) { return a < b; });
485 auto u = std::unique(clientFormats.begin(), clientFormats.end());
486 clientFormats.erase(u, clientFormats.end());
487
488 const CLIPRDR_FORMAT_LIST formatList = {
489 { CB_FORMAT_LIST, 0, 0 },
490 static_cast<UINT32>(clientFormats.size()),
491 clientFormats.data(),
492 };
493
494 WLog_Print(_log, WLOG_TRACE,
495 "-------------- client format list [%" PRIu32 "] ------------------",
496 formatList.numFormats);
497 for (UINT32 x = 0; x < formatList.numFormats; x++)
498 {
499 auto format = &formatList.formats[x];
500 WLog_Print(_log, WLOG_TRACE, "client announces %" PRIu32 " [%s][%s]", format->formatId,
501 ClipboardGetFormatIdString(format->formatId), format->formatName);
502 }
503
504 /* The RDP thread may have closed the channel since the check above (see uninit) */
505 ClipboardLockGuard systemlock(_system);
506 std::scoped_lock lock(_lock);
507 if (!_ctx || !_sync)
508 return true;
509
510 if (cliprdr_file_context_notify_new_client_format_list(_file) != CHANNEL_RC_OK)
511 return false;
512
513 WINPR_ASSERT(_ctx);
514 WINPR_ASSERT(_ctx->ClientFormatList);
515 return _ctx->ClientFormatList(_ctx, &formatList) == CHANNEL_RC_OK;
516}
517
518UINT sdlClip::MonitorReady(CliprdrClientContext* context, const CLIPRDR_MONITOR_READY* monitorReady)
519{
520 WINPR_UNUSED(monitorReady);
521 WINPR_ASSERT(context);
522 WINPR_ASSERT(monitorReady);
523
524 auto clipboard = static_cast<sdlClip*>(
525 cliprdr_file_context_get_context(static_cast<CliprdrFileContext*>(context->custom)));
526 WINPR_ASSERT(clipboard);
527
528 auto ret = clipboard->SendClientCapabilities();
529 if (ret != CHANNEL_RC_OK)
530 return ret;
531
532 clipboard->_sync = true;
533 SDL_Event ev = {};
534 ev.clipboard.type = SDL_EVENT_CLIPBOARD_UPDATE;
535 ev.clipboard.owner = true;
536 ev.clipboard.timestamp = SDL_GetTicksNS();
537 ev.clipboard.num_mime_types = ARRAYSIZE(first_announcement);
538 ev.clipboard.mime_types = first_announcement;
539
540 auto rc = SDL_PushEvent(&ev);
541 if (rc != 1)
542 return ERROR_INTERNAL_ERROR;
543
544 return CHANNEL_RC_OK;
545}
546
547UINT sdlClip::SendClientCapabilities()
548{
549 CLIPRDR_GENERAL_CAPABILITY_SET generalCapabilitySet = {
550 CB_CAPSTYPE_GENERAL, 12, CB_CAPS_VERSION_2,
551 CB_USE_LONG_FORMAT_NAMES | cliprdr_file_context_current_flags(_file)
552 };
553 const CLIPRDR_CAPABILITIES capabilities = {
554 { CB_TYPE_NONE, 0, 0 }, 1, reinterpret_cast<CLIPRDR_CAPABILITY_SET*>(&generalCapabilitySet)
555 };
556
557 WINPR_ASSERT(_ctx);
558 WINPR_ASSERT(_ctx->ClientCapabilities);
559 return _ctx->ClientCapabilities(_ctx, &capabilities);
560}
561
562void sdlClip::clearServerFormats()
563{
564 {
565 ClipboardLockGuard systemlock(_system);
566 std::scoped_lock lock(_lock);
567 _serverFormats.clear();
568 _cache_data.clear();
569 /* The WinPR clipboard may still hold local data converted for an earlier server request.
570 * ClipDataCb() would hand that out instead of requesting the new server data. */
571 ClipboardEmpty(_system);
572 }
573 cliprdr_file_context_clear(_file);
574}
575
576UINT sdlClip::SendFormatListResponse(BOOL status)
577{
578 const CLIPRDR_FORMAT_LIST_RESPONSE formatListResponse = {
579 { CB_FORMAT_LIST_RESPONSE, static_cast<UINT16>(status ? CB_RESPONSE_OK : CB_RESPONSE_FAIL),
580 0 }
581 };
582 WINPR_ASSERT(_ctx);
583 WINPR_ASSERT(_ctx->ClientFormatListResponse);
584 return _ctx->ClientFormatListResponse(_ctx, &formatListResponse);
585}
586
587UINT sdlClip::SendDataResponse(const BYTE* data, size_t size)
588{
589 CLIPRDR_FORMAT_DATA_RESPONSE response = {};
590
591 if (size > UINT32_MAX)
592 return ERROR_INVALID_PARAMETER;
593
594 response.common.msgFlags = (data) ? CB_RESPONSE_OK : CB_RESPONSE_FAIL;
595 response.common.dataLen = static_cast<UINT32>(size);
596 response.requestedFormatData = data;
597
598 WINPR_ASSERT(_ctx);
599 WINPR_ASSERT(_ctx->ClientFormatDataResponse);
600 return _ctx->ClientFormatDataResponse(_ctx, &response);
601}
602
603UINT sdlClip::SendDataRequest(uint32_t formatID, const std::string& mime)
604{
605 const CLIPRDR_FORMAT_DATA_REQUEST request = { { CB_TYPE_NONE, 0, 0 }, formatID };
606
607 _request_queue.emplace(formatID, mime);
608
609 WINPR_ASSERT(_ctx);
610 WINPR_ASSERT(_ctx->ClientFormatDataRequest);
611 UINT ret = _ctx->ClientFormatDataRequest(_ctx, &request);
612 if (ret != CHANNEL_RC_OK)
613 {
614 WLog_Print(_log, WLOG_ERROR, "error sending ClientFormatDataRequest, cancelling request");
615 _request_queue.pop();
616 }
617
618 return ret;
619}
620
621std::string sdlClip::getServerFormat(uint32_t id)
622{
623 for (auto& fmt : _serverFormats)
624 {
625 if (fmt.formatId() == id)
626 {
627 if (fmt.formatName())
628 return fmt.formatName();
629 break;
630 }
631 }
632
633 return "";
634}
635
636uint32_t sdlClip::serverIdForMime(const std::string& mime)
637{
638 std::string cmp = mime;
639 if (mime_is_html(mime))
640 cmp = s_type_HtmlFormat;
641 if (mime_is_file(mime))
642 cmp = s_type_FileGroupDescriptorW;
643
644 if (const auto formatId = sdl_clip_format_selection::formatIdForName(_serverFormats, cmp))
645 return formatId;
646
647 if (mime_is_image(mime) || mime_is_bmp(mime))
648 {
649 /* not offered under this name: CF_DIB, or any other image format of the server; the
650 * WinPR clipboard converts it */
651 uint32_t named = 0;
652 for (auto& format : _serverFormats)
653 {
654 if ((format.formatId() == CF_DIB) || (format.formatId() == CF_DIBV5))
655 return format.formatId();
656 if (!named && format.formatName() &&
657 (mime_is_image(format.formatName()) || mime_is_bmp(format.formatName())))
658 named = format.formatId();
659 }
660 return named;
661 }
662 if (mime_is_text(mime))
663 return sdl_clip_format_selection::textFormat(_serverFormats);
664
665 return 0;
666}
667
668UINT sdlClip::ReceiveServerCapabilities(CliprdrClientContext* context,
669 const CLIPRDR_CAPABILITIES* capabilities)
670{
671 WINPR_ASSERT(context);
672 WINPR_ASSERT(capabilities);
673
674 auto capsPtr = reinterpret_cast<const BYTE*>(capabilities->capabilitySets);
675 WINPR_ASSERT(capsPtr);
676
677 auto clipboard = static_cast<sdlClip*>(
678 cliprdr_file_context_get_context(static_cast<CliprdrFileContext*>(context->custom)));
679 WINPR_ASSERT(clipboard);
680
681 if (!cliprdr_file_context_remote_set_flags(clipboard->_file, 0))
682 return ERROR_INTERNAL_ERROR;
683
684 for (UINT32 i = 0; i < capabilities->cCapabilitiesSets; i++)
685 {
686 auto caps = reinterpret_cast<const CLIPRDR_CAPABILITY_SET*>(capsPtr);
687
688 if (caps->capabilitySetType == CB_CAPSTYPE_GENERAL)
689 {
690 auto generalCaps = reinterpret_cast<const CLIPRDR_GENERAL_CAPABILITY_SET*>(caps);
691
692 if (!cliprdr_file_context_remote_set_flags(clipboard->_file, generalCaps->generalFlags))
693 return ERROR_INTERNAL_ERROR;
694 }
695
696 capsPtr += caps->capabilitySetLength;
697 }
698
699 return CHANNEL_RC_OK;
700}
701
702UINT sdlClip::ReceiveServerFormatList(CliprdrClientContext* context,
703 const CLIPRDR_FORMAT_LIST* formatList)
704{
705 BOOL html = FALSE;
706 BOOL text = FALSE;
707 BOOL image = FALSE;
708 BOOL file = FALSE;
709
710 if (!context || !context->custom)
711 return ERROR_INVALID_PARAMETER;
712
713 auto filecontext = static_cast<CliprdrFileContext*>(context->custom);
714 auto clipboard = static_cast<sdlClip*>(cliprdr_file_context_get_context(filecontext));
715 WINPR_ASSERT(clipboard);
716
717 ClipboardLockGuard systemlock(clipboard->_system);
718 std::scoped_lock lock(clipboard->_lock);
719
720 clipboard->clearServerFormats();
721 /* _system may still hold local clipboard data converted for an earlier server request.
722 * ClipDataCb converts from _system before asking the server, so left in place it would
723 * answer the next local paste with that stale local data instead of the new server data. */
724 ClipboardEmpty(clipboard->_system);
725
726 for (UINT32 i = 0; i < formatList->numFormats; i++)
727 {
728 const CLIPRDR_FORMAT* format = &formatList->formats[i];
729
730 clipboard->_serverFormats.emplace_back(format->formatId, format->formatName);
731
732 if (format->formatName)
733 {
734 if (strcmp(format->formatName, s_type_HtmlFormat) == 0)
735 html = TRUE;
736 else if (strcmp(format->formatName, s_type_FileGroupDescriptorW) == 0)
737 file = TRUE;
738 else if (mime_is_image(format->formatName) || mime_is_bmp(format->formatName))
739 {
740 /* e.g. GNOME Remote Desktop offers image/png alone for PNG-only sources */
741 image = TRUE;
742 }
743 }
744 else
745 {
746 switch (format->formatId)
747 {
748 case CF_TEXT:
749 case CF_OEMTEXT:
750 case CF_UNICODETEXT:
751 text = TRUE;
752 break;
753
754 case CF_DIB:
755 image = TRUE;
756 break;
757
758 default:
759 break;
760 }
761 }
762 }
763
764 clipboard->_current_mimetypes.clear();
765
766 {
767 auto res = cliprdr_file_context_notify_new_server_format_list(filecontext);
768 if (res != CHANNEL_RC_OK)
769 return res;
770 }
771
772 if (text)
773 {
774 clipboard->_current_mimetypes.insert(clipboard->_current_mimetypes.end(),
775 s_mime_text().begin(), s_mime_text().end());
776 }
777 if (image)
778 {
779 clipboard->_current_mimetypes.insert(clipboard->_current_mimetypes.end(),
780 s_mime_bitmap().begin(), s_mime_bitmap().end());
781 clipboard->_current_mimetypes.insert(clipboard->_current_mimetypes.end(),
782 s_mime_image().begin(), s_mime_image().end());
783 }
784 if (html)
785 {
786 clipboard->_current_mimetypes.emplace_back(s_mime_html);
787 }
788 if (file)
789 {
790 clipboard->_current_mimetypes.emplace_back(s_mime_uri_list);
791 clipboard->_current_mimetypes.emplace_back(s_mime_gnome_copied_files);
792 clipboard->_current_mimetypes.emplace_back(s_mime_mate_copied_files);
793 }
794 clipboard->_current_mimetypes.emplace_back(clipboard->_mime_uuid.c_str());
795
796 auto& mime = clipboard->_current_mimetypes;
797 mime.erase(std::unique(mime.begin(), mime.end()), mime.end());
798
799 WLog_Print(clipboard->_log, WLOG_TRACE,
800 "-------------- server mime types [%" PRIuz "] ------------------", mime.size());
801 for (const auto& m : mime)
802 {
803 WLog_Print(clipboard->_log, WLOG_TRACE, "server announces %s]", m.c_str());
804 }
805
806 /* handleEvent picks the mime types up from _current_mimetypes. Set every field: an
807 * initializer list only initializes the union's first member (type). */
808 SDL_Event ev = {};
809 ev.clipboard.type = SDL_EVENT_CLIPBOARD_UPDATE;
810 ev.clipboard.owner = true;
811 ev.clipboard.timestamp = SDL_GetTicksNS();
812 ev.clipboard.num_mime_types = 0;
813 ev.clipboard.mime_types = nullptr;
814
815 auto rc = (SDL_PushEvent(&ev) == 1);
816 const UINT ret = clipboard->SendFormatListResponse(rc);
817#if defined(__EMSCRIPTEN__)
818 clipboard->_web_offers.serverAnnounced();
819 if (ret == CHANNEL_RC_OK)
820 std::ignore = clipboard->webRequestServerText();
821#endif
822 return ret;
823}
824
825UINT sdlClip::ReceiveFormatListResponse(WINPR_ATTR_UNUSED CliprdrClientContext* context,
826 const CLIPRDR_FORMAT_LIST_RESPONSE* formatListResponse)
827{
828 WINPR_ASSERT(context);
829 WINPR_ASSERT(formatListResponse);
830
831 if (formatListResponse->common.msgFlags & CB_RESPONSE_FAIL)
832 WLog_WARN(TAG, "format list update failed");
833 return CHANNEL_RC_OK;
834}
835
836std::shared_ptr<BYTE> sdlClip::getLocalData(uint32_t formatId, uint32_t& len)
837{
838 len = 0;
839
840 const auto offered = localMimeTypes();
841
842 /* The local clipboard still holds what this session received from the server (the
843 * server asked before our format list reached it). Reading it through SDL would call
844 * ClipDataCb and ask the server for its own data, so fail the request instead. */
845 if (hasMime(offered, _mime_uuid.c_str()))
846 {
847 WLog_Print(_log, WLOG_DEBUG, "local clipboard holds server data, not answering request");
848 return {};
849 }
850
851 UINT32 fileFormatId = 0;
852 UINT32 htmlFormatId = 0;
853 {
854 ClipboardLockGuard systemlock(_system);
855 std::scoped_lock lock(_lock);
856 WLog_Print(_log, WLOG_DEBUG, "Requesting format %s [0x%08" PRIx32 "] [%s]",
857 ClipboardGetFormatIdString(formatId), formatId,
858 ClipboardGetFormatName(_system, formatId));
859 fileFormatId = ClipboardGetFormatId(_system, s_type_FileGroupDescriptorW);
860 htmlFormatId = ClipboardGetFormatId(_system, s_type_HtmlFormat);
861 }
862
863 /* Local mime types to try, in order, and the _system format each is stored as for winpr to
864 * convert: its registered format, the requested one, or a newly registered one. */
865 enum class Store
866 {
867 Lookup,
868 Requested,
869 Register
870 };
871 struct Candidate
872 {
873 const char* mime;
874 Store store;
875 };
876 std::vector<Candidate> candidates;
877
878 switch (formatId)
879 {
880 case CF_TEXT:
881 case CF_OEMTEXT:
882 case CF_UNICODETEXT:
883 {
884 const char* mime = firstOffered(offered, s_mime_text());
885 if (mime)
886 candidates.push_back({ mime, Store::Lookup });
887 }
888 break;
889
890 case CF_DIB:
891 case CF_DIBV5:
892 /* Every convertible type on offer (screenshot tools offer image/png only, never
893 * image/bmp), in case a decoder rejects one of them. */
894 for (const auto& mime : s_mime_dib_sources())
895 {
896 if (hasMime(offered, mime))
897 candidates.push_back({ mime, Store::Register });
898 }
899 break;
900
901 case CF_TIFF:
902 candidates.push_back({ s_mime_tiff, Store::Requested });
903 break;
904
905 default:
906 if (formatId == fileFormatId)
907 candidates.push_back({ s_mime_uri_list, Store::Lookup });
908 else if (formatId == htmlFormatId)
909 {
910 /* In case HTML format was requested but we only have images in local clipboard */
911 const char* mime = hasMime(offered, s_mime_html)
912 ? s_mime_html
913 : firstOffered(offered, s_mime_html_image_sources());
914 if (mime)
915 candidates.push_back({ mime, Store::Lookup });
916 }
917 else
918 {
919 ClipboardLockGuard systemlock(_system);
920 std::scoped_lock lock(_lock);
921 const char* formatName = ClipboardGetFormatName(_system, formatId);
922 if (formatName && hasMime(offered, formatName))
923 {
924 /* the name is owned by _system and outlives this function */
925 candidates.push_back({ formatName, Store::Lookup });
926 }
927 else if (formatName && (mime_is_image(formatName) || mime_is_bmp(formatName)))
928 {
929 /* We announce every image format WinPR can convert to, but the SDL backend
930 * may only provide some of them (Windows: image/bmp). Take the ones on
931 * offer and let the WinPR clipboard convert to the requested format. */
932 for (const auto& mime : s_mime_dib_sources())
933 {
934 if (hasMime(offered, mime))
935 candidates.push_back({ mime, Store::Register });
936 }
937 }
938 }
939 break;
940 }
941
942 std::shared_ptr<BYTE> data;
943 for (const auto& candidate : candidates)
944 {
945 /* Read without holding our locks: on X11 this pumps events and can take a while, and
946 * the channel thread needs the locks to deliver server data. */
947 size_t size = 0;
948 std::shared_ptr<void> sdldata;
949 if (formatId == fileFormatId)
950 sdldata =
951 std::shared_ptr<void>(cliprdr_file_context_get_local_uri_list(_file, &size), free);
952 if (!sdldata)
953 sdldata = std::shared_ptr<void>(SDL_GetClipboardData(candidate.mime, &size), SDL_free);
954 if (!sdldata || (size > UINT32_MAX))
955 continue;
956
957 ClipboardLockGuard systemlock(_system);
958 std::scoped_lock lock(_lock);
959
960 if (formatId == fileFormatId)
961 {
962 auto bdata = static_cast<const char*>(sdldata.get());
963 if (!cliprdr_file_context_update_client_data(_file, bdata, size))
964 continue;
965 }
966
967 UINT32 storeId = formatId;
968 if (candidate.store == Store::Lookup)
969 storeId = ClipboardGetFormatId(_system, candidate.mime);
970 else if (candidate.store == Store::Register)
971 storeId = ClipboardRegisterFormat(_system, candidate.mime);
972
973 uint32_t ptrlen = 0;
974 BYTE* ptr = nullptr;
975 if (ClipboardSetData(_system, storeId, sdldata.get(), static_cast<uint32_t>(size)))
976 ptr = static_cast<BYTE*>(ClipboardGetData(_system, formatId, &ptrlen));
977
978 /* _system is also where ClipDataCb looks for server data: leave no local data behind,
979 * or a later local paste would be answered with it. */
980 ClipboardEmpty(_system);
981
982 if (!ptr)
983 {
984 WLog_Print(_log, WLOG_DEBUG, "could not convert local %s", candidate.mime);
985 continue;
986 }
987
988 data = std::shared_ptr<BYTE>(ptr, free);
989 len = ptrlen;
990
991 if (formatId == fileFormatId)
992 {
993 BYTE* ddata = nullptr;
994 UINT32 dsize = 0;
995 const UINT32 flags = cliprdr_file_context_remote_get_flags(_file);
996 const UINT32 error = cliprdr_serialize_file_list_ex(
997 flags, reinterpret_cast<const FILEDESCRIPTORW*>(data.get()),
998 ptrlen / sizeof(FILEDESCRIPTORW), &ddata, &dsize);
999 data = std::shared_ptr<BYTE>(ddata, free);
1000 len = dsize;
1001 if (error)
1002 {
1003 data.reset();
1004 len = 0;
1005 }
1006 }
1007 break;
1008 }
1009 return data;
1010}
1011
1012UINT sdlClip::ReceiveFormatDataRequest(CliprdrClientContext* context,
1013 const CLIPRDR_FORMAT_DATA_REQUEST* formatDataRequest)
1014{
1015 WINPR_ASSERT(context);
1016 WINPR_ASSERT(formatDataRequest);
1017
1018 auto clipboard = static_cast<sdlClip*>(
1019 cliprdr_file_context_get_context(static_cast<CliprdrFileContext*>(context->custom)));
1020 WINPR_ASSERT(clipboard);
1021
1022#if defined(__EMSCRIPTEN__)
1023 /* In the browser, never fall through to the SDL path below: SDL has no browser clipboard,
1024 * its internal one ends in ClipDataCb(), which requests the data from the server and waits
1025 * for the reply on this very channel thread, so nothing can arrive (the server times out and
1026 * all clipboard traffic stalls). Answer from the browser data, or fail at once. */
1027 if (!clipboard->webAnswerDataRequest(formatDataRequest))
1028 return clipboard->SendDataResponse(nullptr, 0);
1029 return CHANNEL_RC_OK;
1030#endif
1031 {
1032 std::scoped_lock lock(clipboard->_lock);
1033 const UINT32 mask = freerdp_settings_get_uint32(context->rdpcontext->settings,
1034 FreeRDP_ClipboardFeatureMask);
1035
1036 const UINT32 fileId =
1037 ClipboardRegisterFormat(clipboard->_system, s_type_FileGroupDescriptorW);
1038 if (fileId == formatDataRequest->requestedFormatId)
1039 {
1040 if ((mask & CLIPRDR_FLAG_LOCAL_TO_REMOTE_FILES) == 0)
1041 return clipboard->SendDataResponse(nullptr, 0);
1042 }
1043 else
1044 {
1045 if ((mask & CLIPRDR_FLAG_LOCAL_TO_REMOTE) == 0)
1046 return clipboard->SendDataResponse(nullptr, 0);
1047 }
1048
1049 /* ClipDataCb is waiting on the main thread for the server: a local application is
1050 * reading our offer of server data, so the local clipboard holds no client data to
1051 * give. Answer now. Queued for the main thread, the request would wait for the end of
1052 * that read while the server may hold its reply until we answer (seen with Windows:
1053 * a 9 s freeze until ClipDataCb timed out). */
1054 if (clipboard->_reading_server)
1055 {
1056 WLog_Print(clipboard->_log, WLOG_DEBUG,
1057 "local read of server data in progress, failing server request");
1058 return clipboard->SendDataResponse(nullptr, 0);
1059 }
1060 clipboard->_server_requests.push_back(formatDataRequest->requestedFormatId);
1061 }
1062
1063 /* This runs on the channel thread, but the SDL clipboard API is main-thread only: on
1064 * Wayland, reading the selection offer here races the main thread replacing it. */
1065 if (!SDL_RunOnMainThread([](void* userdata)
1066 { static_cast<sdlClip*>(userdata)->handleDataRequests(); }, clipboard,
1067 false))
1068 {
1069 std::scoped_lock lock(clipboard->_lock);
1070 if (!clipboard->_server_requests.empty())
1071 clipboard->_server_requests.pop_back();
1072 return clipboard->SendDataResponse(nullptr, 0);
1073 }
1074 return CHANNEL_RC_OK;
1075}
1076
1077void sdlClip::handleDataRequests()
1078{
1079 for (;;)
1080 {
1081 uint32_t formatId = 0;
1082 {
1083 std::scoped_lock lock(_lock);
1084 if (_server_requests.empty())
1085 return;
1086 formatId = _server_requests.front();
1087 _server_requests.pop_front();
1088 if (!_ctx)
1089 continue;
1090 }
1091
1092 uint32_t len = 0;
1093 auto data = getLocalData(formatId, len);
1094 std::scoped_lock lock(_lock);
1095 if (!_ctx)
1096 continue;
1097 if (SendDataResponse(data.get(), len) != CHANNEL_RC_OK)
1098 WLog_Print(_log, WLOG_WARN, "failed to send clipboard data response");
1099 }
1100}
1101
1102UINT sdlClip::ReceiveFormatDataResponse(CliprdrClientContext* context,
1103 const CLIPRDR_FORMAT_DATA_RESPONSE* formatDataResponse)
1104{
1105 WINPR_ASSERT(context);
1106 WINPR_ASSERT(formatDataResponse);
1107
1108 const UINT32 size = formatDataResponse->common.dataLen;
1109 const BYTE* data = formatDataResponse->requestedFormatData;
1110
1111 auto clipboard = static_cast<sdlClip*>(
1112 cliprdr_file_context_get_context(static_cast<CliprdrFileContext*>(context->custom)));
1113 WINPR_ASSERT(clipboard);
1114
1115#if defined(__EMSCRIPTEN__)
1116 if (clipboard->webTakeDataResponse(formatDataResponse))
1117 return CHANNEL_RC_OK;
1118#endif
1119 ClipboardLockGuard systemlock(clipboard->_system);
1120 std::scoped_lock lock(clipboard->_lock);
1121 if (clipboard->_request_queue.empty())
1122 {
1123 /* The matching request already timed out (see the wait below) and was
1124 * popped, so this is a late reply on a slow/high-latency link. Dropping it
1125 * is harmless; returning an error here would kill the cliprdr channel thread
1126 * and tear down the whole session. Warn and continue instead. */
1127 WLog_Print(clipboard->_log, WLOG_WARN,
1128 "format data response with no pending request (late reply?), ignoring");
1129 return CHANNEL_RC_OK;
1130 }
1131
1132 do
1133 {
1134 UINT32 srcFormatId = 0;
1135 auto& request = clipboard->_request_queue.front();
1136 bool success = (formatDataResponse->common.msgFlags & CB_RESPONSE_OK) &&
1137 !(formatDataResponse->common.msgFlags & CB_RESPONSE_FAIL);
1138 request.setSuccess(success);
1139
1140 if (!success)
1141 {
1142 WLog_Print(clipboard->_log, WLOG_WARN,
1143 "clipboard data request for format %" PRIu32 " [%s], mime %s failed",
1144 request.format(), request.formatstr().c_str(), request.mime().c_str());
1145 break;
1146 }
1147
1148 switch (request.format())
1149 {
1150 case CF_TEXT:
1151 case CF_OEMTEXT:
1152 case CF_UNICODETEXT:
1153 srcFormatId = request.format();
1154 break;
1155
1156 case CF_DIB:
1157 case CF_DIBV5:
1158 srcFormatId = request.format();
1159 break;
1160
1161 default:
1162 {
1163 auto name = clipboard->getServerFormat(request.format());
1164 if (!name.empty())
1165 {
1166 if (name == s_type_FileGroupDescriptorW)
1167 {
1168 srcFormatId =
1169 ClipboardGetFormatId(clipboard->_system, s_type_FileGroupDescriptorW);
1170
1171 if (cliprdr_file_context_has_local_support(clipboard->_file))
1172 {
1173 if (!cliprdr_file_context_update_server_data(
1174 clipboard->_file, clipboard->_system, data, size))
1175 {
1176 WLog_Print(clipboard->_log, WLOG_WARN,
1177 "File clipboard failed to update");
1178 }
1179 }
1180 }
1181 else if (name == s_type_HtmlFormat)
1182 {
1183 srcFormatId = ClipboardGetFormatId(clipboard->_system, s_type_HtmlFormat);
1184 }
1185 else if (mime_is_image(name) || mime_is_bmp(name))
1186 {
1187 srcFormatId = ClipboardGetFormatId(clipboard->_system, name.c_str());
1188 }
1189 }
1190 }
1191 break;
1192 }
1193
1194 if (!ClipboardSetData(clipboard->_system, srcFormatId, data, size))
1195 {
1196 /* Fail this request only: an error return here would end the clipboard channel
1197 * and, without auto-reconnect, the session. */
1198 WLog_Print(clipboard->_log, WLOG_ERROR, "error when setting clipboard data");
1199 request.setSuccess(false);
1200 break;
1201 }
1202 WLog_Print(clipboard->_log, WLOG_DEBUG, "updated clipboard data %s [0x%08" PRIx32 "]",
1203 ClipboardGetFormatName(clipboard->_system, srcFormatId), srcFormatId);
1204 } while (false);
1205
1206 if (!SetEvent(clipboard->_event))
1207 {
1208 WLog_Print(clipboard->_log, WLOG_ERROR, "error when setting clipboard event");
1209 return ERROR_INTERNAL_ERROR;
1210 }
1211
1212 return CHANNEL_RC_OK;
1213}
1214
1215const void* sdlClip::ClipDataCb(void* userdata, const char* mime_type, size_t* size)
1216{
1217 auto clip = static_cast<sdlClip*>(userdata);
1218 WINPR_ASSERT(clip);
1219 WINPR_ASSERT(size);
1220 WINPR_ASSERT(mime_type);
1221
1222 *size = 0;
1223 uint32_t len = 0;
1224
1225 if (mime_is_text(mime_type))
1226 {
1227 if (mime_is_utf8(mime_type))
1228 mime_type = mime_text_utf8;
1229 else
1230 mime_type = mime_text_plain;
1231 }
1232
1233 {
1234 ClipboardLockGuard systemlock(clip->_system);
1235 std::scoped_lock lock(clip->_lock);
1236
1237 if (!clip->_ctx)
1238 return nullptr;
1239
1240 /* check if we already used this mime type */
1241 auto cache = clip->_cache_data.find(mime_type);
1242 if (cache != clip->_cache_data.end())
1243 {
1244 clip->_returned_data = cache->second.ptr;
1245 *size = cache->second.size;
1246 return cache->second.ptr.get();
1247 }
1248
1249 auto formatID = clip->serverIdForMime(mime_type);
1250 if (formatID == 0)
1251 {
1252 WLog_Print(clip->_log, WLOG_DEBUG, "server did not announce a format for mime type %s",
1253 mime_type);
1254 return nullptr;
1255 }
1256
1257 /* Can we convert the data from existing formats in the clibpard? */
1258 uint32_t fsize = 0;
1259 auto mimeFormatID = ClipboardRegisterFormat(clip->_system, mime_type);
1260 auto fptr = ClipboardGetData(clip->_system, mimeFormatID, &fsize);
1261 if (fptr)
1262 {
1263 auto ptr = std::shared_ptr<void>(fptr, free);
1264 if (mime_is_text(mime_type))
1265 fsize = textLength(fptr, fsize);
1266 clip->_cache_data.emplace(mime_type, cache_entry{ fsize, ptr });
1267
1268 auto fcache = clip->_cache_data.find(mime_type);
1269 if (fcache != clip->_cache_data.end())
1270 {
1271 clip->_returned_data = fcache->second.ptr;
1272 *size = fcache->second.size;
1273 return fcache->second.ptr.get();
1274 }
1275 }
1276
1277 WLog_Print(clip->_log, WLOG_DEBUG, "requesting format %s [%s 0x%08" PRIx32 "]", mime_type,
1278 ClipboardGetFormatName(clip->_system, formatID), formatID);
1279
1280 /* From here until the reply, server data requests are answered on arrival (see
1281 * ReceiveFormatDataRequest). Those already queued get the same answer now: a local
1282 * application is reading our offer, so there is no client data to give. */
1283 clip->_reading_server = true;
1284 while (!clip->_server_requests.empty())
1285 {
1286 clip->_server_requests.pop_front();
1287 WLog_Print(clip->_log, WLOG_DEBUG,
1288 "local read of server data in progress, failing queued server request");
1289 std::ignore = clip->SendDataResponse(nullptr, 0);
1290 }
1291
1292 if (clip->SendDataRequest(formatID, mime_type))
1293 {
1294 clip->_reading_server = false;
1295 return nullptr;
1296 }
1297 }
1298 {
1299 HANDLE hdl[2] = { freerdp_abort_event(clip->_sdl->context()), clip->_event };
1300
1301 const UINT32 timeout =
1302 freerdp_settings_get_uint32(clip->_sdl->context()->settings, FreeRDP_TcpAckTimeout);
1303 DWORD status = WaitForMultipleObjects(ARRAYSIZE(hdl), hdl, FALSE, timeout);
1304
1305 if (status != WAIT_OBJECT_0 + 1)
1306 {
1307 std::scoped_lock lock(clip->_lock);
1308 clip->_reading_server = false;
1309 if (!clip->_request_queue.empty())
1310 clip->_request_queue.pop();
1311
1312 if (status == WAIT_TIMEOUT)
1313 WLog_Print(clip->_log, WLOG_ERROR,
1314 "no reply in 10 seconds, returning empty content");
1315
1316 return nullptr;
1317 }
1318 }
1319
1320 {
1321 ClipboardLockGuard systemlock(clip->_system);
1322 std::scoped_lock lock(clip->_lock);
1323 clip->_reading_server = false;
1324 if (clip->_request_queue.empty())
1325 return nullptr;
1326 /* take the request out of the queue: pop() destroys the queued one */
1327 auto request = std::move(clip->_request_queue.front());
1328 clip->_request_queue.pop();
1329
1330 if (clip->_request_queue.empty())
1331 std::ignore = ResetEvent(clip->_event);
1332
1333 if (request.success())
1334 {
1335 auto formatID = ClipboardRegisterFormat(clip->_system, mime_type);
1336 auto data = ClipboardGetData(clip->_system, formatID, &len);
1337 if (!data)
1338 {
1339 WLog_Print(clip->_log, WLOG_ERROR, "error retrieving clipboard data");
1340 return nullptr;
1341 }
1342
1343 auto ptr = std::shared_ptr<void>(data, free);
1344 if (mime_is_text(mime_type))
1345 len = textLength(data, len);
1346 clip->_cache_data.emplace(mime_type, cache_entry{ len, ptr });
1347 clip->_returned_data = ptr;
1348 *size = len;
1349 return ptr.get();
1350 }
1351
1352 return nullptr;
1353 }
1354}
1355
1356void sdlClip::ClipCleanCb(void* userdata)
1357{
1358 auto clip = static_cast<sdlClip*>(userdata);
1359 WINPR_ASSERT(clip);
1360 ClipboardLockGuard give_me_a_name(clip->_system);
1361 std::scoped_lock lock(clip->_lock);
1362 ClipboardEmpty(clip->_system);
1363 clip->_returned_data.reset();
1364}
1365
1366bool sdlClip::mime_is_file(const std::string& mime)
1367{
1368 if (strncmp(s_mime_uri_list, mime.c_str(), sizeof(s_mime_uri_list)) == 0)
1369 return true;
1370 if (strncmp(s_mime_gnome_copied_files, mime.c_str(), sizeof(s_mime_gnome_copied_files)) == 0)
1371 return true;
1372 if (strncmp(s_mime_mate_copied_files, mime.c_str(), sizeof(s_mime_mate_copied_files)) == 0)
1373 return true;
1374 return false;
1375}
1376
1377bool sdlClip::mime_is_text(const std::string& mime)
1378{
1379 for (const auto& tmime : s_mime_text())
1380 {
1381 assert(tmime != nullptr);
1382 if (mime == tmime)
1383 return true;
1384 }
1385
1386 return false;
1387}
1388
1389bool sdlClip::mime_is_utf8(const std::string& mime)
1390{
1391 if (mime == std::string(mime_text_utf8))
1392 return true;
1393
1394 return mime == std::string("UTF8_STRING");
1395}
1396
1397bool sdlClip::mime_is_image(const std::string& mime)
1398{
1399 for (const auto& imime : s_mime_image())
1400 {
1401 assert(imime != nullptr);
1402 if (mime == imime)
1403 return true;
1404 }
1405
1406 return false;
1407}
1408
1409bool sdlClip::mime_is_bmp(const std::string& mime)
1410{
1411 for (const auto& imime : s_mime_bitmap())
1412 {
1413 assert(imime != nullptr);
1414 if (mime == imime)
1415 return true;
1416 }
1417
1418 return false;
1419}
1420
1421bool sdlClip::mime_is_html(const std::string& mime)
1422{
1423 return mime.compare(s_mime_html) == 0;
1424}
1425
1426ClipRequest::ClipRequest(UINT32 format, const std::string& mime)
1427 : _format(format), _mime(mime), _success(false)
1428{
1429}
1430
1431uint32_t ClipRequest::format() const
1432{
1433 return _format;
1434}
1435
1436std::string ClipRequest::formatstr() const
1437{
1438 return ClipboardGetFormatIdString(_format);
1439}
1440
1441std::string ClipRequest::mime() const
1442{
1443 return _mime;
1444}
1445
1446bool ClipRequest::success() const
1447{
1448 return _success;
1449}
1450
1451void ClipRequest::setSuccess(bool status)
1452{
1453 _success = status;
1454}
1455
1456#if defined(__EMSCRIPTEN__)
1457/* Browser clipboard (text and images). The page calls freerdp_web_clipboard_offer() with what
1458 * the browser clipboard holds (UTF-8 text and/or an image converted to CF_DIB); we announce the
1459 * formats and answer the server's requests from that data. When the server announces text or a
1460 * CF_DIB image, we fetch it at once and hand it to the page (Module.freerdpClipboardWrite /
1461 * freerdpClipboardWriteImage), which writes it with the async Clipboard API (images as PNG). */
1462static const char s_web_mime_text[] = "x-freerdp-web-text";
1463static const char s_web_mime_dib[] = "x-freerdp-web-dib";
1464static const char s_web_mime_png[] = "x-freerdp-web-png";
1465
1466/* in sdl_clip_emscripten.js */
1467extern "C" void freerdp_web_clipboard_write_js(const char* utf8);
1468extern "C" void freerdp_web_clipboard_write_image_js(const BYTE* data, size_t size, int png);
1469
1470typedef struct
1471{
1472 char* text;
1473 BYTE* dib;
1474 size_t size;
1475 bool png;
1476} web_write_job;
1477
1478static void web_write_on_main(void* arg)
1479{
1480 auto job = static_cast<web_write_job*>(arg);
1481 if (job->text)
1482 freerdp_web_clipboard_write_js(job->text);
1483 if (job->dib)
1484 freerdp_web_clipboard_write_image_js(job->dib, job->size, job->png ? 1 : 0);
1485 free(job->text);
1486 free(job->dib);
1487 free(job);
1488}
1489
1490static void web_write(char* text, BYTE* dib, size_t size, bool png = false)
1491{
1492 auto job = static_cast<web_write_job*>(calloc(1, sizeof(web_write_job)));
1493 if (!job)
1494 {
1495 free(text);
1496 free(dib);
1497 return;
1498 }
1499 job->text = text;
1500 job->dib = dib;
1501 job->size = size;
1502 job->png = png;
1503 if (emscripten_is_main_browser_thread())
1504 web_write_on_main(job);
1505 else if (!emscripten_proxy_async(emscripten_proxy_get_system_queue(),
1506 emscripten_main_runtime_thread_id(), web_write_on_main, job))
1507 {
1508 free(text);
1509 free(dib);
1510 free(job);
1511 }
1512}
1513
1514bool sdlClip::webOffer(const char* utf8, const BYTE* dib, size_t dibSize)
1515{
1516 std::scoped_lock web(s_web_lock);
1517 auto clip = s_web_clip;
1518 if (!clip || !clip->_ctx || !clip->_ctx->ClientFormatList)
1519 return false;
1520 std::vector<CLIPRDR_FORMAT> formats;
1521 {
1522 std::scoped_lock lock(clip->_lock);
1523 const std::string text = utf8 ? utf8 : "";
1524 if (!clip->_web_offers.offer(text, dib, dibSize))
1525 return true;
1526 clip->_web_local = text;
1527 clip->_web_local_dib.assign(dib, dib ? dib + dibSize : dib);
1528 /* remember what we offered: the server may announce it back much later */
1529 if (!clip->_web_local.empty())
1530 clip->_web_recent.push_back(std::hash<std::string>{}(clip->_web_local));
1531 if (dib && dibSize)
1532 clip->_web_recent.push_back(std::hash<std::string_view>{}(
1533 std::string_view(reinterpret_cast<const char*>(dib), dibSize)));
1534 while (clip->_web_recent.size() > 16)
1535 clip->_web_recent.pop_front();
1536 if (!clip->_web_local.empty())
1537 {
1538 formats.push_back({ CF_UNICODETEXT, nullptr });
1539 formats.push_back({ CF_TEXT, nullptr });
1540 }
1541 if (!clip->_web_local_dib.empty())
1542 formats.push_back({ CF_DIB, nullptr });
1543 }
1544 if (formats.empty())
1545 return false;
1546 CLIPRDR_FORMAT_LIST list = {};
1547 list.common.msgType = CB_FORMAT_LIST;
1548 list.numFormats = static_cast<UINT32>(formats.size());
1549 list.formats = formats.data();
1550 return clip->_ctx->ClientFormatList(clip->_ctx, &list) == CHANNEL_RC_OK;
1551}
1552
1553bool sdlClip::webRequestServerText()
1554{
1555 bool has_text = false;
1556 bool has_dib = false;
1557 UINT32 png_id = 0;
1558 std::scoped_lock lock(_lock);
1559 for (const auto& f : _serverFormats)
1560 {
1561 has_text |= (f.formatId() == CF_UNICODETEXT);
1562 has_dib |= (f.formatId() == CF_DIB);
1563 /* GNOME Remote Desktop announces a PNG-only clipboard as "image/png" alone */
1564 if (f.formatName() && (strcmp(f.formatName(), s_mime_png) == 0))
1565 png_id = f.formatId();
1566 }
1567 if (!has_text && !has_dib && !png_id)
1568 return false;
1569 /* Keep the browser data for now: servers often announce our own offer back (an echo, e.g.
1570 * GNOME's clipboard handling). Clearing it here left nothing to answer the following data
1571 * request with. webTakeDataResponse() compares and only then hands over ownership. */
1572 bool ok = true;
1573 if (has_text)
1574 ok &= (SendDataRequest(CF_UNICODETEXT, s_web_mime_text) == CHANNEL_RC_OK);
1575 if (has_dib)
1576 ok &= (SendDataRequest(CF_DIB, s_web_mime_dib) == CHANNEL_RC_OK);
1577 else if (png_id) /* browsers write PNG anyway: take it as it is */
1578 ok &= (SendDataRequest(png_id, s_web_mime_png) == CHANNEL_RC_OK);
1579 return ok;
1580}
1581
1582bool sdlClip::webTakeDataResponse(const CLIPRDR_FORMAT_DATA_RESPONSE* response)
1583{
1584 std::string kind;
1585 {
1586 std::scoped_lock lock(_lock);
1587 if (_request_queue.empty())
1588 return false;
1589 kind = _request_queue.front().mime();
1590 if ((kind != s_web_mime_text) && (kind != s_web_mime_dib) && (kind != s_web_mime_png))
1591 return false;
1592 _request_queue.pop();
1593 }
1594
1595 if (!(response->common.msgFlags & CB_RESPONSE_OK) || !response->requestedFormatData)
1596 return true;
1597 const BYTE* data = response->requestedFormatData;
1598 const size_t size = response->common.dataLen;
1599 if (kind == s_web_mime_text)
1600 {
1601 char* utf8 = ConvertWCharNToUtf8Alloc(reinterpret_cast<const WCHAR*>(data),
1602 size / sizeof(WCHAR), nullptr);
1603 if (!utf8)
1604 return true;
1605 {
1606 std::scoped_lock lock(_lock);
1607 const auto hv = std::hash<std::string>{}(std::string(utf8));
1608 if (std::find(_web_recent.begin(), _web_recent.end(), hv) != _web_recent.end())
1609 {
1610 free(utf8); /* one of our own offers announced back: keep serving ours */
1611 return true;
1612 }
1613 _web_local.clear(); /* new content from the server: it owns the clipboard now */
1614 _web_local_dib.clear();
1615 _web_offers.serverSentText(utf8);
1616 }
1617 web_write(utf8, nullptr, 0);
1618 }
1619 else if ((kind == s_web_mime_png) ? (size > 8)
1620 : (size > 40)) /* PNG signature, BITMAPINFOHEADER */
1621 {
1622 {
1623 std::scoped_lock lock(_lock);
1624 const auto hv = std::hash<std::string_view>{}(
1625 std::string_view(reinterpret_cast<const char*>(data), size));
1626 if (std::find(_web_recent.begin(), _web_recent.end(), hv) != _web_recent.end())
1627 return true; /* one of our own images announced back */
1628 _web_local.clear();
1629 _web_local_dib.clear();
1630 _web_offers.serverSentImage();
1631 }
1632 auto copy = static_cast<BYTE*>(malloc(size));
1633 if (copy)
1634 {
1635 memcpy(copy, data, size);
1636 web_write(nullptr, copy, size, kind == s_web_mime_png);
1637 }
1638 }
1639 return true;
1640}
1641
1642bool sdlClip::webAnswerDataRequest(const CLIPRDR_FORMAT_DATA_REQUEST* request)
1643{
1644 std::string text;
1645 std::vector<BYTE> dib;
1646 {
1647 std::scoped_lock lock(_lock);
1648 if (_web_local.empty() && _web_local_dib.empty())
1649 return false;
1650 text = _web_local;
1651 dib = _web_local_dib;
1652 }
1653 switch (request->requestedFormatId)
1654 {
1655 case CF_UNICODETEXT:
1656 {
1657 if (text.empty())
1658 return false;
1659 WCHAR* wstr = ConvertUtf8NToWCharAlloc(text.c_str(), text.size() + 1, nullptr);
1660 if (!wstr)
1661 return false;
1662 /* UTF-16 including the terminating NUL, as CF_UNICODETEXT requires */
1663 std::ignore = SendDataResponse(reinterpret_cast<const BYTE*>(wstr),
1664 (_wcslen(wstr) + 1) * sizeof(WCHAR));
1665 free(wstr);
1666 return true;
1667 }
1668 case CF_TEXT:
1669 if (text.empty())
1670 return false;
1671 std::ignore =
1672 SendDataResponse(reinterpret_cast<const BYTE*>(text.c_str()), text.size() + 1);
1673 return true;
1674 case CF_DIB:
1675 if (dib.empty())
1676 return false;
1677 std::ignore = SendDataResponse(dib.data(), dib.size());
1678 return true;
1679 default:
1680 return false;
1681 }
1682}
1683
1684/* Called by the page on the main browser thread. That thread also runs FreeRDP's main loop
1685 * under Asyncify: when it is suspended in the middle of a transport write (e.g. waiting inside
1686 * a TLS write), calling into the channel from here would re-enter the same TLS connection on the
1687 * same thread; the transport lock does not stop that (same owner), the records interleave and
1688 * the server fails the connection with "bad record mac". So copy the data and send the format
1689 * list from a separate thread. */
1690typedef struct
1691{
1692 char* text;
1693 BYTE* dib;
1694 size_t size;
1695} web_offer_job;
1696
1697static void* web_offer_thread(void* arg)
1698{
1699 auto job = static_cast<web_offer_job*>(arg);
1700 std::ignore = sdlClip::webOffer(job->text, job->dib, job->size);
1701 free(job->text);
1702 free(job->dib);
1703 free(job);
1704 return nullptr;
1705}
1706
1707extern "C" EMSCRIPTEN_KEEPALIVE int freerdp_web_clipboard_offer(const char* utf8, const BYTE* dib,
1708 size_t dibSize)
1709{
1710 {
1711 std::scoped_lock web(s_web_lock);
1712 if (!s_web_clip)
1713 return 0;
1714 }
1715 auto job = static_cast<web_offer_job*>(calloc(1, sizeof(web_offer_job)));
1716 if (!job)
1717 return 0;
1718 job->text = utf8 ? _strdup(utf8) : nullptr;
1719 if (dib && dibSize)
1720 {
1721 job->dib = static_cast<BYTE*>(malloc(dibSize));
1722 if (job->dib)
1723 {
1724 memcpy(job->dib, dib, dibSize);
1725 job->size = dibSize;
1726 }
1727 }
1728 pthread_t tid = {};
1729 if (pthread_create(&tid, nullptr, web_offer_thread, job) != 0)
1730 {
1731 free(job->text);
1732 free(job->dib);
1733 free(job);
1734 return 0;
1735 }
1736 pthread_detach(tid);
1737 return 1;
1738}
1739#endif
object that handles clipboard context for the SDL3 client
Definition sdl_clip.hpp:66
WINPR_ATTR_NODISCARD FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
#define TAG