summaryrefslogtreecommitdiffstats
path: root/winpr/libwinpr/file/file.c
blob: a016beb1388d1066cbff129f2af393e27b376fa7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
/**
 * WinPR: Windows Portable Runtime
 * File Functions
 *
 * Copyright 2015 Thincast Technologies GmbH
 * Copyright 2015 Bernhard Miklautz <bernhard.miklautz@thincast.com>
 * Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <winpr/config.h>
#include <winpr/debug.h>
#include <winpr/assert.h>

#include <winpr/wtypes.h>
#include <winpr/crt.h>
#include <winpr/file.h>

#ifdef _WIN32

#include <io.h>

#else /* _WIN32 */

#include "../log.h"
#define TAG WINPR_TAG("file")

#include <winpr/wlog.h>
#include <winpr/string.h>

#include "file.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/time.h>

#ifdef ANDROID
#include <sys/vfs.h>
#else
#include <sys/statvfs.h>
#endif

#ifndef MIN
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#endif

static BOOL FileIsHandled(HANDLE handle)
{
	return WINPR_HANDLE_IS_HANDLED(handle, HANDLE_TYPE_FILE, FALSE);
}

static int FileGetFd(HANDLE handle)
{
	WINPR_FILE* file = (WINPR_FILE*)handle;

	if (!FileIsHandled(handle))
		return -1;

	return fileno(file->fp);
}

static BOOL FileCloseHandle(HANDLE handle)
{
	WINPR_FILE* file = (WINPR_FILE*)handle;

	if (!FileIsHandled(handle))
		return FALSE;

	if (file->fp)
	{
		/* Don't close stdin/stdout/stderr */
		if (fileno(file->fp) > 2)
		{
			fclose(file->fp);
			file->fp = NULL;
		}
	}

	free(file->lpFileName);
	free(file);
	return TRUE;
}

static BOOL FileSetEndOfFile(HANDLE hFile)
{
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;

	if (!hFile)
		return FALSE;

	const INT64 size = _ftelli64(pFile->fp);
	if (size < 0)
		return FALSE;

	if (ftruncate(fileno(pFile->fp), (off_t)size) < 0)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "ftruncate %s failed with %s [0x%08X]", pFile->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		SetLastError(map_posix_err(errno));
		return FALSE;
	}

	return TRUE;
}

static DWORD FileSetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh,
                                DWORD dwMoveMethod)
{
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;
	INT64 offset = 0;
	int whence = 0;

	if (!hFile)
		return INVALID_SET_FILE_POINTER;

	/* If there is a high part, the sign is contained in that
	 * and the low integer must be interpreted as unsigned. */
	if (lpDistanceToMoveHigh)
	{
		offset = (INT64)(((UINT64)*lpDistanceToMoveHigh << 32U) | (UINT64)lDistanceToMove);
	}
	else
		offset = lDistanceToMove;

	switch (dwMoveMethod)
	{
		case FILE_BEGIN:
			whence = SEEK_SET;
			break;
		case FILE_END:
			whence = SEEK_END;
			break;
		case FILE_CURRENT:
			whence = SEEK_CUR;
			break;
		default:
			return INVALID_SET_FILE_POINTER;
	}

	if (_fseeki64(pFile->fp, offset, whence))
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "_fseeki64(%s) failed with %s [0x%08X]", pFile->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return INVALID_SET_FILE_POINTER;
	}

	return (DWORD)_ftelli64(pFile->fp);
}

static BOOL FileSetFilePointerEx(HANDLE hFile, LARGE_INTEGER liDistanceToMove,
                                 PLARGE_INTEGER lpNewFilePointer, DWORD dwMoveMethod)
{
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;
	int whence = 0;

	if (!hFile)
		return FALSE;

	switch (dwMoveMethod)
	{
		case FILE_BEGIN:
			whence = SEEK_SET;
			break;
		case FILE_END:
			whence = SEEK_END;
			break;
		case FILE_CURRENT:
			whence = SEEK_CUR;
			break;
		default:
			return FALSE;
	}

	if (_fseeki64(pFile->fp, liDistanceToMove.QuadPart, whence))
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "_fseeki64(%s) failed with %s [0x%08X]", pFile->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return FALSE;
	}

	if (lpNewFilePointer)
		lpNewFilePointer->QuadPart = _ftelli64(pFile->fp);

	return TRUE;
}

static BOOL FileRead(PVOID Object, LPVOID lpBuffer, DWORD nNumberOfBytesToRead,
                     LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
	size_t io_status = 0;
	WINPR_FILE* file = NULL;
	BOOL status = TRUE;

	if (lpOverlapped)
	{
		WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter");
		SetLastError(ERROR_NOT_SUPPORTED);
		return FALSE;
	}

	if (!Object)
		return FALSE;

	file = (WINPR_FILE*)Object;
	clearerr(file->fp);
	io_status = fread(lpBuffer, 1, nNumberOfBytesToRead, file->fp);

	if (io_status == 0 && ferror(file->fp))
	{
		status = FALSE;

		switch (errno)
		{
			case EWOULDBLOCK:
				SetLastError(ERROR_NO_DATA);
				break;
			default:
				SetLastError(map_posix_err(errno));
		}
	}

	if (lpNumberOfBytesRead)
		*lpNumberOfBytesRead = (DWORD)io_status;

	return status;
}

static BOOL FileWrite(PVOID Object, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite,
                      LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped)
{
	size_t io_status = 0;
	WINPR_FILE* file = NULL;

	if (lpOverlapped)
	{
		WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter");
		SetLastError(ERROR_NOT_SUPPORTED);
		return FALSE;
	}

	if (!Object)
		return FALSE;

	file = (WINPR_FILE*)Object;

	clearerr(file->fp);
	io_status = fwrite(lpBuffer, 1, nNumberOfBytesToWrite, file->fp);
	if (io_status == 0 && ferror(file->fp))
	{
		SetLastError(map_posix_err(errno));
		return FALSE;
	}

	*lpNumberOfBytesWritten = (DWORD)io_status;
	return TRUE;
}

static DWORD FileGetFileSize(HANDLE Object, LPDWORD lpFileSizeHigh)
{
	WINPR_FILE* file = NULL;
	INT64 cur = 0;
	INT64 size = 0;

	if (!Object)
		return 0;

	file = (WINPR_FILE*)Object;

	cur = _ftelli64(file->fp);

	if (cur < 0)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "_ftelli64(%s) failed with %s [0x%08X]", file->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return INVALID_FILE_SIZE;
	}

	if (_fseeki64(file->fp, 0, SEEK_END) != 0)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "_fseeki64(%s) failed with %s [0x%08X]", file->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return INVALID_FILE_SIZE;
	}

	size = _ftelli64(file->fp);

	if (size < 0)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "_ftelli64(%s) failed with %s [0x%08X]", file->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return INVALID_FILE_SIZE;
	}

	if (_fseeki64(file->fp, cur, SEEK_SET) != 0)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "_ftelli64(%s) failed with %s [0x%08X]", file->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return INVALID_FILE_SIZE;
	}

	if (lpFileSizeHigh)
		*lpFileSizeHigh = (UINT32)(size >> 32);

	return (UINT32)(size & 0xFFFFFFFF);
}

static BOOL FileGetFileInformationByHandle(HANDLE hFile,
                                           LPBY_HANDLE_FILE_INFORMATION lpFileInformation)
{
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;
	struct stat st;
	UINT64 ft = 0;
	const char* lastSep = NULL;

	if (!pFile)
		return FALSE;
	if (!lpFileInformation)
		return FALSE;

	if (fstat(fileno(pFile->fp), &st) == -1)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "fstat failed with %s [%#08X]", errno,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)));
		return FALSE;
	}

	lpFileInformation->dwFileAttributes = 0;

	if (S_ISDIR(st.st_mode))
		lpFileInformation->dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;

	if (lpFileInformation->dwFileAttributes == 0)
		lpFileInformation->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;

	lastSep = strrchr(pFile->lpFileName, '/');

	if (lastSep)
	{
		const char* name = lastSep + 1;
		const size_t namelen = strlen(name);

		if ((namelen > 1) && (name[0] == '.') && (name[1] != '.'))
			lpFileInformation->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN;
	}

	if (!(st.st_mode & S_IWUSR))
		lpFileInformation->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;

#ifdef _DARWIN_FEATURE_64_BIT_INODE
	ft = STAT_TIME_TO_FILETIME(st.st_birthtime);
#else
	ft = STAT_TIME_TO_FILETIME(st.st_ctime);
#endif
	lpFileInformation->ftCreationTime.dwHighDateTime = ((UINT64)ft) >> 32ULL;
	lpFileInformation->ftCreationTime.dwLowDateTime = ft & 0xFFFFFFFF;
	ft = STAT_TIME_TO_FILETIME(st.st_mtime);
	lpFileInformation->ftLastWriteTime.dwHighDateTime = ((UINT64)ft) >> 32ULL;
	lpFileInformation->ftLastWriteTime.dwLowDateTime = ft & 0xFFFFFFFF;
	ft = STAT_TIME_TO_FILETIME(st.st_atime);
	lpFileInformation->ftLastAccessTime.dwHighDateTime = ((UINT64)ft) >> 32ULL;
	lpFileInformation->ftLastAccessTime.dwLowDateTime = ft & 0xFFFFFFFF;
	lpFileInformation->nFileSizeHigh = ((UINT64)st.st_size) >> 32ULL;
	lpFileInformation->nFileSizeLow = st.st_size & 0xFFFFFFFF;
	lpFileInformation->dwVolumeSerialNumber = st.st_dev;
	lpFileInformation->nNumberOfLinks = st.st_nlink;
	lpFileInformation->nFileIndexHigh = (st.st_ino >> 4) & 0xFFFFFFFF;
	lpFileInformation->nFileIndexLow = st.st_ino & 0xFFFFFFFF;
	return TRUE;
}

static BOOL FileLockFileEx(HANDLE hFile, DWORD dwFlags, DWORD dwReserved,
                           DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh,
                           LPOVERLAPPED lpOverlapped)
{
#ifdef __sun
	struct flock lock;
	int lckcmd;
#else
	int lock = 0;
#endif
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;

	if (lpOverlapped)
	{
		WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter");
		SetLastError(ERROR_NOT_SUPPORTED);
		return FALSE;
	}

	if (!hFile)
		return FALSE;

	if (pFile->bLocked)
	{
		WLog_ERR(TAG, "File %s already locked!", pFile->lpFileName);
		return FALSE;
	}

#ifdef __sun
	lock.l_start = 0;
	lock.l_len = 0;
	lock.l_whence = SEEK_SET;

	if (dwFlags & LOCKFILE_EXCLUSIVE_LOCK)
		lock.l_type = F_WRLCK;
	else
		lock.l_type = F_WRLCK;

	if (dwFlags & LOCKFILE_FAIL_IMMEDIATELY)
		lckcmd = F_SETLK;
	else
		lckcmd = F_SETLKW;

	if (fcntl(fileno(pFile->fp), lckcmd, &lock) == -1)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "F_SETLK failed with %s [0x%08X]",
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return FALSE;
	}
#else
	if (dwFlags & LOCKFILE_EXCLUSIVE_LOCK)
		lock = LOCK_EX;
	else
		lock = LOCK_SH;

	if (dwFlags & LOCKFILE_FAIL_IMMEDIATELY)
		lock |= LOCK_NB;

	if (flock(fileno(pFile->fp), lock) < 0)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "flock failed with %s [0x%08X]",
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return FALSE;
	}
#endif

	pFile->bLocked = TRUE;

	return TRUE;
}

static BOOL FileUnlockFile(HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
                           DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh)
{
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;
#ifdef __sun
	struct flock lock;
#endif

	if (!hFile)
		return FALSE;

	if (!pFile->bLocked)
	{
		WLog_ERR(TAG, "File %s is not locked!", pFile->lpFileName);
		return FALSE;
	}

#ifdef __sun
	lock.l_start = 0;
	lock.l_len = 0;
	lock.l_whence = SEEK_SET;
	lock.l_type = F_UNLCK;
	if (fcntl(fileno(pFile->fp), F_GETLK, &lock) == -1)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "F_UNLCK on %s failed with %s [0x%08X]", pFile->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return FALSE;
	}

#else
	if (flock(fileno(pFile->fp), LOCK_UN) < 0)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "flock(LOCK_UN) %s failed with %s [0x%08X]", pFile->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return FALSE;
	}
#endif

	return TRUE;
}

static BOOL FileUnlockFileEx(HANDLE hFile, DWORD dwReserved, DWORD nNumberOfBytesToUnlockLow,
                             DWORD nNumberOfBytesToUnlockHigh, LPOVERLAPPED lpOverlapped)
{
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;
#ifdef __sun
	struct flock lock;
#endif

	if (lpOverlapped)
	{
		WLog_ERR(TAG, "WinPR does not support the lpOverlapped parameter");
		SetLastError(ERROR_NOT_SUPPORTED);
		return FALSE;
	}

	if (!hFile)
		return FALSE;

	if (!pFile->bLocked)
	{
		WLog_ERR(TAG, "File %s is not locked!", pFile->lpFileName);
		return FALSE;
	}

#ifdef __sun
	lock.l_start = 0;
	lock.l_len = 0;
	lock.l_whence = SEEK_SET;
	lock.l_type = F_UNLCK;
	if (fcntl(fileno(pFile->fp), F_GETLK, &lock) == -1)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "F_UNLCK on %s failed with %s [0x%08X]", pFile->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return FALSE;
	}
#else
	if (flock(fileno(pFile->fp), LOCK_UN) < 0)
	{
		char ebuffer[256] = { 0 };
		WLog_ERR(TAG, "flock(LOCK_UN) %s failed with %s [0x%08X]", pFile->lpFileName,
		         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
		return FALSE;
	}
#endif

	return TRUE;
}

static UINT64 FileTimeToUS(const FILETIME* ft)
{
	const UINT64 EPOCH_DIFF_US = EPOCH_DIFF * 1000000ULL;
	UINT64 tmp = ((UINT64)ft->dwHighDateTime) << 32 | ft->dwLowDateTime;
	tmp /= 10; /* 100ns steps to 1us step */
	tmp -= EPOCH_DIFF_US;
	return tmp;
}

#if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200809L)
static struct timespec filetimeToTimespec(const FILETIME* ftime)
{
	WINPR_ASSERT(ftime);
	UINT64 tmp = FileTimeToUS(ftime);
	struct timespec ts = { 0 };
	ts.tv_sec = tmp / 1000000ULL;
	ts.tv_nsec = (tmp % 1000000ULL) * 1000ULL;
	return ts;
}

static BOOL FileSetFileTime(HANDLE hFile, const FILETIME* lpCreationTime,
                            const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime)
{
	struct timespec times[2] = { { UTIME_OMIT, UTIME_OMIT },
		                         { UTIME_OMIT, UTIME_OMIT } }; /* last access, last modification */
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;

	if (!hFile)
		return FALSE;

	if (lpLastAccessTime)
		times[0] = filetimeToTimespec(lpLastAccessTime);

	if (lpLastWriteTime)
		times[1] = filetimeToTimespec(lpLastWriteTime);

	// TODO: Creation time can not be handled!
	const int rc = futimens(fileno(pFile->fp), times);
	if (rc != 0)
		return FALSE;

	return TRUE;
}
#elif defined(__APPLE__) || defined(ANDROID) || defined(__FreeBSD__) || defined(KFREEBSD)
static struct timeval filetimeToTimeval(const FILETIME* ftime)
{
	WINPR_ASSERT(ftime);
	UINT64 tmp = FileTimeToUS(ftime);
	struct timeval tv = { 0 };
	tv.tv_sec = tmp / 1000000ULL;
	tv.tv_usec = tmp % 1000000ULL;
	return tv;
}

static struct timeval statToTimeval(const struct stat* sval)
{
	WINPR_ASSERT(sval);
	struct timeval tv = { 0 };
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(KFREEBSD)
	tv.tv_sec = sval->st_atime;
#ifdef _POSIX_SOURCE
	TIMESPEC_TO_TIMEVAL(&tv, &sval->st_atim);
#else
	TIMESPEC_TO_TIMEVAL(&tv, &sval->st_atimespec);
#endif
#elif defined(ANDROID)
	tv.tv_sec = sval->st_atime;
	tv.tv_usec = sval->st_atimensec / 1000UL;
#endif
	return tv;
}

static BOOL FileSetFileTime(HANDLE hFile, const FILETIME* lpCreationTime,
                            const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime)
{
	struct stat buf = { 0 };
	/* OpenBSD, NetBSD and DragonflyBSD support POSIX futimens */
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;

	if (!hFile)
		return FALSE;

	const int rc = fstat(fileno(pFile->fp), &buf);
	if (rc < 0)
		return FALSE;

	struct timeval timevals[2] = { statToTimeval(&buf), statToTimeval(&buf) };
	if (lpLastAccessTime)
		timevals[0] = filetimeToTimeval(lpLastAccessTime);

	if (lpLastWriteTime)
		timevals[1] = filetimeToTimeval(lpLastWriteTime);

	// TODO: Creation time can not be handled!
	{
		const int rc = utimes(pFile->lpFileName, timevals);
		if (rc != 0)
			return FALSE;
	}

	return TRUE;
}
#else
static BOOL FileSetFileTime(HANDLE hFile, const FILETIME* lpCreationTime,
                            const FILETIME* lpLastAccessTime, const FILETIME* lpLastWriteTime)
{
	WINPR_FILE* pFile = (WINPR_FILE*)hFile;

	if (!hFile)
		return FALSE;

	WLog_WARN(TAG, "TODO: Creation, Access and Write time can not be handled!");
	WLog_WARN(TAG,
	          "TODO: Define _POSIX_C_SOURCE >= 200809L or implement a platform specific handler!");
	return TRUE;
}
#endif

static HANDLE_OPS fileOps = {
	FileIsHandled,
	FileCloseHandle,
	FileGetFd,
	NULL, /* CleanupHandle */
	FileRead,
	NULL, /* FileReadEx */
	NULL, /* FileReadScatter */
	FileWrite,
	NULL, /* FileWriteEx */
	NULL, /* FileWriteGather */
	FileGetFileSize,
	NULL, /*  FlushFileBuffers */
	FileSetEndOfFile,
	FileSetFilePointer,
	FileSetFilePointerEx,
	NULL, /* FileLockFile */
	FileLockFileEx,
	FileUnlockFile,
	FileUnlockFileEx,
	FileSetFileTime,
	FileGetFileInformationByHandle,
};

static HANDLE_OPS shmOps = {
	FileIsHandled,
	FileCloseHandle,
	FileGetFd,
	NULL, /* CleanupHandle */
	FileRead,
	NULL, /* FileReadEx */
	NULL, /* FileReadScatter */
	FileWrite,
	NULL, /* FileWriteEx */
	NULL, /* FileWriteGather */
	NULL, /* FileGetFileSize */
	NULL, /*  FlushFileBuffers */
	NULL, /* FileSetEndOfFile */
	NULL, /* FileSetFilePointer */
	NULL, /* SetFilePointerEx */
	NULL, /* FileLockFile */
	NULL, /* FileLockFileEx */
	NULL, /* FileUnlockFile */
	NULL, /* FileUnlockFileEx */
	NULL, /* FileSetFileTime */
	FileGetFileInformationByHandle,
};

static const char* FileGetMode(DWORD dwDesiredAccess, DWORD dwCreationDisposition, BOOL* create)
{
	BOOL writeable = (dwDesiredAccess & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0;

	switch (dwCreationDisposition)
	{
		case CREATE_ALWAYS:
			*create = TRUE;
			return (writeable) ? "wb+" : "rwb";
		case CREATE_NEW:
			*create = TRUE;
			return "wb+";
		case OPEN_ALWAYS:
			*create = TRUE;
			return "rb+";
		case OPEN_EXISTING:
			*create = FALSE;
			return (writeable) ? "rb+" : "rb";
		case TRUNCATE_EXISTING:
			*create = FALSE;
			return "wb+";
		default:
			*create = FALSE;
			return "";
	}
}

UINT32 map_posix_err(int fs_errno)
{
	NTSTATUS rc = 0;

	/* try to return NTSTATUS version of error code */

	switch (fs_errno)
	{
		case 0:
			rc = STATUS_SUCCESS;
			break;

		case ENOTCONN:
		case ENODEV:
		case ENOTDIR:
		case ENXIO:
			rc = ERROR_FILE_NOT_FOUND;
			break;

		case EROFS:
		case EPERM:
		case EACCES:
			rc = ERROR_ACCESS_DENIED;
			break;

		case ENOENT:
			rc = ERROR_FILE_NOT_FOUND;
			break;

		case EBUSY:
			rc = ERROR_BUSY_DRIVE;
			break;

		case EEXIST:
			rc = ERROR_FILE_EXISTS;
			break;

		case EISDIR:
			rc = STATUS_FILE_IS_A_DIRECTORY;
			break;

		case ENOTEMPTY:
			rc = STATUS_DIRECTORY_NOT_EMPTY;
			break;

		case EMFILE:
			rc = STATUS_TOO_MANY_OPENED_FILES;
			break;

		default:
		{
			char ebuffer[256] = { 0 };
			WLog_ERR(TAG, "Missing ERRNO mapping %s [%d]",
			         winpr_strerror(fs_errno, ebuffer, sizeof(ebuffer)), fs_errno);
			rc = STATUS_UNSUCCESSFUL;
		}
		break;
	}

	return (UINT32)rc;
}

static HANDLE FileCreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
                              LPSECURITY_ATTRIBUTES lpSecurityAttributes,
                              DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
                              HANDLE hTemplateFile)
{
	WINPR_FILE* pFile = NULL;
	BOOL create = 0;
	const char* mode = FileGetMode(dwDesiredAccess, dwCreationDisposition, &create);
#ifdef __sun
	struct flock lock;
#else
	int lock = 0;
#endif
	FILE* fp = NULL;
	struct stat st;

	if (dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)
	{
		WLog_ERR(TAG, "WinPR does not support the FILE_FLAG_OVERLAPPED flag");
		SetLastError(ERROR_NOT_SUPPORTED);
		return INVALID_HANDLE_VALUE;
	}

	pFile = (WINPR_FILE*)calloc(1, sizeof(WINPR_FILE));
	if (!pFile)
	{
		SetLastError(ERROR_NOT_ENOUGH_MEMORY);
		return INVALID_HANDLE_VALUE;
	}

	WINPR_HANDLE_SET_TYPE_AND_MODE(pFile, HANDLE_TYPE_FILE, WINPR_FD_READ);
	pFile->common.ops = &fileOps;

	pFile->lpFileName = _strdup(lpFileName);
	if (!pFile->lpFileName)
	{
		SetLastError(ERROR_NOT_ENOUGH_MEMORY);
		free(pFile);
		return INVALID_HANDLE_VALUE;
	}

	pFile->dwOpenMode = dwDesiredAccess;
	pFile->dwShareMode = dwShareMode;
	pFile->dwFlagsAndAttributes = dwFlagsAndAttributes;
	pFile->lpSecurityAttributes = lpSecurityAttributes;
	pFile->dwCreationDisposition = dwCreationDisposition;
	pFile->hTemplateFile = hTemplateFile;

	if (create)
	{
		if (dwCreationDisposition == CREATE_NEW)
		{
			if (stat(pFile->lpFileName, &st) == 0)
			{
				SetLastError(ERROR_FILE_EXISTS);
				free(pFile->lpFileName);
				free(pFile);
				return INVALID_HANDLE_VALUE;
			}
		}

		fp = winpr_fopen(pFile->lpFileName, "ab");
		if (!fp)
		{
			SetLastError(map_posix_err(errno));
			free(pFile->lpFileName);
			free(pFile);
			return INVALID_HANDLE_VALUE;
		}

		fp = freopen(pFile->lpFileName, mode, fp);
	}
	else
	{
		if (stat(pFile->lpFileName, &st) != 0)
		{
			SetLastError(map_posix_err(errno));
			free(pFile->lpFileName);
			free(pFile);
			return INVALID_HANDLE_VALUE;
		}

		/* FIFO (named pipe) would block the following fopen
		 * call if not connected. This renders the channel unusable,
		 * therefore abort early. */
		if (S_ISFIFO(st.st_mode))
		{
			SetLastError(ERROR_FILE_NOT_FOUND);
			free(pFile->lpFileName);
			free(pFile);
			return INVALID_HANDLE_VALUE;
		}
	}

	if (NULL == fp)
		fp = winpr_fopen(pFile->lpFileName, mode);

	pFile->fp = fp;
	if (!pFile->fp)
	{
		/* This case can occur when trying to open a
		 * not existing file without create flag. */
		SetLastError(map_posix_err(errno));
		free(pFile->lpFileName);
		free(pFile);
		return INVALID_HANDLE_VALUE;
	}

	setvbuf(fp, NULL, _IONBF, 0);

#ifdef __sun
	lock.l_start = 0;
	lock.l_len = 0;
	lock.l_whence = SEEK_SET;

	if (dwShareMode & FILE_SHARE_READ)
		lock.l_type = F_RDLCK;
	if (dwShareMode & FILE_SHARE_WRITE)
		lock.l_type = F_RDLCK;
#else
	if (dwShareMode & FILE_SHARE_READ)
		lock = LOCK_SH;
	if (dwShareMode & FILE_SHARE_WRITE)
		lock = LOCK_EX;
#endif

	if (dwShareMode & (FILE_SHARE_READ | FILE_SHARE_WRITE))
	{
#ifdef __sun
		if (fcntl(fileno(pFile->fp), F_SETLKW, &lock) == -1)
#else
		if (flock(fileno(pFile->fp), lock) < 0)
#endif
		{
			char ebuffer[256] = { 0 };
#ifdef __sun
			WLog_ERR(TAG, "F_SETLKW failed with %s [0x%08X]",
			         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
#else
			WLog_ERR(TAG, "flock failed with %s [0x%08X]",
			         winpr_strerror(errno, ebuffer, sizeof(ebuffer)), errno);
#endif

			SetLastError(map_posix_err(errno));
			FileCloseHandle(pFile);
			return INVALID_HANDLE_VALUE;
		}

		pFile->bLocked = TRUE;
	}

	if (fstat(fileno(pFile->fp), &st) == 0 && dwFlagsAndAttributes & FILE_ATTRIBUTE_READONLY)
	{
		st.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
		fchmod(fileno(pFile->fp), st.st_mode);
	}

	SetLastError(STATUS_SUCCESS);
	return pFile;
}

static BOOL IsFileDevice(LPCTSTR lpDeviceName)
{
	return TRUE;
}

static HANDLE_CREATOR _FileHandleCreator = { IsFileDevice, FileCreateFileA };

HANDLE_CREATOR* GetFileHandleCreator(void)
{
	return &_FileHandleCreator;
}

static WINPR_FILE* FileHandle_New(FILE* fp)
{
	WINPR_FILE* pFile = NULL;
	char name[MAX_PATH] = { 0 };

	_snprintf(name, sizeof(name), "device_%d", fileno(fp));
	pFile = (WINPR_FILE*)calloc(1, sizeof(WINPR_FILE));
	if (!pFile)
	{
		SetLastError(ERROR_NOT_ENOUGH_MEMORY);
		return NULL;
	}
	pFile->fp = fp;
	pFile->common.ops = &shmOps;
	pFile->lpFileName = _strdup(name);

	WINPR_HANDLE_SET_TYPE_AND_MODE(pFile, HANDLE_TYPE_FILE, WINPR_FD_READ);
	return pFile;
}

HANDLE GetStdHandle(DWORD nStdHandle)
{
	FILE* fp = NULL;
	WINPR_FILE* pFile = NULL;

	switch (nStdHandle)
	{
		case STD_INPUT_HANDLE:
			fp = stdin;
			break;
		case STD_OUTPUT_HANDLE:
			fp = stdout;
			break;
		case STD_ERROR_HANDLE:
			fp = stderr;
			break;
		default:
			return INVALID_HANDLE_VALUE;
	}
	pFile = FileHandle_New(fp);
	if (!pFile)
		return INVALID_HANDLE_VALUE;

	return (HANDLE)pFile;
}

BOOL SetStdHandle(DWORD nStdHandle, HANDLE hHandle)
{
	return FALSE;
}

BOOL SetStdHandleEx(DWORD dwStdHandle, HANDLE hNewHandle, HANDLE* phOldHandle)
{
	return FALSE;
}

BOOL GetDiskFreeSpaceA(LPCSTR lpRootPathName, LPDWORD lpSectorsPerCluster, LPDWORD lpBytesPerSector,
                       LPDWORD lpNumberOfFreeClusters, LPDWORD lpTotalNumberOfClusters)
{
#if defined(ANDROID)
#define STATVFS statfs
#else
#define STATVFS statvfs
#endif

	struct STATVFS svfst = { 0 };
	STATVFS(lpRootPathName, &svfst);
	*lpSectorsPerCluster = (UINT32)MIN(svfst.f_frsize, UINT32_MAX);
	*lpBytesPerSector = 1;
	*lpNumberOfFreeClusters = (UINT32)MIN(svfst.f_bavail, UINT32_MAX);
	*lpTotalNumberOfClusters = (UINT32)MIN(svfst.f_blocks, UINT32_MAX);
	return TRUE;
}

BOOL GetDiskFreeSpaceW(LPCWSTR lpwRootPathName, LPDWORD lpSectorsPerCluster,
                       LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters,
                       LPDWORD lpTotalNumberOfClusters)
{
	LPSTR lpRootPathName = NULL;
	BOOL ret = 0;
	if (!lpwRootPathName)
		return FALSE;

	lpRootPathName = ConvertWCharToUtf8Alloc(lpwRootPathName, NULL);
	if (!lpRootPathName)
	{
		SetLastError(ERROR_NOT_ENOUGH_MEMORY);
		return FALSE;
	}
	ret = GetDiskFreeSpaceA(lpRootPathName, lpSectorsPerCluster, lpBytesPerSector,
	                        lpNumberOfFreeClusters, lpTotalNumberOfClusters);
	free(lpRootPathName);
	return ret;
}

#endif /* _WIN32 */

/**
 * Check if a file name component is valid.
 *
 * Some file names are not valid on Windows. See "Naming Files, Paths, and Namespaces":
 * https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
 */
BOOL ValidFileNameComponent(LPCWSTR lpFileName)
{
	if (!lpFileName)
		return FALSE;

	/* CON */
	if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'C' || lpFileName[0] == L'c')) &&
	    (lpFileName[1] != L'\0' && (lpFileName[1] == L'O' || lpFileName[1] == L'o')) &&
	    (lpFileName[2] != L'\0' && (lpFileName[2] == L'N' || lpFileName[2] == L'n')) &&
	    (lpFileName[3] == L'\0'))
	{
		return FALSE;
	}

	/* PRN */
	if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'P' || lpFileName[0] == L'p')) &&
	    (lpFileName[1] != L'\0' && (lpFileName[1] == L'R' || lpFileName[1] == L'r')) &&
	    (lpFileName[2] != L'\0' && (lpFileName[2] == L'N' || lpFileName[2] == L'n')) &&
	    (lpFileName[3] == L'\0'))
	{
		return FALSE;
	}

	/* AUX */
	if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'A' || lpFileName[0] == L'a')) &&
	    (lpFileName[1] != L'\0' && (lpFileName[1] == L'U' || lpFileName[1] == L'u')) &&
	    (lpFileName[2] != L'\0' && (lpFileName[2] == L'X' || lpFileName[2] == L'x')) &&
	    (lpFileName[3] == L'\0'))
	{
		return FALSE;
	}

	/* NUL */
	if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'N' || lpFileName[0] == L'n')) &&
	    (lpFileName[1] != L'\0' && (lpFileName[1] == L'U' || lpFileName[1] == L'u')) &&
	    (lpFileName[2] != L'\0' && (lpFileName[2] == L'L' || lpFileName[2] == L'l')) &&
	    (lpFileName[3] == L'\0'))
	{
		return FALSE;
	}

	/* LPT0-9 */
	if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'L' || lpFileName[0] == L'l')) &&
	    (lpFileName[1] != L'\0' && (lpFileName[1] == L'P' || lpFileName[1] == L'p')) &&
	    (lpFileName[2] != L'\0' && (lpFileName[2] == L'T' || lpFileName[2] == L't')) &&
	    (lpFileName[3] != L'\0' && (L'0' <= lpFileName[3] && lpFileName[3] <= L'9')) &&
	    (lpFileName[4] == L'\0'))
	{
		return FALSE;
	}

	/* COM0-9 */
	if ((lpFileName[0] != L'\0' && (lpFileName[0] == L'C' || lpFileName[0] == L'c')) &&
	    (lpFileName[1] != L'\0' && (lpFileName[1] == L'O' || lpFileName[1] == L'o')) &&
	    (lpFileName[2] != L'\0' && (lpFileName[2] == L'M' || lpFileName[2] == L'm')) &&
	    (lpFileName[3] != L'\0' && (L'0' <= lpFileName[3] && lpFileName[3] <= L'9')) &&
	    (lpFileName[4] == L'\0'))
	{
		return FALSE;
	}

	/* Reserved characters */
	for (LPCWSTR c = lpFileName; *c; c++)
	{
		if ((*c == L'<') || (*c == L'>') || (*c == L':') || (*c == L'"') || (*c == L'/') ||
		    (*c == L'\\') || (*c == L'|') || (*c == L'?') || (*c == L'*'))
		{
			return FALSE;
		}
	}

	return TRUE;
}

#ifdef _UWP

HANDLE CreateFileW(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
                   LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
                   DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
{
	HANDLE hFile;
	CREATEFILE2_EXTENDED_PARAMETERS params = { 0 };

	params.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);

	if (dwFlagsAndAttributes & FILE_FLAG_BACKUP_SEMANTICS)
		params.dwFileFlags |= FILE_FLAG_BACKUP_SEMANTICS;
	if (dwFlagsAndAttributes & FILE_FLAG_DELETE_ON_CLOSE)
		params.dwFileFlags |= FILE_FLAG_DELETE_ON_CLOSE;
	if (dwFlagsAndAttributes & FILE_FLAG_NO_BUFFERING)
		params.dwFileFlags |= FILE_FLAG_NO_BUFFERING;
	if (dwFlagsAndAttributes & FILE_FLAG_OPEN_NO_RECALL)
		params.dwFileFlags |= FILE_FLAG_OPEN_NO_RECALL;
	if (dwFlagsAndAttributes & FILE_FLAG_OPEN_REPARSE_POINT)
		params.dwFileFlags |= FILE_FLAG_OPEN_REPARSE_POINT;
	if (dwFlagsAndAttributes & FILE_FLAG_OPEN_REQUIRING_OPLOCK)
		params.dwFileFlags |= FILE_FLAG_OPEN_REQUIRING_OPLOCK;
	if (dwFlagsAndAttributes & FILE_FLAG_OVERLAPPED)
		params.dwFileFlags |= FILE_FLAG_OVERLAPPED;
	if (dwFlagsAndAttributes & FILE_FLAG_POSIX_SEMANTICS)
		params.dwFileFlags |= FILE_FLAG_POSIX_SEMANTICS;
	if (dwFlagsAndAttributes & FILE_FLAG_RANDOM_ACCESS)
		params.dwFileFlags |= FILE_FLAG_RANDOM_ACCESS;
	if (dwFlagsAndAttributes & FILE_FLAG_SESSION_AWARE)
		params.dwFileFlags |= FILE_FLAG_SESSION_AWARE;
	if (dwFlagsAndAttributes & FILE_FLAG_SEQUENTIAL_SCAN)
		params.dwFileFlags |= FILE_FLAG_SEQUENTIAL_SCAN;
	if (dwFlagsAndAttributes & FILE_FLAG_WRITE_THROUGH)
		params.dwFileFlags |= FILE_FLAG_WRITE_THROUGH;

	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_ARCHIVE)
		params.dwFileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_COMPRESSED)
		params.dwFileAttributes |= FILE_ATTRIBUTE_COMPRESSED;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_DEVICE)
		params.dwFileAttributes |= FILE_ATTRIBUTE_DEVICE;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_DIRECTORY)
		params.dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_ENCRYPTED)
		params.dwFileAttributes |= FILE_ATTRIBUTE_ENCRYPTED;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_HIDDEN)
		params.dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM)
		params.dwFileAttributes |= FILE_ATTRIBUTE_INTEGRITY_STREAM;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_NORMAL)
		params.dwFileAttributes |= FILE_ATTRIBUTE_NORMAL;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
		params.dwFileAttributes |= FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA)
		params.dwFileAttributes |= FILE_ATTRIBUTE_NO_SCRUB_DATA;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_OFFLINE)
		params.dwFileAttributes |= FILE_ATTRIBUTE_OFFLINE;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_READONLY)
		params.dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
		params.dwFileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_SPARSE_FILE)
		params.dwFileAttributes |= FILE_ATTRIBUTE_SPARSE_FILE;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_SYSTEM)
		params.dwFileAttributes |= FILE_ATTRIBUTE_SYSTEM;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_TEMPORARY)
		params.dwFileAttributes |= FILE_ATTRIBUTE_TEMPORARY;
	if (dwFlagsAndAttributes & FILE_ATTRIBUTE_VIRTUAL)
		params.dwFileAttributes |= FILE_ATTRIBUTE_VIRTUAL;

	if (dwFlagsAndAttributes & SECURITY_ANONYMOUS)
		params.dwSecurityQosFlags |= SECURITY_ANONYMOUS;
	if (dwFlagsAndAttributes & SECURITY_CONTEXT_TRACKING)
		params.dwSecurityQosFlags |= SECURITY_CONTEXT_TRACKING;
	if (dwFlagsAndAttributes & SECURITY_DELEGATION)
		params.dwSecurityQosFlags |= SECURITY_DELEGATION;
	if (dwFlagsAndAttributes & SECURITY_EFFECTIVE_ONLY)
		params.dwSecurityQosFlags |= SECURITY_EFFECTIVE_ONLY;
	if (dwFlagsAndAttributes & SECURITY_IDENTIFICATION)
		params.dwSecurityQosFlags |= SECURITY_IDENTIFICATION;
	if (dwFlagsAndAttributes & SECURITY_IMPERSONATION)
		params.dwSecurityQosFlags |= SECURITY_IMPERSONATION;

	params.lpSecurityAttributes = lpSecurityAttributes;
	params.hTemplateFile = hTemplateFile;

	hFile = CreateFile2(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, &params);

	return hFile;
}

HANDLE CreateFileA(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode,
                   LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
                   DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
{
	HANDLE hFile;
	if (!lpFileName)
		return NULL;

	WCHAR* lpFileNameW = ConvertUtf8ToWCharAlloc(lpFileName, NULL);

	if (!lpFileNameW)
		return NULL;

	hFile = CreateFileW(lpFileNameW, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
	                    dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);

	free(lpFileNameW);

	return hFile;
}

DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh)
{
	BOOL status;
	LARGE_INTEGER fileSize = { 0, 0 };

	if (!lpFileSizeHigh)
		return INVALID_FILE_SIZE;

	status = GetFileSizeEx(hFile, &fileSize);

	if (!status)
		return INVALID_FILE_SIZE;

	*lpFileSizeHigh = fileSize.HighPart;

	return fileSize.LowPart;
}

DWORD SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh,
                     DWORD dwMoveMethod)
{
	BOOL status;
	LARGE_INTEGER liDistanceToMove = { 0, 0 };
	LARGE_INTEGER liNewFilePointer = { 0, 0 };

	liDistanceToMove.LowPart = lDistanceToMove;

	status = SetFilePointerEx(hFile, liDistanceToMove, &liNewFilePointer, dwMoveMethod);

	if (!status)
		return INVALID_SET_FILE_POINTER;

	if (lpDistanceToMoveHigh)
		*lpDistanceToMoveHigh = liNewFilePointer.HighPart;

	return liNewFilePointer.LowPart;
}

HANDLE FindFirstFileA(LPCSTR lpFileName, LPWIN32_FIND_DATAA lpFindFileData)
{
	return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindFileData, FindExSearchNameMatch,
	                        NULL, 0);
}

HANDLE FindFirstFileW(LPCWSTR lpFileName, LPWIN32_FIND_DATAW lpFindFileData)
{
	return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindFileData, FindExSearchNameMatch,
	                        NULL, 0);
}

DWORD GetFullPathNameA(LPCSTR lpFileName, DWORD nBufferLength, LPSTR lpBuffer, LPSTR* lpFilePart)
{
	DWORD dwStatus;
	WCHAR* lpFileNameW = NULL;
	WCHAR* lpBufferW = NULL;
	WCHAR* lpFilePartW = NULL;
	DWORD nBufferLengthW = nBufferLength * sizeof(WCHAR);

	if (!lpFileName || (nBufferLength < 1))
		return 0;

	lpFileNameW = ConvertUtf8ToWCharAlloc(lpFileName, NULL);
	if (!lpFileNameW)
		return 0;

	lpBufferW = (WCHAR*)malloc(nBufferLengthW);

	if (!lpBufferW)
		return 0;

	dwStatus = GetFullPathNameW(lpFileNameW, nBufferLengthW, lpBufferW, &lpFilePartW);

	ConvertWCharNToUtf8(lpBufferW, nBufferLengthW / sizeof(WCHAR), lpBuffer, nBufferLength);

	if (lpFilePart)
		lpFilePart = lpBuffer + (lpFilePartW - lpBufferW);

	free(lpFileNameW);
	free(lpBufferW);

	return dwStatus * 2;
}

BOOL GetDiskFreeSpaceA(LPCSTR lpRootPathName, LPDWORD lpSectorsPerCluster, LPDWORD lpBytesPerSector,
                       LPDWORD lpNumberOfFreeClusters, LPDWORD lpTotalNumberOfClusters)
{
	BOOL status;
	ULARGE_INTEGER FreeBytesAvailableToCaller = { 0, 0 };
	ULARGE_INTEGER TotalNumberOfBytes = { 0, 0 };
	ULARGE_INTEGER TotalNumberOfFreeBytes = { 0, 0 };

	status = GetDiskFreeSpaceExA(lpRootPathName, &FreeBytesAvailableToCaller, &TotalNumberOfBytes,
	                             &TotalNumberOfFreeBytes);

	if (!status)
		return FALSE;

	*lpBytesPerSector = 1;
	*lpSectorsPerCluster = TotalNumberOfBytes.LowPart;
	*lpNumberOfFreeClusters = FreeBytesAvailableToCaller.LowPart;
	*lpTotalNumberOfClusters = TotalNumberOfFreeBytes.LowPart;

	return TRUE;
}

BOOL GetDiskFreeSpaceW(LPCWSTR lpRootPathName, LPDWORD lpSectorsPerCluster,
                       LPDWORD lpBytesPerSector, LPDWORD lpNumberOfFreeClusters,
                       LPDWORD lpTotalNumberOfClusters)
{
	BOOL status;
	ULARGE_INTEGER FreeBytesAvailableToCaller = { 0, 0 };
	ULARGE_INTEGER TotalNumberOfBytes = { 0, 0 };
	ULARGE_INTEGER TotalNumberOfFreeBytes = { 0, 0 };

	status = GetDiskFreeSpaceExW(lpRootPathName, &FreeBytesAvailableToCaller, &TotalNumberOfBytes,
	                             &TotalNumberOfFreeBytes);

	if (!status)
		return FALSE;

	*lpBytesPerSector = 1;
	*lpSectorsPerCluster = TotalNumberOfBytes.LowPart;
	*lpNumberOfFreeClusters = FreeBytesAvailableToCaller.LowPart;
	*lpTotalNumberOfClusters = TotalNumberOfFreeBytes.LowPart;

	return TRUE;
}

DWORD GetLogicalDriveStringsA(DWORD nBufferLength, LPSTR lpBuffer)
{
	SetLastError(ERROR_INVALID_FUNCTION);
	return 0;
}

DWORD GetLogicalDriveStringsW(DWORD nBufferLength, LPWSTR lpBuffer)
{
	SetLastError(ERROR_INVALID_FUNCTION);
	return 0;
}

BOOL PathIsDirectoryEmptyA(LPCSTR pszPath)
{
	return FALSE;
}

UINT GetACP(void)
{
	return CP_UTF8;
}

#endif

/* Extended API */

#ifdef _WIN32
#include <io.h>
#endif

HANDLE GetFileHandleForFileDescriptor(int fd)
{
#ifdef _WIN32
	return (HANDLE)_get_osfhandle(fd);
#else  /* _WIN32 */
	WINPR_FILE* pFile = NULL;
	FILE* fp = NULL;
	int flags = 0;

	/* Make sure it's a valid fd */
	if (fcntl(fd, F_GETFD) == -1 && errno == EBADF)
		return INVALID_HANDLE_VALUE;

	flags = fcntl(fd, F_GETFL);
	if (flags == -1)
		return INVALID_HANDLE_VALUE;

	if (flags & O_WRONLY)
		fp = fdopen(fd, "wb");
	else
		fp = fdopen(fd, "rb");

	if (!fp)
		return INVALID_HANDLE_VALUE;

	setvbuf(fp, NULL, _IONBF, 0);

	pFile = FileHandle_New(fp);
	if (!pFile)
		return INVALID_HANDLE_VALUE;

	return (HANDLE)pFile;
#endif /* _WIN32 */
}

FILE* winpr_fopen(const char* path, const char* mode)
{
#ifndef _WIN32
	return fopen(path, mode);
#else
	LPWSTR lpPathW = NULL;
	LPWSTR lpModeW = NULL;
	FILE* result = NULL;

	if (!path || !mode)
		return NULL;

	lpPathW = ConvertUtf8ToWCharAlloc(path, NULL);
	if (!lpPathW)
		goto cleanup;

	lpModeW = ConvertUtf8ToWCharAlloc(mode, NULL);
	if (!lpModeW)
		goto cleanup;

	result = _wfopen(lpPathW, lpModeW);

cleanup:
	free(lpPathW);
	free(lpModeW);
	return result;
#endif
}