Coverage Report

Created: 2026-10-15 06:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/winpr/libwinpr/clipboard/synthetic_file.c
Line
Count
Source
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * Clipboard Functions: POSIX file handling
4
 *
5
 * Copyright 2017 Alexei Lozovsky <a.lozovsky@gmail.com>
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
20
#include <winpr/config.h>
21
#include <winpr/platform.h>
22
23
WINPR_PRAGMA_DIAG_PUSH
24
WINPR_PRAGMA_DIAG_IGNORED_RESERVED_ID_MACRO
25
WINPR_PRAGMA_DIAG_IGNORED_UNUSED_MACRO
26
27
#define _FILE_OFFSET_BITS 64 // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
28
29
WINPR_PRAGMA_DIAG_POP
30
31
#include <errno.h>
32
33
#include <winpr/wtypes.h>
34
35
#include <winpr/crt.h>
36
#include <winpr/clipboard.h>
37
#include <winpr/collections.h>
38
#include <winpr/file.h>
39
#include <winpr/shell.h>
40
#include <winpr/string.h>
41
#include <winpr/wlog.h>
42
#include <winpr/path.h>
43
#include <winpr/print.h>
44
45
#include "clipboard.h"
46
#include "synthetic_file.h"
47
48
#include "../log.h"
49
#define TAG WINPR_TAG("clipboard.synthetic.file")
50
51
static const char* mime_uri_list = "text/uri-list";
52
static const char* mime_FileGroupDescriptorW = "FileGroupDescriptorW";
53
static const char* mime_gnome_copied_files = "x-special/gnome-copied-files";
54
static const char* mime_mate_copied_files = "x-special/mate-copied-files";
55
56
struct synthetic_file
57
{
58
  WCHAR* local_name;
59
  WCHAR* remote_name;
60
61
  HANDLE fd;
62
  INT64 offset;
63
64
  DWORD dwFileAttributes;
65
  FILETIME ftCreationTime;
66
  FILETIME ftLastAccessTime;
67
  FILETIME ftLastWriteTime;
68
  DWORD nFileSizeHigh;
69
  DWORD nFileSizeLow;
70
};
71
72
void free_synthetic_file(struct synthetic_file* file);
73
74
static struct synthetic_file* make_synthetic_file(const WCHAR* local_name, const WCHAR* remote_name)
75
384k
{
76
384k
  struct synthetic_file* file = nullptr;
77
384k
  WIN32_FIND_DATAW fd = WINPR_C_ARRAY_INIT;
78
384k
  HANDLE hFind = nullptr;
79
80
384k
  WINPR_ASSERT(local_name);
81
384k
  WINPR_ASSERT(remote_name);
82
83
384k
  hFind = FindFirstFileW(local_name, &fd);
84
384k
  if (INVALID_HANDLE_VALUE == hFind)
85
507
  {
86
507
    WLog_ERR(TAG, "FindFirstFile failed (%" PRIu32 ")", GetLastError());
87
507
    return nullptr;
88
507
  }
89
384k
  FindClose(hFind);
90
91
384k
  file = calloc(1, sizeof(*file));
92
384k
  if (!file)
93
0
    return nullptr;
94
95
384k
  file->fd = INVALID_HANDLE_VALUE;
96
384k
  file->offset = 0;
97
384k
  file->local_name = _wcsdup(local_name);
98
384k
  if (!file->local_name)
99
0
    goto fail;
100
101
384k
  file->remote_name = _wcsdup(remote_name);
102
384k
  if (!file->remote_name)
103
0
    goto fail;
104
105
384k
  {
106
384k
    const size_t len = _wcslen(file->remote_name);
107
384k
    if (S_OK != PathCchConvertStyleW(file->remote_name, len, PATH_STYLE_WINDOWS))
108
0
      goto fail;
109
384k
  }
110
111
384k
  file->dwFileAttributes = fd.dwFileAttributes;
112
384k
  file->ftCreationTime = fd.ftCreationTime;
113
384k
  file->ftLastWriteTime = fd.ftLastWriteTime;
114
384k
  file->ftLastAccessTime = fd.ftLastAccessTime;
115
384k
  file->nFileSizeHigh = fd.nFileSizeHigh;
116
384k
  file->nFileSizeLow = fd.nFileSizeLow;
117
118
384k
  return file;
119
0
fail:
120
0
  free_synthetic_file(file);
121
0
  return nullptr;
122
384k
}
123
124
static UINT synthetic_file_read_close(struct synthetic_file* file, BOOL force);
125
126
void free_synthetic_file(struct synthetic_file* file)
127
384k
{
128
384k
  if (!file)
129
0
    return;
130
131
384k
  synthetic_file_read_close(file, TRUE);
132
133
384k
  free(file->local_name);
134
384k
  free(file->remote_name);
135
384k
  free(file);
136
384k
}
137
138
/*
139
 * Note that the function converts a single file name component,
140
 * it does not take care of component separators.
141
 */
142
static WCHAR* convert_local_name_component_to_remote(wClipboard* clipboard, const WCHAR* local_name)
143
384k
{
144
384k
  wClipboardDelegate* delegate = ClipboardGetDelegate(clipboard);
145
384k
  WCHAR* remote_name = nullptr;
146
147
384k
  WINPR_ASSERT(delegate);
148
149
384k
  remote_name = _wcsdup(local_name);
150
151
  /*
152
   * Some file names are not valid on Windows. Check for these now
153
   * so that we won't get ourselves into a trouble later as such names
154
   * are known to crash some Windows shells when pasted via clipboard.
155
   *
156
   * The IsFileNameComponentValid callback can be overridden by the API
157
   * user, if it is known, that the connected peer is not on the
158
   * Windows platform.
159
   */
160
384k
  if (!delegate->IsFileNameComponentValid(remote_name))
161
235
  {
162
235
    char name[MAX_PATH] = WINPR_C_ARRAY_INIT;
163
235
    ConvertWCharToUtf8(local_name, name, sizeof(name) - 1);
164
235
    WLog_ERR(TAG, "invalid file name component: %s", name);
165
235
    goto error;
166
235
  }
167
168
384k
  return remote_name;
169
235
error:
170
235
  free(remote_name);
171
235
  return nullptr;
172
384k
}
173
174
static WCHAR* concat_file_name(const WCHAR* dir, const WCHAR* file)
175
751k
{
176
751k
  size_t len_dir = 0;
177
751k
  size_t len_file = 0;
178
751k
  const WCHAR slash = '/';
179
751k
  WCHAR* buffer = nullptr;
180
181
751k
  WINPR_ASSERT(dir);
182
751k
  WINPR_ASSERT(file);
183
184
751k
  len_dir = _wcslen(dir);
185
751k
  len_file = _wcslen(file);
186
751k
  buffer = calloc(len_dir + 1 + len_file + 2, sizeof(WCHAR));
187
188
751k
  if (!buffer)
189
0
    return nullptr;
190
191
751k
  memcpy(buffer, dir, len_dir * sizeof(WCHAR));
192
751k
  buffer[len_dir] = slash;
193
751k
  memcpy(buffer + len_dir + 1, file, len_file * sizeof(WCHAR));
194
751k
  return buffer;
195
751k
}
196
197
static BOOL add_file_to_list(wClipboard* clipboard, size_t recursionDepth, const WCHAR* local_name,
198
                             const WCHAR* remote_name, wArrayList* files);
199
200
static BOOL add_directory_entry_to_list(wClipboard* clipboard, size_t recursionDepth,
201
                                        const WCHAR* local_dir_name, const WCHAR* remote_dir_name,
202
                                        const LPWIN32_FIND_DATAW pFileData, wArrayList* files)
203
485k
{
204
485k
  BOOL result = FALSE;
205
485k
  WCHAR* local_name = nullptr;
206
485k
  WCHAR* remote_name = nullptr;
207
485k
  WCHAR* remote_base_name = nullptr;
208
209
485k
  WCHAR dotbuffer[6] = WINPR_C_ARRAY_INIT;
210
485k
  WCHAR dotdotbuffer[6] = WINPR_C_ARRAY_INIT;
211
485k
  const WCHAR* dot = InitializeConstWCharFromUtf8(".", dotbuffer, ARRAYSIZE(dotbuffer));
212
485k
  const WCHAR* dotdot = InitializeConstWCharFromUtf8("..", dotdotbuffer, ARRAYSIZE(dotdotbuffer));
213
214
485k
  WINPR_ASSERT(clipboard);
215
485k
  WINPR_ASSERT(local_dir_name);
216
485k
  WINPR_ASSERT(remote_dir_name);
217
485k
  WINPR_ASSERT(pFileData);
218
485k
  WINPR_ASSERT(files);
219
220
  /* Skip special directory entries. */
221
222
485k
  if ((_wcscmp(pFileData->cFileName, dot) == 0) || (_wcscmp(pFileData->cFileName, dotdot) == 0))
223
110k
    return TRUE;
224
225
375k
  remote_base_name = convert_local_name_component_to_remote(clipboard, pFileData->cFileName);
226
227
375k
  if (!remote_base_name)
228
18
    return FALSE;
229
230
375k
  local_name = concat_file_name(local_dir_name, pFileData->cFileName);
231
375k
  remote_name = concat_file_name(remote_dir_name, remote_base_name);
232
233
375k
  if (local_name && remote_name)
234
375k
    result = add_file_to_list(clipboard, recursionDepth, local_name, remote_name, files);
235
236
375k
  free(remote_base_name);
237
375k
  free(remote_name);
238
375k
  free(local_name);
239
375k
  return result;
240
375k
}
241
242
static BOOL do_add_directory_contents_to_list(wClipboard* clipboard, size_t recursionDepth,
243
                                              const WCHAR* local_name, const WCHAR* remote_name,
244
                                              WCHAR* namebuf, wArrayList* files)
245
55.1k
{
246
55.1k
  WINPR_ASSERT(clipboard);
247
55.1k
  WINPR_ASSERT(local_name);
248
55.1k
  WINPR_ASSERT(remote_name);
249
55.1k
  WINPR_ASSERT(files);
250
55.1k
  WINPR_ASSERT(namebuf);
251
252
55.1k
  WIN32_FIND_DATAW FindData = WINPR_C_ARRAY_INIT;
253
55.1k
  HANDLE hFind = FindFirstFileW(namebuf, &FindData);
254
55.1k
  if (INVALID_HANDLE_VALUE == hFind)
255
159
  {
256
159
    WLog_ERR(TAG, "FindFirstFile failed (%" PRIu32 ")", GetLastError());
257
159
    return FALSE;
258
159
  }
259
485k
  while (TRUE)
260
485k
  {
261
485k
    if (!add_directory_entry_to_list(clipboard, recursionDepth, local_name, remote_name,
262
485k
                                     &FindData, files))
263
647
    {
264
647
      FindClose(hFind);
265
647
      return FALSE;
266
647
    }
267
268
484k
    BOOL bRet = FindNextFileW(hFind, &FindData);
269
484k
    if (!bRet)
270
54.3k
    {
271
54.3k
      FindClose(hFind);
272
54.3k
      if (ERROR_NO_MORE_FILES == GetLastError())
273
54.3k
        return TRUE;
274
0
      WLog_WARN(TAG, "FindNextFile failed (%" PRIu32 ")", GetLastError());
275
0
      return FALSE;
276
54.3k
    }
277
484k
  }
278
279
0
  return TRUE;
280
55.0k
}
281
282
static BOOL add_directory_contents_to_list(wClipboard* clipboard, size_t recursionDepth,
283
                                           const WCHAR* local_name, const WCHAR* remote_name,
284
                                           wArrayList* files)
285
55.2k
{
286
55.2k
  BOOL result = FALSE;
287
55.2k
  union
288
55.2k
  {
289
55.2k
    const char* c;
290
55.2k
    const WCHAR* w;
291
55.2k
  } wildcard;
292
55.2k
  const char buffer[6] = { '/', '\0', '*', '\0', '\0', '\0' };
293
55.2k
  wildcard.c = buffer;
294
55.2k
  const size_t wildcardLen = ARRAYSIZE(buffer) / sizeof(WCHAR);
295
296
55.2k
  WINPR_ASSERT(clipboard);
297
55.2k
  WINPR_ASSERT(local_name);
298
55.2k
  WINPR_ASSERT(remote_name);
299
55.2k
  WINPR_ASSERT(files);
300
301
55.2k
  const size_t max = CLIPBOARD_FILE_MAX_RECURSION;
302
55.2k
  if (recursionDepth > max)
303
10
  {
304
10
    WLog_ERR(TAG,
305
10
             "This build only supports recursionDepth=%" PRIuz
306
10
             " <= CLIPBOARD_FILE_MAX_RECURSION=%" PRIuz " recursion depth for folders copied.",
307
10
             recursionDepth, max);
308
10
    return FALSE;
309
10
  }
310
311
55.1k
  size_t len = _wcslen(local_name);
312
55.1k
  WCHAR* namebuf = calloc(len + wildcardLen, sizeof(WCHAR));
313
55.1k
  if (!namebuf)
314
0
    return FALSE;
315
316
55.1k
  _wcsncat(namebuf, local_name, len);
317
55.1k
  _wcsncat(namebuf, wildcard.w, wildcardLen);
318
319
55.1k
  result = do_add_directory_contents_to_list(clipboard, recursionDepth, local_name, remote_name,
320
55.1k
                                             namebuf, files);
321
322
55.1k
  free(namebuf);
323
55.1k
  return result;
324
55.1k
}
325
326
BOOL add_file_to_list(wClipboard* clipboard, size_t recursionDepth, const WCHAR* local_name,
327
                      const WCHAR* remote_name, wArrayList* files)
328
384k
{
329
384k
  struct synthetic_file* file = nullptr;
330
331
384k
  WINPR_ASSERT(clipboard);
332
384k
  WINPR_ASSERT(local_name);
333
384k
  WINPR_ASSERT(remote_name);
334
384k
  WINPR_ASSERT(files);
335
336
384k
  file = make_synthetic_file(local_name, remote_name);
337
338
384k
  if (!file)
339
507
    return FALSE;
340
341
384k
  if (!ArrayList_Append(files, file))
342
0
  {
343
0
    free_synthetic_file(file);
344
0
    return FALSE;
345
0
  }
346
347
384k
  if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
348
55.2k
  {
349
    /*
350
     * This is effectively a recursive call, but we do not track
351
     * recursion depth, thus filesystem loops can cause a crash.
352
     */
353
55.2k
    if (!add_directory_contents_to_list(clipboard, recursionDepth + 1, local_name, remote_name,
354
55.2k
                                        files))
355
816
      return FALSE;
356
55.2k
  }
357
358
383k
  return TRUE;
359
384k
}
360
361
static const WCHAR* get_basename(const WCHAR* name)
362
9.42k
{
363
9.42k
  const WCHAR* c = name;
364
9.42k
  const WCHAR* last_name = name;
365
9.42k
  const WCHAR slash = '/';
366
367
9.42k
  WINPR_ASSERT(name);
368
369
11.5M
  while (*c++)
370
11.5M
  {
371
11.5M
    if (*c == slash)
372
112k
      last_name = c + 1;
373
11.5M
  }
374
375
9.42k
  return last_name;
376
9.42k
}
377
378
static BOOL process_file_name(wClipboard* clipboard, const WCHAR* local_name, wArrayList* files)
379
9.42k
{
380
9.42k
  BOOL result = FALSE;
381
9.42k
  const WCHAR* base_name = nullptr;
382
9.42k
  WCHAR* remote_name = nullptr;
383
384
9.42k
  WINPR_ASSERT(clipboard);
385
9.42k
  WINPR_ASSERT(local_name);
386
9.42k
  WINPR_ASSERT(files);
387
388
  /*
389
   * Start with the base name of the file. text/uri-list contains the
390
   * exact files selected by the user, and we want the remote files
391
   * to have names relative to that selection.
392
   */
393
9.42k
  base_name = get_basename(local_name);
394
9.42k
  remote_name = convert_local_name_component_to_remote(clipboard, base_name);
395
396
9.42k
  if (!remote_name)
397
217
    return FALSE;
398
399
9.20k
  result = add_file_to_list(clipboard, 0, local_name, remote_name, files);
400
9.20k
  free(remote_name);
401
9.20k
  return result;
402
9.42k
}
403
404
static BOOL process_uri(wClipboard* clipboard, const char* uri, size_t uri_len)
405
9.70k
{
406
  // URI is specified by RFC 8089: https://datatracker.ietf.org/doc/html/rfc8089
407
9.70k
  BOOL result = FALSE;
408
9.70k
  char* name = nullptr;
409
410
9.70k
  WINPR_ASSERT(clipboard);
411
412
9.70k
  name = parse_uri_to_local_file(uri, uri_len);
413
9.70k
  if (name)
414
9.51k
  {
415
9.51k
    WCHAR* wname = nullptr;
416
    /*
417
     * Note that local file names are not actually guaranteed to be
418
     * encoded in UTF-8. Filesystems and users can use whatever they
419
     * want. The OS does not care, aside from special treatment of
420
     * '\0' and '/' bytes. But we need to make some decision here.
421
     * Assuming UTF-8 is currently the most sane thing.
422
     */
423
9.51k
    wname = ConvertUtf8ToWCharAlloc(name, nullptr);
424
9.51k
    if (wname)
425
9.42k
      result = process_file_name(clipboard, wname, clipboard->localFiles);
426
427
9.51k
    free(name);
428
9.51k
    free(wname);
429
9.51k
  }
430
431
9.70k
  return result;
432
9.70k
}
433
434
static BOOL process_uri_list(wClipboard* clipboard, const char* data, size_t length)
435
1.37k
{
436
1.37k
  const char* cur = data;
437
1.37k
  const char* lim = data + length;
438
439
1.37k
  WINPR_ASSERT(clipboard);
440
1.37k
  WINPR_ASSERT(data);
441
442
1.37k
  WLog_VRB(TAG, "processing URI list:\n%.*s", WINPR_ASSERTING_INT_CAST(int, length), data);
443
1.37k
  ArrayList_Clear(clipboard->localFiles);
444
445
  /*
446
   * The "text/uri-list" Internet Media Type is specified by RFC 2483.
447
   *
448
   * While the RFCs 2046 and 2483 require the lines of text/... formats
449
   * to be terminated by CRLF sequence, be prepared for those who don't
450
   * read the spec, use plain LFs, and don't leave the trailing CRLF.
451
   */
452
453
11.0k
  while (cur < lim)
454
10.8k
  {
455
10.8k
    BOOL comment = (*cur == '#');
456
10.8k
    const char* start = cur;
457
10.8k
    const char* stop = cur;
458
459
17.9M
    for (; stop < lim; stop++)
460
17.9M
    {
461
17.9M
      if (*stop == '\r')
462
8.66k
      {
463
8.66k
        if ((stop + 1 < lim) && (*(stop + 1) == '\n'))
464
198
          cur = stop + 2;
465
8.46k
        else
466
8.46k
          cur = stop + 1;
467
468
8.66k
        break;
469
8.66k
      }
470
471
17.9M
      if (*stop == '\n')
472
923
      {
473
923
        cur = stop + 1;
474
923
        break;
475
923
      }
476
17.9M
    }
477
478
10.8k
    if (stop == lim)
479
1.25k
    {
480
1.25k
      if (strnlen(start, WINPR_ASSERTING_INT_CAST(size_t, stop - start)) < 1)
481
2
        return TRUE;
482
1.25k
      cur = lim;
483
1.25k
    }
484
485
10.8k
    if (comment)
486
1.13k
      continue;
487
488
9.70k
    if (!process_uri(clipboard, start, WINPR_ASSERTING_INT_CAST(size_t, stop - start)))
489
1.19k
      return FALSE;
490
9.70k
  }
491
492
183
  return TRUE;
493
1.37k
}
494
495
static BOOL convert_local_file_to_filedescriptor(const struct synthetic_file* file,
496
                                                 FILEDESCRIPTORW* descriptor)
497
195k
{
498
195k
  size_t remote_len = 0;
499
500
195k
  WINPR_ASSERT(file);
501
195k
  WINPR_ASSERT(descriptor);
502
503
195k
  descriptor->dwFlags = FD_ATTRIBUTES | FD_FILESIZE | FD_WRITESTIME | FD_PROGRESSUI;
504
505
195k
  if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
506
26.3k
  {
507
26.3k
    descriptor->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
508
26.3k
    descriptor->nFileSizeLow = 0;
509
26.3k
    descriptor->nFileSizeHigh = 0;
510
26.3k
  }
511
169k
  else
512
169k
  {
513
169k
    descriptor->dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
514
169k
    descriptor->nFileSizeLow = file->nFileSizeLow;
515
169k
    descriptor->nFileSizeHigh = file->nFileSizeHigh;
516
169k
  }
517
518
195k
  descriptor->ftLastWriteTime = file->ftLastWriteTime;
519
520
195k
  remote_len = _wcsnlen(file->remote_name, ARRAYSIZE(descriptor->cFileName));
521
522
195k
  if (remote_len >= ARRAYSIZE(descriptor->cFileName))
523
7
  {
524
7
    WLog_ERR(TAG, "file name too long (%" PRIuz " characters)", remote_len);
525
7
    return FALSE;
526
7
  }
527
528
195k
  memcpy(descriptor->cFileName, file->remote_name, remote_len * sizeof(WCHAR));
529
195k
  return TRUE;
530
195k
}
531
532
static FILEDESCRIPTORW* convert_local_file_list_to_filedescriptors(wArrayList* files)
533
185
{
534
185
  size_t count = 0;
535
185
  FILEDESCRIPTORW* descriptors = nullptr;
536
537
185
  count = ArrayList_Count(files);
538
539
185
  descriptors = calloc(count, sizeof(FILEDESCRIPTORW));
540
541
185
  if (!descriptors)
542
0
    goto error;
543
544
195k
  for (size_t i = 0; i < count; i++)
545
195k
  {
546
195k
    const struct synthetic_file* file = ArrayList_GetItem(files, i);
547
548
195k
    if (!convert_local_file_to_filedescriptor(file, &descriptors[i]))
549
7
      goto error;
550
195k
  }
551
552
178
  return descriptors;
553
7
error:
554
7
  free(descriptors);
555
7
  return nullptr;
556
185
}
557
558
static void* convert_any_uri_list_to_filedescriptors(wClipboard* clipboard,
559
                                                     WINPR_ATTR_UNUSED UINT32 formatId,
560
                                                     UINT32* pSize)
561
185
{
562
185
  FILEDESCRIPTORW* descriptors = nullptr;
563
564
185
  WINPR_ASSERT(clipboard);
565
185
  WINPR_ASSERT(pSize);
566
567
185
  descriptors = convert_local_file_list_to_filedescriptors(clipboard->localFiles);
568
185
  *pSize = 0;
569
185
  if (!descriptors)
570
7
    return nullptr;
571
572
178
  *pSize = (UINT32)ArrayList_Count(clipboard->localFiles) * sizeof(FILEDESCRIPTORW);
573
178
  clipboard->fileListSequenceNumber = clipboard->sequenceNumber;
574
178
  return descriptors;
575
185
}
576
577
static void* convert_uri_list_to_filedescriptors(wClipboard* clipboard, UINT32 formatId,
578
                                                 const void* data, UINT32* pSize)
579
1.37k
{
580
1.37k
  if (formatId != ClipboardGetFormatId(clipboard, mime_FileGroupDescriptorW))
581
0
  {
582
0
    WLog_ERR(TAG,
583
0
             "Unuspported destination format %s [0x%04" PRIx32
584
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
585
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
586
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
587
0
    return nullptr;
588
0
  }
589
1.37k
  if (clipboard->formatId != ClipboardGetFormatId(clipboard, mime_uri_list))
590
0
  {
591
0
    WLog_ERR(TAG,
592
0
             "Unuspported destination format %s [0x%04" PRIx32
593
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
594
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
595
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
596
0
    return nullptr;
597
0
  }
598
1.37k
  if (!process_uri_list(clipboard, (const char*)data, *pSize))
599
1.19k
    return nullptr;
600
185
  return convert_any_uri_list_to_filedescriptors(clipboard, clipboard->formatId, pSize);
601
1.37k
}
602
603
static BOOL process_files(wClipboard* clipboard, const char* data, UINT32 pSize, const char* prefix)
604
0
{
605
0
  WINPR_ASSERT(prefix);
606
607
0
  const size_t prefix_len = strlen(prefix);
608
609
0
  WINPR_ASSERT(clipboard);
610
611
0
  ArrayList_Clear(clipboard->localFiles);
612
613
0
  if (!data || (pSize < prefix_len))
614
0
    return FALSE;
615
0
  if (strncmp(data, prefix, prefix_len) != 0)
616
0
    return FALSE;
617
0
  data += prefix_len;
618
0
  if (pSize < prefix_len)
619
0
    return FALSE;
620
0
  pSize -= WINPR_ASSERTING_INT_CAST(uint32_t, prefix_len);
621
622
0
  BOOL rc = FALSE;
623
0
  char* copy = strndup(data, pSize);
624
0
  if (!copy)
625
0
    goto fail;
626
627
0
  {
628
0
    char* endptr = nullptr;
629
0
    char* tok = strtok_s(copy, "\n", &endptr);
630
0
    while (tok)
631
0
    {
632
0
      const size_t tok_len = strnlen(tok, pSize);
633
0
      if (!process_uri(clipboard, tok, tok_len))
634
0
        goto fail;
635
0
      if (pSize < tok_len)
636
0
        goto fail;
637
0
      pSize -= WINPR_ASSERTING_INT_CAST(uint32_t, tok_len);
638
0
      tok = strtok_s(nullptr, "\n", &endptr);
639
0
    }
640
0
  }
641
642
0
  rc = TRUE;
643
644
0
fail:
645
0
  free(copy);
646
0
  return rc;
647
0
}
648
649
static BOOL process_gnome_copied_files(wClipboard* clipboard, const char* data, UINT32 pSize)
650
0
{
651
0
  return process_files(clipboard, data, pSize, "copy\n");
652
0
}
653
654
static BOOL process_mate_copied_files(wClipboard* clipboard, const char* data, UINT32 pSize)
655
0
{
656
0
  return process_files(clipboard, data, pSize, "copy\n");
657
0
}
658
659
static void* convert_gnome_copied_files_to_filedescriptors(wClipboard* clipboard, UINT32 formatId,
660
                                                           const void* data, UINT32* pSize)
661
0
{
662
0
  if (formatId != ClipboardGetFormatId(clipboard, mime_FileGroupDescriptorW))
663
0
  {
664
0
    WLog_ERR(TAG,
665
0
             "Unuspported destination format %s [0x%04" PRIx32
666
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
667
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
668
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
669
0
    return nullptr;
670
0
  }
671
0
  if (clipboard->formatId != ClipboardGetFormatId(clipboard, mime_gnome_copied_files))
672
0
  {
673
0
    WLog_ERR(TAG,
674
0
             "Unuspported destination format %s [0x%04" PRIx32
675
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
676
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
677
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
678
0
    return nullptr;
679
0
  }
680
0
  if (!process_gnome_copied_files(clipboard, (const char*)data, *pSize))
681
0
    return nullptr;
682
0
  return convert_any_uri_list_to_filedescriptors(clipboard, clipboard->formatId, pSize);
683
0
}
684
685
static void* convert_mate_copied_files_to_filedescriptors(wClipboard* clipboard, UINT32 formatId,
686
                                                          const void* data, UINT32* pSize)
687
0
{
688
0
  if (formatId != ClipboardGetFormatId(clipboard, mime_FileGroupDescriptorW))
689
0
  {
690
0
    WLog_ERR(TAG,
691
0
             "Unuspported destination format %s [0x%04" PRIx32
692
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
693
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
694
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
695
0
    return nullptr;
696
0
  }
697
0
  if (clipboard->formatId != ClipboardGetFormatId(clipboard, mime_mate_copied_files))
698
0
  {
699
0
    WLog_ERR(TAG,
700
0
             "Unuspported destination format %s [0x%04" PRIx32
701
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
702
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
703
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
704
0
    return nullptr;
705
0
  }
706
707
0
  if (!process_mate_copied_files(clipboard, (const char*)data, *pSize))
708
0
    return nullptr;
709
710
0
  return convert_any_uri_list_to_filedescriptors(clipboard, formatId, pSize);
711
0
}
712
713
WINPR_ATTR_NODISCARD
714
static size_t count_special_chars(const WCHAR* str, size_t charLen)
715
0
{
716
0
  size_t count = 0;
717
0
  const WCHAR* start = str;
718
0
  const WCHAR* end = &str[charLen];
719
720
0
  WINPR_ASSERT(str);
721
0
  while ((start < end) && (*start))
722
0
  {
723
0
    const WCHAR sharp = '#';
724
0
    const WCHAR questionmark = '?';
725
0
    const WCHAR star = '*';
726
0
    const WCHAR exclamationmark = '!';
727
0
    const WCHAR percent = '%';
728
729
0
    if ((*start == sharp) || (*start == questionmark) || (*start == star) ||
730
0
        (*start == exclamationmark) || (*start == percent))
731
0
    {
732
0
      count++;
733
0
    }
734
0
    start++;
735
0
  }
736
0
  return count;
737
0
}
738
739
static const char* stop_at_special_chars(const char* str)
740
0
{
741
0
  const char* start = str;
742
0
  WINPR_ASSERT(str);
743
744
0
  while (*start)
745
0
  {
746
0
    if (*start == '#' || *start == '?' || *start == '*' || *start == '!' || *start == '%')
747
0
    {
748
0
      return start;
749
0
    }
750
0
    start++;
751
0
  }
752
0
  return nullptr;
753
0
}
754
755
/** @return TRUE if the descriptor is for an entry inside a copied folder (its name contains a
756
 *  '\\'), FALSE for a top level file or folder */
757
WINPR_ATTR_NODISCARD
758
static BOOL descriptor_is_nested(const FILEDESCRIPTORW* dsc)
759
0
{
760
0
  WINPR_ASSERT(dsc);
761
762
0
  union
763
0
  {
764
0
    char c[2];
765
0
    WCHAR w;
766
0
  } backslash;
767
0
  backslash.c[0] = '\\';
768
0
  backslash.c[1] = '\0';
769
770
  /* only search the name: what follows its '\0' in cFileName is not guaranteed to be zeroed */
771
0
  const size_t len = _wcsnlen(dsc->cFileName, ARRAYSIZE(dsc->cFileName));
772
0
  return winpr_wcsnchr(dsc->cFileName, len, backslash.w) != nullptr;
773
0
}
774
775
/* The universal converter from filedescriptors to different file lists */
776
WINPR_ATTR_MALLOC(free, 1)
777
static void* convert_filedescriptors_to_file_list(wClipboard* clipboard, const void* data,
778
                                                  UINT32* pSize, const char* header,
779
                                                  const char* lineprefix, const char* lineending,
780
                                                  BOOL skip_last_lineending)
781
18
{
782
18
  UINT32 nrDescriptors = 0;
783
18
  size_t baseLength = 0;
784
18
  size_t header_len = strlen(header);
785
18
  size_t lineprefix_len = strlen(lineprefix);
786
18
  size_t lineending_len = strlen(lineending);
787
788
18
  if (!clipboard || !data || !pSize)
789
0
    return nullptr;
790
791
18
  if (*pSize < sizeof(UINT32))
792
6
    return nullptr;
793
794
12
  if (clipboard->delegate.basePath)
795
0
    baseLength = strnlen(clipboard->delegate.basePath, MAX_PATH);
796
797
12
  if (baseLength < 1)
798
12
    return nullptr;
799
800
0
  wStream sbuffer = WINPR_C_ARRAY_INIT;
801
0
  wStream* s = Stream_StaticConstInit(&sbuffer, data, *pSize);
802
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
803
0
    return nullptr;
804
805
0
  Stream_Read_UINT32(s, nrDescriptors);
806
807
0
  const size_t count = (*pSize - 4) / sizeof(FILEDESCRIPTORW);
808
809
0
  if ((count < 1) || (count != nrDescriptors))
810
0
    return nullptr;
811
812
0
  const FILEDESCRIPTORW* descriptors = Stream_ConstPointer(s);
813
814
  /* formatId is the destination format (see ClipboardRegisterSynthesizerEx), the descriptors
815
   * are the source data */
816
0
  if (clipboard->formatId != ClipboardGetFormatId(clipboard, mime_FileGroupDescriptorW))
817
0
    return nullptr;
818
819
  /* Plus 1 for '/' between basepath and filename*/
820
0
  const size_t decoration_len = lineprefix_len + lineending_len + baseLength + 1;
821
0
  size_t alloc = header_len;
822
823
  /* Get total size of file/folder names under first level folder only */
824
0
  for (size_t x = 0; x < count; x++)
825
0
  {
826
0
    const FILEDESCRIPTORW* dsc = &descriptors[x];
827
828
0
    if (!descriptor_is_nested(dsc))
829
0
    {
830
0
      alloc += ARRAYSIZE(dsc->cFileName) *
831
0
               8; /* Overallocate, just take the biggest value the result path can have */
832
                  /* # (1 char) -> %23 (3 chars) , the first char is replaced inplace */
833
0
      alloc += count_special_chars(dsc->cFileName, ARRAYSIZE(dsc->cFileName)) * sizeof(WCHAR);
834
0
      alloc += decoration_len;
835
0
    }
836
0
  }
837
838
  /* Append a prefix file:// and postfix \n for each file */
839
  /* We need to keep last \n since snprintf is null terminated!!  */
840
0
  alloc++;
841
0
  char* dst = calloc(alloc, sizeof(char));
842
843
0
  if (!dst)
844
0
    return nullptr;
845
846
0
  (void)_snprintf(&dst[0], alloc, "%s", header);
847
848
0
  size_t pos = header_len;
849
850
0
  for (size_t x = 0; x < count; x++)
851
0
  {
852
0
    const FILEDESCRIPTORW* dsc = &descriptors[x];
853
0
    BOOL fail = TRUE;
854
0
    if (descriptor_is_nested(dsc))
855
0
    {
856
0
      continue;
857
0
    }
858
0
    int rc = -1;
859
0
    char curName[520] = WINPR_C_ARRAY_INIT;
860
0
    const char* stop_at = nullptr;
861
0
    const char* previous_at = nullptr;
862
863
0
    if (ConvertWCharNToUtf8(dsc->cFileName, ARRAYSIZE(dsc->cFileName), curName,
864
0
                            ARRAYSIZE(curName)) < 0)
865
0
      goto loop_fail;
866
867
0
    rc = _snprintf(&dst[pos], alloc - pos, "%s%s/", lineprefix, clipboard->delegate.basePath);
868
869
0
    if (rc < 0)
870
0
      goto loop_fail;
871
872
0
    pos += (size_t)rc;
873
874
0
    previous_at = curName;
875
0
    while ((stop_at = stop_at_special_chars(previous_at)) != nullptr)
876
0
    {
877
0
      const intptr_t diff = stop_at - previous_at;
878
0
      if (diff < 0)
879
0
        goto loop_fail;
880
0
      char* tmp = strndup(previous_at, WINPR_ASSERTING_INT_CAST(size_t, diff));
881
0
      if (!tmp)
882
0
        goto loop_fail;
883
884
0
      rc = _snprintf(&dst[pos], WINPR_ASSERTING_INT_CAST(size_t, diff + 1), "%s", tmp);
885
0
      free(tmp);
886
0
      if (rc < 0)
887
0
        goto loop_fail;
888
889
0
      pos += (size_t)rc;
890
0
      rc = _snprintf(&dst[pos], 4, "%%%x", *stop_at);
891
0
      if (rc < 0)
892
0
        goto loop_fail;
893
894
0
      pos += (size_t)rc;
895
0
      previous_at = stop_at + 1;
896
0
    }
897
898
0
    rc = _snprintf(&dst[pos], alloc - pos, "%s%s", previous_at, lineending);
899
900
0
    fail = FALSE;
901
0
  loop_fail:
902
0
    if ((rc < 0) || fail)
903
0
    {
904
0
      free(dst);
905
0
      return nullptr;
906
0
    }
907
908
0
    pos += (size_t)rc;
909
0
  }
910
911
0
  if (skip_last_lineending)
912
0
  {
913
0
    const size_t endlen = strlen(lineending);
914
0
    if (alloc > endlen)
915
0
    {
916
0
      const size_t len = strnlen(dst, alloc);
917
0
      if (len < endlen)
918
0
      {
919
0
        free(dst);
920
0
        return nullptr;
921
0
      }
922
923
0
      if (memcmp(&dst[len - endlen], lineending, endlen) == 0)
924
0
      {
925
0
        memset(&dst[len - endlen], 0, endlen);
926
0
        alloc -= endlen;
927
0
      }
928
0
    }
929
0
  }
930
931
0
  alloc = strnlen(dst, alloc) + 1;
932
0
  *pSize = (UINT32)alloc;
933
0
  clipboard->fileListSequenceNumber = clipboard->sequenceNumber;
934
0
  return dst;
935
0
}
936
937
/* Prepend header of kde dolphin format to file list
938
 * See:
939
 *   GTK: https://docs.gtk.org/glib/struct.Uri.html
940
 *   uri syntax: https://www.rfc-editor.org/rfc/rfc3986#section-3
941
 *   uri-lists format: https://www.rfc-editor.org/rfc/rfc2483#section-5
942
 */
943
WINPR_ATTR_MALLOC(free, 1)
944
static void* convert_filedescriptors_to_uri_list(wClipboard* clipboard, UINT32 formatId,
945
                                                 const void* data, UINT32* pSize)
946
6
{
947
6
  if (formatId != ClipboardGetFormatId(clipboard, mime_uri_list))
948
0
  {
949
0
    WLog_ERR(TAG,
950
0
             "Unuspported destination format %s [0x%04" PRIx32
951
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
952
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
953
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
954
0
    return nullptr;
955
0
  }
956
6
  if (clipboard->formatId != ClipboardGetFormatId(clipboard, mime_FileGroupDescriptorW))
957
0
  {
958
0
    WLog_ERR(TAG,
959
0
             "Unuspported destination format %s [0x%04" PRIx32
960
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
961
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
962
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
963
0
    return nullptr;
964
0
  }
965
6
  return convert_filedescriptors_to_file_list(clipboard, data, pSize, "", "file://", "\r\n",
966
6
                                              FALSE);
967
6
}
968
969
/* Prepend header of common gnome format to file list*/
970
WINPR_ATTR_MALLOC(free, 1)
971
static void* convert_filedescriptors_to_gnome_copied_files(wClipboard* clipboard, UINT32 formatId,
972
                                                           const void* data, UINT32* pSize)
973
6
{
974
6
  if (formatId != ClipboardGetFormatId(clipboard, mime_gnome_copied_files))
975
0
  {
976
0
    WLog_ERR(TAG,
977
0
             "Unuspported destination format %s [0x%04" PRIx32
978
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
979
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
980
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
981
0
    return nullptr;
982
0
  }
983
6
  if (clipboard->formatId != ClipboardGetFormatId(clipboard, mime_FileGroupDescriptorW))
984
0
  {
985
0
    WLog_ERR(TAG,
986
0
             "Unuspported destination format %s [0x%04" PRIx32
987
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
988
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
989
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
990
0
    return nullptr;
991
0
  }
992
6
  return convert_filedescriptors_to_file_list(clipboard, data, pSize, "copy\n", "file://", "\n",
993
6
                                              TRUE);
994
6
}
995
996
WINPR_ATTR_MALLOC(free, 1)
997
static void* convert_filedescriptors_to_mate_copied_files(wClipboard* clipboard, UINT32 formatId,
998
                                                          const void* data, UINT32* pSize)
999
6
{
1000
6
  if (formatId != ClipboardGetFormatId(clipboard, mime_mate_copied_files))
1001
0
  {
1002
0
    WLog_ERR(TAG,
1003
0
             "Unuspported destination format %s [0x%04" PRIx32
1004
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
1005
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
1006
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
1007
0
    return nullptr;
1008
0
  }
1009
6
  if (clipboard->formatId != ClipboardGetFormatId(clipboard, mime_FileGroupDescriptorW))
1010
0
  {
1011
0
    WLog_ERR(TAG,
1012
0
             "Unuspported destination format %s [0x%04" PRIx32
1013
0
             "], trying to convert from %s [0x%04" PRIx32 "]",
1014
0
             ClipboardGetFormatName(clipboard, formatId), formatId,
1015
0
             ClipboardGetFormatName(clipboard, clipboard->formatId), clipboard->formatId);
1016
0
    return nullptr;
1017
0
  }
1018
6
  char* pDstData = convert_filedescriptors_to_file_list(clipboard, data, pSize, "copy\n",
1019
6
                                                        "file://", "\n", TRUE);
1020
6
  if (!pDstData)
1021
6
  {
1022
6
    return pDstData;
1023
6
  }
1024
  /*  Replace last \n with \0
1025
      see
1026
     mate-desktop/caja/libcaja-private/caja-clipboard.c:caja_clipboard_get_uri_list_from_selection_data
1027
  */
1028
1029
0
  pDstData[*pSize - 1] = '\0';
1030
0
  *pSize = *pSize - 1;
1031
0
  return pDstData;
1032
6
}
1033
1034
static void array_free_synthetic_file(void* the_file)
1035
384k
{
1036
384k
  struct synthetic_file* file = the_file;
1037
384k
  free_synthetic_file(file);
1038
384k
}
1039
1040
static BOOL register_file_formats_and_synthesizers(wClipboard* clipboard)
1041
3.37k
{
1042
3.37k
  wObject* obj = nullptr;
1043
1044
  /*
1045
      1. Gnome Nautilus based file manager (Nautilus only with version >= 3.30 AND < 40):
1046
          TARGET: UTF8_STRING
1047
          format: x-special/nautilus-clipboard\copy\n\file://path\n\0
1048
      2. Kde Dolpin and Qt:
1049
          TARGET: text/uri-list
1050
          format: file:path\r\n\0
1051
          See:
1052
            GTK: https://docs.gtk.org/glib/struct.Uri.html
1053
            uri syntax: https://www.rfc-editor.org/rfc/rfc3986#section-3
1054
            uri-lists format: https://www.rfc-editor.org/rfc/rfc2483#section-5
1055
      3. Gnome and others (Unity/XFCE/Nautilus < 3.30/Nautilus >= 40):
1056
          TARGET: x-special/gnome-copied-files
1057
          format: copy\nfile://path\n\0
1058
      4. Mate Caja:
1059
          TARGET: x-special/mate-copied-files
1060
          format: copy\nfile://path\n
1061
1062
      TODO: other file managers do not use previous targets and formats.
1063
  */
1064
1065
3.37k
  const UINT32 local_gnome_file_format_id =
1066
3.37k
      ClipboardRegisterFormat(clipboard, mime_gnome_copied_files);
1067
3.37k
  const UINT32 local_mate_file_format_id =
1068
3.37k
      ClipboardRegisterFormat(clipboard, mime_mate_copied_files);
1069
3.37k
  const UINT32 file_group_format_id =
1070
3.37k
      ClipboardRegisterFormat(clipboard, mime_FileGroupDescriptorW);
1071
3.37k
  const UINT32 local_file_format_id = ClipboardRegisterFormat(clipboard, mime_uri_list);
1072
1073
3.37k
  if (!file_group_format_id || !local_file_format_id || !local_gnome_file_format_id ||
1074
3.37k
      !local_mate_file_format_id)
1075
0
    goto error;
1076
1077
3.37k
  clipboard->localFiles = ArrayList_New(FALSE);
1078
1079
3.37k
  if (!clipboard->localFiles)
1080
0
    goto error;
1081
1082
3.37k
  obj = ArrayList_Object(clipboard->localFiles);
1083
3.37k
  obj->fnObjectFree = array_free_synthetic_file;
1084
1085
3.37k
  if (!ClipboardRegisterSynthesizerEx(clipboard, local_file_format_id, file_group_format_id,
1086
3.37k
                                      convert_uri_list_to_filedescriptors))
1087
0
    goto error_free_local_files;
1088
1089
3.37k
  if (!ClipboardRegisterSynthesizerEx(clipboard, file_group_format_id, local_file_format_id,
1090
3.37k
                                      convert_filedescriptors_to_uri_list))
1091
0
    goto error_free_local_files;
1092
1093
3.37k
  if (!ClipboardRegisterSynthesizerEx(clipboard, local_gnome_file_format_id, file_group_format_id,
1094
3.37k
                                      convert_gnome_copied_files_to_filedescriptors))
1095
0
    goto error_free_local_files;
1096
1097
3.37k
  if (!ClipboardRegisterSynthesizerEx(clipboard, file_group_format_id, local_gnome_file_format_id,
1098
3.37k
                                      convert_filedescriptors_to_gnome_copied_files))
1099
0
    goto error_free_local_files;
1100
1101
3.37k
  if (!ClipboardRegisterSynthesizerEx(clipboard, local_mate_file_format_id, file_group_format_id,
1102
3.37k
                                      convert_mate_copied_files_to_filedescriptors))
1103
0
    goto error_free_local_files;
1104
1105
3.37k
  if (!ClipboardRegisterSynthesizerEx(clipboard, file_group_format_id, local_mate_file_format_id,
1106
3.37k
                                      convert_filedescriptors_to_mate_copied_files))
1107
0
    goto error_free_local_files;
1108
1109
3.37k
  return TRUE;
1110
0
error_free_local_files:
1111
0
  ArrayList_Free(clipboard->localFiles);
1112
0
  clipboard->localFiles = nullptr;
1113
0
error:
1114
0
  return FALSE;
1115
0
}
1116
1117
static int32_t file_get_size(const struct synthetic_file* file, UINT64* size)
1118
0
{
1119
0
  UINT64 s = 0;
1120
1121
0
  if (!file || !size)
1122
0
    return E_INVALIDARG;
1123
1124
0
  s = file->nFileSizeHigh;
1125
0
  s <<= 32;
1126
0
  s |= file->nFileSizeLow;
1127
0
  *size = s;
1128
0
  return NO_ERROR;
1129
0
}
1130
1131
static UINT delegate_file_request_size(wClipboardDelegate* delegate,
1132
                                       const wClipboardFileSizeRequest* request)
1133
0
{
1134
0
  UINT64 size = 0;
1135
1136
0
  if (!delegate || !delegate->clipboard || !request)
1137
0
    return ERROR_BAD_ARGUMENTS;
1138
1139
0
  if (delegate->clipboard->sequenceNumber != delegate->clipboard->fileListSequenceNumber)
1140
0
    return ERROR_INVALID_STATE;
1141
1142
0
  struct synthetic_file* file =
1143
0
      ArrayList_GetItem(delegate->clipboard->localFiles, request->listIndex);
1144
1145
0
  if (!file)
1146
0
    return ERROR_INDEX_ABSENT;
1147
1148
0
  const int32_t s = file_get_size(file, &size);
1149
0
  uint32_t error = 0;
1150
0
  if (error)
1151
0
    error = delegate->ClipboardFileSizeFailure(delegate, request, (UINT)s);
1152
0
  else
1153
0
    error = delegate->ClipboardFileSizeSuccess(delegate, request, size);
1154
1155
0
  if (error)
1156
0
    WLog_WARN(TAG, "failed to report file size result: 0x%08X", error);
1157
1158
0
  return NO_ERROR;
1159
0
}
1160
1161
UINT synthetic_file_read_close(struct synthetic_file* file, BOOL force)
1162
384k
{
1163
384k
  if (!file || INVALID_HANDLE_VALUE == file->fd)
1164
384k
    return NO_ERROR;
1165
1166
  /* Always force close the file. Clipboard might open hundreds of files
1167
   * so avoid caching to prevent running out of available file descriptors */
1168
0
  UINT64 size = 0;
1169
0
  file_get_size(file, &size);
1170
0
  if ((file->offset < 0) || ((UINT64)file->offset >= size) || force)
1171
0
  {
1172
0
    WLog_VRB(TAG, "close file %p", file->fd);
1173
0
    if (!CloseHandle(file->fd))
1174
0
    {
1175
0
      WLog_WARN(TAG, "failed to close fd %p: %" PRIu32, file->fd, GetLastError());
1176
0
    }
1177
1178
0
    file->fd = INVALID_HANDLE_VALUE;
1179
0
  }
1180
1181
0
  return NO_ERROR;
1182
384k
}
1183
1184
static UINT file_get_range(struct synthetic_file* file, UINT64 offset, UINT32 size,
1185
                           BYTE** actual_data, UINT32* actual_size)
1186
0
{
1187
0
  UINT error = NO_ERROR;
1188
0
  DWORD dwLow = 0;
1189
0
  DWORD dwHigh = 0;
1190
1191
0
  WINPR_ASSERT(file);
1192
0
  WINPR_ASSERT(actual_data);
1193
0
  WINPR_ASSERT(actual_size);
1194
1195
0
  if (INVALID_HANDLE_VALUE == file->fd)
1196
0
  {
1197
0
    BY_HANDLE_FILE_INFORMATION FileInfo = WINPR_C_ARRAY_INIT;
1198
1199
0
    file->fd = CreateFileW(file->local_name, GENERIC_READ, 0, nullptr, OPEN_EXISTING,
1200
0
                           FILE_ATTRIBUTE_NORMAL, nullptr);
1201
0
    if (INVALID_HANDLE_VALUE == file->fd)
1202
0
    {
1203
0
      char name[MAX_PATH] = WINPR_C_ARRAY_INIT;
1204
0
      ConvertWCharToUtf8(file->local_name, name, sizeof(name) - 1);
1205
0
      error = GetLastError();
1206
0
      WLog_ERR(TAG, "failed to open file %s: 0x%08" PRIx32, name, error);
1207
0
      return error;
1208
0
    }
1209
1210
0
    if (!GetFileInformationByHandle(file->fd, &FileInfo))
1211
0
    {
1212
0
      char name[MAX_PATH] = WINPR_C_ARRAY_INIT;
1213
0
      ConvertWCharToUtf8(file->local_name, name, sizeof(name) - 1);
1214
0
      (void)CloseHandle(file->fd);
1215
0
      file->fd = INVALID_HANDLE_VALUE;
1216
0
      error = GetLastError();
1217
0
      WLog_ERR(TAG, "Get file [%s] information fail: 0x%08" PRIx32, name, error);
1218
0
      return error;
1219
0
    }
1220
1221
0
    file->offset = 0;
1222
0
    file->nFileSizeHigh = FileInfo.nFileSizeHigh;
1223
0
    file->nFileSizeLow = FileInfo.nFileSizeLow;
1224
1225
    /*
1226
    {
1227
        UINT64 s = 0;
1228
        file_get_size(file, &s);
1229
        WLog_DBG(TAG, "open file %d -> %s", file->fd, file->local_name);
1230
        WLog_DBG(TAG, "file %d size: %" PRIu64 " bytes", file->fd, s);
1231
    } //*/
1232
0
  }
1233
1234
0
  do
1235
0
  {
1236
    /*
1237
     * We should avoid seeking when possible as some filesystems (e.g.,
1238
     * an FTP server mapped via FUSE) may not support seeking. We keep
1239
     * an accurate account of the current file offset and do not call
1240
     * lseek() if the client requests file content sequentially.
1241
     */
1242
0
    if (offset > INT64_MAX)
1243
0
    {
1244
0
      WLog_ERR(TAG, "offset [%" PRIu64 "] > INT64_MAX", offset);
1245
0
      error = ERROR_SEEK;
1246
0
      break;
1247
0
    }
1248
1249
0
    if (file->offset != (INT64)offset)
1250
0
    {
1251
0
      WLog_DBG(TAG, "file %p force seeking to %" PRIu64 ", current %" PRId64, file->fd,
1252
0
               offset, file->offset);
1253
1254
0
      dwHigh = offset >> 32;
1255
0
      dwLow = offset & 0xFFFFFFFF;
1256
0
      if (INVALID_SET_FILE_POINTER == SetFilePointer(file->fd,
1257
0
                                                     WINPR_ASSERTING_INT_CAST(LONG, dwLow),
1258
0
                                                     (PLONG)&dwHigh, FILE_BEGIN))
1259
0
      {
1260
0
        error = GetLastError();
1261
0
        break;
1262
0
      }
1263
0
    }
1264
1265
0
    BYTE* buffer = malloc(size);
1266
0
    if (!buffer)
1267
0
    {
1268
0
      error = ERROR_NOT_ENOUGH_MEMORY;
1269
0
      break;
1270
0
    }
1271
0
    if (!ReadFile(file->fd, buffer, size, (LPDWORD)actual_size, nullptr))
1272
0
    {
1273
0
      free(buffer);
1274
0
      error = GetLastError();
1275
0
      break;
1276
0
    }
1277
1278
0
    *actual_data = buffer;
1279
0
    file->offset += *actual_size;
1280
0
    WLog_VRB(TAG, "file %p actual read %" PRIu32 " bytes (offset %" PRId64 ")", file->fd,
1281
0
             *actual_size, file->offset);
1282
0
  } while (0);
1283
1284
0
  synthetic_file_read_close(file, TRUE /* (error != NO_ERROR) && (size > 0) */);
1285
0
  return error;
1286
0
}
1287
1288
static UINT delegate_file_request_range(wClipboardDelegate* delegate,
1289
                                        const wClipboardFileRangeRequest* request)
1290
0
{
1291
0
  UINT error = 0;
1292
0
  BYTE* data = nullptr;
1293
0
  UINT32 size = 0;
1294
0
  UINT64 offset = 0;
1295
0
  struct synthetic_file* file = nullptr;
1296
1297
0
  if (!delegate || !delegate->clipboard || !request)
1298
0
    return ERROR_BAD_ARGUMENTS;
1299
1300
0
  if (delegate->clipboard->sequenceNumber != delegate->clipboard->fileListSequenceNumber)
1301
0
    return ERROR_INVALID_STATE;
1302
1303
0
  file = ArrayList_GetItem(delegate->clipboard->localFiles, request->listIndex);
1304
1305
0
  if (!file)
1306
0
    return ERROR_INDEX_ABSENT;
1307
1308
0
  offset = (((UINT64)request->nPositionHigh) << 32) | ((UINT64)request->nPositionLow);
1309
0
  error = file_get_range(file, offset, request->cbRequested, &data, &size);
1310
1311
0
  if (error)
1312
0
    error = delegate->ClipboardFileRangeFailure(delegate, request, error);
1313
0
  else
1314
0
    error = delegate->ClipboardFileRangeSuccess(delegate, request, data, size);
1315
1316
0
  if (error)
1317
0
    WLog_WARN(TAG, "failed to report file range result: 0x%08X", error);
1318
1319
0
  free(data);
1320
0
  return NO_ERROR;
1321
0
}
1322
1323
static UINT dummy_file_size_success(WINPR_ATTR_UNUSED wClipboardDelegate* delegate,
1324
                                    WINPR_ATTR_UNUSED const wClipboardFileSizeRequest* request,
1325
                                    WINPR_ATTR_UNUSED UINT64 fileSize)
1326
0
{
1327
0
  return ERROR_NOT_SUPPORTED;
1328
0
}
1329
1330
static UINT dummy_file_size_failure(WINPR_ATTR_UNUSED wClipboardDelegate* delegate,
1331
                                    WINPR_ATTR_UNUSED const wClipboardFileSizeRequest* request,
1332
                                    WINPR_ATTR_UNUSED UINT errorCode)
1333
0
{
1334
0
  return ERROR_NOT_SUPPORTED;
1335
0
}
1336
1337
static UINT dummy_file_range_success(WINPR_ATTR_UNUSED wClipboardDelegate* delegate,
1338
                                     WINPR_ATTR_UNUSED const wClipboardFileRangeRequest* request,
1339
                                     WINPR_ATTR_UNUSED const BYTE* data,
1340
                                     WINPR_ATTR_UNUSED UINT32 size)
1341
0
{
1342
0
  return ERROR_NOT_SUPPORTED;
1343
0
}
1344
1345
static UINT dummy_file_range_failure(WINPR_ATTR_UNUSED wClipboardDelegate* delegate,
1346
                                     WINPR_ATTR_UNUSED const wClipboardFileRangeRequest* request,
1347
                                     WINPR_ATTR_UNUSED UINT errorCode)
1348
0
{
1349
0
  return ERROR_NOT_SUPPORTED;
1350
0
}
1351
1352
static void setup_delegate(wClipboardDelegate* delegate)
1353
3.37k
{
1354
3.37k
  WINPR_ASSERT(delegate);
1355
1356
3.37k
  delegate->ClientRequestFileSize = delegate_file_request_size;
1357
3.37k
  delegate->ClipboardFileSizeSuccess = dummy_file_size_success;
1358
3.37k
  delegate->ClipboardFileSizeFailure = dummy_file_size_failure;
1359
3.37k
  delegate->ClientRequestFileRange = delegate_file_request_range;
1360
3.37k
  delegate->ClipboardFileRangeSuccess = dummy_file_range_success;
1361
3.37k
  delegate->ClipboardFileRangeFailure = dummy_file_range_failure;
1362
3.37k
  delegate->IsFileNameComponentValid = ValidFileNameComponent;
1363
3.37k
}
1364
1365
BOOL ClipboardInitSyntheticFileSubsystem(wClipboard* clipboard)
1366
3.37k
{
1367
3.37k
  if (!clipboard)
1368
0
    return FALSE;
1369
1370
3.37k
  if (!register_file_formats_and_synthesizers(clipboard))
1371
0
    return FALSE;
1372
1373
3.37k
  setup_delegate(&clipboard->delegate);
1374
3.37k
  return TRUE;
1375
3.37k
}