FreeRDP
Loading...
Searching...
No Matches
client_cliprdr_file.c
1
23
24#include <freerdp/config.h>
25
26#include <stdlib.h>
27#include <errno.h>
28
29#ifdef WITH_FUSE
30#define FUSE_USE_VERSION 30
31#include <fuse_lowlevel.h>
32#endif
33
34#if defined(WITH_FUSE)
35#include <sys/mount.h>
36#include <sys/stat.h>
37#include <errno.h>
38#include <time.h>
39#endif
40
41#include <winpr/crt.h>
42#include <winpr/string.h>
43#include <winpr/assert.h>
44#include <winpr/interlocked.h>
45#include <winpr/image.h>
46#include <winpr/stream.h>
47#include <winpr/clipboard.h>
48#include <winpr/path.h>
49
50#include <freerdp/utils/helpers.h>
51#include <freerdp/utils/signal.h>
52#include <freerdp/log.h>
53#include <freerdp/client/cliprdr.h>
54#include <freerdp/channels/channels.h>
55#include <freerdp/channels/cliprdr.h>
56
57#include <freerdp/client/client_cliprdr_file.h>
58
59#if defined(WITH_CLIPRDR_FILE_APPLE)
60#include <sys/time.h>
61
62#include <winpr/file.h>
63
64#include <freerdp/freerdp.h>
65#include <freerdp/settings.h>
66#include <freerdp/utils/cliprdr_utils.h>
67
68#include "client_cliprdr_file_apple.h"
69#endif
70
71#define NO_CLIP_DATA_ID (UINT64_C(1) << 32)
72#define WIN32_FILETIME_TO_UNIX_EPOCH INT64_C(11644473600)
73
74#ifdef WITH_DEBUG_CLIPRDR
75#define DEBUG_CLIPRDR(log, ...) WLog_Print(log, WLOG_DEBUG, __VA_ARGS__)
76#else
77#define DEBUG_CLIPRDR(log, ...) \
78 do \
79 { \
80 } while (0)
81#endif
82
83#if defined(WITH_FUSE)
84typedef enum eFuseLowlevelOperationType
85{
86 FUSE_LL_OPERATION_NONE,
87 FUSE_LL_OPERATION_LOOKUP,
88 FUSE_LL_OPERATION_GETATTR,
89 FUSE_LL_OPERATION_READ,
90} FuseLowlevelOperationType;
91
92typedef struct sCliprdrFuseFile CliprdrFuseFile;
93
94struct sCliprdrFuseFile
95{
96 CliprdrFuseFile* parent;
97 wArrayList* children;
98
99 size_t filename_len;
100 const char* filename;
101
102 size_t filename_with_root_len;
103 char* filename_with_root;
104 UINT32 list_idx;
105 fuse_ino_t ino;
106
107 BOOL is_directory;
108 BOOL is_readonly;
109
110 BOOL has_size;
111 UINT64 size;
112
113 BOOL has_last_write_time;
114 INT64 last_write_time_unix;
115
116 BOOL has_clip_data_id;
117 UINT32 clip_data_id;
118};
119
120typedef struct
121{
122 CliprdrFileContext* file_context;
123
124 CliprdrFuseFile* clip_data_dir;
125
126 BOOL has_clip_data_id;
127 UINT32 clip_data_id;
128} CliprdrFuseClipDataEntry;
129
130typedef struct
131{
132 CliprdrFileContext* file_context;
133
134 wArrayList* fuse_files;
135
136 BOOL all_files;
137 BOOL has_clip_data_id;
138 UINT32 clip_data_id;
139} FuseFileClearContext;
140
141typedef struct
142{
143 FuseLowlevelOperationType operation_type;
144 CliprdrFuseFile* fuse_file;
145 fuse_req_t fuse_req;
146 UINT32 stream_id;
147} CliprdrFuseRequest;
148#endif
149
150typedef struct
151{
152 char* name;
153 FILE* fp;
154 INT64 size;
155 CliprdrFileContext* context;
156} CliprdrLocalFile;
157
158typedef struct
159{
160 UINT32 lockId;
161 BOOL locked;
162 size_t count;
163 CliprdrLocalFile* files;
164 CliprdrFileContext* context;
165} CliprdrLocalStream;
166
167struct cliprdr_file_context
168{
169#if defined(WITH_FUSE)
170 /* FUSE related**/
171 HANDLE fuse_start_sync;
172 HANDLE fuse_stop_sync;
173 HANDLE fuse_thread;
174 LONG fuse_failed; /* no mount: what the server copies cannot be pasted here */
175 struct fuse_session* fuse_sess;
176#if FUSE_USE_VERSION < 30
177 struct fuse_chan* ch;
178#endif
179
180 wHashTable* inode_table;
181 wHashTable* dir_table;
182 wHashTable* clip_data_table;
183 wHashTable* request_table;
184
185 CliprdrFuseClipDataEntry* clip_data_entry_without_id;
186 UINT32 current_clip_data_id;
187
188 fuse_ino_t next_ino;
189 UINT32 next_clip_data_id;
190 UINT32 next_stream_id;
191#endif
192
193#if defined(WITH_CLIPRDR_FILE_APPLE)
194 /* The pending FILECONTENTS request of the download queue, answered on the channel
195 * thread */
196 CRITICAL_SECTION apple_lock;
197 BOOL apple_cancelled;
198 UINT32 apple_generation; /* changes with the server clipboard, see apple_lock */
199 HANDLE apple_contents_event;
200 UINT32 apple_stream_id;
201 BOOL apple_contents_success;
202 BYTE* apple_contents_data;
203 UINT32 apple_contents_size;
204#endif
205
206 /* File clipping */
207 BOOL file_formats_registered;
208 UINT32 file_capability_flags;
209
210 UINT32 local_lock_id;
211
212 wHashTable* local_streams;
213 wLog* log;
214 void* clipboard;
215 CliprdrClientContext* context;
216 char* path;
217 char* exposed_path;
218 BYTE server_data_hash[WINPR_SHA256_DIGEST_LENGTH];
219 BYTE client_data_hash[WINPR_SHA256_DIGEST_LENGTH];
220};
221
222#if defined(WITH_FUSE)
223static CliprdrFuseFile* get_fuse_file_by_ino(CliprdrFileContext* file_context, fuse_ino_t fuse_ino);
224
225static void fuse_file_free(void* data)
226{
227 CliprdrFuseFile* fuse_file = data;
228
229 if (!fuse_file)
230 return;
231
232 ArrayList_Free(fuse_file->children);
233 free(fuse_file->filename_with_root);
234
235 free(fuse_file);
236}
237
238WINPR_ATTR_FORMAT_ARG(1, 2)
239WINPR_ATTR_MALLOC(fuse_file_free, 1)
240WINPR_ATTR_NODISCARD
241static CliprdrFuseFile* fuse_file_new(WINPR_FORMAT_ARG const char* fmt, ...)
242{
243 CliprdrFuseFile* file = calloc(1, sizeof(CliprdrFuseFile));
244 if (!file)
245 return nullptr;
246
247 file->children = ArrayList_New(FALSE);
248 if (!file->children)
249 goto fail;
250
251 WINPR_ASSERT(fmt);
252
253 {
254 va_list ap = WINPR_C_ARRAY_INIT;
255 va_start(ap, fmt);
256 const int rc =
257 winpr_vasprintf(&file->filename_with_root, &file->filename_with_root_len, fmt, ap);
258 va_end(ap);
259
260 if (rc < 0)
261 goto fail;
262 }
263
264 if (file->filename_with_root && (file->filename_with_root_len > 0))
265 {
266 file->filename_len = 0;
267 file->filename = strrchr(file->filename_with_root, '/') + 1;
268 if (file->filename)
269 file->filename_len = strnlen(file->filename, file->filename_with_root_len);
270 }
271 return file;
272fail:
273 fuse_file_free(file);
274 return nullptr;
275}
276
277static void clip_data_entry_free(void* data)
278{
279 CliprdrFuseClipDataEntry* clip_data_entry = data;
280
281 if (!clip_data_entry)
282 return;
283
284 if (clip_data_entry->has_clip_data_id)
285 {
286 CliprdrFileContext* file_context = clip_data_entry->file_context;
287 CLIPRDR_UNLOCK_CLIPBOARD_DATA unlock_clipboard_data = WINPR_C_ARRAY_INIT;
288
289 WINPR_ASSERT(file_context);
290
291 unlock_clipboard_data.common.msgType = CB_UNLOCK_CLIPDATA;
292 unlock_clipboard_data.clipDataId = clip_data_entry->clip_data_id;
293
294 const UINT rc = file_context->context->ClientUnlockClipboardData(file_context->context,
295 &unlock_clipboard_data);
296 if (rc != CHANNEL_RC_OK)
297 WLog_Print(file_context->log, WLOG_DEBUG,
298 "ClientUnlockClipboardData failed with %" PRIu32, rc);
299
300 clip_data_entry->has_clip_data_id = FALSE;
301
302 WLog_Print(file_context->log, WLOG_DEBUG, "Destroyed ClipDataEntry with id %u",
303 clip_data_entry->clip_data_id);
304 }
305
306 free(clip_data_entry);
307}
308
309static BOOL does_server_support_clipdata_locking(CliprdrFileContext* file_context)
310{
311 WINPR_ASSERT(file_context);
312
313 return (cliprdr_file_context_remote_get_flags(file_context) & CB_CAN_LOCK_CLIPDATA) != 0;
314}
315
316static UINT32 get_next_free_clip_data_id(CliprdrFileContext* file_context)
317{
318 UINT32 clip_data_id = 0;
319
320 WINPR_ASSERT(file_context);
321
322 HashTable_Lock(file_context->inode_table);
323 clip_data_id = file_context->next_clip_data_id;
324 while (clip_data_id == 0 ||
325 HashTable_GetItemValue(file_context->clip_data_table, (void*)(uintptr_t)clip_data_id))
326 ++clip_data_id;
327
328 file_context->next_clip_data_id = clip_data_id + 1;
329 HashTable_Unlock(file_context->inode_table);
330
331 return clip_data_id;
332}
333
334static CliprdrFuseClipDataEntry* clip_data_entry_new(CliprdrFileContext* file_context,
335 BOOL needs_clip_data_id)
336{
337 CliprdrFuseClipDataEntry* clip_data_entry = nullptr;
338 CLIPRDR_LOCK_CLIPBOARD_DATA lock_clipboard_data = WINPR_C_ARRAY_INIT;
339
340 WINPR_ASSERT(file_context);
341
342 clip_data_entry = calloc(1, sizeof(CliprdrFuseClipDataEntry));
343 if (!clip_data_entry)
344 return nullptr;
345
346 clip_data_entry->file_context = file_context;
347 clip_data_entry->clip_data_id = get_next_free_clip_data_id(file_context);
348
349 if (!needs_clip_data_id)
350 return clip_data_entry;
351
352 lock_clipboard_data.common.msgType = CB_LOCK_CLIPDATA;
353 lock_clipboard_data.clipDataId = clip_data_entry->clip_data_id;
354
355 if (file_context->context->ClientLockClipboardData(file_context->context, &lock_clipboard_data))
356 {
357 HashTable_Lock(file_context->inode_table);
358 clip_data_entry_free(clip_data_entry);
359 HashTable_Unlock(file_context->inode_table);
360 return nullptr;
361 }
362 clip_data_entry->has_clip_data_id = TRUE;
363
364 WLog_Print(file_context->log, WLOG_DEBUG, "Created ClipDataEntry with id %u",
365 clip_data_entry->clip_data_id);
366
367 return clip_data_entry;
368}
369
370static BOOL should_remove_fuse_file(CliprdrFuseFile* fuse_file, BOOL all_files,
371 BOOL has_clip_data_id, UINT32 clip_data_id)
372{
373 if (all_files)
374 return TRUE;
375
376 if (fuse_file->ino == FUSE_ROOT_ID)
377 return FALSE;
378 if (!fuse_file->has_clip_data_id && !has_clip_data_id)
379 return TRUE;
380 if (fuse_file->has_clip_data_id && has_clip_data_id &&
381 (fuse_file->clip_data_id == clip_data_id))
382 return TRUE;
383
384 return FALSE;
385}
386
387static BOOL maybe_clear_fuse_request(const void* key, void* value, void* arg)
388{
389 CliprdrFuseRequest* fuse_request = value;
390 FuseFileClearContext* clear_context = arg;
391 CliprdrFileContext* file_context = clear_context->file_context;
392 CliprdrFuseFile* fuse_file = fuse_request->fuse_file;
393
394 WINPR_ASSERT(file_context);
395
396 if (!should_remove_fuse_file(fuse_file, clear_context->all_files,
397 clear_context->has_clip_data_id, clear_context->clip_data_id))
398 return TRUE;
399
400 DEBUG_CLIPRDR(file_context->log, "Clearing FileContentsRequest for file \"%s\"",
401 fuse_file->filename_with_root);
402
403 fuse_reply_err(fuse_request->fuse_req, EIO);
404 HashTable_Remove(file_context->request_table, key);
405
406 return TRUE;
407}
408
409static BOOL maybe_steal_inode(const void* key, void* value, void* arg)
410{
411 CliprdrFuseFile* fuse_file = value;
412 FuseFileClearContext* clear_context = arg;
413 CliprdrFileContext* file_context = clear_context->file_context;
414
415 WINPR_ASSERT(file_context);
416
417 if (should_remove_fuse_file(fuse_file, clear_context->all_files,
418 clear_context->has_clip_data_id, clear_context->clip_data_id))
419 {
420 if (!ArrayList_Append(clear_context->fuse_files, fuse_file))
421 WLog_Print(file_context->log, WLOG_ERROR,
422 "Failed to append FUSE file to list for deletion");
423
424 if (!clear_context->all_files && fuse_file->is_directory)
425 {
426 HashTable_Remove(file_context->dir_table, fuse_file->filename_with_root);
427 }
428 HashTable_Remove(file_context->inode_table, key);
429 }
430
431 return TRUE;
432}
433
434static BOOL notify_delete_child(void* data, WINPR_ATTR_UNUSED size_t index, va_list ap)
435{
436 CliprdrFuseFile* child = data;
437
438 WINPR_ASSERT(child);
439
440 CliprdrFileContext* file_context = va_arg(ap, CliprdrFileContext*);
441 CliprdrFuseFile* parent = va_arg(ap, CliprdrFuseFile*);
442
443 WINPR_ASSERT(file_context);
444 WINPR_ASSERT(parent);
445
446 WINPR_ASSERT(file_context->fuse_sess);
447 fuse_lowlevel_notify_delete(file_context->fuse_sess, parent->ino, child->ino, child->filename,
448 child->filename_len);
449
450 return TRUE;
451}
452
453static BOOL invalidate_inode(void* data, WINPR_ATTR_UNUSED size_t index, va_list ap)
454{
455 CliprdrFuseFile* fuse_file = data;
456
457 WINPR_ASSERT(fuse_file);
458
459 CliprdrFileContext* file_context = va_arg(ap, CliprdrFileContext*);
460 WINPR_ASSERT(file_context);
461 WINPR_ASSERT(file_context->fuse_sess);
462
463 const BOOL res =
464 ArrayList_ForEach(fuse_file->children, notify_delete_child, file_context, fuse_file);
465
466 DEBUG_CLIPRDR(file_context->log, "Invalidating inode %lu for file \"%s\"", fuse_file->ino,
467 fuse_file->filename);
468 fuse_lowlevel_notify_inval_inode(file_context->fuse_sess, fuse_file->ino, 0, 0);
469 WLog_Print(file_context->log, WLOG_DEBUG, "Inode %lu invalidated", fuse_file->ino);
470
471 return res;
472}
473
474WINPR_ATTR_NODISCARD
475static bool clear_selection(CliprdrFileContext* file_context, BOOL all_selections,
476 CliprdrFuseClipDataEntry* clip_data_entry)
477{
478 bool res = true;
479 FuseFileClearContext clear_context = WINPR_C_ARRAY_INIT;
480 CliprdrFuseFile* clip_data_dir = nullptr;
481
482 WINPR_ASSERT(file_context);
483
484 clear_context.file_context = file_context;
485 clear_context.fuse_files = ArrayList_New(FALSE);
486 WINPR_ASSERT(clear_context.fuse_files);
487
488 wObject* aobj = ArrayList_Object(clear_context.fuse_files);
489 WINPR_ASSERT(aobj);
490 aobj->fnObjectFree = fuse_file_free;
491
492 if (clip_data_entry)
493 {
494 clip_data_dir = clip_data_entry->clip_data_dir;
495 clip_data_entry->clip_data_dir = nullptr;
496
497 WINPR_ASSERT(clip_data_dir);
498
499 CliprdrFuseFile* root_dir = get_fuse_file_by_ino(file_context, FUSE_ROOT_ID);
500 if (root_dir)
501 ArrayList_Remove(root_dir->children, clip_data_dir);
502
503 clear_context.has_clip_data_id = clip_data_dir->has_clip_data_id;
504 clear_context.clip_data_id = clip_data_dir->clip_data_id;
505 }
506 clear_context.all_files = all_selections;
507
508 if (clip_data_entry && clip_data_entry->has_clip_data_id)
509 WLog_Print(file_context->log, WLOG_DEBUG, "Clearing selection for clipDataId %u",
510 clip_data_entry->clip_data_id);
511 else
512 WLog_Print(file_context->log, WLOG_DEBUG, "Clearing selection%s",
513 all_selections ? "s" : "");
514
515 if (!HashTable_Foreach(file_context->request_table, maybe_clear_fuse_request, &clear_context))
516 res = false;
517 if (all_selections)
518 {
519 HashTable_Clear(file_context->dir_table);
520 }
521 if (!HashTable_Foreach(file_context->inode_table, maybe_steal_inode, &clear_context))
522 res = false;
523 HashTable_Unlock(file_context->inode_table);
524
525 if (file_context->fuse_sess)
526 {
527 /*
528 * fuse_lowlevel_notify_inval_inode() is a blocking operation. If we receive a
529 * FUSE request (e.g. read()), then FUSE would block in read(), since the
530 * mutex of the inode_table would still be locked, if we wouldn't unlock it
531 * here.
532 * So, to avoid a deadlock here, unlock the mutex and reply all incoming
533 * operations with -ENOENT until the invalidation process is complete.
534 */
535 if (!ArrayList_ForEach(clear_context.fuse_files, invalidate_inode, file_context))
536 res = false;
537 CliprdrFuseFile* root_dir = get_fuse_file_by_ino(file_context, FUSE_ROOT_ID);
538 if (clip_data_dir && root_dir)
539 {
540 fuse_lowlevel_notify_delete(file_context->fuse_sess, root_dir->ino, clip_data_dir->ino,
541 clip_data_dir->filename, clip_data_dir->filename_len);
542 }
543 }
544 ArrayList_Free(clear_context.fuse_files);
545
546 HashTable_Lock(file_context->inode_table);
547 if (clip_data_entry && clip_data_entry->has_clip_data_id)
548 WLog_Print(file_context->log, WLOG_DEBUG, "Selection cleared for clipDataId %u",
549 clip_data_entry->clip_data_id);
550 else
551 WLog_Print(file_context->log, WLOG_DEBUG, "Selection%s cleared", all_selections ? "s" : "");
552 return res;
553}
554
555WINPR_ATTR_NODISCARD
556static bool clear_entry_selection(CliprdrFuseClipDataEntry* clip_data_entry)
557{
558 WINPR_ASSERT(clip_data_entry);
559
560 if (!clip_data_entry->clip_data_dir)
561 return true;
562
563 return clear_selection(clip_data_entry->file_context, FALSE, clip_data_entry);
564}
565
566WINPR_ATTR_NODISCARD
567static bool clear_no_cdi_entry(CliprdrFileContext* file_context)
568{
569 BOOL res = true;
570 WINPR_ASSERT(file_context);
571
572 WINPR_ASSERT(file_context->inode_table);
573 HashTable_Lock(file_context->inode_table);
574 if (file_context->clip_data_entry_without_id)
575 {
576 res = clear_entry_selection(file_context->clip_data_entry_without_id);
577
578 clip_data_entry_free(file_context->clip_data_entry_without_id);
579 file_context->clip_data_entry_without_id = nullptr;
580 }
581 HashTable_Unlock(file_context->inode_table);
582 return res;
583}
584
585WINPR_ATTR_NODISCARD
586static BOOL clear_clip_data_entries(WINPR_ATTR_UNUSED const void* key, void* value,
587 WINPR_ATTR_UNUSED void* arg)
588{
589 return clear_entry_selection(value);
590}
591
592WINPR_ATTR_NODISCARD
593static UINT clear_cdi_entries(CliprdrFileContext* file_context)
594{
595 UINT res = CHANNEL_RC_OK;
596 WINPR_ASSERT(file_context);
597
598 HashTable_Lock(file_context->inode_table);
599 if (!HashTable_Foreach(file_context->clip_data_table, clear_clip_data_entries, nullptr))
600 res = ERROR_INTERNAL_ERROR;
601
602 HashTable_Clear(file_context->clip_data_table);
603 HashTable_Unlock(file_context->inode_table);
604
605 return res;
606}
607
608static UINT prepare_clip_data_entry_with_id(CliprdrFileContext* file_context)
609{
610 CliprdrFuseClipDataEntry* clip_data_entry = nullptr;
611
612 WINPR_ASSERT(file_context);
613
614 clip_data_entry = clip_data_entry_new(file_context, TRUE);
615 if (!clip_data_entry)
616 {
617 WLog_Print(file_context->log, WLOG_ERROR, "Failed to create clipDataEntry");
618 return ERROR_INTERNAL_ERROR;
619 }
620
621 HashTable_Lock(file_context->inode_table);
622 if (!HashTable_Insert(file_context->clip_data_table,
623 (void*)(uintptr_t)clip_data_entry->clip_data_id, clip_data_entry))
624 {
625 WLog_Print(file_context->log, WLOG_ERROR, "Failed to insert clipDataEntry");
626 clip_data_entry_free(clip_data_entry);
627 HashTable_Unlock(file_context->inode_table);
628 return ERROR_INTERNAL_ERROR;
629 }
630 HashTable_Unlock(file_context->inode_table);
631
632 // HashTable_Insert owns clip_data_entry
633 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
634 file_context->current_clip_data_id = clip_data_entry->clip_data_id;
635
636 return CHANNEL_RC_OK;
637}
638
639static UINT prepare_clip_data_entry_without_id(CliprdrFileContext* file_context)
640{
641 WINPR_ASSERT(file_context);
642 WINPR_ASSERT(!file_context->clip_data_entry_without_id);
643
644 file_context->clip_data_entry_without_id = clip_data_entry_new(file_context, FALSE);
645 if (!file_context->clip_data_entry_without_id)
646 {
647 WLog_Print(file_context->log, WLOG_ERROR, "Failed to create clipDataEntry");
648 return ERROR_INTERNAL_ERROR;
649 }
650
651 return CHANNEL_RC_OK;
652}
653#endif
654
655#if defined(WITH_CLIPRDR_FILE_APPLE)
656/* The clipboard the server files were offered from is gone: their list indices would address
657 * the files of another copy now. Fail the pending FILECONTENTS request of such an offer and
658 * every later one. */
659static void apple_new_generation(CliprdrFileContext* file)
660{
661 WINPR_ASSERT(file);
662
663 EnterCriticalSection(&file->apple_lock);
664 file->apple_generation++;
665 (void)SetEvent(file->apple_contents_event);
666 LeaveCriticalSection(&file->apple_lock);
667}
668#endif
669
670UINT cliprdr_file_context_notify_new_server_format_list(CliprdrFileContext* file_context)
671{
672 UINT rc = CHANNEL_RC_OK;
673 WINPR_ASSERT(file_context);
674 WINPR_ASSERT(file_context->context);
675
676#if defined(WITH_FUSE)
677 if (!clear_no_cdi_entry(file_context))
678 return ERROR_INTERNAL_ERROR;
679 /* TODO: assign timeouts to old locks instead */
680 rc = clear_cdi_entries(file_context);
681 if (rc != CHANNEL_RC_OK)
682 return rc;
683
684 if (does_server_support_clipdata_locking(file_context))
685 rc = prepare_clip_data_entry_with_id(file_context);
686 else
687 rc = prepare_clip_data_entry_without_id(file_context);
688#endif
689#if defined(WITH_CLIPRDR_FILE_APPLE)
690 apple_new_generation(file_context);
691#endif
692 return rc;
693}
694
695UINT cliprdr_file_context_notify_new_client_format_list(CliprdrFileContext* file_context)
696{
697 WINPR_ASSERT(file_context);
698 WINPR_ASSERT(file_context->context);
699
700#if defined(WITH_CLIPRDR_FILE_APPLE)
701 apple_new_generation(file_context);
702#endif
703#if defined(WITH_FUSE)
704 if (!clear_no_cdi_entry(file_context))
705 return ERROR_INTERNAL_ERROR;
706 /* TODO: assign timeouts to old locks instead */
707 return clear_cdi_entries(file_context);
708#endif
709
710 return CHANNEL_RC_OK;
711}
712
713static CliprdrLocalStream* cliprdr_local_stream_new(CliprdrFileContext* context, UINT32 streamID,
714 const char* data, size_t size);
715static void cliprdr_file_session_terminate(CliprdrFileContext* file, BOOL stop_thread);
716static BOOL local_stream_discard(const void* key, void* value, void* arg);
717
718WINPR_ATTR_FORMAT_ARG(6, 7)
719static void writelog(wLog* log, DWORD level, const char* fname, const char* fkt, size_t line,
720 WINPR_FORMAT_ARG const char* fmt, ...)
721{
722 if (!WLog_IsLevelActive(log, level))
723 return;
724
725 va_list ap = WINPR_C_ARRAY_INIT;
726 va_start(ap, fmt);
727 WLog_PrintTextMessageVA(log, level, line, fname, fkt, fmt, ap);
728 va_end(ap);
729}
730
731#if defined(WITH_FUSE)
732static CliprdrFuseFile* fuse_file_new_root(CliprdrFileContext* file_context);
733static void cliprdr_file_fuse_lookup(fuse_req_t req, fuse_ino_t parent, const char* name);
734static void cliprdr_file_fuse_getattr(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi);
735static void cliprdr_file_fuse_readdir(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
736 struct fuse_file_info* fi);
737static void cliprdr_file_fuse_read(fuse_req_t req, fuse_ino_t ino, size_t size, off_t off,
738 struct fuse_file_info* fi);
739static void cliprdr_file_fuse_open(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi);
740static void cliprdr_file_fuse_opendir(fuse_req_t req, fuse_ino_t ino, struct fuse_file_info* fi);
741
742static const struct fuse_lowlevel_ops cliprdr_file_fuse_oper = {
743 .lookup = cliprdr_file_fuse_lookup,
744 .getattr = cliprdr_file_fuse_getattr,
745 .readdir = cliprdr_file_fuse_readdir,
746 .open = cliprdr_file_fuse_open,
747 .read = cliprdr_file_fuse_read,
748 .opendir = cliprdr_file_fuse_opendir,
749};
750
751CliprdrFuseFile* get_fuse_file_by_ino(CliprdrFileContext* file_context, fuse_ino_t fuse_ino)
752{
753 WINPR_ASSERT(file_context);
754
755 return HashTable_GetItemValue(file_context->inode_table, (void*)(uintptr_t)fuse_ino);
756}
757
758static CliprdrFuseFile*
759get_fuse_file_by_name_from_parent(WINPR_ATTR_UNUSED CliprdrFileContext* file_context,
760 CliprdrFuseFile* parent, const char* name)
761{
762 WINPR_ASSERT(file_context);
763 WINPR_ASSERT(parent);
764
765 for (size_t i = 0; i < ArrayList_Count(parent->children); ++i)
766 {
767 CliprdrFuseFile* child = ArrayList_GetItem(parent->children, i);
768
769 WINPR_ASSERT(child);
770
771 if (strncmp(name, child->filename, child->filename_len + 1) == 0)
772 return child;
773 }
774
775 DEBUG_CLIPRDR(file_context->log, "Requested file \"%s\" in directory \"%s\" does not exist",
776 name, parent->filename);
777
778 return nullptr;
779}
780
781static CliprdrFuseRequest* cliprdr_fuse_request_new(CliprdrFileContext* file_context,
782 CliprdrFuseFile* fuse_file, fuse_req_t fuse_req,
783 FuseLowlevelOperationType operation_type)
784{
785 CliprdrFuseRequest* fuse_request = nullptr;
786 UINT32 stream_id = file_context->next_stream_id;
787
788 WINPR_ASSERT(file_context);
789 WINPR_ASSERT(fuse_file);
790
791 fuse_request = calloc(1, sizeof(CliprdrFuseRequest));
792 if (!fuse_request)
793 {
794 WLog_Print(file_context->log, WLOG_ERROR, "Failed to allocate FUSE request for file \"%s\"",
795 fuse_file->filename_with_root);
796 return nullptr;
797 }
798
799 fuse_request->fuse_file = fuse_file;
800 fuse_request->fuse_req = fuse_req;
801 fuse_request->operation_type = operation_type;
802
803 while (stream_id == 0 ||
804 HashTable_GetItemValue(file_context->request_table, (void*)(uintptr_t)stream_id))
805 ++stream_id;
806 fuse_request->stream_id = stream_id;
807
808 file_context->next_stream_id = stream_id + 1;
809
810 if (!HashTable_Insert(file_context->request_table, (void*)(uintptr_t)fuse_request->stream_id,
811 fuse_request))
812 {
813 WLog_Print(file_context->log, WLOG_ERROR, "Failed to track FUSE request for file \"%s\"",
814 fuse_file->filename_with_root);
815 free(fuse_request);
816 return nullptr;
817 }
818
819 return fuse_request;
820}
821
822static BOOL request_file_size_async(CliprdrFileContext* file_context, CliprdrFuseFile* fuse_file,
823 fuse_req_t fuse_req, FuseLowlevelOperationType operation_type)
824{
825 CliprdrFuseRequest* fuse_request = nullptr;
826 CLIPRDR_FILE_CONTENTS_REQUEST file_contents_request = WINPR_C_ARRAY_INIT;
827
828 WINPR_ASSERT(file_context);
829 WINPR_ASSERT(fuse_file);
830
831 fuse_request = cliprdr_fuse_request_new(file_context, fuse_file, fuse_req, operation_type);
832 if (!fuse_request)
833 return FALSE;
834
835 file_contents_request.common.msgType = CB_FILECONTENTS_REQUEST;
836 file_contents_request.streamId = fuse_request->stream_id;
837 file_contents_request.listIndex = fuse_file->list_idx;
838 file_contents_request.dwFlags = FILECONTENTS_SIZE;
839 file_contents_request.cbRequested = 0x8;
840 file_contents_request.haveClipDataId = fuse_file->has_clip_data_id;
841 file_contents_request.clipDataId = fuse_file->clip_data_id;
842
843 if (file_context->context->ClientFileContentsRequest(file_context->context,
844 &file_contents_request))
845 {
846 WLog_Print(file_context->log, WLOG_ERROR,
847 "Failed to send FileContentsRequest for file \"%s\"",
848 fuse_file->filename_with_root);
849 HashTable_Remove(file_context->request_table, (void*)(uintptr_t)fuse_request->stream_id);
850 return FALSE;
851 }
852 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
853 DEBUG_CLIPRDR(file_context->log, "Requested file size for file \"%s\" with stream id %u",
854 fuse_file->filename, fuse_request->stream_id);
855
856 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
857 return TRUE;
858}
859
860WINPR_ATTR_NODISCARD
861static BOOL write_file_attributes(CliprdrFuseFile* fuse_file, struct stat* attr)
862{
863 memset(attr, 0, sizeof(struct stat));
864
865 if (!fuse_file || (fuse_file->size > INT64_MAX))
866 return FALSE;
867
868 attr->st_ino = fuse_file->ino;
869 if (fuse_file->is_directory)
870 {
871 attr->st_mode = S_IFDIR | (fuse_file->is_readonly ? 0555 : 0755);
872 attr->st_nlink = 2;
873 }
874 else
875 {
876 attr->st_mode = S_IFREG | (fuse_file->is_readonly ? 0444 : 0644);
877 attr->st_nlink = 1;
878 attr->st_size = WINPR_ASSERTING_INT_CAST(off_t, fuse_file->size);
879 }
880 attr->st_uid = getuid();
881 attr->st_gid = getgid();
882 attr->st_atime = attr->st_mtime = attr->st_ctime =
883 (fuse_file->has_last_write_time ? fuse_file->last_write_time_unix : time(nullptr));
884 return TRUE;
885}
886
887static void cliprdr_file_fuse_lookup(fuse_req_t fuse_req, fuse_ino_t parent_ino, const char* name)
888{
889 CliprdrFileContext* file_context = fuse_req_userdata(fuse_req);
890 CliprdrFuseFile* parent = nullptr;
891 CliprdrFuseFile* fuse_file = nullptr;
892 struct fuse_entry_param entry = WINPR_C_ARRAY_INIT;
893
894 WINPR_ASSERT(file_context);
895
896 HashTable_Lock(file_context->inode_table);
897 if (!(parent = get_fuse_file_by_ino(file_context, parent_ino)) || !parent->is_directory)
898 {
899 HashTable_Unlock(file_context->inode_table);
900 fuse_reply_err(fuse_req, ENOENT);
901 return;
902 }
903 if (!(fuse_file = get_fuse_file_by_name_from_parent(file_context, parent, name)))
904 {
905 HashTable_Unlock(file_context->inode_table);
906 fuse_reply_err(fuse_req, ENOENT);
907 return;
908 }
909
910 DEBUG_CLIPRDR(file_context->log, "lookup() has been called for \"%s\"", name);
911 DEBUG_CLIPRDR(file_context->log, "Parent is \"%s\", child is \"%s\"",
912 parent->filename_with_root, fuse_file->filename_with_root);
913
914 if (!fuse_file->is_directory && !fuse_file->has_size)
915 {
916 BOOL result = 0;
917
918 result =
919 request_file_size_async(file_context, fuse_file, fuse_req, FUSE_LL_OPERATION_LOOKUP);
920 HashTable_Unlock(file_context->inode_table);
921
922 if (!result)
923 fuse_reply_err(fuse_req, EIO);
924
925 return;
926 }
927
928 entry.ino = fuse_file->ino;
929 if (!write_file_attributes(fuse_file, &entry.attr))
930 {
931 HashTable_Unlock(file_context->inode_table);
932 fuse_reply_err(fuse_req, ERANGE);
933 return;
934 }
935 entry.attr_timeout = 1.0;
936 entry.entry_timeout = 1.0;
937 HashTable_Unlock(file_context->inode_table);
938
939 fuse_reply_entry(fuse_req, &entry);
940}
941
942static void cliprdr_file_fuse_getattr(fuse_req_t fuse_req, fuse_ino_t fuse_ino,
943 WINPR_ATTR_UNUSED struct fuse_file_info* file_info)
944{
945 CliprdrFileContext* file_context = fuse_req_userdata(fuse_req);
946 CliprdrFuseFile* fuse_file = nullptr;
947 struct stat attr = WINPR_C_ARRAY_INIT;
948
949 WINPR_ASSERT(file_context);
950
951 HashTable_Lock(file_context->inode_table);
952 if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino)))
953 {
954 HashTable_Unlock(file_context->inode_table);
955 fuse_reply_err(fuse_req, ENOENT);
956 return;
957 }
958
959 DEBUG_CLIPRDR(file_context->log, "getattr() has been called for file \"%s\"",
960 fuse_file->filename_with_root);
961
962 if (!fuse_file->is_directory && !fuse_file->has_size)
963 {
964 BOOL result = 0;
965
966 result =
967 request_file_size_async(file_context, fuse_file, fuse_req, FUSE_LL_OPERATION_GETATTR);
968 HashTable_Unlock(file_context->inode_table);
969
970 if (!result)
971 fuse_reply_err(fuse_req, EIO);
972
973 return;
974 }
975
976 if (!write_file_attributes(fuse_file, &attr))
977 {
978 fuse_reply_err(fuse_req, ERANGE);
979 HashTable_Unlock(file_context->inode_table);
980 return;
981 }
982 HashTable_Unlock(file_context->inode_table);
983
984 fuse_reply_attr(fuse_req, &attr, 1.0);
985}
986
987static void cliprdr_file_fuse_open(fuse_req_t fuse_req, fuse_ino_t fuse_ino,
988 struct fuse_file_info* file_info)
989{
990 CliprdrFileContext* file_context = fuse_req_userdata(fuse_req);
991 CliprdrFuseFile* fuse_file = nullptr;
992
993 WINPR_ASSERT(file_context);
994
995 HashTable_Lock(file_context->inode_table);
996 if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino)))
997 {
998 HashTable_Unlock(file_context->inode_table);
999 fuse_reply_err(fuse_req, ENOENT);
1000 return;
1001 }
1002 if (fuse_file->is_directory)
1003 {
1004 HashTable_Unlock(file_context->inode_table);
1005 fuse_reply_err(fuse_req, EISDIR);
1006 return;
1007 }
1008 HashTable_Unlock(file_context->inode_table);
1009
1010 if ((file_info->flags & O_ACCMODE) != O_RDONLY)
1011 {
1012 fuse_reply_err(fuse_req, EACCES);
1013 return;
1014 }
1015
1016 /* Important for KDE to get file correctly */
1017 file_info->direct_io = 1;
1018
1019 fuse_reply_open(fuse_req, file_info);
1020}
1021
1022static BOOL request_file_range_async(CliprdrFileContext* file_context, CliprdrFuseFile* fuse_file,
1023 fuse_req_t fuse_req, off_t offset, size_t requested_size)
1024{
1025 CLIPRDR_FILE_CONTENTS_REQUEST file_contents_request = WINPR_C_ARRAY_INIT;
1026
1027 WINPR_ASSERT(file_context);
1028 WINPR_ASSERT(fuse_file);
1029
1030 if (requested_size > UINT32_MAX)
1031 return FALSE;
1032
1033 CliprdrFuseRequest* fuse_request =
1034 cliprdr_fuse_request_new(file_context, fuse_file, fuse_req, FUSE_LL_OPERATION_READ);
1035 if (!fuse_request)
1036 return FALSE;
1037
1038 file_contents_request.common.msgType = CB_FILECONTENTS_REQUEST;
1039 file_contents_request.streamId = fuse_request->stream_id;
1040 file_contents_request.listIndex = fuse_file->list_idx;
1041 file_contents_request.dwFlags = FILECONTENTS_RANGE;
1042 file_contents_request.nPositionLow = (UINT32)(offset & 0xFFFFFFFF);
1043 file_contents_request.nPositionHigh = (UINT32)((offset >> 32) & 0xFFFFFFFF);
1044 file_contents_request.cbRequested = (UINT32)requested_size;
1045 file_contents_request.haveClipDataId = fuse_file->has_clip_data_id;
1046 file_contents_request.clipDataId = fuse_file->clip_data_id;
1047
1048 if (file_context->context->ClientFileContentsRequest(file_context->context,
1049 &file_contents_request))
1050 {
1051 WLog_Print(file_context->log, WLOG_ERROR,
1052 "Failed to send FileContentsRequest for file \"%s\"",
1053 fuse_file->filename_with_root);
1054 HashTable_Remove(file_context->request_table, (void*)(uintptr_t)fuse_request->stream_id);
1055 return FALSE;
1056 }
1057
1058 // file_context->request_table owns fuse_request
1059 // NOLINTBEGIN(clang-analyzer-unix.Malloc)
1060 DEBUG_CLIPRDR(
1061 file_context->log,
1062 "Requested file range (%zu Bytes at offset %ld) for file \"%s\" with stream id %u",
1063 requested_size, offset, fuse_file->filename, fuse_request->stream_id);
1064
1065 return TRUE;
1066 // NOLINTEND(clang-analyzer-unix.Malloc)
1067}
1068
1069static void cliprdr_file_fuse_read(fuse_req_t fuse_req, fuse_ino_t fuse_ino, size_t size,
1070 off_t offset, WINPR_ATTR_UNUSED struct fuse_file_info* file_info)
1071{
1072 CliprdrFileContext* file_context = fuse_req_userdata(fuse_req);
1073 CliprdrFuseFile* fuse_file = nullptr;
1074 BOOL result = 0;
1075
1076 WINPR_ASSERT(file_context);
1077
1078 HashTable_Lock(file_context->inode_table);
1079 if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino)))
1080 {
1081 HashTable_Unlock(file_context->inode_table);
1082 fuse_reply_err(fuse_req, ENOENT);
1083 return;
1084 }
1085 if (fuse_file->is_directory)
1086 {
1087 HashTable_Unlock(file_context->inode_table);
1088 fuse_reply_err(fuse_req, EISDIR);
1089 return;
1090 }
1091 if (!fuse_file->has_size || (offset < 0) || ((size_t)offset > fuse_file->size))
1092 {
1093 HashTable_Unlock(file_context->inode_table);
1094 fuse_reply_err(fuse_req, EINVAL);
1095 return;
1096 }
1097
1098 size = MIN(size, 8ULL * 1024ULL * 1024ULL);
1099
1100 result = request_file_range_async(file_context, fuse_file, fuse_req, offset, size);
1101 HashTable_Unlock(file_context->inode_table);
1102
1103 if (!result)
1104 fuse_reply_err(fuse_req, EIO);
1105}
1106
1107static void cliprdr_file_fuse_opendir(fuse_req_t fuse_req, fuse_ino_t fuse_ino,
1108 struct fuse_file_info* file_info)
1109{
1110 CliprdrFileContext* file_context = fuse_req_userdata(fuse_req);
1111 CliprdrFuseFile* fuse_file = nullptr;
1112
1113 WINPR_ASSERT(file_context);
1114
1115 HashTable_Lock(file_context->inode_table);
1116 if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino)))
1117 {
1118 HashTable_Unlock(file_context->inode_table);
1119 fuse_reply_err(fuse_req, ENOENT);
1120 return;
1121 }
1122 if (!fuse_file->is_directory)
1123 {
1124 HashTable_Unlock(file_context->inode_table);
1125 fuse_reply_err(fuse_req, ENOTDIR);
1126 return;
1127 }
1128 HashTable_Unlock(file_context->inode_table);
1129
1130 if ((file_info->flags & O_ACCMODE) != O_RDONLY)
1131 {
1132 fuse_reply_err(fuse_req, EACCES);
1133 return;
1134 }
1135
1136 fuse_reply_open(fuse_req, file_info);
1137}
1138
1139static void cliprdr_file_fuse_readdir(fuse_req_t fuse_req, fuse_ino_t fuse_ino, size_t max_size,
1140 off_t offset,
1141 WINPR_ATTR_UNUSED struct fuse_file_info* file_info)
1142{
1143 CliprdrFileContext* file_context = fuse_req_userdata(fuse_req);
1144 CliprdrFuseFile* fuse_file = nullptr;
1145 CliprdrFuseFile* child = nullptr;
1146 struct stat attr = WINPR_C_ARRAY_INIT;
1147 size_t written_size = 0;
1148 size_t entry_size = 0;
1149 char* filename = nullptr;
1150 char* buf = nullptr;
1151
1152 WINPR_ASSERT(file_context);
1153
1154 HashTable_Lock(file_context->inode_table);
1155 if (!(fuse_file = get_fuse_file_by_ino(file_context, fuse_ino)))
1156 {
1157 HashTable_Unlock(file_context->inode_table);
1158 fuse_reply_err(fuse_req, ENOENT);
1159 return;
1160 }
1161 if (!fuse_file->is_directory)
1162 {
1163 HashTable_Unlock(file_context->inode_table);
1164 fuse_reply_err(fuse_req, ENOTDIR);
1165 return;
1166 }
1167
1168 DEBUG_CLIPRDR(file_context->log, "Reading directory \"%s\" at offset %ld",
1169 fuse_file->filename_with_root, offset);
1170
1171 if ((offset < 0) || ((size_t)offset >= ArrayList_Count(fuse_file->children)))
1172 {
1173 HashTable_Unlock(file_context->inode_table);
1174 fuse_reply_buf(fuse_req, nullptr, 0);
1175 return;
1176 }
1177
1178 buf = calloc(max_size, sizeof(char));
1179 if (!buf)
1180 {
1181 HashTable_Unlock(file_context->inode_table);
1182 fuse_reply_err(fuse_req, ENOMEM);
1183 return;
1184 }
1185 written_size = 0;
1186
1187 for (off_t i = offset; i < 2; ++i)
1188 {
1189 if (i == 0)
1190 {
1191 if (!write_file_attributes(fuse_file, &attr))
1192 {
1193 HashTable_Unlock(file_context->inode_table);
1194 fuse_reply_err(fuse_req, ERANGE);
1195 free(buf);
1196 return;
1197 }
1198
1199 filename = ".";
1200 }
1201 else if (i == 1)
1202 {
1203 if (!write_file_attributes(fuse_file->parent, &attr))
1204 {
1205 HashTable_Unlock(file_context->inode_table);
1206 fuse_reply_err(fuse_req, ERANGE);
1207 free(buf);
1208 return;
1209 }
1210 attr.st_ino = fuse_file->parent ? attr.st_ino : FUSE_ROOT_ID;
1211 attr.st_mode = fuse_file->parent ? attr.st_mode : 0555;
1212 filename = "..";
1213 }
1214 else
1215 {
1216 WINPR_ASSERT(FALSE);
1217 }
1218
1223 entry_size = fuse_add_direntry(fuse_req, buf + written_size, max_size - written_size,
1224 filename, &attr, i + 1);
1225 if (entry_size > max_size - written_size)
1226 break;
1227
1228 written_size += entry_size;
1229 }
1230
1231 for (size_t j = 0, i = 2; j < ArrayList_Count(fuse_file->children); ++j, ++i)
1232 {
1233 if (i < (size_t)offset)
1234 continue;
1235
1236 child = ArrayList_GetItem(fuse_file->children, j);
1237
1238 if (!write_file_attributes(child, &attr))
1239 {
1240 HashTable_Unlock(file_context->inode_table);
1241 fuse_reply_err(fuse_req, ERANGE);
1242 free(buf);
1243 return;
1244 }
1245
1246 entry_size =
1247 fuse_add_direntry(fuse_req, buf + written_size, max_size - written_size,
1248 child->filename, &attr, WINPR_ASSERTING_INT_CAST(off_t, i + 1));
1249 if (entry_size > max_size - written_size)
1250 break;
1251
1252 written_size += entry_size;
1253 }
1254 HashTable_Unlock(file_context->inode_table);
1255
1256 fuse_reply_buf(fuse_req, buf, written_size);
1257 free(buf);
1258}
1259
1260static void fuse_abort(int sig, const char* signame, void* context)
1261{
1262 CliprdrFileContext* file = (CliprdrFileContext*)context;
1263
1264 if (file)
1265 {
1266 WLog_Print(file->log, WLOG_INFO, "signal %s [%d] aborting session", signame, sig);
1267 cliprdr_file_session_terminate(file, FALSE);
1268 }
1269}
1270
1271static DWORD WINAPI cliprdr_file_fuse_thread(LPVOID arg)
1272{
1273 CliprdrFileContext* file = (CliprdrFileContext*)arg;
1274
1275 WINPR_ASSERT(file);
1276
1277 DEBUG_CLIPRDR(file->log, "Starting fuse with mountpoint '%s'", file->path);
1278
1279 struct fuse_args args = FUSE_ARGS_INIT(0, nullptr);
1280 fuse_opt_add_arg(&args, file->path);
1281#if defined(__linux__)
1282 /* fusermount3 releases the mount point if this process dies without unmounting it (SIGKILL,
1283 * a crash): otherwise it stays behind, and every access to it fails with ENOTCONN.
1284 * Only libfuse's Linux mount code knows the option: elsewhere (mount_bsd.c) it would stay in
1285 * the arguments and fuse_session_new would refuse them. */
1286 fuse_opt_add_arg(&args, "-oauto_unmount");
1287#endif
1288 file->fuse_sess = fuse_session_new(&args, &cliprdr_file_fuse_oper,
1289 sizeof(cliprdr_file_fuse_oper), (void*)file);
1290 (void)SetEvent(file->fuse_start_sync);
1291
1292 if (file->fuse_sess != nullptr)
1293 {
1294 if (freerdp_add_signal_cleanup_handler(file, fuse_abort))
1295 {
1296 if (0 == fuse_session_mount(file->fuse_sess, file->path))
1297 {
1298 fuse_session_loop(file->fuse_sess);
1299 fuse_session_unmount(file->fuse_sess);
1300 }
1301 else
1302 {
1303 const LONG old = InterlockedExchange(&file->fuse_failed, 1);
1304 WLog_Print(
1305 file->log, WLOG_WARN,
1306 "cannot mount '%s': files from the server cannot be pasted here (%" PRId32 ")",
1307 file->path, old);
1308 }
1309 freerdp_del_signal_cleanup_handler(file, fuse_abort);
1310 }
1311
1312 WLog_Print(file->log, WLOG_DEBUG, "Waiting for FUSE stop sync");
1313 if (WaitForSingleObject(file->fuse_stop_sync, INFINITE) == WAIT_FAILED)
1314 WLog_Print(file->log, WLOG_ERROR, "Failed to wait for stop sync");
1315 fuse_session_destroy(file->fuse_sess);
1316 }
1317 fuse_opt_free_args(&args);
1318
1319 DEBUG_CLIPRDR(file->log, "Quitting fuse with mountpoint '%s'", file->path);
1320
1321 ExitThread(0);
1322 return 0;
1323}
1324
1325WINPR_ATTR_NODISCARD
1326WINPR_ATTR_FORMAT_ARG(4, 5)
1327static UINT cliprdr_fail_content_reponse(CliprdrFileContext* file_context,
1328 CliprdrFuseRequest* fuse_request, UINT32 streamID,
1329 WINPR_FORMAT_ARG const char* format, ...)
1330{
1331 WINPR_ASSERT(file_context);
1332 WINPR_ASSERT(fuse_request);
1333 WINPR_ASSERT(format);
1334
1335 const DWORD level = WLOG_WARN;
1336 if (WLog_IsLevelActive(file_context->log, level))
1337 {
1338 va_list ap;
1339 va_start(ap, format);
1340 WLog_PrintVA(file_context->log, WLOG_WARN, format, ap);
1341 va_end(ap);
1342 }
1343
1344 fuse_reply_err(fuse_request->fuse_req, EIO);
1345 HashTable_Remove(file_context->request_table, (void*)(uintptr_t)streamID);
1346 HashTable_Unlock(file_context->inode_table);
1347 return CHANNEL_RC_OK;
1348}
1349
1350static UINT cliprdr_file_context_server_file_contents_response(
1351 CliprdrClientContext* cliprdr_context,
1352 const CLIPRDR_FILE_CONTENTS_RESPONSE* file_contents_response)
1353{
1354 CliprdrFileContext* file_context = nullptr;
1355 CliprdrFuseRequest* fuse_request = nullptr;
1356 struct fuse_entry_param entry = WINPR_C_ARRAY_INIT;
1357
1358 WINPR_ASSERT(cliprdr_context);
1359 WINPR_ASSERT(file_contents_response);
1360
1361 file_context = cliprdr_context->custom;
1362 WINPR_ASSERT(file_context);
1363
1364 HashTable_Lock(file_context->inode_table);
1365 fuse_request = HashTable_GetItemValue(file_context->request_table,
1366 (void*)(uintptr_t)file_contents_response->streamId);
1367 if (!fuse_request)
1368 {
1369 HashTable_Unlock(file_context->inode_table);
1370 return CHANNEL_RC_OK;
1371 }
1372
1373 if (!(file_contents_response->common.msgFlags & CB_RESPONSE_OK))
1374 {
1375 return cliprdr_fail_content_reponse(file_context, fuse_request,
1376 file_contents_response->streamId,
1377 "FileContentsRequests for file \"%s\" was unsuccessful",
1378 fuse_request->fuse_file->filename);
1379 }
1380
1381 if ((fuse_request->operation_type == FUSE_LL_OPERATION_LOOKUP ||
1382 fuse_request->operation_type == FUSE_LL_OPERATION_GETATTR) &&
1383 file_contents_response->cbRequested != sizeof(UINT64))
1384 {
1385 return cliprdr_fail_content_reponse(
1386 file_context, fuse_request, file_contents_response->streamId,
1387 "Received invalid file size for file \"%s\" from the client",
1388 fuse_request->fuse_file->filename);
1389 }
1390
1391 if (fuse_request->operation_type == FUSE_LL_OPERATION_LOOKUP ||
1392 fuse_request->operation_type == FUSE_LL_OPERATION_GETATTR)
1393 {
1394 DEBUG_CLIPRDR(file_context->log, "Received file size for file \"%s\" with stream id %u",
1395 fuse_request->fuse_file->filename, file_contents_response->streamId);
1396
1397 fuse_request->fuse_file->size =
1398 winpr_Data_Get_UINT64(file_contents_response->requestedData);
1399 fuse_request->fuse_file->has_size = TRUE;
1400
1401 entry.ino = fuse_request->fuse_file->ino;
1402 if (!write_file_attributes(fuse_request->fuse_file, &entry.attr))
1403 {
1404 return cliprdr_fail_content_reponse(
1405 file_context, fuse_request, file_contents_response->streamId,
1406 "Received invalid file size for file \"%s\" from the client",
1407 fuse_request->fuse_file->filename);
1408 }
1409 entry.attr_timeout = 1.0;
1410 entry.entry_timeout = 1.0;
1411 }
1412 else if (fuse_request->operation_type == FUSE_LL_OPERATION_READ)
1413 {
1414 DEBUG_CLIPRDR(file_context->log, "Received file range for file \"%s\" with stream id %u",
1415 fuse_request->fuse_file->filename, file_contents_response->streamId);
1416 }
1417
1418 /* request_table is only accessed under the inode_table lock and owns fuse_request, so
1419 * keep what the reply needs and remove the request before releasing the lock */
1420 const FuseLowlevelOperationType operation_type = fuse_request->operation_type;
1421 fuse_req_t fuse_req = fuse_request->fuse_req;
1422 HashTable_Remove(file_context->request_table,
1423 (void*)(uintptr_t)file_contents_response->streamId);
1424 HashTable_Unlock(file_context->inode_table);
1425
1426 switch (operation_type)
1427 {
1428 case FUSE_LL_OPERATION_NONE:
1429 break;
1430 case FUSE_LL_OPERATION_LOOKUP:
1431 fuse_reply_entry(fuse_req, &entry);
1432 break;
1433 case FUSE_LL_OPERATION_GETATTR:
1434 fuse_reply_attr(fuse_req, &entry.attr, entry.attr_timeout);
1435 break;
1436 case FUSE_LL_OPERATION_READ:
1437 fuse_reply_buf(fuse_req, (const char*)file_contents_response->requestedData,
1438 file_contents_response->cbRequested);
1439 break;
1440 default:
1441 break;
1442 }
1443
1444 return CHANNEL_RC_OK;
1445}
1446#endif
1447
1448#if defined(WITH_CLIPRDR_FILE_APPLE)
1449/* The files of one server copy. Empty placeholders for them are on the pasteboard, the
1450 * contents are downloaded when an application (the Finder) starts to read one of them.
1451 * Owned by the pasteboard part, which calls apple_download() on its download queue only. */
1452typedef struct
1453{
1454 CliprdrFileContext* file;
1455 UINT32 generation; /* the server clipboard the files are from */
1456 FILEDESCRIPTORW* files;
1457 UINT32 count;
1458 char** paths; /* the local path of every entry, nullptr if it can not be offered */
1459 BYTE* done; /* the entries downloaded already */
1460} AppleOffer;
1461
1462static void apple_offer_free(void* userdata)
1463{
1464 AppleOffer* offer = userdata;
1465 if (!offer)
1466 return;
1467
1468 for (UINT32 x = 0; offer->paths && (x < offer->count); x++)
1469 free(offer->paths[x]);
1470 free(offer->paths);
1471 free(offer->done);
1472 free(offer->files);
1473 free(offer);
1474}
1475
1476static char* apple_descriptor_name(const FILEDESCRIPTORW* descriptor)
1477{
1478 WINPR_ASSERT(descriptor);
1479 return ConvertWCharNToUtf8Alloc(descriptor->cFileName, ARRAYSIZE(descriptor->cFileName),
1480 nullptr);
1481}
1482
1483static BOOL apple_is_directory(const FILEDESCRIPTORW* descriptor)
1484{
1485 WINPR_ASSERT(descriptor);
1486 return (descriptor->dwFlags & FD_ATTRIBUTES) &&
1487 (descriptor->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
1488}
1489
1490/* Map a server relative path (dir\file) to a local relative path (dir/file) */
1491static char* apple_local_relative_path(const char* name)
1492{
1493 WINPR_ASSERT(name);
1494
1495 const size_t len = strlen(name);
1496 if (len == 0)
1497 return nullptr;
1498
1499 char* path = _strdup(name);
1500 if (!path)
1501 return nullptr;
1502
1503 size_t start = 0;
1504 for (size_t x = 0; x <= len; x++)
1505 {
1506 if ((x < len) && (name[x] == '/'))
1507 goto fail;
1508 if ((x < len) && (name[x] != '\\'))
1509 continue;
1510
1511 const char* component = &name[start];
1512 const size_t clen = x - start;
1513 if ((clen == 0) || ((clen == 1) && (component[0] == '.')) ||
1514 ((clen == 2) && (strncmp(component, "..", 2) == 0)))
1515 goto fail;
1516 if (x < len)
1517 path[x] = '/';
1518 start = x + 1;
1519 }
1520 return path;
1521
1522fail:
1523 free(path);
1524 return nullptr;
1525}
1526
1527static BOOL apple_request_file_contents(CliprdrFileContext* file, UINT32 generation,
1528 UINT32 listIndex, UINT32 flags, UINT64 offset, UINT32 size,
1529 BYTE** pdata, UINT32* plen)
1530{
1531 WINPR_ASSERT(file);
1532 WINPR_ASSERT(pdata);
1533 WINPR_ASSERT(plen);
1534
1535 *pdata = nullptr;
1536 *plen = 0;
1537
1538 CLIPRDR_FILE_CONTENTS_REQUEST request = WINPR_C_ARRAY_INIT;
1539 request.common.msgType = CB_FILECONTENTS_REQUEST;
1540 request.listIndex = listIndex;
1541 request.dwFlags = flags;
1542 request.nPositionLow = (UINT32)(offset & 0xFFFFFFFF);
1543 request.nPositionHigh = (UINT32)(offset >> 32);
1544 request.cbRequested = size;
1545
1546 /* cliprdr_file_context_uninit() cancels under this lock and then waits for the download
1547 * queue, so the channel is valid for as long as this request is not cancelled. */
1548 EnterCriticalSection(&file->apple_lock);
1549 CliprdrClientContext* cliprdr = file->apple_cancelled ? nullptr : file->context;
1550 if (!cliprdr || !cliprdr->ClientFileContentsRequest || (generation != file->apple_generation))
1551 {
1552 LeaveCriticalSection(&file->apple_lock);
1553 return FALSE;
1554 }
1555 request.streamId = ++file->apple_stream_id;
1556 file->apple_contents_success = FALSE;
1557 free(file->apple_contents_data);
1558 file->apple_contents_data = nullptr;
1559 file->apple_contents_size = 0;
1560 (void)ResetEvent(file->apple_contents_event);
1561 LeaveCriticalSection(&file->apple_lock);
1562
1563 if (cliprdr->ClientFileContentsRequest(cliprdr, &request) != CHANNEL_RC_OK)
1564 return FALSE;
1565
1566 rdpContext* context = cliprdr->rdpcontext;
1567 WINPR_ASSERT(context);
1568
1569 HANDLE hdl[2] = { freerdp_abort_event(context), file->apple_contents_event };
1570 const UINT32 timeout = freerdp_settings_get_uint32(context->settings, FreeRDP_TcpAckTimeout);
1571 if (WaitForMultipleObjects(ARRAYSIZE(hdl), hdl, FALSE, timeout) != WAIT_OBJECT_0 + 1)
1572 {
1573 WLog_Print(file->log, WLOG_ERROR, "no file contents reply for stream %" PRIu32,
1574 request.streamId);
1575 return FALSE;
1576 }
1577
1578 EnterCriticalSection(&file->apple_lock);
1579 const BOOL rc = file->apple_contents_success && !file->apple_cancelled &&
1580 (generation == file->apple_generation);
1581 if (rc)
1582 {
1583 *pdata = file->apple_contents_data;
1584 *plen = file->apple_contents_size;
1585 file->apple_contents_data = nullptr;
1586 file->apple_contents_size = 0;
1587 }
1588 LeaveCriticalSection(&file->apple_lock);
1589 return rc;
1590}
1591
1592/* Fail the pending FILECONTENTS request and every later one */
1593static void apple_cancel_downloads(CliprdrFileContext* file)
1594{
1595 WINPR_ASSERT(file);
1596
1597 EnterCriticalSection(&file->apple_lock);
1598 file->apple_cancelled = TRUE;
1599 file->apple_generation++;
1600 (void)SetEvent(file->apple_contents_event);
1601 LeaveCriticalSection(&file->apple_lock);
1602}
1603
1604static UINT
1605cliprdr_file_context_apple_contents_response(CliprdrClientContext* cliprdr_context,
1606 const CLIPRDR_FILE_CONTENTS_RESPONSE* response)
1607{
1608 WINPR_ASSERT(cliprdr_context);
1609 WINPR_ASSERT(response);
1610
1611 CliprdrFileContext* file = cliprdr_context->custom;
1612 WINPR_ASSERT(file);
1613
1614 EnterCriticalSection(&file->apple_lock);
1615 if (response->streamId != file->apple_stream_id)
1616 {
1617 /* A late reply to a request that already timed out */
1618 WLog_Print(file->log, WLOG_WARN,
1619 "file contents response for stale stream %" PRIu32 ", ignoring",
1620 response->streamId);
1621 LeaveCriticalSection(&file->apple_lock);
1622 return CHANNEL_RC_OK;
1623 }
1624
1625 BOOL success = (response->common.msgFlags & CB_RESPONSE_OK) &&
1626 !(response->common.msgFlags & CB_RESPONSE_FAIL);
1627 if (success && response->requestedData && (response->cbRequested > 0))
1628 {
1629 file->apple_contents_data = malloc(response->cbRequested);
1630 if (file->apple_contents_data)
1631 {
1632 memcpy(file->apple_contents_data, response->requestedData, response->cbRequested);
1633 file->apple_contents_size = response->cbRequested;
1634 }
1635 else
1636 success = FALSE;
1637 }
1638 file->apple_contents_success = success;
1639 (void)SetEvent(file->apple_contents_event);
1640 LeaveCriticalSection(&file->apple_lock);
1641 return CHANNEL_RC_OK;
1642}
1643
1644/* An application that copies the file (the Finder) keeps its modification time */
1645static BOOL apple_set_write_time(const FILEDESCRIPTORW* descriptor, const char* path)
1646{
1647 WINPR_ASSERT(descriptor);
1648 WINPR_ASSERT(path);
1649
1650 if ((descriptor->dwFlags & FD_WRITESTIME) == 0)
1651 return TRUE;
1652
1653 const UINT64 filetime = ((1ull * descriptor->ftLastWriteTime.dwHighDateTime) << 32u) |
1654 descriptor->ftLastWriteTime.dwLowDateTime;
1655 UINT64 seconds = filetime / (10ULL * 1000ULL * 1000ULL);
1656 const int32_t usec = (filetime % (10ll * 1000ll * 1000ll)) / 10ll;
1657
1658 if (seconds < WIN32_FILETIME_TO_UNIX_EPOCH)
1659 seconds = 0;
1660 else
1661 seconds -= WIN32_FILETIME_TO_UNIX_EPOCH;
1662
1663 struct timeval times[2] = { { .tv_sec = (time_t)seconds, .tv_usec = usec },
1664 { .tv_sec = (time_t)seconds, .tv_usec = usec } };
1665 return utimes(path, times) == 0;
1666}
1667
1668static BOOL apple_download_file(CliprdrFileContext* file, UINT32 generation, UINT32 listIndex,
1669 const FILEDESCRIPTORW* descriptor, const char* path)
1670{
1671 WINPR_ASSERT(file);
1672 WINPR_ASSERT(descriptor);
1673 WINPR_ASSERT(path);
1674
1675 UINT64 size = 0;
1676 if (descriptor->dwFlags & FD_FILESIZE)
1677 size = ((UINT64)descriptor->nFileSizeHigh << 32) | descriptor->nFileSizeLow;
1678 else
1679 {
1680 BYTE* data = nullptr;
1681 UINT32 len = 0;
1682 const BOOL rc = apple_request_file_contents(file, generation, listIndex, FILECONTENTS_SIZE,
1683 0, sizeof(UINT64), &data, &len);
1684 if (rc && (len >= sizeof(UINT64)))
1685 memcpy(&size, data, sizeof(size));
1686 free(data);
1687 if (!rc || (len < sizeof(UINT64)))
1688 return FALSE;
1689 }
1690
1691 FILE* fp = winpr_fopen(path, "wb");
1692 if (!fp)
1693 return FALSE;
1694
1695 BOOL rc = TRUE;
1696 const UINT32 chunk = 1024 * 1024;
1697 for (UINT64 offset = 0; offset < size;)
1698 {
1699 const UINT32 requested = (size - offset < chunk) ? (UINT32)(size - offset) : chunk;
1700 BYTE* data = nullptr;
1701 UINT32 len = 0;
1702 if (!apple_request_file_contents(file, generation, listIndex, FILECONTENTS_RANGE, offset,
1703 requested, &data, &len) ||
1704 (len == 0) || (len > requested) || (fwrite(data, 1, len, fp) != len))
1705 {
1706 free(data);
1707 rc = FALSE;
1708 break;
1709 }
1710 free(data);
1711 offset += len;
1712 }
1713
1714 if (fclose(fp) != 0)
1715 rc = FALSE;
1716 if (!rc)
1717 (void)winpr_DeleteFile(path);
1718 else if (!apple_set_write_time(descriptor, path))
1719 WLog_Print(file->log, WLOG_WARN, "failed to set the modification time of %s", path);
1720 return rc;
1721}
1722
1723/* Download file x unless that was done already. A file that is not complete is removed:
1724 * better no file than an empty one. A later read creates and downloads it again. */
1725static BOOL apple_download_entry(AppleOffer* offer, UINT32 x)
1726{
1727 WINPR_ASSERT(offer);
1728
1729 if (offer->done[x])
1730 return TRUE;
1731
1732 if (!apple_download_file(offer->file, offer->generation, x, &offer->files[x], offer->paths[x]))
1733 {
1734 WLog_Print(offer->file->log, WLOG_ERROR, "failed to download %s", offer->paths[x]);
1735 (void)winpr_DeleteFile(offer->paths[x]);
1736 return FALSE;
1737 }
1738 offer->done[x] = 1;
1739 return TRUE;
1740}
1741
1742/* Called on the download queue when an application starts to read entry index: download
1743 * the file, or every file below the directory. The reader waits until this returns. */
1744static BOOL apple_download(void* userdata, size_t index)
1745{
1746 AppleOffer* offer = userdata;
1747 WINPR_ASSERT(offer);
1748
1749 if ((index >= offer->count) || !offer->paths[index])
1750 return FALSE;
1751
1752 if (!apple_is_directory(&offer->files[index]))
1753 return apple_download_entry(offer, (UINT32)index);
1754
1755 const char* top = offer->paths[index];
1756 const size_t toplen = strlen(top);
1757
1758 BOOL rc = TRUE;
1759 for (UINT32 x = 0; x < offer->count; x++)
1760 {
1761 const char* path = offer->paths[x];
1762 if (!path || apple_is_directory(&offer->files[x]) || (strncmp(path, top, toplen) != 0) ||
1763 (path[toplen] != '/'))
1764 continue;
1765
1766 /* After a failure keep what was downloaded, but leave no empty files behind */
1767 if (rc)
1768 rc = apple_download_entry(offer, x);
1769 else if (!offer->done[x])
1770 (void)winpr_DeleteFile(path);
1771 }
1772 return rc;
1773}
1774
1775/* Create the directory, or an empty placeholder for the file */
1776static BOOL apple_create_placeholder(const FILEDESCRIPTORW* descriptor, char* path)
1777{
1778 WINPR_ASSERT(descriptor);
1779 WINPR_ASSERT(path);
1780
1781 if (apple_is_directory(descriptor))
1782 return winpr_PathMakePath(path, nullptr);
1783
1784 char* slash = strrchr(path, '/');
1785 WINPR_ASSERT(slash);
1786 *slash = '\0';
1787 const BOOL parent = winpr_PathMakePath(path, nullptr);
1788 *slash = '/';
1789 if (!parent)
1790 return FALSE;
1791
1792 FILE* fp = winpr_fopen(path, "wb");
1793 if (!fp)
1794 return FALSE;
1795 if (fclose(fp) != 0)
1796 return FALSE;
1797 /* The Finder may read the attributes of the files below a directory before their
1798 * contents: the placeholder already has the modification time of the server file */
1799 (void)apple_set_write_time(descriptor, path);
1800 return TRUE;
1801}
1802
1803/* Parse the server file list and create the placeholders below dir */
1804static AppleOffer* apple_offer_new(CliprdrFileContext* file, UINT32 generation, const void* data,
1805 size_t size, const char* dir)
1806{
1807 WINPR_ASSERT(file);
1808 WINPR_ASSERT(dir);
1809
1810 if (size > UINT32_MAX)
1811 return nullptr;
1812
1813 AppleOffer* offer = calloc(1, sizeof(AppleOffer));
1814 if (!offer)
1815 return nullptr;
1816 offer->file = file;
1817 offer->generation = generation;
1818
1819 if (cliprdr_parse_file_list(data, (UINT32)size, &offer->files, &offer->count) != 0)
1820 goto fail;
1821 if (offer->count == 0)
1822 goto fail;
1823
1824 offer->paths = calloc(offer->count, sizeof(char*));
1825 offer->done = calloc(offer->count, sizeof(BYTE));
1826 if (!offer->paths || !offer->done)
1827 goto fail;
1828
1829 for (UINT32 x = 0; x < offer->count; x++)
1830 {
1831 char* name = apple_descriptor_name(&offer->files[x]);
1832 char* relative = name ? apple_local_relative_path(name) : nullptr;
1833 if (!relative)
1834 {
1835 WLog_Print(file->log, WLOG_WARN, "skipping invalid server file name %s",
1836 name ? name : "(null)");
1837 free(name);
1838 continue;
1839 }
1840 free(name);
1841
1842 size_t pathlen = 0;
1843 const int rc = winpr_asprintf(&offer->paths[x], &pathlen, "%s/%s", dir, relative);
1844 free(relative);
1845 if (rc < 0)
1846 {
1847 offer->paths[x] = nullptr;
1848 goto fail;
1849 }
1850 if (!apple_create_placeholder(&offer->files[x], offer->paths[x]))
1851 {
1852 /* e.g. a name that is too long here: offer the other files */
1853 WLog_Print(file->log, WLOG_WARN, "skipping %s, failed to create it", offer->paths[x]);
1854 free(offer->paths[x]);
1855 offer->paths[x] = nullptr;
1856 }
1857 }
1858 return offer;
1859
1860fail:
1861 apple_offer_free(offer);
1862 return nullptr;
1863}
1864
1865/* Put the server files on the pasteboard, the pasteboard part takes the offer */
1866static BOOL apple_offer_server_files(CliprdrFileContext* file, UINT32 generation, const void* data,
1867 size_t size, const char** mime_types, size_t mime_count,
1868 cliprdr_file_context_data_fkt fkt, void* userdata)
1869{
1870 WINPR_ASSERT(file);
1871
1872 char* dir = cliprdr_file_apple_new_download_dir();
1873 if (!dir)
1874 return FALSE;
1875
1876 BOOL rc = FALSE;
1877 BOOL taken = FALSE;
1878 size_t* top_level = nullptr;
1879 BOOL* present = nullptr;
1880 size_t top_level_count = 0;
1881 AppleOffer* offer = apple_offer_new(file, generation, data, size, dir);
1882 if (!offer)
1883 goto fail;
1884
1885 top_level = calloc(offer->count, sizeof(size_t));
1886 present = calloc(offer->count, sizeof(BOOL));
1887 if (!top_level || !present)
1888 goto fail;
1889
1890 for (UINT32 x = 0; x < offer->count; x++)
1891 {
1892 if (!offer->paths[x])
1893 continue;
1894
1895 /* Only the top level entries are on the pasteboard. An application reading a
1896 * directory might announce that for the directory or for the files in it. */
1897 const BOOL top = (strchr(offer->paths[x] + strlen(dir) + 1, '/') == nullptr);
1898 if (top)
1899 top_level[top_level_count++] = x;
1900 present[x] = top || !apple_is_directory(&offer->files[x]);
1901 }
1902 if (top_level_count == 0)
1903 goto fail;
1904
1905 WLog_Print(file->log, WLOG_DEBUG, "offering %" PRIuz " server files (%" PRIu32 " entries)",
1906 top_level_count, offer->count);
1907 taken = TRUE;
1908 rc = cliprdr_file_apple_offer(dir, (const char**)offer->paths, present, offer->count, top_level,
1909 top_level_count, apple_download, apple_offer_free, offer,
1910 mime_types, mime_count, fkt, userdata);
1911 offer = nullptr;
1912
1913fail:
1914 if (!taken)
1915 (void)winpr_RemoveDirectory_RecursiveA(dir);
1916 apple_offer_free(offer);
1917 free(top_level);
1918 free(present);
1919 free(dir);
1920 return rc;
1921}
1922#endif
1923
1924static UINT cliprdr_file_context_send_file_contents_failure(
1925 CliprdrFileContext* file, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest)
1926{
1927 CLIPRDR_FILE_CONTENTS_RESPONSE response = WINPR_C_ARRAY_INIT;
1928
1929 WINPR_ASSERT(file);
1930 WINPR_ASSERT(fileContentsRequest);
1931
1932 const UINT64 offset = (((UINT64)fileContentsRequest->nPositionHigh) << 32) |
1933 ((UINT64)fileContentsRequest->nPositionLow);
1934 writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__,
1935 "server file contents request [lockID %" PRIu32 ", streamID %" PRIu32
1936 ", index %" PRIu32 "] offset %" PRIu64 ", size %" PRIu32 " failed",
1937 fileContentsRequest->clipDataId, fileContentsRequest->streamId,
1938 fileContentsRequest->listIndex, offset, fileContentsRequest->cbRequested);
1939
1940 response.common.msgFlags = CB_RESPONSE_FAIL;
1941 response.streamId = fileContentsRequest->streamId;
1942
1943 WINPR_ASSERT(file->context);
1944 WINPR_ASSERT(file->context->ClientFileContentsResponse);
1945 return file->context->ClientFileContentsResponse(file->context, &response);
1946}
1947
1948static UINT
1949cliprdr_file_context_send_contents_response(CliprdrFileContext* file,
1950 const CLIPRDR_FILE_CONTENTS_REQUEST* request,
1951 const void* data, size_t size)
1952{
1953 if (size > UINT32_MAX)
1954 return ERROR_INVALID_PARAMETER;
1955
1956 CLIPRDR_FILE_CONTENTS_RESPONSE response = { .streamId = request->streamId,
1957 .requestedData = data,
1958 .cbRequested = (UINT32)size,
1959 .common.msgFlags = CB_RESPONSE_OK };
1960
1961 WINPR_ASSERT(request);
1962 WINPR_ASSERT(file);
1963
1964 WLog_Print(file->log, WLOG_DEBUG, "send contents response streamID=%" PRIu32 ", size=%" PRIu32,
1965 response.streamId, response.cbRequested);
1966 WINPR_ASSERT(file->context);
1967 WINPR_ASSERT(file->context->ClientFileContentsResponse);
1968 return file->context->ClientFileContentsResponse(file->context, &response);
1969}
1970
1971static BOOL dump_streams(const void* key, void* value, WINPR_ATTR_UNUSED void* arg)
1972{
1973 const UINT32* ukey = key;
1974 CliprdrLocalStream* cur = value;
1975
1976 writelog(cur->context->log, WLOG_WARN, __FILE__, __func__, __LINE__,
1977 "[key %" PRIu32 "] lockID %" PRIu32 ", count %" PRIuz ", locked %d", *ukey,
1978 cur->lockId, cur->count, cur->locked);
1979 for (size_t x = 0; x < cur->count; x++)
1980 {
1981 const CliprdrLocalFile* file = &cur->files[x];
1982 writelog(cur->context->log, WLOG_WARN, __FILE__, __func__, __LINE__,
1983 "file [%" PRIuz "] %s: %" PRId64, x, file->name, file->size);
1984 }
1985 return TRUE;
1986}
1987
1988static CliprdrLocalFile* file_info_for_request(CliprdrFileContext* file, UINT32 lockId,
1989 UINT32 listIndex)
1990{
1991 WINPR_ASSERT(file);
1992
1993 CliprdrLocalStream* cur = HashTable_GetItemValue(file->local_streams, &lockId);
1994 if (cur)
1995 {
1996 if (listIndex < cur->count)
1997 {
1998 CliprdrLocalFile* f = &cur->files[listIndex];
1999 return f;
2000 }
2001 else
2002 {
2003 writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__,
2004 "invalid entry index for lockID %" PRIu32 ", index %" PRIu32 " [count %" PRIuz
2005 "] [locked %d]",
2006 lockId, listIndex, cur->count, cur->locked);
2007 }
2008 }
2009 else
2010 {
2011 writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__,
2012 "missing entry for lockID %" PRIu32 ", index %" PRIu32, lockId, listIndex);
2013 if (!HashTable_Foreach(file->local_streams, dump_streams, file))
2014 writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__,
2015 "HashTable_Foreach failed");
2016 }
2017
2018 return nullptr;
2019}
2020
2021static CliprdrLocalFile* file_for_request(CliprdrFileContext* file, UINT32 lockId, UINT32 listIndex)
2022{
2023 CliprdrLocalFile* f = file_info_for_request(file, lockId, listIndex);
2024 if (f)
2025 {
2026 if (!f->fp)
2027 {
2028 const char* name = f->name;
2029 f->fp = winpr_fopen(name, "rb");
2030 }
2031 if (!f->fp)
2032 {
2033 char ebuffer[256] = WINPR_C_ARRAY_INIT;
2034 writelog(file->log, WLOG_WARN, __FILE__, __func__, __LINE__,
2035 "[lockID %" PRIu32 ", index %" PRIu32
2036 "] failed to open file '%s' [size %" PRId64 "] %s [%d]",
2037 lockId, listIndex, f->name, f->size,
2038 winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
2039 return nullptr;
2040 }
2041 }
2042
2043 return f;
2044}
2045
2046static void cliprdr_local_file_try_close(CliprdrLocalFile* file, UINT res, UINT64 offset,
2047 UINT64 size)
2048{
2049 WINPR_ASSERT(file);
2050
2051 if (res != 0)
2052 {
2053 WINPR_ASSERT(file->context);
2054 WLog_Print(file->context->log, WLOG_DEBUG, "closing file %s after error %" PRIu32,
2055 file->name, res);
2056 }
2057 else if (((file->size > 0) && (offset + size >= (UINT64)file->size)))
2058 {
2059 WINPR_ASSERT(file->context);
2060 WLog_Print(file->context->log, WLOG_DEBUG, "closing file %s after read", file->name);
2061 }
2062 else
2063 {
2064 // TODO: we need to keep track of open files to avoid running out of file descriptors
2065 // TODO: for the time being just close again.
2066 }
2067 if (file->fp)
2068 (void)fclose(file->fp);
2069 file->fp = nullptr;
2070}
2071
2072static UINT cliprdr_file_context_server_file_size_request(
2073 CliprdrFileContext* file, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest)
2074{
2075 WINPR_ASSERT(fileContentsRequest);
2076
2077 if (fileContentsRequest->cbRequested != sizeof(UINT64))
2078 {
2079 WLog_Print(file->log, WLOG_WARN, "unexpected FILECONTENTS_SIZE request: %" PRIu32 " bytes",
2080 fileContentsRequest->cbRequested);
2081 }
2082
2083 HashTable_Lock(file->local_streams);
2084
2085 UINT res = CHANNEL_RC_OK;
2086 CliprdrLocalFile* rfile =
2087 file_for_request(file, fileContentsRequest->clipDataId, fileContentsRequest->listIndex);
2088 if (!rfile)
2089 res = cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest);
2090 else
2091 {
2092 if (_fseeki64(rfile->fp, 0, SEEK_END) < 0)
2093 res = cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest);
2094 else
2095 {
2096 const INT64 size = _ftelli64(rfile->fp);
2097 rfile->size = size;
2098 cliprdr_local_file_try_close(rfile, res, 0, 0);
2099
2100 res = cliprdr_file_context_send_contents_response(file, fileContentsRequest, &size,
2101 sizeof(size));
2102 }
2103 }
2104
2105 HashTable_Unlock(file->local_streams);
2106 return res;
2107}
2108
2109static UINT cliprdr_file_context_server_file_range_request(
2110 CliprdrFileContext* file, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest)
2111{
2112 BYTE* data = nullptr;
2113
2114 WINPR_ASSERT(fileContentsRequest);
2115
2116 const UINT64 offset = ((1ull * fileContentsRequest->nPositionHigh) << 32) |
2117 (1ull * fileContentsRequest->nPositionLow);
2118 if (offset > INT64_MAX)
2119 return ERROR_INVALID_DATA;
2120
2121 HashTable_Lock(file->local_streams);
2122 CliprdrLocalFile* rfile =
2123 file_for_request(file, fileContentsRequest->clipDataId, fileContentsRequest->listIndex);
2124 if (!rfile)
2125 goto fail;
2126
2127 if (_fseeki64(rfile->fp, WINPR_ASSERTING_INT_CAST(int64_t, offset), SEEK_SET) < 0)
2128 goto fail;
2129
2130 data = malloc(fileContentsRequest->cbRequested);
2131 if (!data)
2132 goto fail;
2133
2134 {
2135 const size_t r = fread(data, 1, fileContentsRequest->cbRequested, rfile->fp);
2136 const UINT rc =
2137 cliprdr_file_context_send_contents_response(file, fileContentsRequest, data, r);
2138 free(data);
2139
2140 cliprdr_local_file_try_close(rfile, rc, offset, fileContentsRequest->cbRequested);
2141 HashTable_Unlock(file->local_streams);
2142 return rc;
2143 }
2144fail:
2145 if (rfile)
2146 cliprdr_local_file_try_close(rfile, ERROR_INTERNAL_ERROR, offset,
2147 fileContentsRequest->cbRequested);
2148 free(data);
2149 HashTable_Unlock(file->local_streams);
2150 return cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest);
2151}
2152
2153static void cliprdr_local_stream_free(void* obj);
2154
2155static UINT change_lock(CliprdrFileContext* file, UINT32 lockId, BOOL lock)
2156{
2157 UINT rc = CHANNEL_RC_OK;
2158
2159 WINPR_ASSERT(file);
2160
2161 HashTable_Lock(file->local_streams);
2162
2163 {
2164 CliprdrLocalStream* stream = HashTable_GetItemValue(file->local_streams, &lockId);
2165 if (lock && !stream)
2166 {
2167 stream = cliprdr_local_stream_new(file, lockId, nullptr, 0);
2168 if (!HashTable_Insert(file->local_streams, &lockId, stream))
2169 {
2170 rc = ERROR_INTERNAL_ERROR;
2171 cliprdr_local_stream_free(stream);
2172 stream = nullptr;
2173 }
2174 file->local_lock_id = lockId;
2175 }
2176 if (stream)
2177 {
2178 stream->locked = lock;
2179 stream->lockId = lockId;
2180 }
2181 }
2182
2183 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): HashTable_Insert ownership stream
2184 if (!lock)
2185 {
2186 if (!HashTable_Foreach(file->local_streams, local_stream_discard, file))
2187 rc = ERROR_INTERNAL_ERROR;
2188 }
2189
2190 HashTable_Unlock(file->local_streams);
2191 return rc;
2192}
2193
2194static UINT cliprdr_file_context_lock(CliprdrClientContext* context,
2195 const CLIPRDR_LOCK_CLIPBOARD_DATA* lockClipboardData)
2196{
2197 WINPR_ASSERT(context);
2198 WINPR_ASSERT(lockClipboardData);
2199 CliprdrFileContext* file = (context->custom);
2200 return change_lock(file, lockClipboardData->clipDataId, TRUE);
2201}
2202
2203static UINT cliprdr_file_context_unlock(CliprdrClientContext* context,
2204 const CLIPRDR_UNLOCK_CLIPBOARD_DATA* unlockClipboardData)
2205{
2206 WINPR_ASSERT(context);
2207 WINPR_ASSERT(unlockClipboardData);
2208 CliprdrFileContext* file = (context->custom);
2209 return change_lock(file, unlockClipboardData->clipDataId, FALSE);
2210}
2211
2212static UINT cliprdr_file_context_server_file_contents_request(
2213 CliprdrClientContext* context, const CLIPRDR_FILE_CONTENTS_REQUEST* fileContentsRequest)
2214{
2215 UINT error = NO_ERROR;
2216
2217 WINPR_ASSERT(context);
2218 WINPR_ASSERT(fileContentsRequest);
2219
2220 CliprdrFileContext* file = (context->custom);
2221 WINPR_ASSERT(file);
2222
2223 /*
2224 * MS-RDPECLIP 2.2.5.3 File Contents Request PDU (CLIPRDR_FILECONTENTS_REQUEST):
2225 * The FILECONTENTS_SIZE and FILECONTENTS_RANGE flags MUST NOT be set at the same time.
2226 */
2227 if ((fileContentsRequest->dwFlags & (FILECONTENTS_SIZE | FILECONTENTS_RANGE)) ==
2228 (FILECONTENTS_SIZE | FILECONTENTS_RANGE))
2229 {
2230 WLog_Print(file->log, WLOG_ERROR, "invalid CLIPRDR_FILECONTENTS_REQUEST.dwFlags");
2231 return cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest);
2232 }
2233
2234 if (fileContentsRequest->dwFlags & FILECONTENTS_SIZE)
2235 error = cliprdr_file_context_server_file_size_request(file, fileContentsRequest);
2236
2237 if (fileContentsRequest->dwFlags & FILECONTENTS_RANGE)
2238 error = cliprdr_file_context_server_file_range_request(file, fileContentsRequest);
2239
2240 if (error)
2241 {
2242 WLog_Print(file->log, WLOG_ERROR, "failed to handle CLIPRDR_FILECONTENTS_REQUEST: 0x%08X",
2243 error);
2244 return cliprdr_file_context_send_file_contents_failure(file, fileContentsRequest);
2245 }
2246
2247 return CHANNEL_RC_OK;
2248}
2249
2250BOOL cliprdr_file_context_init(CliprdrFileContext* file, CliprdrClientContext* cliprdr)
2251{
2252 WINPR_ASSERT(file);
2253 WINPR_ASSERT(cliprdr);
2254
2255 cliprdr->custom = file;
2256 file->context = cliprdr;
2257
2258 cliprdr->ServerLockClipboardData = cliprdr_file_context_lock;
2259 cliprdr->ServerUnlockClipboardData = cliprdr_file_context_unlock;
2260 cliprdr->ServerFileContentsRequest = cliprdr_file_context_server_file_contents_request;
2261#if defined(WITH_FUSE)
2262 cliprdr->ServerFileContentsResponse = cliprdr_file_context_server_file_contents_response;
2263
2264 CliprdrFuseFile* root_dir = fuse_file_new_root(file);
2265 return root_dir != nullptr;
2266#elif defined(WITH_CLIPRDR_FILE_APPLE)
2267 cliprdr->ServerFileContentsResponse = cliprdr_file_context_apple_contents_response;
2268 EnterCriticalSection(&file->apple_lock);
2269 file->apple_cancelled = FALSE;
2270 LeaveCriticalSection(&file->apple_lock);
2271 return TRUE;
2272#else
2273 return TRUE;
2274#endif
2275}
2276
2277#if defined(WITH_FUSE)
2278WINPR_ATTR_NODISCARD
2279static bool clear_all_selections(CliprdrFileContext* file_context)
2280{
2281 WINPR_ASSERT(file_context);
2282 WINPR_ASSERT(file_context->inode_table);
2283
2284 HashTable_Lock(file_context->inode_table);
2285 const bool rc = clear_selection(file_context, TRUE, nullptr);
2286
2287 HashTable_Clear(file_context->clip_data_table);
2288 HashTable_Unlock(file_context->inode_table);
2289 return rc;
2290}
2291#endif
2292
2293BOOL cliprdr_file_context_uninit(CliprdrFileContext* file, CliprdrClientContext* cliprdr)
2294{
2295
2296 // Clear all data before the channel is closed
2297 // the cleanup handlers are dependent on a working channel.
2298 if (file)
2299 {
2300#if defined(WITH_FUSE)
2301 if (file->inode_table)
2302 {
2303 if (!clear_no_cdi_entry(file))
2304 return FALSE;
2305 if (!clear_all_selections(file))
2306 return FALSE;
2307 }
2308#endif
2309#if defined(WITH_CLIPRDR_FILE_APPLE)
2310 /* A download uses the channel: fail it, then wait until the download queue is idle */
2311 apple_cancel_downloads(file);
2312 cliprdr_file_apple_detach();
2313#endif
2314
2315 HashTable_Clear(file->local_streams);
2316
2317 file->context = nullptr;
2318 }
2319
2320 if (cliprdr)
2321 {
2322#if defined(WITH_FUSE) || defined(WITH_CLIPRDR_FILE_APPLE)
2323 cliprdr->ServerFileContentsResponse = nullptr;
2324#endif
2325 }
2326
2327 return TRUE;
2328}
2329
2330static BOOL cliprdr_file_content_changed_and_update(void* ihash, size_t hsize, const void* data,
2331 size_t size)
2332{
2333
2334 BYTE hash[WINPR_SHA256_DIGEST_LENGTH] = WINPR_C_ARRAY_INIT;
2335
2336 if (hsize < sizeof(hash))
2337 return FALSE;
2338
2339 if (!winpr_Digest(WINPR_MD_SHA256, data, size, hash, sizeof(hash)))
2340 return FALSE;
2341
2342 const BOOL changed = memcmp(hash, ihash, sizeof(hash)) != 0;
2343 if (changed)
2344 memcpy(ihash, hash, sizeof(hash));
2345 return changed;
2346}
2347
2348static BOOL cliprdr_file_client_content_changed_and_update(CliprdrFileContext* file,
2349 const void* data, size_t size)
2350{
2351 WINPR_ASSERT(file);
2352 return cliprdr_file_content_changed_and_update(file->client_data_hash,
2353 sizeof(file->client_data_hash), data, size);
2354}
2355
2356#if defined(WITH_FUSE)
2357static fuse_ino_t get_next_free_inode(CliprdrFileContext* file_context)
2358{
2359 fuse_ino_t ino = 0;
2360
2361 WINPR_ASSERT(file_context);
2362
2363 ino = file_context->next_ino;
2364 while (ino == 0 || ino == FUSE_ROOT_ID ||
2365 HashTable_GetItemValue(file_context->inode_table, (void*)(uintptr_t)ino))
2366 ++ino;
2367
2368 file_context->next_ino = ino + 1;
2369
2370 return ino;
2371}
2372
2373static CliprdrFuseFile* clip_data_dir_new(CliprdrFileContext* file_context, BOOL has_clip_data_id,
2374 UINT32 clip_data_id)
2375{
2376 WINPR_ASSERT(file_context);
2377
2378 UINT64 data_id = clip_data_id;
2379 if (!has_clip_data_id)
2380 data_id = NO_CLIP_DATA_ID;
2381
2382 CliprdrFuseFile* clip_data_dir = fuse_file_new("/%" PRIu64, data_id);
2383 if (!clip_data_dir)
2384 return nullptr;
2385
2386 clip_data_dir->ino = get_next_free_inode(file_context);
2387 clip_data_dir->is_directory = TRUE;
2388 clip_data_dir->is_readonly = TRUE;
2389 clip_data_dir->has_clip_data_id = has_clip_data_id;
2390 clip_data_dir->clip_data_id = clip_data_id;
2391
2392 CliprdrFuseFile* root_dir = get_fuse_file_by_ino(file_context, FUSE_ROOT_ID);
2393 if (!root_dir)
2394 {
2395 WLog_Print(file_context->log, WLOG_ERROR, "FUSE root directory missing");
2396 fuse_file_free(clip_data_dir);
2397 return nullptr;
2398 }
2399 if (!ArrayList_Append(root_dir->children, clip_data_dir))
2400 {
2401 WLog_Print(file_context->log, WLOG_ERROR, "Failed to append FUSE file");
2402 fuse_file_free(clip_data_dir);
2403 return nullptr;
2404 }
2405 clip_data_dir->parent = root_dir;
2406
2407 if (!HashTable_Insert(file_context->inode_table, (void*)(uintptr_t)clip_data_dir->ino,
2408 clip_data_dir))
2409 {
2410 WLog_Print(file_context->log, WLOG_ERROR, "Failed to insert inode into inode table");
2411 ArrayList_Remove(root_dir->children, clip_data_dir);
2412 fuse_file_free(clip_data_dir);
2413 return nullptr;
2414 }
2415
2416 if (!HashTable_Insert(file_context->dir_table, clip_data_dir->filename_with_root,
2417 clip_data_dir))
2418 {
2419 WLog_Print(file_context->log, WLOG_ERROR, "Failed to insert inode into dir table");
2420 ArrayList_Remove(root_dir->children, clip_data_dir);
2421 fuse_file_free(clip_data_dir);
2422 return nullptr;
2423 }
2424
2425 return clip_data_dir;
2426}
2427
2428static char* get_parent_path(const char* filepath)
2429{
2430 const char* base = strrchr(filepath, '/');
2431 WINPR_ASSERT(base);
2432
2433 while ((base > filepath) && (*base == '/'))
2434 --base;
2435
2436 WINPR_ASSERT(base >= filepath);
2437 const size_t parent_path_length = 1ULL + (size_t)(base - filepath);
2438 char* parent_path = calloc(parent_path_length + 1, sizeof(char));
2439 if (!parent_path)
2440 return nullptr;
2441
2442 memcpy(parent_path, filepath, parent_path_length);
2443
2444 return parent_path;
2445}
2446
2447static CliprdrFuseFile* get_parent_directory(CliprdrFileContext* file_context, const char* path)
2448{
2449
2450 WINPR_ASSERT(file_context);
2451 WINPR_ASSERT(path);
2452
2453 char* parent_path = get_parent_path(path);
2454 if (!parent_path)
2455 return nullptr;
2456
2457 CliprdrFuseFile* parent = HashTable_GetItemValue(file_context->dir_table, parent_path);
2458 free(parent_path);
2459 return parent;
2460}
2461
2462// NOLINTBEGIN(clang-analyzer-unix.Malloc) HashTable_Insert owns fuse_file
2463static BOOL selection_handle_file(CliprdrFileContext* file_context,
2464 CliprdrFuseClipDataEntry* clip_data_entry, uint32_t index,
2465 const FILEDESCRIPTORW* file)
2466{
2467
2468 WINPR_ASSERT(file_context);
2469 WINPR_ASSERT(clip_data_entry);
2470 WINPR_ASSERT(file);
2471
2472 CliprdrFuseFile* clip_data_dir = clip_data_entry->clip_data_dir;
2473 WINPR_ASSERT(clip_data_dir);
2474
2475 char filename[ARRAYSIZE(file->cFileName) * 8] = WINPR_C_ARRAY_INIT;
2476 const SSIZE_T filenamelen = ConvertWCharNToUtf8(file->cFileName, ARRAYSIZE(file->cFileName),
2477 filename, ARRAYSIZE(filename) - 1);
2478 if (filenamelen < 0)
2479 {
2480 WLog_Print(file_context->log, WLOG_ERROR, "Failed to convert filename");
2481 return FALSE;
2482 }
2483
2484 for (size_t j = 0; filename[j]; ++j)
2485 {
2486 if (filename[j] == '\\')
2487 filename[j] = '/';
2488 }
2489
2490 BOOL crc = FALSE;
2491 CliprdrFuseFile* fuse_file = fuse_file_new(
2492 "%.*s/%s", WINPR_ASSERTING_INT_CAST(int, clip_data_dir->filename_with_root_len),
2493 clip_data_dir->filename_with_root, filename);
2494 if (!fuse_file)
2495 {
2496 WLog_Print(file_context->log, WLOG_ERROR, "Failed to create FUSE file");
2497 goto end;
2498 }
2499
2500 fuse_file->parent = get_parent_directory(file_context, fuse_file->filename_with_root);
2501 if (!fuse_file->parent)
2502 {
2503 WLog_Print(file_context->log, WLOG_ERROR, "Found no parent for FUSE file");
2504 goto end;
2505 }
2506
2507 if (!ArrayList_Append(fuse_file->parent->children, fuse_file))
2508 {
2509 WLog_Print(file_context->log, WLOG_ERROR, "Failed to append FUSE file");
2510 goto end;
2511 }
2512
2513 fuse_file->list_idx = index;
2514 fuse_file->ino = get_next_free_inode(file_context);
2515 fuse_file->has_clip_data_id = clip_data_entry->has_clip_data_id;
2516 fuse_file->clip_data_id = clip_data_entry->clip_data_id;
2517 if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2518 fuse_file->is_directory = TRUE;
2519 if (file->dwFileAttributes & FILE_ATTRIBUTE_READONLY)
2520 fuse_file->is_readonly = TRUE;
2521 if (file->dwFlags & FD_FILESIZE)
2522 {
2523 fuse_file->size = (1ull * file->nFileSizeHigh << 32) + 1ull * file->nFileSizeLow;
2524 fuse_file->has_size = TRUE;
2525 }
2526 if (file->dwFlags & FD_WRITESTIME)
2527 {
2528 INT64 filetime = 0;
2529
2530 filetime = file->ftLastWriteTime.dwHighDateTime;
2531 filetime <<= 32;
2532 filetime += file->ftLastWriteTime.dwLowDateTime;
2533
2534 fuse_file->last_write_time_unix =
2535 1LL * filetime / (10LL * 1000LL * 1000LL) - WIN32_FILETIME_TO_UNIX_EPOCH;
2536 fuse_file->has_last_write_time = TRUE;
2537 }
2538
2539 if (!HashTable_Insert(file_context->inode_table, (void*)(uintptr_t)fuse_file->ino, fuse_file))
2540 {
2541 WLog_Print(file_context->log, WLOG_ERROR, "Failed to insert inode into inode table");
2542 goto end;
2543 }
2544
2545 if (fuse_file->is_directory)
2546 {
2547
2548 if (!HashTable_Insert(file_context->dir_table, fuse_file->filename_with_root, fuse_file))
2549 {
2550 WLog_Print(file_context->log, WLOG_ERROR, "Failed to insert inode into dir table");
2551 goto end;
2552 }
2553 }
2554
2555 crc = TRUE;
2556
2557end:
2558 if (!crc)
2559 {
2560 fuse_file_free(fuse_file);
2561 if (!clear_entry_selection(clip_data_entry))
2562 WLog_Print(file_context->log, WLOG_WARN, "failed to clear selection");
2563 return FALSE;
2564 }
2565 return TRUE;
2566}
2567// NOLINTEND(clang-analyzer-unix.Malloc) HashTable_Insert owns fuse_file
2568
2569static BOOL set_selection_for_clip_data_entry(CliprdrFileContext* file_context,
2570 CliprdrFuseClipDataEntry* clip_data_entry,
2571 const FILEDESCRIPTORW* files, UINT32 n_files)
2572{
2573 WINPR_ASSERT(file_context);
2574 WINPR_ASSERT(clip_data_entry);
2575 WINPR_ASSERT(files);
2576
2577 if (clip_data_entry->has_clip_data_id)
2578 WLog_Print(file_context->log, WLOG_DEBUG, "Setting selection for clipDataId %u",
2579 clip_data_entry->clip_data_id);
2580 else
2581 WLog_Print(file_context->log, WLOG_DEBUG, "Setting selection");
2582
2583 for (UINT32 i = 0; i < n_files; ++i)
2584 {
2585 const FILEDESCRIPTORW* file = &files[i];
2586 if (!selection_handle_file(file_context, clip_data_entry, i, file))
2587 return FALSE;
2588 }
2589
2590 if (clip_data_entry->has_clip_data_id)
2591 WLog_Print(file_context->log, WLOG_DEBUG, "Selection set for clipDataId %u",
2592 clip_data_entry->clip_data_id);
2593 else
2594 WLog_Print(file_context->log, WLOG_DEBUG, "Selection set");
2595
2596 return TRUE;
2597}
2598
2599static BOOL update_exposed_path(CliprdrFileContext* file_context, wClipboard* clip,
2600 CliprdrFuseClipDataEntry* clip_data_entry)
2601{
2602 wClipboardDelegate* delegate = nullptr;
2603 CliprdrFuseFile* clip_data_dir = nullptr;
2604
2605 WINPR_ASSERT(file_context);
2606 WINPR_ASSERT(clip);
2607 WINPR_ASSERT(clip_data_entry);
2608
2609 delegate = ClipboardGetDelegate(clip);
2610 WINPR_ASSERT(delegate);
2611
2612 clip_data_dir = clip_data_entry->clip_data_dir;
2613 WINPR_ASSERT(clip_data_dir);
2614
2615 free(file_context->exposed_path);
2616 file_context->exposed_path = GetCombinedPath(file_context->path, clip_data_dir->filename);
2617 if (file_context->exposed_path)
2618 WLog_Print(file_context->log, WLOG_DEBUG, "Updated exposed path to \"%s\"",
2619 file_context->exposed_path);
2620
2621 delegate->basePath = file_context->exposed_path;
2622
2623 return delegate->basePath != nullptr;
2624}
2625#endif
2626
2627BOOL cliprdr_file_context_update_server_data(CliprdrFileContext* file_context, wClipboard* clip,
2628 const void* data, size_t size)
2629{
2630#if defined(WITH_FUSE)
2631 CliprdrFuseClipDataEntry* clip_data_entry = nullptr;
2632 FILEDESCRIPTORW* files = nullptr;
2633 UINT32 n_files = 0;
2634 BOOL rc = FALSE;
2635
2636 WINPR_ASSERT(file_context);
2637 WINPR_ASSERT(clip);
2638 if (size > UINT32_MAX)
2639 return FALSE;
2640
2641 /* paths below the mount point would lead nowhere: without a base there are none */
2642 if (InterlockedCompareExchange(&file_context->fuse_failed, 0, 0) != 0)
2643 {
2644 wClipboardDelegate* delegate = ClipboardGetDelegate(clip);
2645 WINPR_ASSERT(delegate);
2646 delegate->basePath = nullptr;
2647 return FALSE;
2648 }
2649
2650 if (cliprdr_parse_file_list(data, (UINT32)size, &files, &n_files))
2651 {
2652 WLog_Print(file_context->log, WLOG_ERROR, "Failed to parse file list");
2653 return FALSE;
2654 }
2655
2656 HashTable_Lock(file_context->inode_table);
2657 HashTable_Lock(file_context->clip_data_table);
2658 if (does_server_support_clipdata_locking(file_context))
2659 clip_data_entry = HashTable_GetItemValue(
2660 file_context->clip_data_table, (void*)(uintptr_t)file_context->current_clip_data_id);
2661 else
2662 clip_data_entry = file_context->clip_data_entry_without_id;
2663
2664 /* The entry is prepared when the server format list arrives. It is gone if the clipboard
2665 * owner or the server capabilities changed since then. */
2666 if (!clip_data_entry)
2667 {
2668 WLog_Print(file_context->log, WLOG_WARN, "No clipDataEntry for the server file list");
2669 goto fail;
2670 }
2671
2672 if (!clear_entry_selection(clip_data_entry))
2673 goto fail;
2674 WINPR_ASSERT(!clip_data_entry->clip_data_dir);
2675
2676 clip_data_entry->clip_data_dir =
2677 clip_data_dir_new(file_context, does_server_support_clipdata_locking(file_context),
2678 file_context->current_clip_data_id);
2679 if (!clip_data_entry->clip_data_dir)
2680 goto fail;
2681 if (!update_exposed_path(file_context, clip, clip_data_entry))
2682 goto fail;
2683 if (!set_selection_for_clip_data_entry(file_context, clip_data_entry, files, n_files))
2684 goto fail;
2685
2686 rc = TRUE;
2687
2688fail:
2689 HashTable_Unlock(file_context->clip_data_table);
2690 HashTable_Unlock(file_context->inode_table);
2691 free(files);
2692 return rc;
2693#else
2694 return FALSE;
2695#endif
2696}
2697
2698void* cliprdr_file_context_get_context(CliprdrFileContext* file)
2699{
2700 WINPR_ASSERT(file);
2701 return file->clipboard;
2702}
2703
2704void cliprdr_file_session_terminate(CliprdrFileContext* file, BOOL stop_thread)
2705{
2706 if (!file)
2707 return;
2708
2709#if defined(WITH_FUSE)
2710 WINPR_ASSERT(file->fuse_stop_sync);
2711
2712 WLog_Print(file->log, WLOG_DEBUG, "Setting FUSE exit flag");
2713 if (file->fuse_sess)
2714 fuse_session_exit(file->fuse_sess);
2715
2716 if (stop_thread)
2717 {
2718 WLog_Print(file->log, WLOG_DEBUG, "Setting FUSE stop event");
2719 (void)SetEvent(file->fuse_stop_sync);
2720 }
2721#endif
2722 /* not elegant but works for umounting FUSE
2723 fuse_chan must receive an oper buf to unblock fuse_session_receive_buf function.
2724 */
2725#if defined(WITH_FUSE)
2726 WLog_Print(file->log, WLOG_DEBUG, "Forcing FUSE to check exit flag");
2727#endif
2728 if (winpr_PathFileExists(file->path))
2729 WLog_Print(file->log, WLOG_WARN, "winpr_PathFileExists(%s) failed", file->path);
2730}
2731
2732void cliprdr_file_context_free(CliprdrFileContext* file)
2733{
2734 if (!file)
2735 return;
2736
2737#if defined(WITH_FUSE)
2738 if (file->fuse_thread)
2739 {
2740 WINPR_ASSERT(file->fuse_stop_sync);
2741
2742 WLog_Print(file->log, WLOG_DEBUG, "Stopping FUSE thread");
2743 cliprdr_file_session_terminate(file, TRUE);
2744
2745 WLog_Print(file->log, WLOG_DEBUG, "Waiting on FUSE thread");
2746 (void)WaitForSingleObject(file->fuse_thread, INFINITE);
2747 (void)CloseHandle(file->fuse_thread);
2748 }
2749 if (file->fuse_stop_sync)
2750 (void)CloseHandle(file->fuse_stop_sync);
2751 if (file->fuse_start_sync)
2752 (void)CloseHandle(file->fuse_start_sync);
2753
2754 HashTable_Free(file->request_table);
2755 HashTable_Free(file->clip_data_table);
2756 HashTable_Free(file->dir_table);
2757 HashTable_Free(file->inode_table);
2758
2759#endif
2760#if defined(WITH_CLIPRDR_FILE_APPLE)
2761 if (file->apple_contents_event)
2762 {
2763 /* An offer made after cliprdr_file_context_uninit() still refers to this context */
2764 apple_cancel_downloads(file);
2765 cliprdr_file_apple_detach();
2766 }
2767 free(file->apple_contents_data);
2768 if (file->apple_contents_event)
2769 {
2770 (void)CloseHandle(file->apple_contents_event);
2771 DeleteCriticalSection(&file->apple_lock);
2772 }
2773#endif
2774 HashTable_Free(file->local_streams);
2775 winpr_RemoveDirectory(file->path);
2776 free(file->path);
2777 free(file->exposed_path);
2778 free(file);
2779}
2780
2781static BOOL create_base_path(CliprdrFileContext* file)
2782{
2783 WINPR_ASSERT(file);
2784
2785 const char* details = freerdp_getApplicationDetailsString();
2786 WINPR_ASSERT(details);
2787
2788 /* Multiple RDP sessions can share a process, so include the clipboard
2789 * context address to keep their FUSE mount points separate. */
2790 char* base = nullptr;
2791 size_t blen = 0;
2792 winpr_asprintf(&base, &blen, "%s.%" PRIu32 ".%p", details, GetCurrentProcessId(), (void*)file);
2793 if (!base)
2794 return FALSE;
2795
2796 file->path = GetKnownSubPath(KNOWN_PATH_TEMP, base);
2797 winpr_znfree(base, blen);
2798 if (!file->path)
2799 return FALSE;
2800
2801 if (!winpr_PathFileExists(file->path) && !winpr_PathMakePath(file->path, nullptr))
2802 {
2803 WLog_Print(file->log, WLOG_ERROR, "Failed to create directory '%s'", file->path);
2804 return FALSE;
2805 }
2806 return TRUE;
2807}
2808
2809static void cliprdr_local_file_free(CliprdrLocalFile* file)
2810{
2811 const CliprdrLocalFile empty = WINPR_C_ARRAY_INIT;
2812 if (!file)
2813 return;
2814 if (file->fp)
2815 {
2816 WLog_Print(file->context->log, WLOG_DEBUG, "closing file %s, discarding entry", file->name);
2817 (void)fclose(file->fp);
2818 }
2819 free(file->name);
2820 *file = empty;
2821}
2822
2823static BOOL cliprdr_local_file_new(CliprdrFileContext* context, CliprdrLocalFile* f,
2824 const char* path)
2825{
2826 const CliprdrLocalFile empty = WINPR_C_ARRAY_INIT;
2827 WINPR_ASSERT(f);
2828 WINPR_ASSERT(context);
2829 WINPR_ASSERT(path);
2830
2831 *f = empty;
2832 f->context = context;
2833 f->name = _strdup(path);
2834 if (!f->name)
2835 goto fail;
2836
2837 return TRUE;
2838fail:
2839 cliprdr_local_file_free(f);
2840 return FALSE;
2841}
2842
2843static void cliprdr_local_files_free(CliprdrLocalStream* stream)
2844{
2845 WINPR_ASSERT(stream);
2846
2847 for (size_t x = 0; x < stream->count; x++)
2848 cliprdr_local_file_free(&stream->files[x]);
2849 free(stream->files);
2850
2851 stream->files = nullptr;
2852 stream->count = 0;
2853}
2854
2855static void cliprdr_local_stream_free(void* obj)
2856{
2857 CliprdrLocalStream* stream = (CliprdrLocalStream*)obj;
2858 if (stream)
2859 cliprdr_local_files_free(stream);
2860
2861 free(stream);
2862}
2863
2864static BOOL append_entry(CliprdrLocalStream* stream, const char* path)
2865{
2866 CliprdrLocalFile* tmp = realloc(stream->files, sizeof(CliprdrLocalFile) * (stream->count + 1));
2867 if (!tmp)
2868 return FALSE;
2869 stream->files = tmp;
2870 CliprdrLocalFile* f = &stream->files[stream->count++];
2871
2872 return cliprdr_local_file_new(stream->context, f, path);
2873}
2874
2875static BOOL is_directory(const char* path)
2876{
2877 WCHAR* wpath = ConvertUtf8ToWCharAlloc(path, nullptr);
2878 if (!wpath)
2879 return FALSE;
2880
2881 HANDLE hFile = CreateFileW(wpath, 0, FILE_SHARE_DELETE, nullptr, OPEN_EXISTING,
2882 FILE_ATTRIBUTE_NORMAL, nullptr);
2883 free(wpath);
2884
2885 if (hFile == INVALID_HANDLE_VALUE)
2886 return FALSE;
2887
2888 BY_HANDLE_FILE_INFORMATION fileInformation = WINPR_C_ARRAY_INIT;
2889 const BOOL status = GetFileInformationByHandle(hFile, &fileInformation);
2890 (void)CloseHandle(hFile);
2891 if (!status)
2892 return FALSE;
2893
2894 return (fileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
2895}
2896
2897static BOOL add_directory(CliprdrLocalStream* stream, const char* path)
2898{
2899 char* wildcardpath = GetCombinedPath(path, "*");
2900 if (!wildcardpath)
2901 return FALSE;
2902 WCHAR* wpath = ConvertUtf8ToWCharAlloc(wildcardpath, nullptr);
2903 free(wildcardpath);
2904 if (!wpath)
2905 return FALSE;
2906
2907 WIN32_FIND_DATAW FindFileData = WINPR_C_ARRAY_INIT;
2908 HANDLE hFind = FindFirstFileW(wpath, &FindFileData);
2909 free(wpath);
2910
2911 if (hFind == INVALID_HANDLE_VALUE)
2912 return FALSE;
2913
2914 BOOL rc = FALSE;
2915 char* next = nullptr;
2916
2917 WCHAR dotbuffer[6] = WINPR_C_ARRAY_INIT;
2918 WCHAR dotdotbuffer[6] = WINPR_C_ARRAY_INIT;
2919 const WCHAR* dot = InitializeConstWCharFromUtf8(".", dotbuffer, ARRAYSIZE(dotbuffer));
2920 const WCHAR* dotdot = InitializeConstWCharFromUtf8("..", dotdotbuffer, ARRAYSIZE(dotdotbuffer));
2921 do
2922 {
2923 if (_wcscmp(FindFileData.cFileName, dot) == 0)
2924 continue;
2925 if (_wcscmp(FindFileData.cFileName, dotdot) == 0)
2926 continue;
2927
2928 char cFileName[MAX_PATH] = WINPR_C_ARRAY_INIT;
2929 (void)ConvertWCharNToUtf8(FindFileData.cFileName, ARRAYSIZE(FindFileData.cFileName),
2930 cFileName, ARRAYSIZE(cFileName));
2931
2932 free(next);
2933 next = GetCombinedPath(path, cFileName);
2934 if (!next)
2935 goto fail;
2936
2937 if (!append_entry(stream, next))
2938 goto fail;
2939 if (is_directory(next))
2940 {
2941 if (!add_directory(stream, next))
2942 goto fail;
2943 }
2944 } while (FindNextFileW(hFind, &FindFileData));
2945
2946 rc = TRUE;
2947fail:
2948 free(next);
2949 FindClose(hFind);
2950
2951 return rc;
2952}
2953
2954static BOOL cliprdr_local_stream_update(CliprdrLocalStream* stream, const char* data, size_t size)
2955{
2956 BOOL rc = FALSE;
2957 WINPR_ASSERT(stream);
2958 if (size == 0)
2959 return TRUE;
2960
2961 cliprdr_local_files_free(stream);
2962
2963 stream->files = calloc(size, sizeof(CliprdrLocalFile));
2964 if (!stream->files)
2965 return FALSE;
2966
2967 char* copy = strndup(data, size);
2968 if (!copy)
2969 return FALSE;
2970
2971 char* dname = nullptr;
2972 char* saveptr = nullptr;
2973 char* ptr = strtok_s(copy, "\r\n", &saveptr);
2974 while (ptr)
2975 {
2976 const char* cname = ptr;
2977 if (strncmp("file:///", ptr, 8) == 0)
2978 cname = &ptr[7];
2979 else if (strncmp("file:/", ptr, 6) == 0)
2980 cname = &ptr[5];
2981
2982 const size_t nlen = strnlen(cname, size);
2983 free(dname);
2984 dname = winpr_str_url_decode(cname, nlen);
2985 if (!dname)
2986 goto fail;
2987 if (!append_entry(stream, dname))
2988 goto fail;
2989
2990 if (is_directory(dname))
2991 {
2992 const BOOL res = add_directory(stream, dname);
2993 if (!res)
2994 goto fail;
2995 }
2996 ptr = strtok_s(nullptr, "\r\n", &saveptr);
2997 }
2998
2999 rc = TRUE;
3000fail:
3001 free(dname);
3002 free(copy);
3003 return rc;
3004}
3005
3006CliprdrLocalStream* cliprdr_local_stream_new(CliprdrFileContext* context, UINT32 streamID,
3007 const char* data, size_t size)
3008{
3009 WINPR_ASSERT(context);
3010 CliprdrLocalStream* stream = calloc(1, sizeof(CliprdrLocalStream));
3011 if (!stream)
3012 return nullptr;
3013
3014 stream->context = context;
3015 if (!cliprdr_local_stream_update(stream, data, size))
3016 goto fail;
3017
3018 stream->lockId = streamID;
3019 return stream;
3020
3021fail:
3022 cliprdr_local_stream_free(stream);
3023 return nullptr;
3024}
3025
3026static UINT32 UINTPointerHash(const void* id)
3027{
3028 WINPR_ASSERT(id);
3029 return *((const UINT32*)id);
3030}
3031
3032static BOOL UINTPointerCompare(const void* pointer1, const void* pointer2)
3033{
3034 if (!pointer1 || !pointer2)
3035 return pointer1 == pointer2;
3036
3037 const UINT32* a = pointer1;
3038 const UINT32* b = pointer2;
3039 return *a == *b;
3040}
3041
3042static void* UINTPointerClone(const void* other)
3043{
3044 const UINT32* src = other;
3045 if (!src)
3046 return nullptr;
3047
3048 UINT32* copy = calloc(1, sizeof(UINT32));
3049 if (!copy)
3050 return nullptr;
3051
3052 *copy = *src;
3053 return copy;
3054}
3055
3056#if defined(WITH_FUSE)
3057CliprdrFuseFile* fuse_file_new_root(CliprdrFileContext* file_context)
3058{
3059 CliprdrFuseFile* root_dir = fuse_file_new("/");
3060 if (!root_dir)
3061 return nullptr;
3062
3063 root_dir->ino = FUSE_ROOT_ID;
3064 root_dir->is_directory = TRUE;
3065 root_dir->is_readonly = TRUE;
3066
3067 if (!HashTable_Insert(file_context->inode_table, (void*)(uintptr_t)root_dir->ino, root_dir))
3068 {
3069 fuse_file_free(root_dir);
3070 return nullptr;
3071 }
3072
3073 if (!HashTable_Insert(file_context->dir_table, root_dir->filename_with_root, root_dir))
3074 {
3075 fuse_file_free(root_dir);
3076 return nullptr;
3077 }
3078
3079 return root_dir;
3080}
3081#endif
3082
3083CliprdrFileContext* cliprdr_file_context_new(void* context)
3084{
3085 CliprdrFileContext* file = calloc(1, sizeof(CliprdrFileContext));
3086 if (!file)
3087 return nullptr;
3088
3089 file->log = WLog_Get(CLIENT_TAG("common.cliprdr.file"));
3090 file->clipboard = context;
3091
3092 file->local_streams = HashTable_New(FALSE);
3093 if (!file->local_streams)
3094 goto fail;
3095
3096 if (!HashTable_SetHashFunction(file->local_streams, UINTPointerHash))
3097 goto fail;
3098
3099 {
3100 wObject* hkobj = HashTable_KeyObject(file->local_streams);
3101 WINPR_ASSERT(hkobj);
3102 hkobj->fnObjectEquals = UINTPointerCompare;
3103 hkobj->fnObjectFree = free;
3104 hkobj->fnObjectNew = UINTPointerClone;
3105 }
3106
3107 {
3108 wObject* hobj = HashTable_ValueObject(file->local_streams);
3109 WINPR_ASSERT(hobj);
3110 hobj->fnObjectFree = cliprdr_local_stream_free;
3111 }
3112
3113#if defined(WITH_FUSE)
3114 file->inode_table = HashTable_New(FALSE);
3115 file->dir_table = HashTable_New(FALSE);
3116 file->clip_data_table = HashTable_New(FALSE);
3117 file->request_table = HashTable_New(FALSE);
3118 if (!file->inode_table || !file->dir_table || !file->clip_data_table || !file->request_table)
3119 goto fail;
3120
3121 {
3122 wObject* ctobj = HashTable_ValueObject(file->request_table);
3123 WINPR_ASSERT(ctobj);
3124 ctobj->fnObjectFree = free;
3125 }
3126 {
3127 wObject* ctobj = HashTable_ValueObject(file->clip_data_table);
3128 WINPR_ASSERT(ctobj);
3129 ctobj->fnObjectFree = clip_data_entry_free;
3130 }
3131 {
3132 if (!HashTable_SetHashFunction(file->dir_table, HashTable_StringHash))
3133 goto fail;
3134 wObject* kobj = HashTable_KeyObject(file->dir_table);
3135 WINPR_ASSERT(kobj);
3136 kobj->fnObjectEquals = HashTable_StringCompare;
3137 }
3138#endif
3139
3140 if (!create_base_path(file))
3141 goto fail;
3142
3143#if defined(WITH_CLIPRDR_FILE_APPLE)
3144 if (!InitializeCriticalSectionAndSpinCount(&file->apple_lock, 4000))
3145 goto fail;
3146 if (!(file->apple_contents_event = CreateEvent(nullptr, TRUE, FALSE, nullptr)))
3147 {
3148 DeleteCriticalSection(&file->apple_lock);
3149 goto fail;
3150 }
3151#endif
3152
3153#if defined(WITH_FUSE)
3154 if (!(file->fuse_start_sync = CreateEvent(nullptr, TRUE, FALSE, nullptr)))
3155 goto fail;
3156 if (!(file->fuse_stop_sync = CreateEvent(nullptr, TRUE, FALSE, nullptr)))
3157 goto fail;
3158 if (!(file->fuse_thread = CreateThread(nullptr, 0, cliprdr_file_fuse_thread, file, 0, nullptr)))
3159 goto fail;
3160
3161 if (WaitForSingleObject(file->fuse_start_sync, INFINITE) == WAIT_FAILED)
3162 WLog_Print(file->log, WLOG_ERROR, "Failed to wait for start sync");
3163#endif
3164 return file;
3165
3166fail:
3167 WINPR_PRAGMA_DIAG_PUSH
3168 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
3169 cliprdr_file_context_free(file);
3170 WINPR_PRAGMA_DIAG_POP
3171 return nullptr;
3172}
3173
3174BOOL local_stream_discard(const void* key, void* value, void* arg)
3175{
3176 CliprdrFileContext* file = arg;
3177 CliprdrLocalStream* stream = value;
3178 WINPR_ASSERT(file);
3179 WINPR_ASSERT(stream);
3180
3181 if (!stream->locked)
3182 HashTable_Remove(file->local_streams, key);
3183 return TRUE;
3184}
3185
3186BOOL cliprdr_file_context_clear(CliprdrFileContext* file)
3187{
3188 WINPR_ASSERT(file);
3189
3190 WLog_Print(file->log, WLOG_DEBUG, "clear file clipboard...");
3191
3192 HashTable_Lock(file->local_streams);
3193 const BOOL res = HashTable_Foreach(file->local_streams, local_stream_discard, file);
3194 HashTable_Unlock(file->local_streams);
3195
3196 memset(file->server_data_hash, 0, sizeof(file->server_data_hash));
3197 memset(file->client_data_hash, 0, sizeof(file->client_data_hash));
3198 return res;
3199}
3200
3201BOOL cliprdr_file_context_update_client_data(CliprdrFileContext* file, const char* data,
3202 size_t size)
3203{
3204 BOOL rc = FALSE;
3205
3206 WINPR_ASSERT(file);
3207 if (!cliprdr_file_client_content_changed_and_update(file, data, size))
3208 return TRUE;
3209
3210 if (!cliprdr_file_context_clear(file))
3211 return FALSE;
3212
3213 UINT32 lockId = file->local_lock_id;
3214
3215 HashTable_Lock(file->local_streams);
3216 CliprdrLocalStream* stream = HashTable_GetItemValue(file->local_streams, &lockId);
3217
3218 WLog_Print(file->log, WLOG_DEBUG, "update client file list (stream=%p)...", (void*)stream);
3219 if (stream)
3220 rc = cliprdr_local_stream_update(stream, data, size);
3221 else
3222 {
3223 stream = cliprdr_local_stream_new(file, lockId, data, size);
3224 rc = HashTable_Insert(file->local_streams, &stream->lockId, stream);
3225 if (!rc)
3226 cliprdr_local_stream_free(stream);
3227 }
3228 // HashTable_Insert owns stream
3229 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
3230 HashTable_Unlock(file->local_streams);
3231 return rc;
3232}
3233
3234UINT32 cliprdr_file_context_current_flags(CliprdrFileContext* file)
3235{
3236 WINPR_ASSERT(file);
3237
3238 if ((file->file_capability_flags & CB_STREAM_FILECLIP_ENABLED) == 0)
3239 return 0;
3240
3241 if (!file->file_formats_registered)
3242 return 0;
3243
3244 return CB_STREAM_FILECLIP_ENABLED | CB_FILECLIP_NO_FILE_PATHS |
3245 CB_HUGE_FILE_SUPPORT_ENABLED; // | CB_CAN_LOCK_CLIPDATA;
3246}
3247
3248BOOL cliprdr_file_context_set_locally_available(CliprdrFileContext* file, BOOL available)
3249{
3250 WINPR_ASSERT(file);
3251 file->file_formats_registered = available;
3252 return TRUE;
3253}
3254
3255BOOL cliprdr_file_context_remote_set_flags(CliprdrFileContext* file, UINT32 flags)
3256{
3257 WINPR_ASSERT(file);
3258 file->file_capability_flags = flags;
3259 return TRUE;
3260}
3261
3262UINT32 cliprdr_file_context_remote_get_flags(CliprdrFileContext* file)
3263{
3264 WINPR_ASSERT(file);
3265 return file->file_capability_flags;
3266}
3267
3268BOOL cliprdr_file_context_has_local_support(CliprdrFileContext* file)
3269{
3270#if defined(WITH_FUSE)
3271 WINPR_ASSERT(file);
3272 return InterlockedCompareExchange(&file->fuse_failed, 0, 0) == 0;
3273#else
3274 WINPR_UNUSED(file);
3275 return FALSE;
3276#endif
3277}
3278
3279BOOL cliprdr_file_context_set_local_clipboard_data(CliprdrFileContext* file,
3280 cliprdr_file_context_data_fkt fkt,
3281 void* userdata, const char** mime_types,
3282 size_t count)
3283{
3284 WINPR_ASSERT(file);
3285 WINPR_ASSERT(fkt);
3286 WINPR_ASSERT(mime_types || (count == 0));
3287
3288#if defined(WITH_CLIPRDR_FILE_APPLE)
3289 if (!file->context)
3290 return FALSE;
3291
3292 BOOL files = FALSE;
3293 for (size_t x = 0; x < count; x++)
3294 {
3295 if (mime_types[x] && (strcmp(mime_types[x], "text/uri-list") == 0))
3296 files = TRUE;
3297 }
3298 if (!files)
3299 return FALSE;
3300
3301 /* Taken before the file list: if the server clipboard changes meanwhile, the offer is
3302 * outdated and must not download anything */
3303 EnterCriticalSection(&file->apple_lock);
3304 const UINT32 generation = file->apple_generation;
3305 LeaveCriticalSection(&file->apple_lock);
3306
3307 /* Only the file list is fetched now, the contents follow when the files are read */
3308 size_t size = 0;
3309 const void* data = fkt(userdata, "FileGroupDescriptorW", &size);
3310 if (!data)
3311 return FALSE;
3312
3313 return apple_offer_server_files(file, generation, data, size, mime_types, count, fkt, userdata);
3314#else
3315 WINPR_UNUSED(file);
3316 WINPR_UNUSED(fkt);
3317 WINPR_UNUSED(userdata);
3318 WINPR_UNUSED(mime_types);
3319 WINPR_UNUSED(count);
3320 return FALSE;
3321#endif
3322}
3323
3324char* cliprdr_file_context_get_local_uri_list(CliprdrFileContext* file, size_t* size)
3325{
3326 WINPR_ASSERT(file);
3327 WINPR_ASSERT(size);
3328
3329 *size = 0;
3330#if defined(WITH_CLIPRDR_FILE_APPLE)
3331 return cliprdr_file_apple_get_uri_list(size);
3332#else
3333 WINPR_UNUSED(file);
3334 return nullptr;
3335#endif
3336}
WINPR_ATTR_NODISCARD FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
This struct contains function pointer to initialize/free objects.
Definition collections.h:52
OBJECT_FREE_FN fnObjectFree
Definition collections.h:59
WINPR_ATTR_NODISCARD OBJECT_EQUALS_FN fnObjectEquals
Definition collections.h:61
WINPR_ATTR_NODISCARD OBJECT_NEW_FN fnObjectNew
Definition collections.h:54