-
Notifications
You must be signed in to change notification settings - Fork 6
/
file.c
1104 lines (1025 loc) · 28.4 KB
/
file.c
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
/* *********************************************************************
* This Original Work is copyright of 51 Degrees Mobile Experts Limited.
* Copyright 2023 51 Degrees Mobile Experts Limited, Davidson House,
* Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
*
* This Original Work is licensed under the European Union Public Licence
* (EUPL) v.1.2 and is subject to its terms as set out below.
*
* If a copy of the EUPL was not distributed with this file, You can obtain
* one at https://opensource.org/licenses/EUPL-1.2.
*
* The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
* amended by the European Commission) shall be deemed incompatible for
* the purposes of the Work and the provisions of the compatibility
* clause in Article 5 of the EUPL shall not apply.
*
* If using the Work as, or as part of, a network application, by
* including the attribution notice(s) required under Article 5 of the EUPL
* in the end user terms of the application under an appropriate heading,
* such notice(s) shall fulfill the requirements of that article.
* ********************************************************************* */
#include "file.h"
#include "fiftyone.h"
#include <inttypes.h>
#ifdef _MSC_VER
#include <windows.h>
#else
#include <unistd.h>
#endif
#ifdef __APPLE__
#include <libproc.h>
#include <sys/proc_info.h>
#endif
/* Compare method passed to the iterate method. */
typedef bool(*fileCompare)(const char*, void*);
/* Match method called by the iterate method if the compare method returns true. */
typedef bool(*fileMatch)(const char*, void*);
/* State passed to the iterator methods. */
typedef struct fileIteratorState_t {
const char *masterFileName; /* Path to the master file */
const char *baseName; /* Base name of the master file (i.e. without
the path and extension) */
size_t baseNameLength; /* Length of baseName */
const char *destination; /* Memory to write the matching file path to */
long bytesToCompare; /* Number of bytes to compare from the start of the
file */
} fileIteratorState;
#ifdef _MSC_VER
#pragma warning (disable:4100)
#endif
static void* createFileHandle(Pool *pool, void *state, Exception *exception) {
FILE *fileHandle;
StatusCode status = FileOpen(
(const char*)state,
&fileHandle);
if (status != SUCCESS) {
EXCEPTION_SET(status)
fileHandle = NULL;
}
return (void*)fileHandle;
}
static void freeFileHandle(Pool *pool, void *fileHandle) {
fclose((FILE*)fileHandle);
}
#ifdef _MSC_VER
#pragma warning (default:4100)
#endif
static long fileGetSize(FILE *file) {
if (fseek(file, 0L, SEEK_END) == 0) {
return ftell(file);
}
return -1;
}
static long setLength(FilePool *reader, Exception *exception) {
FileHandle *handle;
reader->length = 0;
handle = FileHandleGet(reader, exception);
if (handle != NULL && EXCEPTION_OKAY) {
reader->length = fileGetSize(handle->file);
FileHandleRelease(handle);
}
return reader->length;
}
static StatusCode fileOpen(
const char* fileName,
FILE** handle,
const char *mode) {
// Open the file and hold on to the data.ptr.
#ifndef _MSC_FULL_VER
unsigned int originalMask = 0;
if (strcmp(mode, "wb") == 0) {
originalMask = umask(0);
}
*handle = fopen(fileName, mode);
if (strcmp(mode, "wb") == 0) {
umask(originalMask);
}
if (*handle == NULL) {
if (strcmp(mode, "rb") == 0) {
return FILE_NOT_FOUND;
}
else if (strcmp(mode, "wb") == 0) {
return FILE_WRITE_ERROR;
}
else {
return FILE_FAILURE;
}
}
#else
/* If using Microsoft use the fopen_s method to avoid warning */
errno_t error = fopen_s(handle, fileName, mode);
if (error != 0) {
switch (error) {
case ENFILE:
case EMFILE:
return TOO_MANY_OPEN_FILES;
case EACCES:
case EROFS:
return FILE_PERMISSION_DENIED;
case EEXIST:
return FILE_EXISTS_ERROR;
case ENOENT:
default:
return FILE_NOT_FOUND;
}
}
#endif
return SUCCESS;
}
static StatusCode fileCopy(FILE *source, FILE *destination) {
unsigned char buffer[8192];
size_t lengthRead, lengthWritten = 0;
if (fseek(source, 0L, SEEK_END) == 0) {
fseek(source, 0L, SEEK_SET);
lengthRead = fread(buffer, 1, sizeof(buffer), source);
while (lengthRead > 0) {
lengthWritten = fwrite(buffer, 1, lengthRead, destination);
if (lengthWritten != lengthRead) {
return FILE_COPY_ERROR;
}
lengthRead = fread(buffer, 1, sizeof(buffer), source);
}
}
return SUCCESS;
}
/**
* Attempts to open a file to determine whether or not it exists.
* @param fileName name of the file to check
* @return true if the file exists
*/
static bool fileExists(const char *fileName) {
FILE *file;
if (fileOpen(fileName, &file, "rb") == SUCCESS) {
fclose(file);
return true;
}
return false;
}
static long getRandSeed() {
struct timespec ts;
#ifdef _MSC_VER
if (timespec_get(&ts, TIME_UTC) != 0) {
return ts.tv_nsec;
}
#else
if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
return ts.tv_nsec;
}
#endif
else {
return -1;
}
}
/**
* Generates a random string consisting of random ASCII characters. The
* random name is written to the destination parameter, and the number of
* characters written are returned.
* @param length the number of characters including null terminator
* @param destination allocated memory where the string will be written
* @return number of characters written. Negative if error occurs.
*/
static int getRandomString(
size_t length,
char *destination) {
size_t i;
// Seed the random function. If this is not done, then the same random
// names will be generated each time an executable is run.
long seed = getRandSeed();
if (seed == -1) {
return -1;
}
srand((unsigned int)seed);
// Generate a random string using ASCII characters in the range [65,90)
// i.e. uppercase alphabet.
for (i = 0; i < length - 1; i++) {
destination[i] = (char)(rand() % 26 + 65);
}
destination[length - 1] = '\0';
return (int)length;
}
/**
* Generates a unique file name consisting of random ASCII characters. The
* unique name is written to the destination parameter, and the number of
* characters written are returned. This is used by the old CreateTempFile
* @param length the number of characters including null terminator
* @param destination allocated memory where the string will be written
* @param nameStart the character position to in destination to start writing
* the file name
* @return number of characters written
*/
static int getUniqueLegacyFileName(
size_t length,
char* destination,
size_t nameStart) {
int charAdded = 0;
do {
charAdded = getRandomString(length, destination + nameStart);
} while (fileExists(destination) && (charAdded >= 0 && charAdded <= (int)length));
return charAdded;
}
/**
* Compare two files, first by their sizes, then the contents.
* @param fileName first file to compare
* @param otherFileName second file to compare
* @param bytesToCompare number of from the start of the file to compare for
* equality with the master file, or -1 to compare the whole file
* @return true if files are identical
*/
static bool compareFiles(
const char *fileName,
const char *otherFileName,
long bytesToCompare) {
StatusCode status;
FILE *file, *otherFile;
long size, read;
byte buffer[1024], otherBuffer[1024];
// Compare the sizes.
size = FileGetSize(fileName);
if (size > 0 && size != FileGetSize(otherFileName)) {
return false;
}
// Open both files.
status = FileOpen(fileName, &file);
if (status != SUCCESS) {
return false;
}
status = FileOpen(otherFileName, &otherFile);
if (status != SUCCESS) {
fclose(file);
return false;
}
while (ftell(file) < size &&
(bytesToCompare < 0 || ftell(file) < bytesToCompare)) {
read = bytesToCompare > 0 ? bytesToCompare : (long)sizeof(buffer);
if (size - ftell(file) < read) {
read = size - ftell(file);
}
if (fread(buffer, read, 1, file) != 1) {
fclose(file);
fclose(otherFile);
return false;
}
if (fread(otherBuffer, read, 1, otherFile) != 1) {
fclose(file);
fclose(otherFile);
return false;
}
if (memcmp(buffer, otherBuffer, read) != 0) {
fclose(file);
fclose(otherFile);
return false;
}
}
fclose(file);
fclose(otherFile);
return true;
}
/**
* Gets the file name from the full path.
* @param path path to get the file name from
* @return the file name in the path
*/
static const char* getNameFromPath(const char *path) {
char *last = (char*)path,
*current = (char*)path;
while (*current != '\0') {
if (*current == '/' || *current == '\\') {
last = current + 1;
}
current++;
}
return last;
}
/**
* Checks whether the names of two files are the same. The paths to the files
* are not taken into account, as this would return false when comparing a
* relative path to an absolute path.
* @param path first path to compare
* @param otherPath second path to compare
* @return true if both file paths have the same file name
*/
static bool fileNamesMatch(const char *path, const char *otherPath) {
return strcmp(
getNameFromPath(path),
getNameFromPath(otherPath)) == 0;
}
/**
* Iterates over all files in the path provided. If a matching file is
* identified by the compare method, then the match method is called and true
* returned. No more iterations are performed after the first file is found.
* @param path directory to iterate over
* @param state pointer to a structure to pass to the compare and match methods
* @param compare method called to check if the file is a match
* @param match method called if a matching file is found
* @return true if a matching file was found in the directory
*/
static bool iterateFiles(
const char *path,
void *state,
fileCompare compare,
fileMatch match) {
char tempPath[FIFTYONE_DEGREES_FILE_MAX_PATH];
size_t nameStart;
// Append a slash to the path if one is not there already.
strcpy(tempPath, path);
nameStart = strlen(path);
if (nameStart != 0 &&
tempPath[nameStart - 1] != '/' &&
tempPath[nameStart - 1] != '\\') {
tempPath[nameStart++] = '/';
}
#ifdef _MSC_VER
wchar_t wString[FIFTYONE_DEGREES_FILE_MAX_PATH];
WIN32_FIND_DATA file;
HANDLE searchHandle;
if (nameStart + 1 > FIFTYONE_DEGREES_FILE_MAX_PATH) {
return false;
}
// Build the search pattern, e.g. /some/path/*
tempPath[nameStart] = '*';
tempPath[nameStart + 1] = '\0';
// Convert the path to a wide char string.
if (MultiByteToWideChar(
CP_ACP,
0,
tempPath,
-1,
wString,
FIFTYONE_DEGREES_FILE_MAX_PATH) == 0) {
return false;
}
// Iterate over all files.
if ((searchHandle = FindFirstFile(wString, &file))
!= INVALID_HANDLE_VALUE) {
do {
// Append the name to the path.
if (WideCharToMultiByte(
CP_ACP,
0,
file.cFileName,
-1,
&tempPath[nameStart],
(int)(sizeof(char) *
(FIFTYONE_DEGREES_FILE_MAX_PATH - nameStart)),
NULL,
NULL) == 0) {
FindClose(searchHandle);
return false;
}
// Call match and return if the file is a match.
if (compare(tempPath, state)) {
if (match(tempPath, state) == true) {
FindClose(searchHandle);
return true;
}
}
} while (FindNextFile(searchHandle, &file) != 0);
FindClose(searchHandle);
}
#else
DIR *dir;
struct dirent *ent;
dir = opendir(path);
if (dir != NULL) {
// Iterate over all files.
while ((ent = readdir(dir)) != NULL) {
// Append the name to the path.
strcpy(tempPath + nameStart, ent->d_name);
// Call match and return if the file is a match.
if (compare(tempPath, state)) {
if (match(tempPath, state) == true) {
closedir(dir);
return true;
}
}
}
closedir(dir);
}
#endif
return false;
}
/**
* Compares the file, and the master file who's name is stored in the state.
* If the contents of the files are the same (up to the bytesToCompare limit)
* and the file names are not the same, then true is returned.
* @param fileName name of the file to compare to the master file
* @param state pointer to the file iterator state with the search parameters
* @return true if the files are equal, but different files
*/
static bool iteratorFileCompare(const char *fileName, void *state) {
fileIteratorState *fileState = (fileIteratorState*)state;
if (strncmp(fileState->baseName, getNameFromPath(fileName), fileState->baseNameLength) == 0 &&
compareFiles(
fileState->masterFileName,
fileName,
fileState->bytesToCompare) == true &&
fileNamesMatch(fileName, fileState->masterFileName) == false) {
return true;
}
return false;
}
/**
* Copies the name of the file to the destination memory pointed to by the
* state structure.
* @param fileName path to the matching file
* @param state pointer to the file iterator state with the destination pointer
* @return true to indicate that the search should end
*/
static bool iteratorFileMatch(const char *fileName, void *state) {
fileIteratorState *fileState = (fileIteratorState*)state;
strcpy((char*)fileState->destination, fileName);
return true;
}
#ifdef _MSC_VER
// For MSC version, the parameter is not required
#pragma warning (disable: 4100)
#endif
#ifdef __linux__
/**
* Returns true if the file is in use. Note that this is only functional on
* Linux systems. Windows does not need this for the usage in this file.
* The Apple implementation is currently unstable (so is not used). Also note
* that the file MUST exist. If it does not, then this method will result in
* undefined behaviour.
* @param pathName path to the file to check
* @return true if the file is in use
*/
static bool isFileInUse(const char *pathName) {
DIR *procDir;
struct dirent *ent1, *ent2;
char fdPath[FILE_MAX_PATH];
char linkFile[FILE_MAX_PATH];
char linkPath[FILE_MAX_PATH];
procDir = opendir("/proc");
if (procDir != NULL) {
// Iterate over all directories in /proc
while ((ent1 = readdir(procDir)) != NULL) {
// Get the path to the file descriptor directory for a PID
Snprintf(fdPath, FILE_MAX_PATH, "/proc/%s/fd", ent1->d_name);
DIR *fdDir = opendir(fdPath);
if (fdDir != NULL) {
while ((ent2 = readdir(fdDir)) != NULL) {
// Check that the file is not '.' or '..'
if (strcmp(ent2->d_name, ".") != 0 &&
strcmp(ent2->d_name, "..") != 0) {
// Get the path which the symlink is pointing to
if (Snprintf(
linkFile,
FILE_MAX_PATH,
"%s/%s",
fdPath,
ent2->d_name) >= 0) {
ssize_t written =
readlink(linkFile, linkPath, FILE_MAX_PATH);
if (written >= 0) {
linkPath[written] = '\0';
size_t linkPathLen = strlen(linkPath);
size_t pathNameLen = strlen(pathName);
if (pathNameLen <= linkPathLen &&
strncmp(linkPath + linkPathLen - pathNameLen,
pathName,
pathNameLen) == 0) {
closedir(fdDir);
closedir(procDir);
return true;
}
}
}
}
}
}
closedir(fdDir);
}
closedir(procDir);
}
else {
// This method cannot be used to determine whether the file is in use.
// So to be safe, lets report true so it is not deleted.
return true;
}
return false;
}
#endif
#ifdef _MSC_VER
#pragma warning (default: 4100)
#endif
/**
* Deletes the file is it is not in use. The first byte of state->destination
* is used as a counter to indicate how many files were successfully deleted.
* @param fileName path to matching file
* @param state pointer to the file iterator state with the destination pointer
* @return false to indicate that the search should continue
*/
static bool iteratorFileDelete(const char *fileName, void *state) {
fileIteratorState *fileState = (fileIteratorState*)state;
#ifdef __linux__
/*
On non Windows platforms, the file locking is advisory. Therefore,
an explicit check is required. Currently no stable solution has been
implemented for MacOS platform so only perform this for Linux.
TODO: Implement a 'isFileInUse' solution for MacOS.
*/
if (isFileInUse(fileName) == false) {
#endif
if (fiftyoneDegreesFileDelete(fileName) == SUCCESS) {
((byte*)fileState->destination)[0]++;
}
#ifdef __linux__
}
#endif
return false;
}
fiftyoneDegreesStatusCode fiftyoneDegreesFileOpen(
const char* fileName,
FILE** handle) {
return fileOpen(fileName, handle, "rb");
}
fiftyoneDegreesStatusCode fiftyoneDegreesFileWrite(
const char* fileName,
const void *data,
const size_t length) {
FILE *file;
StatusCode status = fileOpen(fileName, &file, "wb");
if (status == SUCCESS) {
if (fwrite(data, length, 1, file) != 1) {
status = FILE_FAILURE;
}
fclose(file);
}
return status;
}
fiftyoneDegreesStatusCode fiftyoneDegreesFileCreateDirectory(
const char *pathName) {
#ifdef _MSC_VER
int error = _mkdir(pathName);
#else
#ifdef __MINGW32__
int error = mkdir(pathName);
#else
int error = mkdir(pathName, S_IRUSR | S_IWUSR | S_IXUSR);
#endif
#endif
if (error != 0) {
switch (errno) {
case 0:
case EACCES:
case EROFS:
return FILE_PERMISSION_DENIED;
case EEXIST:
return FILE_EXISTS_ERROR;
case ENOENT:
default:
return FILE_NOT_FOUND;
}
}
return SUCCESS;
}
static fiftyoneDegreesStatusCode getBasenameWithoutExtension(
const char* path,
char* dest,
size_t length) {
StatusCode status = NOT_SET;
const char* pos = getNameFromPath(path);
char* dot = strrchr(path, '.');
size_t end = strlen(pos);
if (dot != NULL) {
end = dot - pos;
}
if (end + 1 > length) {
status = INSUFFICIENT_MEMORY;
}
else {
strncpy(dest, pos, end);
dest[end] = '\0';
status = SUCCESS;
}
return status;
}
int fiftyoneDegreesFileDeleteUnusedTempFiles(
const char *masterFileName,
const char **paths,
int count,
long bytesToCompare) {
int i;
byte deleted = 0;
fileIteratorState state;
state.masterFileName = masterFileName;
// The iteratorFileDelete method will use the first byte of
// state.destination to keep track of the number of files deleted. This is
// a slight misuse of the structure, but we'll allow it as the structure
// is internal only.
state.destination = (const char*)&deleted;
state.bytesToCompare = bytesToCompare;
char basename[FIFTYONE_DEGREES_FILE_MAX_PATH];
StatusCode status = getBasenameWithoutExtension(
masterFileName, basename, FIFTYONE_DEGREES_FILE_MAX_PATH);
if (status != SUCCESS) {
return 0;
}
state.baseName = basename;
state.baseNameLength = strlen(basename);
if (paths == NULL || count == 0) {
// Look in the working directory.
iterateFiles("", &state, iteratorFileCompare, iteratorFileDelete);
}
else {
// Look in the directories provided.
for (i = 0; i < count; i++) {
iterateFiles(
paths[0],
&state,
iteratorFileCompare,
iteratorFileDelete);
}
}
return (int)deleted;
}
bool fiftyoneDegreesFileGetExistingTempFile(
const char *masterFileName,
const char **paths,
int count,
long bytesToCompare,
const char *destination) {
int i;
fileIteratorState state;
char basename[FIFTYONE_DEGREES_FILE_MAX_PATH];
state.masterFileName = masterFileName;
state.destination = destination;
state.bytesToCompare = bytesToCompare;
StatusCode status = getBasenameWithoutExtension(
masterFileName, basename, FIFTYONE_DEGREES_FILE_MAX_PATH);
if (status != SUCCESS) {
return 0;
}
state.baseName = basename;
state.baseNameLength = strlen(basename);
if (paths == NULL || count == 0) {
// Look in the working directory.
return iterateFiles("", &state, iteratorFileCompare, iteratorFileMatch);
}
else {
// Look in the directories provided.
for (i = 0; i < count; i++) {
if (iterateFiles(
paths[0],
&state,
iteratorFileCompare,
iteratorFileMatch) == true) {
return true;
}
}
}
return false;
}
fiftyoneDegreesStatusCode fiftyoneDegreesFileAddTempFileName(
const char* masterFileName,
char* destination,
size_t nameStart,
size_t length) {
char uniqueString[TEMP_UNIQUE_STRING_LENGTH + 1];
char basename[FIFTYONE_DEGREES_FILE_MAX_PATH];
uint64_t processId = ProcessGetId();
StatusCode status = getBasenameWithoutExtension(
masterFileName, basename, FIFTYONE_DEGREES_FILE_MAX_PATH);
if (status != SUCCESS) {
return status;
}
do {
if (getRandomString(TEMP_UNIQUE_STRING_LENGTH + 1, uniqueString) < 0) {
return TEMP_FILE_ERROR;
}
int charsAdded = Snprintf(
destination + nameStart,
length,
"%s-%" PRId64 "-%s",
basename,
processId,
uniqueString);
if (charsAdded < 0) {
status = ENCODING_ERROR;
}
else if ((size_t)charsAdded > length) {
status = INSUFFICIENT_MEMORY;
}
else {
status = SUCCESS;
}
// Discard any changes to the destination if error occurred
if (status != NOT_SET && status != SUCCESS) {
memset(destination + nameStart, 0, length);
}
} while (status == SUCCESS && fileExists(destination));
return status;
}
const char* fiftyoneDegreesFileGetBaseName(const char *path) {
char* lastSlash = NULL;
if ((lastSlash = strrchr(path, '/')) == NULL) {
lastSlash = strrchr(path, '\\');
if (lastSlash != NULL && strlen(lastSlash) != 1) {
return lastSlash + 1;
}
}
return NULL;
}
fiftyoneDegreesStatusCode createTempFileWithoutPaths(
const char* masterFile,
char* destination,
size_t length) {
const char* masterFileName = getNameFromPath(masterFile);
StatusCode status = fiftyoneDegreesFileAddTempFileName(
masterFileName, destination, 0, length);
if (status != SUCCESS) {
return status;
}
status = FileCopy(masterFile, destination);
if (status != SUCCESS && length > 0) {
memset(destination, 0, length);
}
return status;
}
fiftyoneDegreesStatusCode createTempFileWithPaths(
const char* masterFile,
const char** paths,
int count,
char* destination,
size_t length) {
size_t nameStart;
StatusCode status = NOT_SET;
const char* masterFileName = getNameFromPath(masterFile);
for (int i = 0; i < count; i++) {
int charAdded = 0;
nameStart = strlen(paths[i]);
if (nameStart != 0 &&
paths[i][nameStart - 1] != '/' &&
paths[i][nameStart - 1] != '\\') {
charAdded = Snprintf(
destination, length, "%s/", paths[i]);
nameStart++;
}
else {
charAdded = Snprintf(
destination, length, "%s", paths[i]);
}
if (charAdded < 0) {
status = ENCODING_ERROR;
}
else if ((size_t)charAdded > length) {
status = INSUFFICIENT_MEMORY;
}
else {
status = fiftyoneDegreesFileAddTempFileName(
masterFileName, destination, nameStart, length - nameStart - 1);
if (status == SUCCESS) {
// Create the temp file
status = FileCopy(masterFile, destination);
}
}
// Reset the destination
if (status != SUCCESS && length > 0) {
memset(destination, 0, length);
}
}
return status;
}
fiftyoneDegreesStatusCode fiftyoneDegreesFileNewTempFile(
const char* masterFile,
const char** paths,
int count,
char* destination,
size_t length) {
StatusCode status = NOT_SET;
if (paths == NULL || count == 0) {
status = createTempFileWithoutPaths(
masterFile, destination, length);
}
else if (paths != NULL) {
status = createTempFileWithPaths(
masterFile, paths, count, destination, length);
}
assert(status != NOT_SET);
return status;
}
fiftyoneDegreesStatusCode fiftyoneDegreesFileCreateTempFile(
const char *masterFile,
const char **paths,
int count,
const char *destination) {
int i;
size_t nameStart;
StatusCode status = NOT_SET;
char fileName[TEMP_UNIQUE_STRING_LENGTH];
char tempPath[FIFTYONE_DEGREES_FILE_MAX_PATH];
if (paths == NULL || count == 0) {
getUniqueLegacyFileName(TEMP_UNIQUE_STRING_LENGTH, fileName, 0);
status = FileCopy(masterFile, fileName);
if (status == SUCCESS) {
strcpy((char*)destination, fileName);
return status;
}
}
else if (paths != NULL) {
for (i = 0; i < count; i++) {
strcpy(tempPath, paths[i]);
nameStart = strlen(paths[i]);
if (nameStart != 0 &&
tempPath[nameStart - 1] != '/' &&
tempPath[nameStart - 1] != '\\') {
tempPath[nameStart++] = '/';
}
if (nameStart + TEMP_UNIQUE_STRING_LENGTH < FIFTYONE_DEGREES_FILE_MAX_PATH) {
getUniqueLegacyFileName(TEMP_UNIQUE_STRING_LENGTH, tempPath, nameStart);
status = FileCopy(masterFile, tempPath);
if (status == SUCCESS) {
strcpy((char*)destination, tempPath);
return status;
}
}
else {
status = FILE_PATH_TOO_LONG;
}
}
}
assert(status != NOT_SET);
return status;
}
fiftyoneDegreesStatusCode fiftyoneDegreesFileGetPath(
const char *dataFolderName,
const char *fileName,
char *destination,
size_t size) {
size_t i;
FILE *handle;
int charsWritten;
char testPath[FIFTYONE_DEGREES_FILE_MAX_PATH];
if (GET_CURRENT_DIR(
testPath,
FIFTYONE_DEGREES_FILE_MAX_PATH) == testPath) {
for (i = strlen(testPath); i > 0; i--) {
if (testPath[i] == '\\' || testPath[i] == '/' ||
testPath[i] == '\0') {
charsWritten = Snprintf(
testPath + i,
sizeof(testPath) - (i * sizeof(char)),
"/%s/%s",
dataFolderName,
fileName);
if (charsWritten < 0) {
return ENCODING_ERROR;
}
if ((size_t)charsWritten >=
(sizeof(testPath) / sizeof(char)) - i) {
return INSUFFICIENT_MEMORY;
}
if (fileOpen(testPath, &handle, "rb") ==
SUCCESS) {
fclose(handle);
charsWritten = Snprintf(destination, size, "%s", testPath);
if (charsWritten < 0) {
return ENCODING_ERROR;
}
if ((size_t)charsWritten >= size / sizeof(char)) {
return INSUFFICIENT_MEMORY;
}
return SUCCESS;
}
}
}
}
return FILE_NOT_FOUND;
}
fiftyoneDegreesStatusCode fiftyoneDegreesFilePoolInit(
fiftyoneDegreesFilePool *filePool,
const char *fileName,
uint16_t concurrency,
fiftyoneDegreesException *exception) {
StatusCode status = SUCCESS;
if (concurrency <= 0) {
return INVALID_COLLECTION_CONFIG;
}
if (PoolInit(
&filePool->pool,
concurrency,
(void*)fileName,
createFileHandle,
freeFileHandle,
exception) != NULL &&
EXCEPTION_OKAY) {
if (setLength(filePool, exception) == 0) {
status = FILE_FAILURE;
}
}
else if (EXCEPTION_FAILED) {
status = exception->status;
}
else {
status = INSUFFICIENT_MEMORY;
}
return status;
}
fiftyoneDegreesFileHandle* fiftyoneDegreesFileHandleGet(
fiftyoneDegreesFilePool *filePool,
fiftyoneDegreesException *exception) {
return (FileHandle*)PoolItemGet(&filePool->pool, exception);
}
void fiftyoneDegreesFileHandleRelease(fiftyoneDegreesFileHandle* handle) {
PoolItemRelease(&handle->item);
}