Coverage Report

Created: 2026-10-15 06:30

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
0
{
76
0
  struct synthetic_file* file = nullptr;
77
0
  WIN32_FIND_DATAW fd = WINPR_C_ARRAY_INIT;
78
0
  HANDLE hFind = nullptr;
79
80
0
  WINPR_ASSERT(local_name);
81
0
  WINPR_ASSERT(remote_name);
82
83
0
  hFind = FindFirstFileW(local_name, &fd);
84
0
  if (INVALID_HANDLE_VALUE == hFind)
85
0
  {
86
0
    WLog_ERR(TAG, "FindFirstFile failed (%" PRIu32 ")", GetLastError());
87
0
    return nullptr;
88
0
  }
89
0
  FindClose(hFind);
90
91
0
  file = calloc(1, sizeof(*file));
92
0
  if (!file)
93
0
    return nullptr;
94
95
0
  file->fd = INVALID_HANDLE_VALUE;
96
0
  file->offset = 0;
97
0
  file->local_name = _wcsdup(local_name);
98
0
  if (!file->local_name)
99
0
    goto fail;
100
101
0
  file->remote_name = _wcsdup(remote_name);
102
0
  if (!file->remote_name)
103
0
    goto fail;
104
105
0
  {
106
0
    const size_t len = _wcslen(file->remote_name);
107
0
    if (S_OK != PathCchConvertStyleW(file->remote_name, len, PATH_STYLE_WINDOWS))
108
0
      goto fail;
109
0
  }
110
111
0
  file->dwFileAttributes = fd.dwFileAttributes;
112
0
  file->ftCreationTime = fd.ftCreationTime;
113
0
  file->ftLastWriteTime = fd.ftLastWriteTime;
114
0
  file->ftLastAccessTime = fd.ftLastAccessTime;
115
0
  file->nFileSizeHigh = fd.nFileSizeHigh;
116
0
  file->nFileSizeLow = fd.nFileSizeLow;
117
118
0
  return file;
119
0
fail:
120
0
  free_synthetic_file(file);
121
0
  return nullptr;
122
0
}
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
0
{
128
0
  if (!file)
129
0
    return;
130
131
0
  synthetic_file_read_close(file, TRUE);
132
133
0
  free(file->local_name);
134
0
  free(file->remote_name);
135
0
  free(file);
136
0
}
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
0
{
144
0
  wClipboardDelegate* delegate = ClipboardGetDelegate(clipboard);
145
0
  WCHAR* remote_name = nullptr;
146
147
0
  WINPR_ASSERT(delegate);
148
149
0
  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
0
  if (!delegate->IsFileNameComponentValid(remote_name))
161
0
  {
162
0
    char name[MAX_PATH] = WINPR_C_ARRAY_INIT;
163
0
    ConvertWCharToUtf8(local_name, name, sizeof(name) - 1);
164
0
    WLog_ERR(TAG, "invalid file name component: %s", name);
165
0
    goto error;
166
0
  }
167
168
0
  return remote_name;
169
0
error:
170
0
  free(remote_name);
171
0
  return nullptr;
172
0
}
173
174
static WCHAR* concat_file_name(const WCHAR* dir, const WCHAR* file)
175
0
{
176
0
  size_t len_dir = 0;
177
0
  size_t len_file = 0;
178
0
  const WCHAR slash = '/';
179
0
  WCHAR* buffer = nullptr;
180
181
0
  WINPR_ASSERT(dir);
182
0
  WINPR_ASSERT(file);
183
184
0
  len_dir = _wcslen(dir);
185
0
  len_file = _wcslen(file);
186
0
  buffer = calloc(len_dir + 1 + len_file + 2, sizeof(WCHAR));
187
188
0
  if (!buffer)
189
0
    return nullptr;
190
191
0
  memcpy(buffer, dir, len_dir * sizeof(WCHAR));
192
0
  buffer[len_dir] = slash;
193
0
  memcpy(buffer + len_dir + 1, file, len_file * sizeof(WCHAR));
194
0
  return buffer;
195
0
}
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
0
{
204
0
  BOOL result = FALSE;
205
0
  WCHAR* local_name = nullptr;
206
0
  WCHAR* remote_name = nullptr;
207
0
  WCHAR* remote_base_name = nullptr;
208
209
0
  WCHAR dotbuffer[6] = WINPR_C_ARRAY_INIT;
210
0
  WCHAR dotdotbuffer[6] = WINPR_C_ARRAY_INIT;
211
0
  const WCHAR* dot = InitializeConstWCharFromUtf8(".", dotbuffer, ARRAYSIZE(dotbuffer));
212
0
  const WCHAR* dotdot = InitializeConstWCharFromUtf8("..", dotdotbuffer, ARRAYSIZE(dotdotbuffer));
213
214
0
  WINPR_ASSERT(clipboard);
215
0
  WINPR_ASSERT(local_dir_name);
216
0
  WINPR_ASSERT(remote_dir_name);
217
0
  WINPR_ASSERT(pFileData);
218
0
  WINPR_ASSERT(files);
219
220
  /* Skip special directory entries. */
221
222
0
  if ((_wcscmp(pFileData->cFileName, dot) == 0) || (_wcscmp(pFileData->cFileName, dotdot) == 0))
223
0
    return TRUE;
224
225
0
  remote_base_name = convert_local_name_component_to_remote(clipboard, pFileData->cFileName);
226
227
0
  if (!remote_base_name)
228
0
    return FALSE;
229
230
0
  local_name = concat_file_name(local_dir_name, pFileData->cFileName);
231
0
  remote_name = concat_file_name(remote_dir_name, remote_base_name);
232
233
0
  if (local_name && remote_name)
234
0
    result = add_file_to_list(clipboard, recursionDepth, local_name, remote_name, files);
235
236
0
  free(remote_base_name);
237
0
  free(remote_name);
238
0
  free(local_name);
239
0
  return result;
240
0
}
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
0
{
246
0
  WINPR_ASSERT(clipboard);
247
0
  WINPR_ASSERT(local_name);
248
0
  WINPR_ASSERT(remote_name);
249
0
  WINPR_ASSERT(files);
250
0
  WINPR_ASSERT(namebuf);
251
252
0
  WIN32_FIND_DATAW FindData = WINPR_C_ARRAY_INIT;
253
0
  HANDLE hFind = FindFirstFileW(namebuf, &FindData);
254
0
  if (INVALID_HANDLE_VALUE == hFind)
255
0
  {
256
0
    WLog_ERR(TAG, "FindFirstFile failed (%" PRIu32 ")", GetLastError());
257
0
    return FALSE;
258
0
  }
259
0
  while (TRUE)
260
0
  {
261
0
    if (!add_directory_entry_to_list(clipboard, recursionDepth, local_name, remote_name,
262
0
                                     &FindData, files))
263
0
    {
264
0
      FindClose(hFind);
265
0
      return FALSE;
266
0
    }
267
268
0
    BOOL bRet = FindNextFileW(hFind, &FindData);
269
0
    if (!bRet)
270
0
    {
271
0
      FindClose(hFind);
272
0
      if (ERROR_NO_MORE_FILES == GetLastError())
273
0
        return TRUE;
274
0
      WLog_WARN(TAG, "FindNextFile failed (%" PRIu32 ")", GetLastError());
275
0
      return FALSE;
276
0
    }
277
0
  }
278
279
0
  return TRUE;
280
0
}
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
0
{
286
0
  BOOL result = FALSE;
287
0
  union
288
0
  {
289
0
    const char* c;
290
0
    const WCHAR* w;
291
0
  } wildcard;
292
0
  const char buffer[6] = { '/', '\0', '*', '\0', '\0', '\0' };
293
0
  wildcard.c = buffer;
294
0
  const size_t wildcardLen = ARRAYSIZE(buffer) / sizeof(WCHAR);
295
296
0
  WINPR_ASSERT(clipboard);
297
0
  WINPR_ASSERT(local_name);
298
0
  WINPR_ASSERT(remote_name);
299
0
  WINPR_ASSERT(files);
300
301
0
  const size_t max = CLIPBOARD_FILE_MAX_RECURSION;
302
0
  if (recursionDepth > max)
303
0
  {
304
0
    WLog_ERR(TAG,
305
0
             "This build only supports recursionDepth=%" PRIuz
306
0
             " <= CLIPBOARD_FILE_MAX_RECURSION=%" PRIuz " recursion depth for folders copied.",
307
0
             recursionDepth, max);
308
0
    return FALSE;
309
0
  }
310
311
0
  size_t len = _wcslen(local_name);
312
0
  WCHAR* namebuf = calloc(len + wildcardLen, sizeof(WCHAR));
313
0
  if (!namebuf)
314
0
    return FALSE;
315
316
0
  _wcsncat(namebuf, local_name, len);
317
0
  _wcsncat(namebuf, wildcard.w, wildcardLen);
318
319
0
  result = do_add_directory_contents_to_list(clipboard, recursionDepth, local_name, remote_name,
320
0
                                             namebuf, files);
321
322
0
  free(namebuf);
323
0
  return result;
324
0
}
325
326
BOOL add_file_to_list(wClipboard* clipboard, size_t recursionDepth, const WCHAR* local_name,
327
                      const WCHAR* remote_name, wArrayList* files)
328
0
{
329
0
  struct synthetic_file* file = nullptr;
330
331
0
  WINPR_ASSERT(clipboard);
332
0
  WINPR_ASSERT(local_name);
333
0
  WINPR_ASSERT(remote_name);
334
0
  WINPR_ASSERT(files);
335
336
0
  file = make_synthetic_file(local_name, remote_name);
337
338
0
  if (!file)
339
0
    return FALSE;
340
341
0
  if (!ArrayList_Append(files, file))
342
0
  {
343
0
    free_synthetic_file(file);
344
0
    return FALSE;
345
0
  }
346
347
0
  if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
348
0
  {
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
0
    if (!add_directory_contents_to_list(clipboard, recursionDepth + 1, local_name, remote_name,
354
0
                                        files))
355
0
      return FALSE;
356
0
  }
357
358
0
  return TRUE;
359
0
}
360
361
static const WCHAR* get_basename(const WCHAR* name)
362
0
{
363
0
  const WCHAR* c = name;
364
0
  const WCHAR* last_name = name;
365
0
  const WCHAR slash = '/';
366
367
0
  WINPR_ASSERT(name);
368
369
0
  while (*c++)
370
0
  {
371
0
    if (*c == slash)
372
0
      last_name = c + 1;
373
0
  }
374
375
0
  return last_name;
376
0
}
377
378
static BOOL process_file_name(wClipboard* clipboard, const WCHAR* local_name, wArrayList* files)
379
0
{
380
0
  BOOL result = FALSE;
381
0
  const WCHAR* base_name = nullptr;
382
0
  WCHAR* remote_name = nullptr;
383
384
0
  WINPR_ASSERT(clipboard);
385
0
  WINPR_ASSERT(local_name);
386
0
  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
0
  base_name = get_basename(local_name);
394
0
  remote_name = convert_local_name_component_to_remote(clipboard, base_name);
395
396
0
  if (!remote_name)
397
0
    return FALSE;
398
399
0
  result = add_file_to_list(clipboard, 0, local_name, remote_name, files);
400
0
  free(remote_name);
401
0
  return result;
402
0
}
403
404
static BOOL process_uri(wClipboard* clipboard, const char* uri, size_t uri_len)
405
0
{
406
  // URI is specified by RFC 8089: https://datatracker.ietf.org/doc/html/rfc8089
407
0
  BOOL result = FALSE;
408
0
  char* name = nullptr;
409
410
0
  WINPR_ASSERT(clipboard);
411
412
0
  name = parse_uri_to_local_file(uri, uri_len);
413
0
  if (name)
414
0
  {
415
0
    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
0
    wname = ConvertUtf8ToWCharAlloc(name, nullptr);
424
0
    if (wname)
425
0
      result = process_file_name(clipboard, wname, clipboard->localFiles);
426
427
0
    free(name);
428
0
    free(wname);
429
0
  }
430
431
0
  return result;
432
0
}
433
434
static BOOL process_uri_list(wClipboard* clipboard, const char* data, size_t length)
435
0
{
436
0
  const char* cur = data;
437
0
  const char* lim = data + length;
438
439
0
  WINPR_ASSERT(clipboard);
440
0
  WINPR_ASSERT(data);
441
442
0
  WLog_VRB(TAG, "processing URI list:\n%.*s", WINPR_ASSERTING_INT_CAST(int, length), data);
443
0
  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
0
  while (cur < lim)
454
0
  {
455
0
    BOOL comment = (*cur == '#');
456
0
    const char* start = cur;
457
0
    const char* stop = cur;
458
459
0
    for (; stop < lim; stop++)
460
0
    {
461
0
      if (*stop == '\r')
462
0
      {
463
0
        if ((stop + 1 < lim) && (*(stop + 1) == '\n'))
464
0
          cur = stop + 2;
465
0
        else
466
0
          cur = stop + 1;
467
468
0
        break;
469
0
      }
470
471
0
      if (*stop == '\n')
472
0
      {
473
0
        cur = stop + 1;
474
0
        break;
475
0
      }
476
0
    }
477
478
0
    if (stop == lim)
479
0
    {
480
0
      if (strnlen(start, WINPR_ASSERTING_INT_CAST(size_t, stop - start)) < 1)
481
0
        return TRUE;
482
0
      cur = lim;
483
0
    }
484
485
0
    if (comment)
486
0
      continue;
487
488
0
    if (!process_uri(clipboard, start, WINPR_ASSERTING_INT_CAST(size_t, stop - start)))
489
0
      return FALSE;
490
0
  }
491
492
0
  return TRUE;
493
0
}
494
495
static BOOL convert_local_file_to_filedescriptor(const struct synthetic_file* file,
496
                                                 FILEDESCRIPTORW* descriptor)
497
0
{
498
0
  size_t remote_len = 0;
499
500
0
  WINPR_ASSERT(file);
501
0
  WINPR_ASSERT(descriptor);
502
503
0
  descriptor->dwFlags = FD_ATTRIBUTES | FD_FILESIZE | FD_WRITESTIME | FD_PROGRESSUI;
504
505
0
  if (file->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
506
0
  {
507
0
    descriptor->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
508
0
    descriptor->nFileSizeLow = 0;
509
0
    descriptor->nFileSizeHigh = 0;
510
0
  }
511
0
  else
512
0
  {
513
0
    descriptor->dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
514
0
    descriptor->nFileSizeLow = file->nFileSizeLow;
515
0
    descriptor->nFileSizeHigh = file->nFileSizeHigh;
516
0
  }
517
518
0
  descriptor->ftLastWriteTime = file->ftLastWriteTime;
519
520
0
  remote_len = _wcsnlen(file->remote_name, ARRAYSIZE(descriptor->cFileName));
521
522
0
  if (remote_len >= ARRAYSIZE(descriptor->cFileName))
523
0
  {
524
0
    WLog_ERR(TAG, "file name too long (%" PRIuz " characters)", remote_len);
525
0
    return FALSE;
526
0
  }
527
528
0
  memcpy(descriptor->cFileName, file->remote_name, remote_len * sizeof(WCHAR));
529
0
  return TRUE;
530
0
}
531
532
static FILEDESCRIPTORW* convert_local_file_list_to_filedescriptors(wArrayList* files)
533
0
{
534
0
  size_t count = 0;
535
0
  FILEDESCRIPTORW* descriptors = nullptr;
536
537
0
  count = ArrayList_Count(files);
538
539
0
  descriptors = calloc(count, sizeof(FILEDESCRIPTORW));
540
541
0
  if (!descriptors)
542
0
    goto error;
543
544
0
  for (size_t i = 0; i < count; i++)
545
0
  {
546
0
    const struct synthetic_file* file = ArrayList_GetItem(files, i);
547
548
0
    if (!convert_local_file_to_filedescriptor(file, &descriptors[i]))
549
0
      goto error;
550
0
  }
551
552
0
  return descriptors;
553
0
error:
554
0
  free(descriptors);
555
0
  return nullptr;
556
0
}
557
558
static void* convert_any_uri_list_to_filedescriptors(wClipboard* clipboard,
559
                                                     WINPR_ATTR_UNUSED UINT32 formatId,
560
                                                     UINT32* pSize)
561
0
{
562
0
  FILEDESCRIPTORW* descriptors = nullptr;
563
564
0
  WINPR_ASSERT(clipboard);
565
0
  WINPR_ASSERT(pSize);
566
567
0
  descriptors = convert_local_file_list_to_filedescriptors(clipboard->localFiles);
568
0
  *pSize = 0;
569
0
  if (!descriptors)
570
0
    return nullptr;
571
572
0
  *pSize = (UINT32)ArrayList_Count(clipboard->localFiles) * sizeof(FILEDESCRIPTORW);
573
0
  clipboard->fileListSequenceNumber = clipboard->sequenceNumber;
574
0
  return descriptors;
575
0
}
576
577
static void* convert_uri_list_to_filedescriptors(wClipboard* clipboard, UINT32 formatId,
578
                                                 const void* data, UINT32* pSize)
579
0
{
580
0
  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
0
  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
0
  if (!process_uri_list(clipboard, (const char*)data, *pSize))
599
0
    return nullptr;
600
0
  return convert_any_uri_list_to_filedescriptors(clipboard, clipboard->formatId, pSize);
601
0
}
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
0
{
782
0
  UINT32 nrDescriptors = 0;
783
0
  size_t baseLength = 0;
784
0
  size_t header_len = strlen(header);
785
0
  size_t lineprefix_len = strlen(lineprefix);
786
0
  size_t lineending_len = strlen(lineending);
787
788
0
  if (!clipboard || !data || !pSize)
789
0
    return nullptr;
790
791
0
  if (*pSize < sizeof(UINT32))
792
0
    return nullptr;
793
794
0
  if (clipboard->delegate.basePath)
795
0
    baseLength = strnlen(clipboard->delegate.basePath, MAX_PATH);
796
797
0
  if (baseLength < 1)
798
0
    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
0
{
947
0
  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
0
  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
0
  return convert_filedescriptors_to_file_list(clipboard, data, pSize, "", "file://", "\r\n",
966
0
                                              FALSE);
967
0
}
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
0
{
974
0
  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
0
  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
0
  return convert_filedescriptors_to_file_list(clipboard, data, pSize, "copy\n", "file://", "\n",
993
0
                                              TRUE);
994
0
}
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
0
{
1000
0
  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
0
  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
0
  char* pDstData = convert_filedescriptors_to_file_list(clipboard, data, pSize, "copy\n",
1019
0
                                                        "file://", "\n", TRUE);
1020
0
  if (!pDstData)
1021
0
  {
1022
0
    return pDstData;
1023
0
  }
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
0
}
1033
1034
static void array_free_synthetic_file(void* the_file)
1035
0
{
1036
0
  struct synthetic_file* file = the_file;
1037
0
  free_synthetic_file(file);
1038
0
}
1039
1040
static BOOL register_file_formats_and_synthesizers(wClipboard* clipboard)
1041
0
{
1042
0
  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
0
  const UINT32 local_gnome_file_format_id =
1066
0
      ClipboardRegisterFormat(clipboard, mime_gnome_copied_files);
1067
0
  const UINT32 local_mate_file_format_id =
1068
0
      ClipboardRegisterFormat(clipboard, mime_mate_copied_files);
1069
0
  const UINT32 file_group_format_id =
1070
0
      ClipboardRegisterFormat(clipboard, mime_FileGroupDescriptorW);
1071
0
  const UINT32 local_file_format_id = ClipboardRegisterFormat(clipboard, mime_uri_list);
1072
1073
0
  if (!file_group_format_id || !local_file_format_id || !local_gnome_file_format_id ||
1074
0
      !local_mate_file_format_id)
1075
0
    goto error;
1076
1077
0
  clipboard->localFiles = ArrayList_New(FALSE);
1078
1079
0
  if (!clipboard->localFiles)
1080
0
    goto error;
1081
1082
0
  obj = ArrayList_Object(clipboard->localFiles);
1083
0
  obj->fnObjectFree = array_free_synthetic_file;
1084
1085
0
  if (!ClipboardRegisterSynthesizerEx(clipboard, local_file_format_id, file_group_format_id,
1086
0
                                      convert_uri_list_to_filedescriptors))
1087
0
    goto error_free_local_files;
1088
1089
0
  if (!ClipboardRegisterSynthesizerEx(clipboard, file_group_format_id, local_file_format_id,
1090
0
                                      convert_filedescriptors_to_uri_list))
1091
0
    goto error_free_local_files;
1092
1093
0
  if (!ClipboardRegisterSynthesizerEx(clipboard, local_gnome_file_format_id, file_group_format_id,
1094
0
                                      convert_gnome_copied_files_to_filedescriptors))
1095
0
    goto error_free_local_files;
1096
1097
0
  if (!ClipboardRegisterSynthesizerEx(clipboard, file_group_format_id, local_gnome_file_format_id,
1098
0
                                      convert_filedescriptors_to_gnome_copied_files))
1099
0
    goto error_free_local_files;
1100
1101
0
  if (!ClipboardRegisterSynthesizerEx(clipboard, local_mate_file_format_id, file_group_format_id,
1102
0
                                      convert_mate_copied_files_to_filedescriptors))
1103
0
    goto error_free_local_files;
1104
1105
0
  if (!ClipboardRegisterSynthesizerEx(clipboard, file_group_format_id, local_mate_file_format_id,
1106
0
                                      convert_filedescriptors_to_mate_copied_files))
1107
0
    goto error_free_local_files;
1108
1109
0
  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
0
{
1163
0
  if (!file || INVALID_HANDLE_VALUE == file->fd)
1164
0
    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
0
}
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
0
{
1354
0
  WINPR_ASSERT(delegate);
1355
1356
0
  delegate->ClientRequestFileSize = delegate_file_request_size;
1357
0
  delegate->ClipboardFileSizeSuccess = dummy_file_size_success;
1358
0
  delegate->ClipboardFileSizeFailure = dummy_file_size_failure;
1359
0
  delegate->ClientRequestFileRange = delegate_file_request_range;
1360
0
  delegate->ClipboardFileRangeSuccess = dummy_file_range_success;
1361
0
  delegate->ClipboardFileRangeFailure = dummy_file_range_failure;
1362
0
  delegate->IsFileNameComponentValid = ValidFileNameComponent;
1363
0
}
1364
1365
BOOL ClipboardInitSyntheticFileSubsystem(wClipboard* clipboard)
1366
0
{
1367
0
  if (!clipboard)
1368
0
    return FALSE;
1369
1370
0
  if (!register_file_formats_and_synthesizers(clipboard))
1371
0
    return FALSE;
1372
1373
0
  setup_delegate(&clipboard->delegate);
1374
0
  return TRUE;
1375
0
}