Coverage Report

Created: 2026-10-15 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/winpr/libwinpr/file/generic.c
Line
Count
Source
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * File Functions
4
 *
5
 * Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2014 Hewlett-Packard Development Company, L.P.
7
 * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>
8
 *
9
 * Licensed under the Apache License, Version 2.0 (the "License");
10
 * you may not use this file except in compliance with the License.
11
 * You may obtain a copy of the License at
12
 *
13
 *     http://www.apache.org/licenses/LICENSE-2.0
14
 *
15
 * Unless required by applicable law or agreed to in writing, software
16
 * distributed under the License is distributed on an "AS IS" BASIS,
17
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
 * See the License for the specific language governing permissions and
19
 * limitations under the License.
20
 */
21
22
#include <winpr/config.h>
23
24
#include <winpr/crt.h>
25
#include <winpr/wlog.h>
26
#include <winpr/string.h>
27
#include <winpr/path.h>
28
#include <winpr/file.h>
29
30
#ifdef WINPR_HAVE_UNISTD_H
31
#include <unistd.h>
32
#endif
33
34
#ifdef WINPR_HAVE_FCNTL_H
35
#include <fcntl.h>
36
#endif
37
38
#include "../log.h"
39
#define TAG WINPR_TAG("file")
40
41
#ifdef _WIN32
42
#include <io.h>
43
#include <sys/stat.h>
44
#else
45
#include <winpr/assert.h>
46
#include <pthread.h>
47
#include <dirent.h>
48
#include <libgen.h>
49
#include <errno.h>
50
51
#include <arpa/inet.h>
52
#include <sys/un.h>
53
#include <sys/stat.h>
54
#include <sys/socket.h>
55
#if defined(WINPR_HAVE_SYS_XATTR_H)
56
#include <sys/xattr.h>
57
#endif
58
#if defined(WINPR_HAVE_LINUX_MSDOS_FS_H)
59
#include <linux/msdos_fs.h>
60
#include <sys/ioctl.h>
61
#endif
62
#ifdef WINPR_HAVE_AIO_H
63
#undef WINPR_HAVE_AIO_H /* disable for now, incomplete */
64
#endif
65
66
#ifdef WINPR_HAVE_AIO_H
67
#include <aio.h>
68
#endif
69
70
#ifdef ANDROID
71
#include <sys/vfs.h>
72
#else
73
#include <sys/statvfs.h>
74
#endif
75
76
#include "../handle/handle.h"
77
78
#include "../pipe/pipe.h"
79
#include "../path/path.h"
80
81
#include "file.h"
82
83
/**
84
 * api-ms-win-core-file-l1-2-0.dll:
85
 *
86
 * CreateFileA
87
 * CreateFileW
88
 * CreateFile2
89
 * DeleteFileA
90
 * DeleteFileW
91
 * CreateDirectoryA
92
 * CreateDirectoryW
93
 * RemoveDirectoryA
94
 * RemoveDirectoryW
95
 * CompareFileTime
96
 * DefineDosDeviceW
97
 * DeleteVolumeMountPointW
98
 * FileTimeToLocalFileTime
99
 * LocalFileTimeToFileTime
100
 * FindClose
101
 * FindCloseChangeNotification
102
 * FindFirstChangeNotificationA
103
 * FindFirstChangeNotificationW
104
 * FindFirstFileA
105
 * FindFirstFileExA
106
 * FindFirstFileExW
107
 * FindFirstFileW
108
 * FindFirstVolumeW
109
 * FindNextChangeNotification
110
 * FindNextFileA
111
 * FindNextFileW
112
 * FindNextVolumeW
113
 * FindVolumeClose
114
 * GetDiskFreeSpaceA
115
 * GetDiskFreeSpaceExA
116
 * GetDiskFreeSpaceExW
117
 * GetDiskFreeSpaceW
118
 * GetDriveTypeA
119
 * GetDriveTypeW
120
 * GetFileAttributesA
121
 * GetFileAttributesExA
122
 * GetFileAttributesExW
123
 * GetFileAttributesW
124
 * GetFileInformationByHandle
125
 * GetFileSize
126
 * GetFileSizeEx
127
 * GetFileTime
128
 * GetFileType
129
 * GetFinalPathNameByHandleA
130
 * GetFinalPathNameByHandleW
131
 * GetFullPathNameA
132
 * GetFullPathNameW
133
 * GetLogicalDrives
134
 * GetLogicalDriveStringsW
135
 * GetLongPathNameA
136
 * GetLongPathNameW
137
 * GetShortPathNameW
138
 * GetTempFileNameW
139
 * GetTempPathW
140
 * GetVolumeInformationByHandleW
141
 * GetVolumeInformationW
142
 * GetVolumeNameForVolumeMountPointW
143
 * GetVolumePathNamesForVolumeNameW
144
 * GetVolumePathNameW
145
 * QueryDosDeviceW
146
 * SetFileAttributesA
147
 * SetFileAttributesW
148
 * SetFileTime
149
 * SetFileValidData
150
 * SetFileInformationByHandle
151
 * ReadFile
152
 * ReadFileEx
153
 * ReadFileScatter
154
 * WriteFile
155
 * WriteFileEx
156
 * WriteFileGather
157
 * FlushFileBuffers
158
 * SetEndOfFile
159
 * SetFilePointer
160
 * SetFilePointerEx
161
 * LockFile
162
 * LockFileEx
163
 * UnlockFile
164
 * UnlockFileEx
165
 */
166
167
/**
168
 * File System Behavior in the Microsoft Windows Environment:
169
 * http://download.microsoft.com/download/4/3/8/43889780-8d45-4b2e-9d3a-c696a890309f/File%20System%20Behavior%20Overview.pdf
170
 */
171
172
/**
173
 * Asynchronous I/O - The GNU C Library:
174
 * http://www.gnu.org/software/libc/manual/html_node/Asynchronous-I_002fO.html
175
 */
176
177
/**
178
 * aio.h - asynchronous input and output:
179
 * http://pubs.opengroup.org/onlinepubs/009695399/basedefs/aio.h.html
180
 */
181
182
/**
183
 * Asynchronous I/O User Guide:
184
 * http://code.google.com/p/kernel/wiki/AIOUserGuide
185
 */
186
static wArrayList* HandleCreators;
187
188
static pthread_once_t HandleCreatorsInitialized = PTHREAD_ONCE_INIT;
189
190
#include "../comm/comm.h"
191
#include "namedPipeClient.h"
192
193
WINPR_ATTR_NODISCARD
194
static DWORD FileAttributesFromStat(const char* path, const struct stat* fileStat);
195
196
WINPR_ATTR_NODISCARD
197
static BOOL FindDataFromStat(const char* path, const struct stat* fileStat,
198
                             LPWIN32_FIND_DATAA lpFindFileData);
199
static void SetDosAttributesToXAttr(const char* path, DWORD dwFileAttributes);
200
201
static void HandleCreatorsInit(void)
202
0
{
203
0
  WINPR_ASSERT(HandleCreators == nullptr);
204
0
  HandleCreators = ArrayList_New(TRUE);
205
206
0
  if (!HandleCreators)
207
0
    return;
208
209
  /*
210
   * Register all file handle creators.
211
   */
212
0
  ArrayList_Append(HandleCreators, GetNamedPipeClientHandleCreator());
213
0
  const HANDLE_CREATOR* serial = GetCommHandleCreator();
214
0
  if (serial)
215
0
    ArrayList_Append(HandleCreators, serial);
216
0
  ArrayList_Append(HandleCreators, GetFileHandleCreator());
217
0
}
218
219
#ifdef WINPR_HAVE_AIO_H
220
221
static BOOL g_AioSignalHandlerInstalled = FALSE;
222
223
void AioSignalHandler(int signum, siginfo_t* siginfo, void* arg)
224
{
225
  WLog_INFO("%d", signum);
226
}
227
228
int InstallAioSignalHandler()
229
{
230
  if (!g_AioSignalHandlerInstalled)
231
  {
232
    struct sigaction action;
233
    sigemptyset(&action.sa_mask);
234
    sigaddset(&action.sa_mask, SIGIO);
235
    action.sa_flags = SA_SIGINFO;
236
    action.sa_sigaction = (void*)&AioSignalHandler;
237
    sigaction(SIGIO, &action, nullptr);
238
    g_AioSignalHandlerInstalled = TRUE;
239
  }
240
241
  return 0;
242
}
243
244
#endif /* WINPR_HAVE_AIO_H */
245
246
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
247
HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
248
                   LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
249
                   DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
250
0
{
251
0
  return winpr_CreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
252
0
                          dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
253
0
}
254
#endif
255
256
HANDLE winpr_CreateFile(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
257
                        LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
258
                        DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
259
0
{
260
0
  if (!lpFileName)
261
0
    return INVALID_HANDLE_VALUE;
262
263
0
  if (pthread_once(&HandleCreatorsInitialized, HandleCreatorsInit) != 0)
264
0
  {
265
0
    SetLastError(ERROR_DLL_INIT_FAILED);
266
0
    return INVALID_HANDLE_VALUE;
267
0
  }
268
269
0
  if (HandleCreators == nullptr)
270
0
  {
271
0
    SetLastError(ERROR_DLL_INIT_FAILED);
272
0
    return INVALID_HANDLE_VALUE;
273
0
  }
274
275
0
  ArrayList_Lock(HandleCreators);
276
277
0
  for (size_t i = 0; i <= ArrayList_Count(HandleCreators); i++)
278
0
  {
279
0
    const HANDLE_CREATOR* creator = ArrayList_GetItem(HandleCreators, i);
280
281
0
    if (creator && creator->IsHandled(lpFileName))
282
0
    {
283
0
      HANDLE newHandle =
284
0
          creator->CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
285
0
                               dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
286
0
      ArrayList_Unlock(HandleCreators);
287
0
      return newHandle;
288
0
    }
289
0
  }
290
291
0
  ArrayList_Unlock(HandleCreators);
292
0
  return INVALID_HANDLE_VALUE;
293
0
}
294
295
HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
296
                   LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
297
                   DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
298
0
{
299
0
  HANDLE hdl = nullptr;
300
0
  if (!lpFileName)
301
0
    return nullptr;
302
0
  char* lpFileNameA = ConvertWCharToUtf8Alloc(lpFileName, nullptr);
303
304
0
  if (!lpFileNameA)
305
0
  {
306
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
307
0
    goto fail;
308
0
  }
309
310
0
  hdl = winpr_CreateFile(lpFileNameA, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
311
0
                         dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
312
0
fail:
313
0
  free(lpFileNameA);
314
0
  return hdl;
315
0
}
316
317
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
318
BOOL DeleteFileA(LPCSTR lpFileName)
319
0
{
320
0
  return winpr_DeleteFile(lpFileName);
321
0
}
322
#endif
323
324
BOOL DeleteFileW(LPCWSTR lpFileName)
325
0
{
326
0
  if (!lpFileName)
327
0
    return FALSE;
328
0
  LPSTR lpFileNameA = ConvertWCharToUtf8Alloc(lpFileName, nullptr);
329
0
  BOOL rc = winpr_DeleteFile(lpFileNameA);
330
0
  free(lpFileNameA);
331
0
  return rc;
332
0
}
333
334
BOOL ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead,
335
              LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
336
0
{
337
0
  ULONG Type = 0;
338
0
  WINPR_HANDLE* handle = nullptr;
339
340
0
  if (hFile == INVALID_HANDLE_VALUE)
341
0
    return FALSE;
342
343
  /*
344
   * from http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467%28v=vs.85%29.aspx
345
   * lpNumberOfBytesRead can be nullptr only when the lpOverlapped parameter is not nullptr.
346
   */
347
348
0
  if (!lpNumberOfBytesRead && !lpOverlapped)
349
0
    return FALSE;
350
351
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
352
0
    return FALSE;
353
354
0
  handle = (WINPR_HANDLE*)hFile;
355
356
0
  if (handle->ops->ReadFile)
357
0
    return handle->ops->ReadFile(handle, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead,
358
0
                                 lpOverlapped);
359
360
0
  WLog_ERR(TAG, "ReadFile operation not implemented");
361
0
  return FALSE;
362
0
}
363
364
BOOL ReadFileEx(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead,
365
                LPOVERLAPPED lpOverlapped, LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
366
0
{
367
0
  ULONG Type = 0;
368
0
  WINPR_HANDLE* handle = nullptr;
369
370
0
  if (hFile == INVALID_HANDLE_VALUE)
371
0
    return FALSE;
372
373
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
374
0
    return FALSE;
375
376
0
  handle = (WINPR_HANDLE*)hFile;
377
378
0
  if (handle->ops->ReadFileEx)
379
0
    return handle->ops->ReadFileEx(handle, lpBuffer, nNumberOfBytesToRead, lpOverlapped,
380
0
                                   lpCompletionRoutine);
381
382
0
  WLog_ERR(TAG, "ReadFileEx operation not implemented");
383
0
  return FALSE;
384
0
}
385
386
BOOL ReadFileScatter(HANDLE hFile, FILE_SEGMENT_ELEMENT aSegmentArray[], DWORD nNumberOfBytesToRead,
387
                     LPDWORD lpReserved, LPOVERLAPPED lpOverlapped)
388
0
{
389
0
  ULONG Type = 0;
390
0
  WINPR_HANDLE* handle = nullptr;
391
392
0
  if (hFile == INVALID_HANDLE_VALUE)
393
0
    return FALSE;
394
395
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
396
0
    return FALSE;
397
398
0
  handle = (WINPR_HANDLE*)hFile;
399
400
0
  if (handle->ops->ReadFileScatter)
401
0
    return handle->ops->ReadFileScatter(handle, aSegmentArray, nNumberOfBytesToRead, lpReserved,
402
0
                                        lpOverlapped);
403
404
0
  WLog_ERR(TAG, "ReadFileScatter operation not implemented");
405
0
  return FALSE;
406
0
}
407
408
BOOL WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
409
               LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped)
410
0
{
411
0
  ULONG Type = 0;
412
0
  WINPR_HANDLE* handle = nullptr;
413
414
0
  if (hFile == INVALID_HANDLE_VALUE)
415
0
    return FALSE;
416
417
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
418
0
    return FALSE;
419
420
0
  handle = (WINPR_HANDLE*)hFile;
421
422
0
  if (handle->ops->WriteFile)
423
0
    return handle->ops->WriteFile(handle, lpBuffer, nNumberOfBytesToWrite,
424
0
                                  lpNumberOfBytesWritten, lpOverlapped);
425
426
0
  WLog_ERR(TAG, "WriteFile operation not implemented");
427
0
  return FALSE;
428
0
}
429
430
BOOL WriteFileEx(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
431
                 LPOVERLAPPED lpOverlapped, LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
432
0
{
433
0
  ULONG Type = 0;
434
0
  WINPR_HANDLE* handle = nullptr;
435
436
0
  if (hFile == INVALID_HANDLE_VALUE)
437
0
    return FALSE;
438
439
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
440
0
    return FALSE;
441
442
0
  handle = (WINPR_HANDLE*)hFile;
443
444
0
  if (handle->ops->WriteFileEx)
445
0
    return handle->ops->WriteFileEx(handle, lpBuffer, nNumberOfBytesToWrite, lpOverlapped,
446
0
                                    lpCompletionRoutine);
447
448
0
  WLog_ERR(TAG, "WriteFileEx operation not implemented");
449
0
  return FALSE;
450
0
}
451
452
BOOL WriteFileGather(HANDLE hFile, FILE_SEGMENT_ELEMENT aSegmentArray[],
453
                     DWORD nNumberOfBytesToWrite, LPDWORD lpReserved, LPOVERLAPPED lpOverlapped)
454
0
{
455
0
  ULONG Type = 0;
456
0
  WINPR_HANDLE* handle = nullptr;
457
458
0
  if (hFile == INVALID_HANDLE_VALUE)
459
0
    return FALSE;
460
461
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
462
0
    return FALSE;
463
464
0
  handle = (WINPR_HANDLE*)hFile;
465
466
0
  if (handle->ops->WriteFileGather)
467
0
    return handle->ops->WriteFileGather(handle, aSegmentArray, nNumberOfBytesToWrite,
468
0
                                        lpReserved, lpOverlapped);
469
470
0
  WLog_ERR(TAG, "WriteFileGather operation not implemented");
471
0
  return FALSE;
472
0
}
473
474
BOOL FlushFileBuffers(HANDLE hFile)
475
0
{
476
0
  ULONG Type = 0;
477
0
  WINPR_HANDLE* handle = nullptr;
478
479
0
  if (hFile == INVALID_HANDLE_VALUE)
480
0
    return FALSE;
481
482
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
483
0
    return FALSE;
484
485
0
  handle = (WINPR_HANDLE*)hFile;
486
487
0
  if (handle->ops->FlushFileBuffers)
488
0
    return handle->ops->FlushFileBuffers(handle);
489
490
0
  WLog_ERR(TAG, "FlushFileBuffers operation not implemented");
491
0
  return FALSE;
492
0
}
493
494
BOOL WINAPI GetFileAttributesExA(LPCSTR lpFileName,
495
                                 WINPR_ATTR_UNUSED GET_FILEEX_INFO_LEVELS fInfoLevelId,
496
                                 LPVOID lpFileInformation)
497
0
{
498
0
  LPWIN32_FILE_ATTRIBUTE_DATA fd = lpFileInformation;
499
0
  if (!fd)
500
0
    return FALSE;
501
502
0
  struct stat fileStat = WINPR_C_ARRAY_INIT;
503
0
  if (stat(lpFileName, &fileStat) != 0)
504
0
    return FALSE;
505
506
0
  WIN32_FIND_DATAA findFileData = WINPR_C_ARRAY_INIT;
507
0
  if (!FindDataFromStat(lpFileName, &fileStat, &findFileData))
508
0
    return FALSE;
509
510
0
  fd->dwFileAttributes = findFileData.dwFileAttributes;
511
0
  fd->ftCreationTime = findFileData.ftCreationTime;
512
0
  fd->ftLastAccessTime = findFileData.ftLastAccessTime;
513
0
  fd->ftLastWriteTime = findFileData.ftLastWriteTime;
514
0
  fd->nFileSizeHigh = findFileData.nFileSizeHigh;
515
0
  fd->nFileSizeLow = findFileData.nFileSizeLow;
516
0
  return TRUE;
517
0
}
518
519
BOOL WINAPI GetFileAttributesExW(LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
520
                                 LPVOID lpFileInformation)
521
0
{
522
0
  BOOL ret = 0;
523
0
  if (!lpFileName)
524
0
    return FALSE;
525
0
  LPSTR lpCFileName = ConvertWCharToUtf8Alloc(lpFileName, nullptr);
526
527
0
  if (!lpCFileName)
528
0
  {
529
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
530
0
    return FALSE;
531
0
  }
532
533
0
  ret = GetFileAttributesExA(lpCFileName, fInfoLevelId, lpFileInformation);
534
0
  free(lpCFileName);
535
0
  return ret;
536
0
}
537
538
DWORD WINAPI GetFileAttributesA(LPCSTR lpFileName)
539
0
{
540
0
  struct stat fileStat = WINPR_C_ARRAY_INIT;
541
0
  if (stat(lpFileName, &fileStat) != 0)
542
0
    return INVALID_FILE_ATTRIBUTES;
543
544
0
  return FileAttributesFromStat(lpFileName, &fileStat);
545
0
}
546
547
DWORD WINAPI GetFileAttributesW(LPCWSTR lpFileName)
548
0
{
549
0
  DWORD ret = 0;
550
0
  if (!lpFileName)
551
0
    return FALSE;
552
0
  LPSTR lpCFileName = ConvertWCharToUtf8Alloc(lpFileName, nullptr);
553
0
  if (!lpCFileName)
554
0
  {
555
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
556
0
    return FALSE;
557
0
  }
558
559
0
  ret = GetFileAttributesA(lpCFileName);
560
0
  free(lpCFileName);
561
0
  return ret;
562
0
}
563
564
BOOL GetFileInformationByHandle(HANDLE hFile, LPBY_HANDLE_FILE_INFORMATION lpFileInformation)
565
0
{
566
0
  ULONG Type = 0;
567
0
  WINPR_HANDLE* handle = nullptr;
568
569
0
  if (hFile == INVALID_HANDLE_VALUE)
570
0
    return FALSE;
571
572
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
573
0
    return FALSE;
574
575
0
  handle = (WINPR_HANDLE*)hFile;
576
577
0
  if (handle->ops->GetFileInformationByHandle)
578
0
    return handle->ops->GetFileInformationByHandle(handle, lpFileInformation);
579
580
0
  WLog_ERR(TAG, "GetFileInformationByHandle operation not implemented");
581
0
  return 0;
582
0
}
583
584
static char* append(char* buffer, size_t size, const char* append)
585
0
{
586
0
  (void)winpr_str_append(append, buffer, size, "|");
587
0
  return buffer;
588
0
}
589
590
WINPR_ATTR_NODISCARD
591
static const char* flagsToStr(char* buffer, size_t size, DWORD flags)
592
0
{
593
0
  char strflags[32] = WINPR_C_ARRAY_INIT;
594
0
  if (flags & FILE_ATTRIBUTE_READONLY)
595
0
    append(buffer, size, "FILE_ATTRIBUTE_READONLY");
596
0
  if (flags & FILE_ATTRIBUTE_HIDDEN)
597
0
    append(buffer, size, "FILE_ATTRIBUTE_HIDDEN");
598
0
  if (flags & FILE_ATTRIBUTE_SYSTEM)
599
0
    append(buffer, size, "FILE_ATTRIBUTE_SYSTEM");
600
0
  if (flags & FILE_ATTRIBUTE_DIRECTORY)
601
0
    append(buffer, size, "FILE_ATTRIBUTE_DIRECTORY");
602
0
  if (flags & FILE_ATTRIBUTE_ARCHIVE)
603
0
    append(buffer, size, "FILE_ATTRIBUTE_ARCHIVE");
604
0
  if (flags & FILE_ATTRIBUTE_DEVICE)
605
0
    append(buffer, size, "FILE_ATTRIBUTE_DEVICE");
606
0
  if (flags & FILE_ATTRIBUTE_NORMAL)
607
0
    append(buffer, size, "FILE_ATTRIBUTE_NORMAL");
608
0
  if (flags & FILE_ATTRIBUTE_TEMPORARY)
609
0
    append(buffer, size, "FILE_ATTRIBUTE_TEMPORARY");
610
0
  if (flags & FILE_ATTRIBUTE_SPARSE_FILE)
611
0
    append(buffer, size, "FILE_ATTRIBUTE_SPARSE_FILE");
612
0
  if (flags & FILE_ATTRIBUTE_REPARSE_POINT)
613
0
    append(buffer, size, "FILE_ATTRIBUTE_REPARSE_POINT");
614
0
  if (flags & FILE_ATTRIBUTE_COMPRESSED)
615
0
    append(buffer, size, "FILE_ATTRIBUTE_COMPRESSED");
616
0
  if (flags & FILE_ATTRIBUTE_OFFLINE)
617
0
    append(buffer, size, "FILE_ATTRIBUTE_OFFLINE");
618
0
  if (flags & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
619
0
    append(buffer, size, "FILE_ATTRIBUTE_NOT_CONTENT_INDEXED");
620
0
  if (flags & FILE_ATTRIBUTE_ENCRYPTED)
621
0
    append(buffer, size, "FILE_ATTRIBUTE_ENCRYPTED");
622
0
  if (flags & FILE_ATTRIBUTE_VIRTUAL)
623
0
    append(buffer, size, "FILE_ATTRIBUTE_VIRTUAL");
624
625
0
  (void)_snprintf(strflags, sizeof(strflags), " [0x%08" PRIx32 "]", flags);
626
0
  winpr_str_append(strflags, buffer, size, nullptr);
627
0
  return buffer;
628
0
}
629
630
BOOL SetFileAttributesA(LPCSTR lpFileName, DWORD dwFileAttributes)
631
0
{
632
0
  BOOL rc = FALSE;
633
0
#ifdef WINPR_HAVE_FCNTL_H
634
0
  const uint32_t mask = ~(FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_NORMAL |
635
0
                          FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);
636
0
  if (dwFileAttributes & mask)
637
0
  {
638
0
    char buffer[8192] = WINPR_C_ARRAY_INIT;
639
0
    const char* flags = flagsToStr(buffer, sizeof(buffer), dwFileAttributes & mask);
640
0
    WLog_WARN(TAG, "Unsupported flags %s, ignoring!", flags);
641
0
  }
642
643
0
  SetDosAttributesToXAttr(lpFileName, dwFileAttributes);
644
645
0
  int fd = open(lpFileName, O_RDONLY);
646
0
  if (fd < 0)
647
0
    return FALSE;
648
649
0
  struct stat st = WINPR_C_ARRAY_INIT;
650
0
  if (fstat(fd, &st) != 0)
651
0
    goto fail;
652
653
0
  if (dwFileAttributes & FILE_ATTRIBUTE_READONLY)
654
0
  {
655
0
    st.st_mode &= WINPR_ASSERTING_INT_CAST(mode_t, (mode_t)(~(S_IWUSR | S_IWGRP | S_IWOTH)));
656
0
  }
657
0
  else
658
0
  {
659
0
    st.st_mode |= S_IWUSR;
660
0
  }
661
662
0
  if (fchmod(fd, st.st_mode) != 0)
663
0
    goto fail;
664
665
0
  rc = TRUE;
666
0
fail:
667
0
  close(fd);
668
0
#endif
669
0
  return rc;
670
0
}
671
672
BOOL SetFileAttributesW(LPCWSTR lpFileName, DWORD dwFileAttributes)
673
0
{
674
0
  BOOL ret = 0;
675
676
0
  if (!lpFileName)
677
0
    return FALSE;
678
679
0
  char* lpCFileName = ConvertWCharToUtf8Alloc(lpFileName, nullptr);
680
0
  if (!lpCFileName)
681
0
  {
682
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
683
0
    return FALSE;
684
0
  }
685
686
0
  ret = SetFileAttributesA(lpCFileName, dwFileAttributes);
687
0
  free(lpCFileName);
688
0
  return ret;
689
0
}
690
691
BOOL SetEndOfFile(HANDLE hFile)
692
0
{
693
0
  ULONG Type = 0;
694
0
  WINPR_HANDLE* handle = nullptr;
695
696
0
  if (hFile == INVALID_HANDLE_VALUE)
697
0
    return FALSE;
698
699
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
700
0
    return FALSE;
701
702
0
  handle = (WINPR_HANDLE*)hFile;
703
704
0
  if (handle->ops->SetEndOfFile)
705
0
    return handle->ops->SetEndOfFile(handle);
706
707
0
  WLog_ERR(TAG, "SetEndOfFile operation not implemented");
708
0
  return FALSE;
709
0
}
710
711
DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh)
712
0
{
713
0
  ULONG Type = 0;
714
0
  WINPR_HANDLE* handle = nullptr;
715
716
0
  if (hFile == INVALID_HANDLE_VALUE)
717
0
    return FALSE;
718
719
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
720
0
    return FALSE;
721
722
0
  handle = (WINPR_HANDLE*)hFile;
723
724
0
  if (handle->ops->GetFileSize)
725
0
    return handle->ops->GetFileSize(handle, lpFileSizeHigh);
726
727
0
  WLog_ERR(TAG, "GetFileSize operation not implemented");
728
0
  return 0;
729
0
}
730
731
DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh,
732
                     DWORD dwMoveMethod)
733
0
{
734
0
  ULONG Type = 0;
735
0
  WINPR_HANDLE* handle = nullptr;
736
737
0
  if (hFile == INVALID_HANDLE_VALUE)
738
0
    return FALSE;
739
740
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
741
0
    return FALSE;
742
743
0
  handle = (WINPR_HANDLE*)hFile;
744
745
0
  if (handle->ops->SetFilePointer)
746
0
    return handle->ops->SetFilePointer(handle, lDistanceToMove, lpDistanceToMoveHigh,
747
0
                                       dwMoveMethod);
748
749
0
  WLog_ERR(TAG, "SetFilePointer operation not implemented");
750
0
  return 0;
751
0
}
752
753
BOOL SetFilePointerEx(HANDLE hFile, LARGE_INTEGER liDistanceToMove, PLARGE_INTEGER lpNewFilePointer,
754
                      DWORD dwMoveMethod)
755
0
{
756
0
  ULONG Type = 0;
757
0
  WINPR_HANDLE* handle = nullptr;
758
759
0
  if (hFile == INVALID_HANDLE_VALUE)
760
0
    return FALSE;
761
762
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
763
0
    return FALSE;
764
765
0
  handle = (WINPR_HANDLE*)hFile;
766
767
0
  if (handle->ops->SetFilePointerEx)
768
0
    return handle->ops->SetFilePointerEx(handle, liDistanceToMove, lpNewFilePointer,
769
0
                                         dwMoveMethod);
770
771
0
  WLog_ERR(TAG, "SetFilePointerEx operation not implemented");
772
0
  return 0;
773
0
}
774
775
BOOL LockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
776
              DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh)
777
0
{
778
0
  ULONG Type = 0;
779
0
  WINPR_HANDLE* handle = nullptr;
780
781
0
  if (hFile == INVALID_HANDLE_VALUE)
782
0
    return FALSE;
783
784
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
785
0
    return FALSE;
786
787
0
  handle = (WINPR_HANDLE*)hFile;
788
789
0
  if (handle->ops->LockFile)
790
0
    return handle->ops->LockFile(handle, dwFileOffsetLow, dwFileOffsetHigh,
791
0
                                 nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh);
792
793
0
  WLog_ERR(TAG, "LockFile operation not implemented");
794
0
  return FALSE;
795
0
}
796
797
BOOL LockFileEx(HANDLE hFile, DWORD dwFlags, DWORD dwReserved, DWORD nNumberOfBytesToLockLow,
798
                DWORD nNumberOfBytesToLockHigh, LPOVERLAPPED lpOverlapped)
799
0
{
800
0
  ULONG Type = 0;
801
0
  WINPR_HANDLE* handle = nullptr;
802
803
0
  if (hFile == INVALID_HANDLE_VALUE)
804
0
    return FALSE;
805
806
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
807
0
    return FALSE;
808
809
0
  handle = (WINPR_HANDLE*)hFile;
810
811
0
  if (handle->ops->LockFileEx)
812
0
    return handle->ops->LockFileEx(handle, dwFlags, dwReserved, nNumberOfBytesToLockLow,
813
0
                                   nNumberOfBytesToLockHigh, lpOverlapped);
814
815
0
  WLog_ERR(TAG, "LockFileEx operation not implemented");
816
0
  return FALSE;
817
0
}
818
819
BOOL UnlockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
820
                DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh)
821
0
{
822
0
  ULONG Type = 0;
823
0
  WINPR_HANDLE* handle = nullptr;
824
825
0
  if (hFile == INVALID_HANDLE_VALUE)
826
0
    return FALSE;
827
828
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
829
0
    return FALSE;
830
831
0
  handle = (WINPR_HANDLE*)hFile;
832
833
0
  if (handle->ops->UnlockFile)
834
0
    return handle->ops->UnlockFile(handle, dwFileOffsetLow, dwFileOffsetHigh,
835
0
                                   nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
836
837
0
  WLog_ERR(TAG, "UnLockFile operation not implemented");
838
0
  return FALSE;
839
0
}
840
841
BOOL UnlockFileEx(HANDLE hFile, DWORD dwReserved, DWORD nNumberOfBytesToUnlockLow,
842
                  DWORD nNumberOfBytesToUnlockHigh, LPOVERLAPPED lpOverlapped)
843
0
{
844
0
  ULONG Type = 0;
845
0
  WINPR_HANDLE* handle = nullptr;
846
847
0
  if (hFile == INVALID_HANDLE_VALUE)
848
0
    return FALSE;
849
850
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
851
0
    return FALSE;
852
853
0
  handle = (WINPR_HANDLE*)hFile;
854
855
0
  if (handle->ops->UnlockFileEx)
856
0
    return handle->ops->UnlockFileEx(handle, dwReserved, nNumberOfBytesToUnlockLow,
857
0
                                     nNumberOfBytesToUnlockHigh, lpOverlapped);
858
859
0
  WLog_ERR(TAG, "UnLockFileEx operation not implemented");
860
0
  return FALSE;
861
0
}
862
863
BOOL WINAPI SetFileTime(HANDLE hFile, const FILETIME* lpCreationTime,
864
                        const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime)
865
0
{
866
0
  ULONG Type = 0;
867
0
  WINPR_HANDLE* handle = nullptr;
868
869
0
  if (hFile == INVALID_HANDLE_VALUE)
870
0
    return FALSE;
871
872
0
  if (!winpr_Handle_GetInfo(hFile, &Type, &handle))
873
0
    return FALSE;
874
875
0
  handle = (WINPR_HANDLE*)hFile;
876
877
0
  if (handle->ops->SetFileTime)
878
0
    return handle->ops->SetFileTime(handle, lpCreationTime, lpLastAccessTime, lpLastWriteTime);
879
880
0
  WLog_ERR(TAG, "operation not implemented");
881
0
  return FALSE;
882
0
}
883
884
typedef struct
885
{
886
  char magic[16];
887
  LPSTR lpPath;
888
  LPSTR lpPattern;
889
  DIR* pDir;
890
} WIN32_FILE_SEARCH;
891
892
static const char file_search_magic[] = "file_srch_magic";
893
894
WINPR_ATTR_MALLOC(FindClose, 1)
895
static WIN32_FILE_SEARCH* file_search_new(const char* name, size_t namelen, const char* pattern,
896
                                          size_t patternlen)
897
0
{
898
0
  WIN32_FILE_SEARCH* pFileSearch = (WIN32_FILE_SEARCH*)calloc(1, sizeof(WIN32_FILE_SEARCH));
899
0
  if (!pFileSearch)
900
0
    return nullptr;
901
0
  WINPR_ASSERT(sizeof(file_search_magic) == sizeof(pFileSearch->magic));
902
0
  memcpy(pFileSearch->magic, file_search_magic, sizeof(pFileSearch->magic));
903
904
0
  pFileSearch->lpPath = strndup(name, namelen);
905
0
  pFileSearch->lpPattern = strndup(pattern, patternlen);
906
0
  if (!pFileSearch->lpPath || !pFileSearch->lpPattern)
907
0
    goto fail;
908
909
0
  pFileSearch->pDir = opendir(pFileSearch->lpPath);
910
0
  if (!pFileSearch->pDir)
911
0
  {
912
    /* Work around for android:
913
     * parent directories are not accessible, so if we have a directory without pattern
914
     * try to open it directly and set pattern to '*'
915
     */
916
0
    struct stat fileStat = WINPR_C_ARRAY_INIT;
917
0
    if (stat(name, &fileStat) == 0)
918
0
    {
919
0
      if (S_ISDIR(fileStat.st_mode))
920
0
      {
921
0
        pFileSearch->pDir = opendir(name);
922
0
        if (pFileSearch->pDir)
923
0
        {
924
0
          free(pFileSearch->lpPath);
925
0
          free(pFileSearch->lpPattern);
926
0
          pFileSearch->lpPath = _strdup(name);
927
0
          pFileSearch->lpPattern = _strdup("*");
928
0
          if (!pFileSearch->lpPath || !pFileSearch->lpPattern)
929
0
          {
930
0
            closedir(pFileSearch->pDir);
931
0
            pFileSearch->pDir = nullptr;
932
0
          }
933
0
        }
934
0
      }
935
0
    }
936
0
    else
937
0
    {
938
0
      char buffer[128] = WINPR_C_ARRAY_INIT;
939
0
      const DWORD err = map_posix_err(errno);
940
0
      WLog_DBG(TAG, "stat failed with %s [%d] -> %s",
941
0
               winpr_strerror(errno, buffer, sizeof(buffer)), errno,
942
0
               Win32ErrorCode2Tag(err & 0xFFFF));
943
0
      SetLastError(err);
944
0
    }
945
0
  }
946
0
  if (!pFileSearch->pDir)
947
0
    goto fail;
948
949
0
  return pFileSearch;
950
0
fail:
951
0
  WINPR_PRAGMA_DIAG_PUSH
952
0
  WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
953
0
  FindClose(pFileSearch);
954
0
  WINPR_PRAGMA_DIAG_POP
955
0
  return nullptr;
956
0
}
957
958
WINPR_ATTR_NODISCARD
959
static BOOL is_valid_file_search_handle(HANDLE handle)
960
0
{
961
0
  WIN32_FILE_SEARCH* pFileSearch = (WIN32_FILE_SEARCH*)handle;
962
0
  if (!pFileSearch)
963
0
    return FALSE;
964
0
  if (pFileSearch == INVALID_HANDLE_VALUE)
965
0
    return FALSE;
966
0
  if (strncmp(file_search_magic, pFileSearch->magic, sizeof(file_search_magic)) != 0)
967
0
    return FALSE;
968
0
  return TRUE;
969
0
}
970
971
WINPR_ATTR_NODISCARD
972
static DWORD GetDosAttributesFromXAttr(WINPR_ATTR_UNUSED const char* path)
973
0
{
974
0
#if defined(WINPR_HAVE_SYS_XATTR_H) || defined(WINPR_HAVE_LINUX_MSDOS_FS_H)
975
0
  DWORD dwFileAttributes = 0;
976
0
  uint32_t intAttr = 0;
977
0
  ssize_t length = -1;
978
0
  const DWORD supportedMask = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN |
979
0
                              FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_DIRECTORY |
980
0
                              FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_NORMAL;
981
982
0
#if defined(WINPR_HAVE_SYS_XATTR_H)
983
0
  length = getxattr(path, "system.ntfs_attrib_be", &intAttr, sizeof(intAttr));
984
0
  if (length >= 0)
985
0
  {
986
0
    intAttr = ntohl(intAttr);
987
0
    dwFileAttributes = intAttr;
988
0
  }
989
0
#endif
990
991
0
#if defined(WINPR_HAVE_SYS_XATTR_H)
992
0
  if ((dwFileAttributes & supportedMask) == 0)
993
0
  {
994
0
    length = getxattr(path, "user.cifs.dosattrib", &intAttr, sizeof(intAttr));
995
0
    if (length >= 0)
996
0
      dwFileAttributes = intAttr;
997
0
  }
998
0
#endif
999
1000
0
  if ((dwFileAttributes & supportedMask) == 0)
1001
0
  {
1002
0
#if defined(WINPR_HAVE_LINUX_MSDOS_FS_H)
1003
0
    int fd = open(path, O_RDONLY | O_CLOEXEC);
1004
0
    if (fd != -1)
1005
0
    {
1006
0
      const int rc = ioctl(fd, FAT_IOCTL_GET_ATTRIBUTES, &intAttr);
1007
0
      if (rc < 0)
1008
0
      {
1009
0
        char buffer[64] = WINPR_C_ARRAY_INIT;
1010
0
        WLog_DBG(TAG, "ioctl(%d, FAT_IOCTL_GET_ATTRIBUTES) failed with %s", fd,
1011
0
                 winpr_strerror(errno, buffer, sizeof(buffer)));
1012
0
      }
1013
0
      else
1014
0
        dwFileAttributes = intAttr;
1015
1016
0
      const int crc = close(fd);
1017
0
      if (crc < 0)
1018
0
      {
1019
0
        char buffer[64] = WINPR_C_ARRAY_INIT;
1020
0
        WLog_DBG(TAG, "close(%d) failed with %s", fd,
1021
0
                 winpr_strerror(errno, buffer, sizeof(buffer)));
1022
0
      }
1023
0
    }
1024
0
#endif
1025
0
  }
1026
1027
0
#if defined(WINPR_HAVE_SYS_XATTR_H)
1028
0
  if ((dwFileAttributes & supportedMask) == 0)
1029
0
  {
1030
    // if no xattr is set, default to archive attribute
1031
0
    dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1032
1033
0
    char attrValue[11] = WINPR_C_ARRAY_INIT;
1034
0
    length = getxattr(path, "user.DOSATTRIB", attrValue, sizeof(attrValue) - 1);
1035
0
    if (length >= 0)
1036
0
    {
1037
0
      errno = 0;
1038
0
      const unsigned long val = strtoul(attrValue, nullptr, 0);
1039
0
      if (errno == 0)
1040
0
        dwFileAttributes = WINPR_ASSERTING_INT_CAST(DWORD, val);
1041
0
    }
1042
0
  }
1043
#else
1044
  if ((dwFileAttributes & supportedMask) == 0)
1045
  {
1046
    /* fallback default when no xattr available */
1047
    dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1048
  }
1049
#endif
1050
1051
0
  return dwFileAttributes;
1052
#else
1053
  return 0;
1054
#endif
1055
0
}
1056
1057
static void SetDosAttributesToXAttr(const char* path, DWORD dwFileAttributes)
1058
0
{
1059
0
#if defined(WINPR_HAVE_SYS_XATTR_H) || defined(WINPR_HAVE_LINUX_MSDOS_FS_H)
1060
0
  uint32_t intAttr =
1061
0
      dwFileAttributes & (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN |
1062
0
                          FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_NORMAL);
1063
0
  uint32_t intAttrBE = htonl(intAttr);
1064
1065
0
#if defined(WINPR_HAVE_SYS_XATTR_H)
1066
0
  if (setxattr(path, "system.ntfs_attrib_be", &intAttrBE, sizeof(intAttrBE), 0) >= 0)
1067
0
  {
1068
0
    WLog_DBG(TAG, "Set NTFS attribute xattr for %s", path);
1069
0
    return;
1070
0
  }
1071
1072
  /* set cifs.dosattrib xattr if it exists, otherwise set user.DOSATTRIB xattr */
1073
0
  ssize_t length = getxattr(path, "user.cifs.dosattrib", nullptr, 0);
1074
0
  if (length >= 0)
1075
0
  {
1076
0
    if (setxattr(path, "user.cifs.dosattrib", &intAttrBE, sizeof(intAttrBE), 0) >= 0)
1077
0
    {
1078
0
      WLog_DBG(TAG, "Set CIFS DOS attribute xattr for %s", path);
1079
0
      return;
1080
0
    }
1081
0
  }
1082
0
#endif
1083
1084
  /* set FAT attributes if other methods fail */
1085
0
#if defined(WINPR_HAVE_LINUX_MSDOS_FS_H)
1086
0
  int fd = open(path, O_RDONLY | O_CLOEXEC);
1087
0
  if (fd != -1)
1088
0
  {
1089
0
    if (ioctl(fd, FAT_IOCTL_SET_ATTRIBUTES, &intAttr) != -1)
1090
0
    {
1091
0
      close(fd);
1092
0
      WLog_DBG(TAG, "Set FAT attribute for %s", path);
1093
0
      return;
1094
0
    }
1095
0
    close(fd);
1096
0
  }
1097
0
#endif
1098
1099
0
#if defined(WINPR_HAVE_SYS_XATTR_H)
1100
  /* set user.DOSATTRIB xattr */
1101
1102
  /* if only ARCHIVE remove attribute */
1103
0
  if (intAttr == FILE_ATTRIBUTE_ARCHIVE)
1104
0
  {
1105
0
    const int rc = removexattr(path, "user.DOSATTRIB");
1106
0
    if (rc != 0)
1107
0
    {
1108
0
      char buffer[128] = WINPR_C_ARRAY_INIT;
1109
0
      WLog_DBG(TAG, "removexattr(%s) failed with %s", path,
1110
0
               winpr_strerror(errno, buffer, sizeof(buffer)));
1111
0
    }
1112
0
    return;
1113
0
  }
1114
1115
0
  char attrValue[11] = WINPR_C_ARRAY_INIT;
1116
0
  const int written = snprintf(attrValue, sizeof(attrValue), "0x%x", intAttr);
1117
0
  if (written < 0)
1118
0
    return;
1119
1120
0
  if (setxattr(path, "user.DOSATTRIB", attrValue, strlen(attrValue), 0) < 0)
1121
0
    WLog_DBG(TAG, "Failed to set DOS attribute xattr for %s", path);
1122
1123
0
  WLog_DBG(TAG, "Set DOS attribute xattr for %s", path);
1124
0
#endif
1125
0
#endif
1126
0
}
1127
1128
WINPR_ATTR_NODISCARD
1129
static DWORD FileAttributesFromStat(const char* path, const struct stat* fileStat)
1130
0
{
1131
0
  DWORD dwFileAttributes = GetDosAttributesFromXAttr(path);
1132
1133
0
  if (S_ISDIR(fileStat->st_mode))
1134
0
    dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
1135
1136
0
  if (dwFileAttributes == 0)
1137
0
    dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1138
1139
0
  const char* lastSep = strrchr(path, '/');
1140
0
  if (lastSep)
1141
0
  {
1142
0
    const char* name = lastSep + 1;
1143
0
    const size_t namelen = strlen(name);
1144
1145
0
    if ((namelen > 1) && (name[0] == '.') && (name[1] != '.'))
1146
0
      dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1147
0
  }
1148
1149
0
  if (!(fileStat->st_mode & S_IWUSR))
1150
0
    dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
1151
1152
0
  return dwFileAttributes;
1153
0
}
1154
1155
WINPR_ATTR_NODISCARD
1156
static BOOL FindDataFromStat(const char* path, const struct stat* fileStat,
1157
                             LPWIN32_FIND_DATAA lpFindFileData)
1158
0
{
1159
0
  UINT64 ft = 0;
1160
0
  lpFindFileData->dwFileAttributes = FileAttributesFromStat(path, fileStat);
1161
1162
#ifdef _DARWIN_FEATURE_64_BIT_INODE
1163
  ft = STAT_TIME_TO_FILETIME(fileStat->st_birthtime);
1164
#else
1165
0
  ft = STAT_TIME_TO_FILETIME(fileStat->st_ctime);
1166
0
#endif
1167
0
  lpFindFileData->ftCreationTime.dwHighDateTime = (ft) >> 32ULL;
1168
0
  lpFindFileData->ftCreationTime.dwLowDateTime = ft & 0xFFFFFFFF;
1169
0
  ft = STAT_TIME_TO_FILETIME(fileStat->st_mtime);
1170
0
  lpFindFileData->ftLastWriteTime.dwHighDateTime = (ft) >> 32ULL;
1171
0
  lpFindFileData->ftLastWriteTime.dwLowDateTime = ft & 0xFFFFFFFF;
1172
0
  ft = STAT_TIME_TO_FILETIME(fileStat->st_atime);
1173
0
  lpFindFileData->ftLastAccessTime.dwHighDateTime = (ft) >> 32ULL;
1174
0
  lpFindFileData->ftLastAccessTime.dwLowDateTime = ft & 0xFFFFFFFF;
1175
0
  lpFindFileData->nFileSizeHigh = ((UINT64)fileStat->st_size) >> 32ULL;
1176
0
  lpFindFileData->nFileSizeLow = fileStat->st_size & 0xFFFFFFFF;
1177
0
  return TRUE;
1178
0
}
1179
1180
HANDLE FindFirstFileA(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData)
1181
0
{
1182
0
  if (!lpFindFileData || !lpFileName)
1183
0
  {
1184
0
    SetLastError(ERROR_BAD_ARGUMENTS);
1185
0
    return INVALID_HANDLE_VALUE;
1186
0
  }
1187
1188
0
  const WIN32_FIND_DATAA empty = WINPR_C_ARRAY_INIT;
1189
0
  *lpFindFileData = empty;
1190
1191
0
  WIN32_FILE_SEARCH* pFileSearch = nullptr;
1192
0
  size_t patternlen = 0;
1193
0
  const size_t flen = strlen(lpFileName);
1194
0
  const char sep = PathGetSeparatorA(PATH_STYLE_NATIVE);
1195
0
  const char* ptr = strrchr(lpFileName, sep);
1196
0
  if (!ptr)
1197
0
    goto fail;
1198
0
  patternlen = strlen(ptr + 1);
1199
0
  if (patternlen == 0)
1200
0
    goto fail;
1201
1202
0
  pFileSearch = file_search_new(lpFileName, flen - patternlen, ptr + 1, patternlen);
1203
1204
0
  if (!pFileSearch)
1205
0
    return INVALID_HANDLE_VALUE;
1206
1207
0
  if (FindNextFileA((HANDLE)pFileSearch, lpFindFileData))
1208
0
    return (HANDLE)pFileSearch;
1209
1210
0
fail:
1211
0
  FindClose(pFileSearch);
1212
0
  return INVALID_HANDLE_VALUE;
1213
0
}
1214
1215
WINPR_ATTR_NODISCARD
1216
static BOOL ConvertFindDataAToW(LPWIN32_FIND_DATAA lpFindFileDataA,
1217
                                LPWIN32_FIND_DATAW lpFindFileDataW)
1218
0
{
1219
0
  if (!lpFindFileDataA || !lpFindFileDataW)
1220
0
    return FALSE;
1221
1222
0
  lpFindFileDataW->dwFileAttributes = lpFindFileDataA->dwFileAttributes;
1223
0
  lpFindFileDataW->ftCreationTime = lpFindFileDataA->ftCreationTime;
1224
0
  lpFindFileDataW->ftLastAccessTime = lpFindFileDataA->ftLastAccessTime;
1225
0
  lpFindFileDataW->ftLastWriteTime = lpFindFileDataA->ftLastWriteTime;
1226
0
  lpFindFileDataW->nFileSizeHigh = lpFindFileDataA->nFileSizeHigh;
1227
0
  lpFindFileDataW->nFileSizeLow = lpFindFileDataA->nFileSizeLow;
1228
0
  lpFindFileDataW->dwReserved0 = lpFindFileDataA->dwReserved0;
1229
0
  lpFindFileDataW->dwReserved1 = lpFindFileDataA->dwReserved1;
1230
1231
0
  if (ConvertUtf8NToWChar(lpFindFileDataA->cFileName, ARRAYSIZE(lpFindFileDataA->cFileName),
1232
0
                          lpFindFileDataW->cFileName, ARRAYSIZE(lpFindFileDataW->cFileName)) < 0)
1233
0
    return FALSE;
1234
1235
0
  return ConvertUtf8NToWChar(lpFindFileDataA->cAlternateFileName,
1236
0
                             ARRAYSIZE(lpFindFileDataA->cAlternateFileName),
1237
0
                             lpFindFileDataW->cAlternateFileName,
1238
0
                             ARRAYSIZE(lpFindFileDataW->cAlternateFileName)) >= 0;
1239
0
}
1240
1241
HANDLE FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData)
1242
0
{
1243
0
  LPSTR utfFileName = nullptr;
1244
0
  HANDLE h = nullptr;
1245
0
  if (!lpFileName)
1246
0
    return INVALID_HANDLE_VALUE;
1247
1248
0
  LPWIN32_FIND_DATAA fd = (LPWIN32_FIND_DATAA)calloc(1, sizeof(WIN32_FIND_DATAA));
1249
1250
0
  if (!fd)
1251
0
  {
1252
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1253
0
    return INVALID_HANDLE_VALUE;
1254
0
  }
1255
1256
0
  utfFileName = ConvertWCharToUtf8Alloc(lpFileName, nullptr);
1257
0
  if (!utfFileName)
1258
0
  {
1259
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1260
0
    free(fd);
1261
0
    return INVALID_HANDLE_VALUE;
1262
0
  }
1263
1264
0
  h = FindFirstFileA(utfFileName, fd);
1265
0
  free(utfFileName);
1266
1267
0
  if (h != INVALID_HANDLE_VALUE)
1268
0
  {
1269
0
    if (!ConvertFindDataAToW(fd, lpFindFileData))
1270
0
    {
1271
0
      SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1272
0
      FindClose(h);
1273
0
      h = INVALID_HANDLE_VALUE;
1274
0
      goto out;
1275
0
    }
1276
0
  }
1277
1278
0
out:
1279
0
  free(fd);
1280
0
  return h;
1281
0
}
1282
1283
HANDLE FindFirstFileExA(WINPR_ATTR_UNUSED LPCSTR lpFileName,
1284
                        WINPR_ATTR_UNUSED FINDEX_INFO_LEVELS fInfoLevelId,
1285
                        WINPR_ATTR_UNUSED LPVOID lpFindFileData,
1286
                        WINPR_ATTR_UNUSED FINDEX_SEARCH_OPS fSearchOp,
1287
                        WINPR_ATTR_UNUSED LPVOID lpSearchFilter,
1288
                        WINPR_ATTR_UNUSED DWORD dwAdditionalFlags)
1289
0
{
1290
0
  WLog_ERR("TODO", "TODO: Implement");
1291
0
  return INVALID_HANDLE_VALUE;
1292
0
}
1293
1294
HANDLE FindFirstFileExW(WINPR_ATTR_UNUSED LPCWSTR lpFileName,
1295
                        WINPR_ATTR_UNUSED FINDEX_INFO_LEVELS fInfoLevelId,
1296
                        WINPR_ATTR_UNUSED LPVOID lpFindFileData,
1297
                        WINPR_ATTR_UNUSED FINDEX_SEARCH_OPS fSearchOp,
1298
                        WINPR_ATTR_UNUSED LPVOID lpSearchFilter,
1299
                        WINPR_ATTR_UNUSED DWORD dwAdditionalFlags)
1300
0
{
1301
0
  WLog_ERR("TODO", "TODO: Implement");
1302
0
  return INVALID_HANDLE_VALUE;
1303
0
}
1304
1305
BOOL FindNextFileA(HANDLE hFindFile, LPWIN32_FIND_DATAA lpFindFileData)
1306
0
{
1307
0
  if (!lpFindFileData)
1308
0
    return FALSE;
1309
1310
0
  const WIN32_FIND_DATAA empty = WINPR_C_ARRAY_INIT;
1311
0
  *lpFindFileData = empty;
1312
1313
0
  if (!is_valid_file_search_handle(hFindFile))
1314
0
    return FALSE;
1315
1316
0
  WIN32_FILE_SEARCH* pFileSearch = (WIN32_FILE_SEARCH*)hFindFile;
1317
0
  struct dirent* pDirent = nullptr;
1318
  // NOLINTNEXTLINE(concurrency-mt-unsafe)
1319
0
  while ((pDirent = readdir(pFileSearch->pDir)) != nullptr)
1320
0
  {
1321
0
    if (FilePatternMatchA(pDirent->d_name, pFileSearch->lpPattern))
1322
0
    {
1323
0
      BOOL success = FALSE;
1324
1325
0
      strncpy(lpFindFileData->cFileName, pDirent->d_name, MAX_PATH);
1326
0
      const size_t namelen = strnlen(lpFindFileData->cFileName, MAX_PATH);
1327
0
      size_t pathlen = strlen(pFileSearch->lpPath);
1328
0
      char* fullpath = (char*)malloc(pathlen + namelen + 2);
1329
1330
0
      if (fullpath == nullptr)
1331
0
      {
1332
0
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1333
0
        return FALSE;
1334
0
      }
1335
1336
0
      memcpy(fullpath, pFileSearch->lpPath, pathlen);
1337
      /* Ensure path is terminated with a separator, but prevent
1338
       * duplicate separators */
1339
0
      if (fullpath[pathlen - 1] != '/')
1340
0
        fullpath[pathlen++] = '/';
1341
0
      memcpy(fullpath + pathlen, pDirent->d_name, namelen);
1342
0
      fullpath[pathlen + namelen] = 0;
1343
1344
0
      char* canonical = winpr_PathCanonicalize(fullpath);
1345
0
      free(fullpath);
1346
1347
0
      if (!canonical)
1348
0
        continue;
1349
1350
0
      struct stat fileStat = WINPR_C_ARRAY_INIT;
1351
0
      if (stat(canonical, &fileStat) != 0)
1352
0
      {
1353
0
        free(canonical);
1354
0
        SetLastError(map_posix_err(errno));
1355
0
        errno = 0;
1356
0
        continue;
1357
0
      }
1358
1359
      /* Skip FIFO entries. */
1360
0
      if (S_ISFIFO(fileStat.st_mode))
1361
0
      {
1362
0
        free(canonical);
1363
0
        continue;
1364
0
      }
1365
1366
0
      success = FindDataFromStat(canonical, &fileStat, lpFindFileData);
1367
0
      free(canonical);
1368
0
      return success;
1369
0
    }
1370
0
  }
1371
1372
0
  SetLastError(ERROR_NO_MORE_FILES);
1373
0
  return FALSE;
1374
0
}
1375
1376
BOOL FindNextFileW(HANDLE hFindFile, LPWIN32_FIND_DATAW lpFindFileData)
1377
0
{
1378
0
  LPWIN32_FIND_DATAA fd = (LPWIN32_FIND_DATAA)calloc(1, sizeof(WIN32_FIND_DATAA));
1379
1380
0
  if (!fd)
1381
0
  {
1382
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1383
0
    return FALSE;
1384
0
  }
1385
1386
0
  if (FindNextFileA(hFindFile, fd))
1387
0
  {
1388
0
    if (!ConvertFindDataAToW(fd, lpFindFileData))
1389
0
    {
1390
0
      SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1391
0
      free(fd);
1392
0
      return FALSE;
1393
0
    }
1394
1395
0
    free(fd);
1396
0
    return TRUE;
1397
0
  }
1398
1399
0
  free(fd);
1400
0
  return FALSE;
1401
0
}
1402
1403
BOOL FindClose(HANDLE hFindFile)
1404
0
{
1405
0
  WIN32_FILE_SEARCH* pFileSearch = (WIN32_FILE_SEARCH*)hFindFile;
1406
0
  if (!pFileSearch)
1407
0
    return FALSE;
1408
1409
  /* Since INVALID_HANDLE_VALUE != nullptr the analyzer guesses that there
1410
   * is a initialized HANDLE that is not freed properly.
1411
   * Disable this return to stop confusing the analyzer. */
1412
0
#ifndef __clang_analyzer__
1413
0
  if (!is_valid_file_search_handle(hFindFile))
1414
0
    return FALSE;
1415
0
#endif
1416
1417
0
  free(pFileSearch->lpPath);
1418
0
  free(pFileSearch->lpPattern);
1419
1420
0
  if (pFileSearch->pDir)
1421
0
    closedir(pFileSearch->pDir);
1422
1423
  // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
1424
0
  free(pFileSearch);
1425
0
  return TRUE;
1426
0
}
1427
1428
BOOL CreateDirectoryA(LPCSTR lpPathName,
1429
                      WINPR_ATTR_UNUSED LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1430
0
{
1431
0
  return mkdir(lpPathName, S_IRUSR | S_IWUSR | S_IXUSR) == 0;
1432
0
}
1433
1434
BOOL CreateDirectoryW(LPCWSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1435
0
{
1436
0
  if (!lpPathName)
1437
0
    return FALSE;
1438
0
  char* utfPathName = ConvertWCharToUtf8Alloc(lpPathName, nullptr);
1439
0
  BOOL ret = FALSE;
1440
1441
0
  if (!utfPathName)
1442
0
  {
1443
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1444
0
    goto fail;
1445
0
  }
1446
1447
0
  ret = CreateDirectoryA(utfPathName, lpSecurityAttributes);
1448
0
fail:
1449
0
  free(utfPathName);
1450
0
  return ret;
1451
0
}
1452
1453
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
1454
BOOL RemoveDirectoryA(LPCSTR lpPathName)
1455
0
{
1456
0
  return winpr_RemoveDirectory(lpPathName);
1457
0
}
1458
#endif
1459
1460
BOOL RemoveDirectoryW(LPCWSTR lpPathName)
1461
0
{
1462
0
  if (!lpPathName)
1463
0
    return FALSE;
1464
0
  char* utfPathName = ConvertWCharToUtf8Alloc(lpPathName, nullptr);
1465
0
  BOOL ret = FALSE;
1466
1467
0
  if (!utfPathName)
1468
0
  {
1469
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1470
0
    goto fail;
1471
0
  }
1472
1473
0
  ret = winpr_RemoveDirectory(utfPathName);
1474
0
fail:
1475
0
  free(utfPathName);
1476
0
  return ret;
1477
0
}
1478
1479
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
1480
BOOL MoveFileExA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName, DWORD dwFlags)
1481
0
{
1482
0
  return winpr_MoveFileEx(lpExistingFileName, lpNewFileName, dwFlags);
1483
0
}
1484
#endif
1485
1486
BOOL MoveFileExW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, DWORD dwFlags)
1487
0
{
1488
0
  if (!lpExistingFileName || !lpNewFileName)
1489
0
    return FALSE;
1490
1491
0
  LPSTR lpCExistingFileName = ConvertWCharToUtf8Alloc(lpExistingFileName, nullptr);
1492
0
  LPSTR lpCNewFileName = ConvertWCharToUtf8Alloc(lpNewFileName, nullptr);
1493
0
  BOOL ret = FALSE;
1494
1495
0
  if (!lpCExistingFileName || !lpCNewFileName)
1496
0
  {
1497
0
    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1498
0
    goto fail;
1499
0
  }
1500
1501
0
  ret = winpr_MoveFileEx(lpCExistingFileName, lpCNewFileName, dwFlags);
1502
0
fail:
1503
0
  free(lpCNewFileName);
1504
0
  free(lpCExistingFileName);
1505
0
  return ret;
1506
0
}
1507
1508
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
1509
BOOL MoveFileA(LPCSTR lpExistingFileName, LPCSTR lpNewFileName)
1510
0
{
1511
0
  return winpr_MoveFileEx(lpExistingFileName, lpNewFileName, 0);
1512
0
}
1513
#endif
1514
1515
BOOL MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName)
1516
0
{
1517
0
  return MoveFileExW(lpExistingFileName, lpNewFileName, 0);
1518
0
}
1519
1520
#endif
1521
1522
/* Extended API */
1523
1524
int UnixChangeFileMode(const char* filename, int flags)
1525
0
{
1526
0
  if (!filename)
1527
0
    return -1;
1528
0
#ifndef _WIN32
1529
0
  mode_t fl = 0;
1530
0
  fl |= (flags & 0x4000) ? S_ISUID : 0;
1531
0
  fl |= (flags & 0x2000) ? S_ISGID : 0;
1532
0
  fl |= (flags & 0x1000) ? S_ISVTX : 0;
1533
0
  fl |= (flags & 0x0400) ? S_IRUSR : 0;
1534
0
  fl |= (flags & 0x0200) ? S_IWUSR : 0;
1535
0
  fl |= (flags & 0x0100) ? S_IXUSR : 0;
1536
0
  fl |= (flags & 0x0040) ? S_IRGRP : 0;
1537
0
  fl |= (flags & 0x0020) ? S_IWGRP : 0;
1538
0
  fl |= (flags & 0x0010) ? S_IXGRP : 0;
1539
0
  fl |= (flags & 0x0004) ? S_IROTH : 0;
1540
0
  fl |= (flags & 0x0002) ? S_IWOTH : 0;
1541
0
  fl |= (flags & 0x0001) ? S_IXOTH : 0;
1542
0
  return chmod(filename, fl);
1543
#else
1544
  int rc;
1545
  WCHAR* wfl = ConvertUtf8ToWCharAlloc(filename, nullptr);
1546
1547
  if (!wfl)
1548
    return -1;
1549
1550
  /* Check for unsupported flags. */
1551
  if (flags & ~(_S_IREAD | _S_IWRITE))
1552
    WLog_WARN(TAG, "Unsupported file mode %d for _wchmod", flags);
1553
1554
  rc = _wchmod(wfl, flags);
1555
  free(wfl);
1556
  return rc;
1557
#endif
1558
0
}
1559
1560
#if defined(_WIN32) || defined(_UWP)
1561
HANDLE winpr_CreateFile(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
1562
                        LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
1563
                        DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
1564
{
1565
  WCHAR* filename = ConvertUtf8ToWCharAlloc(lpFileName, nullptr);
1566
  if (!filename)
1567
    return nullptr;
1568
1569
  HANDLE hdl = CreateFileW(filename, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
1570
                           dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
1571
  free(filename);
1572
  return hdl;
1573
}
1574
#endif