-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibnfsviv.h
3416 lines (3052 loc) · 110 KB
/
libnfsviv.h
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
/*
libnfsviv.h - simple BIGF BIGH BIG4 decoder/encoder (commonly known as VIV/BIG)
unvivtool Copyright (C) 2020-2024 Benjamin Futasz <https://github.com/bfut>
Portions copyright, see each source file for more information.
You may not redistribute this program without its source code.
README.md may not be removed or altered from any unvivtool redistribution.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/*
The API in this header-only library is composed of two parts:
1. LIBNFSVIV_Unviv() and LIBNFSVIV_Viv() are one-and-done functions
2. Data analysis via
LIBNFSVIV_GetVivVersion*()
LIBNFSVIV_GetVivDirectory*() - returns struct *VivDirectory, the archive header
LIBNFSVIV_VivDirectoryToFileList*() - returns char** of filenames listed in the archive header
The decoder performs a single pass buffered read of the archive header.
The encoder allows archiving in user-determined order.
All functions are designed to be safe (and fast).
A known BIGF variation with fixed directory entry length and non-printable
filenames is supported in a first.
Compiling:
* little-endian, 32-bit|64-bit
* Win98+ (MSVC 6.0+), Linux, macOS
* non-Win32 requires _GNU_SOURCE #define'd for realpath()
* optionally #define UVTUTF8 for the UVTUTF8 branch (decoder supports utf8-filenames within archive header), forces dfa.h dependency
BIGF theoretical limits, assuming signed int:
min header len: 16 0x10
max header len: 2147483631 0x7fffffef
min directory entry len: 10 0xa
min dir entries count: 0
max dir entries count: 214748363 0x0ccccccb
BIGF BIGH headers usually contain big-endian numeric values.
Special cases:
archive header can have filesize encoded in little endian
BIGF header can have a fixed directory entry length (e.g., 80 bytes). This allows names with embedded nul's.
LIBNFSVIV_unviv() handles the following format deviations {with strategy}:
* Archive header has incorrect filesize {value unused}
* Archive header has incorrect number of directory entries {check endianness and/or assume large enough value}
* Archive header has incorrect number for directory length {value unused}
* Archive header has incorrect offset {value unused}
* At least 1 directory entry has illegal offset or length {skip file}
* Two directory entries have the same file name (use opt_overwrite == 1) {overwrite or rename existing}
* Directory entry would overwrite archive on extraction {skip file}
* Directory entry file name contains non-ASCII UTF8 characters {native support in UVTUTF8-branch}
* Directory entry file name contains non-printable characters (use opt_filenameshex == 1) {skip file or represent filename in base16}
* Directory entry file name is too long {skip file}
* Directory entry has fixed length and filename string is followed by large number of nul's (use opt_direnlenfixed == sz) {native support via option opt_direnlenfixed}
*/
#ifndef LIBNFSVIV_H_
#define LIBNFSVIV_H_
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _WIN32
#include <windows.h> /* GetFullPathNameA, GetLongPathNameA */
#include <direct.h>
#ifndef chdir
#define chdir _chdir
#endif
#ifndef mkdir
#define mkdir(a,b) _mkdir(a)
#endif
#ifndef stat
#define stat _stat
#endif
#ifndef S_IFDIR
#define S_IFDIR _S_IFDIR
#endif
#ifndef S_IFMT
#define S_IFMT _S_IFMT
#endif
#else
#include <unistd.h>
#if defined(__STDC__)
#include <dirent.h>
#endif
#endif
#if defined(_WIN32) /* for LIBNFSVIV_CopyFile() */
#include <windows.h> /* CopyFile() */
#elif defined(__APPLE__)
#include <copyfile.h> /* copyfile() */
#elif !defined(_WIN32) && !defined(__APPLE__)
#include <fcntl.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#ifndef SCL_DEBUG
#define SCL_DEBUG 0 /* 1: dev console output */
#endif
#if SCL_DEBUG > 0
#include <assert.h>
#define SCL_printf printf
#define SCL_assert assert
#else
/* #define SCL_printf(format, ...) { } */ /* C89-incompatible */
static void SCL_printf(const char *format, ...) { (void)format; }
#define SCL_assert(x)
#endif
#define UVTVERS "3.5"
#define UVTCOPYRIGHT "Copyright (C) 2020-2024 Benjamin Futasz (GPLv3+)"
#ifdef UVTUTF8 /* optional branch: unviv() utf8-filename support */
#include "./include/dfa.h"
#endif
#ifndef LIBNFSVIV_max
#define LIBNFSVIV_max(x,y) ((x)<(y)?(y):(x))
#define LIBNFSVIV_min(x,y) ((x)<(y)?(x):(y))
#define LIBNFSVIV_clamp(x,minv,maxv) ((maxv)<(minv)||(x)<(minv)?(minv):((x)>(maxv)?(maxv):(x)))
#define LIBNFSVIV_ceil(x,y) ((x)/(y)+((x)%(y)!=0)) /* ceil(x/y) for x>=0,y>0 */
#endif
#if !defined(PATH_MAX) && !defined(_WIN32)
#define PATH_MAX 4096 /* for realpath() */
#endif
#define LIBNFSVIV_BufferSize 4096
#if !defined(_WIN32)
#define LIBNFSVIV_FilenameMaxLen PATH_MAX
#else
#define LIBNFSVIV_FilenameMaxLen 256 * 4 /* utf8 */
#endif
#define LIBNFSVIV_DirEntrMax 1572864 /* ceil(((1024 << 10) * 24) / 16) */
#define LIBNFSVIV_CircBuf_Size LIBNFSVIV_BufferSize + 16
/* #define LIBNFSVIV_CircBuf_Size 0x10 + 16 */
#define LIBNFSVIV_WENCFileEnding ".txt"
#ifndef __cplusplus
typedef struct VivDirEntr VivDirEntr;
typedef struct VivDirectory VivDirectory;
#define LIBNFSVIV_extern
#else
#define LIBNFSVIV_extern extern "C"
#endif
struct VivDirEntr {
int offset;
int filesize;
int filename_ofs_;
int filename_len_; /* string length without nul */
};
#if defined(_WIN64) || defined(__LP64__) || defined(_M_X64) || defined(__x86_64__)
#define LIBNFSVIV_VivDirectoryPaddingSize 12
#else
#define LIBNFSVIV_VivDirectoryPaddingSize 20
#endif
struct VivDirectory {
char format[4]; /* BIGF, BIGH or BIG4 */
int filesize;
int count_dir_entries; /* per header */
int header_size; /* per header. includes VIV directory*/
int count_dir_entries_true; /* parsed valid entries count */
int viv_hdr_size_true; /* parsed unpadded. includes VIV directory. filename lengths include nul */
int length; /* length of buffer */
int null_count;
char *bitmap; /* len >= ceil(length/8) */
VivDirEntr *buffer;
/*
keep 64 byte aligned;
char[0] bitfield: 0 unused, 1-3 True for big-endianness
char[>0], used for bitmap if length sufficiently small
*/
char __padding[LIBNFSVIV_VivDirectoryPaddingSize];
};
/* util --------------------------------------------------------------------- */
LIBNFSVIV_extern int LIBNFSVIV_GetVivVersion_FromBuf(const char * const buf);
/* fixed length entries with all-printable names are not known to exist */
static
int LIBNFSVIV_Fix_opt_filenameshex(const int opt_filenameshex, const int opt_direnlenfixed)
{
return (opt_filenameshex || (opt_direnlenfixed >= 10));
}
static
int LIBNFSVIV_Clamp_opt_direnlenfixed(int opt_direnlenfixed, const int opt_verbose)
{
const int temp_ = opt_direnlenfixed;
opt_direnlenfixed = LIBNFSVIV_clamp(opt_direnlenfixed, 10, LIBNFSVIV_BufferSize + 16 - 1);
if (opt_verbose && temp_ != opt_direnlenfixed) printf("Setting fixed directory entry length: %d (0x%x) (clamped to 0xA,0x%x)\n", opt_direnlenfixed, opt_direnlenfixed, LIBNFSVIV_BufferSize + 16 - 1);
return opt_direnlenfixed;
}
static
void SCL_BITMAP_Set(char *bitmap, const int idx)
{
bitmap[idx >> 3] |= 1 << (idx & 7);
}
static
void SCL_BITMAP_Unset(char *bitmap, const int idx)
{
bitmap[idx >> 3] &= ~(1 << (idx & 7));
}
static
char SCL_BITMAP_IsSet(const char *bitmap, const int idx)
{
return (bitmap[idx >> 3] >> (idx & 7)) & 1;
}
static
void *LIBNFSVIV_CallocBitmapVivDirectory(VivDirectory *vd)
{
#if SCL_DEBUG > 0
printf("LIBNFSVIV_CallocBitmapVivDirectory: length %d (case2: %d)\n", vd->length, vd->length >= 0 && vd->length <= (LIBNFSVIV_VivDirectoryPaddingSize - 1) * 8);
#endif
if (vd->length <= (LIBNFSVIV_VivDirectoryPaddingSize - 1) * 8)
{
char *p = vd->__padding + 1;
#if SCL_DEBUG > 0
printf("LIBNFSVIV_CallocBitmapVivDirectory %p %p\n", p, vd->__padding);
#endif
memset(p, 0, sizeof(vd->__padding) - 1);
return p;
}
else
return calloc(LIBNFSVIV_ceil(vd->length, 32) * 32 * sizeof(*vd->bitmap), 1);
}
static
void LIBNFSVIV_FreeBitmapVivDirectory(VivDirectory *vd)
{
if (vd->length > (LIBNFSVIV_VivDirectoryPaddingSize - 1) * 8) free(vd->bitmap);
}
/* free's buffer and bitmap */
static
void LIBNFSVIV_FreeVivDirectory(VivDirectory *vd)
{
if (vd->buffer) free(vd->buffer);
if (vd->bitmap) LIBNFSVIV_FreeBitmapVivDirectory(vd);
}
static
VivDirectory *LIBNFSVIV_VivDirectory_Init(VivDirectory *vd, const int len)
{
if (len < 0 || len > LIBNFSVIV_DirEntrMax) return NULL;
vd->length = len + LIBNFSVIV_ceil(len, 2); /* 2*sizeof(VivDirEntr) == 32 */
#if SCL_DEBUG != 0
printf("LIBNFSVIV_VivDirectory_Init: vd->length: %d, len: %d\n", vd->length, len);
#endif
vd->bitmap = (char *)LIBNFSVIV_CallocBitmapVivDirectory(vd);
if (!vd->bitmap) return NULL;
vd->buffer = (VivDirEntr *)calloc(vd->length * sizeof(*vd->buffer), 1);
if (!vd->buffer)
{
free(vd->bitmap);
return NULL;
}
return vd;
}
#if defined(UVTUTF8)
/* Returns UTF8 length without nul. If __s is not nul-terminated, call with nul_terminate=0 */
static
int LIBNFSVIV_IsUTF8String(void *__s, const size_t max_len, const char nul_terminate)
{
unsigned char *s = (unsigned char *)__s;
size_t pos = 0;
unsigned int codepoint, state = 0;
if (!__s) return 0;
while (!(state == UTF8_REJECT) && (pos < max_len) && *s)
{
DFA_decode(&state, &codepoint, *s++);
++pos;
}
SCL_printf(" IsUTF8String: pos = %d, max_len = %d, state = %d (UTF8_ACCEPT %d); return=%d\n", (int)pos, (int)max_len, (int)state, UTF8_ACCEPT, (int)(pos * (!nul_terminate || (pos < max_len)) * (state == UTF8_ACCEPT)));
return (int)pos * (!nul_terminate || (pos < max_len)) * (state == UTF8_ACCEPT);
}
#else
/* Returns isprint length without nul. If __s is not nul-terminated, set nul_terminate=0 */
static
int LIBNFSVIV_IsPrintString(void *__s, const size_t max_len, const char nul_terminate)
{
unsigned char *s = (unsigned char *)__s;
size_t pos = 0;
if (!__s) return 0;
while ((pos < max_len) && *s)
{
if (!isprint(*s++))
pos = max_len;
++pos;
}
return pos * (!nul_terminate || (pos < max_len));
}
#endif
static
int LIBNFSVIV_SwapEndian(const int y)
{
unsigned int x;
int z;
memcpy(&x, &y, sizeof(x));
x = ((x >> 24) & 0x000000ff) | ((x << 24) & 0xff000000) |
((x << 8) & 0xff0000) | ((x >> 8) & 0x00ff00);
memcpy(&z, &x, sizeof(x));
return z;
}
/* Assumes (buf) and (bufsz > 1). Returns len == strlen(buf) on success, otherwise -1.*/
static
int LIBNFSVIV_FreadToStr(char *buf, const int bufsz, const int ofs, int len, FILE *src)
{
len = LIBNFSVIV_min(len, bufsz - 1);
if (len >= 0 && !fseek(src, ofs, SEEK_SET) && (int)fread(buf, 1, len, src) == len)
{
buf[len] = '\0';
return len;
}
buf[0] = '\0';
return -1;
}
/* Assumes src_len is length without nul. */
static
void *LIBNFSVIV_memcpyToString(void *dest, const void *src,
const int src_len, const int dest_len)
{
unsigned char *p = (unsigned char *)dest;
#if SCL_DEBUG > 0
if (dest_len > 0)
{
#endif
memcpy(dest, src, src_len);
p[LIBNFSVIV_min(src_len, dest_len - 1)] = '\0';
return dest;
#if SCL_DEBUG > 0
}
return NULL;
#endif
}
/* Assumes input \in 0123456ABCDEFabcdef */
static
int LIBNFSVIV_hextoint(const char in)
{
if (in >= '0' && in <= '9')
return in - '0';
if (in >= 'a' && in <= 'f')
return in - 'a' + 10;
if (in >= 'A' && in <= 'F')
return in - 'A' + 10;
return 0;
}
/* Assumes (0x0 <= in <= 0xF). Returns upper-case hexadecimal. */
static
char LIBNFSVIV_inttohex(const int in)
{
if (in >= 0 && in < 0xA)
return in + '0';
if (in >= 0xA && in <= 0xF)
/* return in + 'a' - 10; */
return in + 'A' - 10;
return '0';
}
/*
Decodes Base16 string to binary string. Clips overlong. Returns strlen()
Examples:
"666F6F" -> "foo"
"0066006F6F" -> "\0f\0oo" (i.e., keeps leading/embedded null)
*/
static
int LIBNFSVIV_DecBase16(char *str)
{
const char *ptr = str;
int i = 0;
char buf[LIBNFSVIV_FilenameMaxLen];
while (*ptr && *ptr + 1 && i < LIBNFSVIV_FilenameMaxLen - 2) /* buf always ends on nul */
{
buf[i] = LIBNFSVIV_hextoint(*ptr) << 4;
buf[i] += LIBNFSVIV_hextoint(*(ptr + 1));
ptr += 2;
++i;
}
buf[i] = '\0';
memcpy(str, buf, i + 1);
return i;
}
/*
Encodes binary string to Base16 string, clips overlong
use min_len == -1 for strings, positive value if string has leading nul
Example:
e.g., "foo" -> "666F6F"
*/
static
void LIBNFSVIV_EncBase16(char *str, const int min_len)
{
const char *ptr = str;
int i = 0;
char buf[LIBNFSVIV_FilenameMaxLen];
while ((*ptr || i < 2*min_len) && i < LIBNFSVIV_FilenameMaxLen - 2 - 1) /* buf always ends on nul */
{
buf[i] = LIBNFSVIV_inttohex((*ptr & 0xF0) >> 4);
buf[i + 1] = LIBNFSVIV_inttohex(*ptr & 0xF);
++ptr;
i += 2;
}
buf[i] = '\0';
memcpy(str, buf, i + 1);
}
#ifdef _WIN32
static
void LIBNFSVIV_BkwdToFwdSlash(char *filename)
{
char *ptr;
while ((ptr = strrchr(filename, '\\')))
ptr[0] = '/';
}
#endif
/* 'path/to/file.ext' returns pointer to 'file.ext'
filename is not changed; except on Windows, converts '\\' to '/'. */
static
char *LIBNFSVIV_GetPathBasename(char *filename)
{
char *ptr;
#ifdef _WIN32
LIBNFSVIV_BkwdToFwdSlash(filename);
#endif
if ((ptr = strrchr(filename, '/')))
return ptr + 1;
else
return filename;
}
/* Returns -1 on error. Allows (path==NULL). */
static
int LIBNFSVIV_GetFilesize(const char *path)
{
struct stat sb;
SCL_printf("LIBNFSVIV_GetFilesize: %d\n", !!path && !stat(path, &sb) ? (int)sb.st_size : 0 );
return !!path && !stat(path, &sb) ? (int)sb.st_size : -1;
}
static
int LIBNFSVIV_IsFile(const char *path)
{
FILE *file = fopen(path, "rb");
if (!file) return 0;
fclose(file);
return 1;
}
static
int LIBNFSVIV_IsDir(const char *path)
{
struct stat sb;
#if !defined(S_IFDIR)
SCL_printf("LIBNFSVIV_IsDir: %d\n", !stat(path, &sb) && S_ISDIR(sb.st_mode));
return (!stat(path, &sb) && S_ISDIR(sb.st_mode)) ? 1 : 0;
#else
SCL_printf("LIBNFSVIV_IsDir: %d\n", (!stat(path, &sb) && (sb.st_mode & S_IFMT) == S_IFDIR));
return (!stat(path, &sb) && (sb.st_mode & S_IFMT) == S_IFDIR) ? 1 : 0;
#endif
}
/* Assumes !buf. Removes trailing '/'. Returned path never ends on '/' */
static
void LIBNFSVIV_GetParentDir(char *buf)
{
char *ptr = buf + strlen(buf) - 1;
if (ptr[0] == '/')
ptr[0] = '\0';
ptr = strrchr(buf, '/');
if (ptr)
ptr[0] = '\0';
else
{
buf[0] = '.';
buf[1] = '\0';
}
}
#ifdef _WIN32
/* Wrapper for GetFullPathName()
If (!dst): updates src, returns updated src, keeps (!dst) unchanged and ignores nBufferLength.
Else: updates dst, returns updated dst, keeps src unchanged.
[out] lpFilePart
A pointer to a buffer that receives the address (within lpBuffer) of the final file name component in the path.
This parameter can be NULL.
If lpBuffer refers to a directory and not a file, lpFilePart receives zero. */
static
char *LIBNFSVIV_GetFullPathName(char *src, char *dst, const size_t nBufferLength, char **lpFilePart)
{
size_t len;
if (!dst)
{
char buf[LIBNFSVIV_FilenameMaxLen];
len = (size_t)GetFullPathName(src, LIBNFSVIV_FilenameMaxLen, buf, lpFilePart); /* returns length without nul */
if (len == 0 || len >= LIBNFSVIV_FilenameMaxLen)
src[0] = '\0';
else
{
memcpy(src, buf, len + 1);
LIBNFSVIV_BkwdToFwdSlash(src);
}
return src;
}
else
{
len = (size_t)GetFullPathName(src, nBufferLength, dst, lpFilePart); /* returns length without nul */
if (len == 0 || len >= nBufferLength)
dst[0] = '\0';
else
LIBNFSVIV_BkwdToFwdSlash(dst);
return dst;
}
}
#else
/* Wrapper for realpath(const char *src, char *dst)
If (!dst): updates src, returns updated src, keeps (!dst) unchanged.
Else: updates dst, returns updated dst, keeps src unchanged.
Assumes (src) and sizeof(src) >= 4096 (PATH_MAX) and src is string.
gcc -std=c89 requires sizeof(dst) >= 4096 to avoid buffer overflow */
static
char *LIBNFSVIV_GetFullPathName(char *src, char *dst)
{
char *ptr;
if (!dst)
{
char buf[LIBNFSVIV_FilenameMaxLen];
ptr = realpath(src, buf);
if (!ptr)
src[0] = '\0';
else
memcpy(src, ptr, strlen(ptr) + 1);
}
else
{
ptr = realpath(src, dst);
if (!ptr)
dst[0] = '\0';
}
return ptr;
}
#endif
static
int LIBNFSVIV_HasWritePermission(const char *path)
{
#ifdef _WIN32
struct _stat sb;
return !!path && !_stat(path, &sb) && (sb.st_mode & _S_IWRITE) ? 1 : 0;
#else
struct stat sb;
return !!path && !stat(path, &sb) && (sb.st_mode & S_IWUSR) ? 1 : 0;
#endif
}
/* buf will hold "/path/to/temp/". Returns strlen() > 0 on success. */
static
int LIBNFSVIV_GetTempPath(const int bufsz, char *buf)
{
#ifdef _WIN32
const int ret = (int)GetTempPath(bufsz, buf);
if (ret > 0) LIBNFSVIV_BkwdToFwdSlash(buf);
return ret;
#else
if (!buf) return -1;
buf[0] = '\0';
if (LIBNFSVIV_IsDir("/tmp/") && LIBNFSVIV_HasWritePermission("/tmp/"))
sprintf(buf, "/tmp/");
else if (LIBNFSVIV_IsDir("/usr/tmp/") && LIBNFSVIV_HasWritePermission("/usr/tmp/"))
sprintf(buf, "/usr/tmp/");
else if (LIBNFSVIV_IsDir("/var/tmp/") && LIBNFSVIV_HasWritePermission("/var/tmp/"))
sprintf(buf, "/var/tmp/");
/* else if (strlen(buf) < 1 && !getcwd(buf, bufsz) && sprintf(buf + strlen(buf), "/") != 1) return -1; */
else
return -1;
#if __APPLE__ || _DEFAULT_SOURCE || _BSD_SOURCE || _POSIX_C_SOURCE >= 200809L
SCL_printf("has mkdtemp()\n");
if ((int)strlen(buf) + 8 > bufsz) return -1;
buf[strlen(buf) + 6] = '\0';
memset(buf + strlen(buf), 'X', 6);
if (!mkdtemp(buf)) return -1;
sprintf(buf + strlen(buf), "/");
#else /* non-Windows non-Python C89 fallback, assumes that last 6 characters are digits. quietly bail on failures */
SCL_printf("using tmpnam(), missing mkdtemp()\n");
for (;;)
{
char temp[LIBNFSVIV_FilenameMaxLen];
char *p_;
if (!tmpnam(temp)) break;
p_ = strrchr(temp, '/');
if (!p_) break;
p_[strlen(p_)] = '\0';
if ((int)strlen(buf) + (int)strlen(p_) > bufsz) break;
sprintf(buf + strlen(buf), "%s", p_);
if (strlen(p_) > 0) sprintf(buf + strlen(buf), "/");
break;
}
#endif
SCL_printf("LIBNFSVIV_GetTempPath: %s\n", buf);
return (int)strlen(buf);
#endif
}
/* Returns !0 on success, 0 on failure. */
static
int LIBNFSVIV_CopyFile(char *lpExistingFileName, char *lpNewFileName, int bFailIfExists)
{
#ifdef _WIN32
return (int)CopyFile(lpExistingFileName, lpNewFileName, bFailIfExists); /* CopyFile() !0 on success */
#elif defined(__APPLE__)
return copyfile(lpExistingFileName, lpNewFileName, NULL, COPYFILE_DATA | COPYFILE_XATTR | ((bFailIfExists) ? COPYFILE_EXCL : 0) | COPYFILE_NOFOLLOW) == 0;
#else
int retv = 0;
FILE *file = fopen(lpNewFileName, "wb");
if (file) fclose(file);
for (;;)
{
if (!lpExistingFileName || !lpNewFileName) break;
if (!LIBNFSVIV_IsDir(lpExistingFileName) && !LIBNFSVIV_IsDir(lpNewFileName))
{
int fd_in, fd_out;
struct stat sb;
off_t offset = 0;
fd_in = open(lpExistingFileName, O_RDONLY);
if (fd_in < 0) break;
if (fstat(fd_in, &sb) < 0)
{
close(fd_in);
break;
}
if (!bFailIfExists)
fd_out = open(lpNewFileName, O_WRONLY | O_CREAT, sb.st_mode);
else
fd_out = open(lpNewFileName, O_WRONLY | O_CREAT | O_EXCL, sb.st_mode);
if (fd_out >= 0)
{
if (sendfile(fd_out, fd_in, &offset, sb.st_size) == (int)sb.st_size) /* sendfile() bytes on success, -1 on failure */
retv = (int)sb.st_size;
close(fd_out);
}
close(fd_in);
}
break;
} /* for (;;) */
return retv;
#endif
}
/*
Write len bytes from infile to outfile. Returns 1 on success, 0 on failure.
Assumes (dst) and (src) and (buf).
*/
static
int LIBNFSVIV_FileCopyData(FILE *dest, FILE *src, int len, char *buf, const int bufsz)
{
int err = 1;
int chunk;
#if SCL_DEBUG > 0
if (bufsz > 0)
{
#endif
while (len > 0)
{
chunk = LIBNFSVIV_min(bufsz, len);
err &= chunk == (int)fread(buf, 1, chunk, src);
err &= chunk == (int)fwrite(buf, 1, chunk, dest);
len -= chunk;
}
#if SCL_DEBUG > 0
}
#endif
return len == 0 && err == 1;
}
/*
Invalidates entries whose output path is identical to the archive.
Assumes (vd) and both, viv_name and outpath are strings.
*/
static
void LIBNFSVIV_EnsureVivPathNotInVivDirWritePaths(VivDirectory *vd, char *viv_name, const char *outpath, FILE *viv, const size_t viv_sz)
{
char buf[LIBNFSVIV_FilenameMaxLen];
/** Case: viv parentdir != outpath -> return */
memcpy(buf, viv_name, LIBNFSVIV_min(strlen(viv_name), LIBNFSVIV_FilenameMaxLen - 1));
buf[LIBNFSVIV_min(strlen(viv_name), LIBNFSVIV_FilenameMaxLen - 1)] = '\0';
LIBNFSVIV_GetParentDir(buf);
if (strcmp(buf, outpath))
return;
/** Case: viv parentdir == outpath
if for all i: viv filename != vivdirentry[i]->filename -> return
else: vivdirentry[i] is invalid
*/
{
char *viv_basename = LIBNFSVIV_GetPathBasename(viv_name);
int chunk_size;
int i;
for (i = 0; i < vd->count_dir_entries_true; ++i)
{
fseek(viv, vd->buffer[i].filename_ofs_, SEEK_SET);
chunk_size = LIBNFSVIV_min(viv_sz - vd->buffer[i].filename_ofs_, LIBNFSVIV_FilenameMaxLen);
if (fread(buf, 1, chunk_size, viv) != (size_t)chunk_size) { fprintf(stderr, "EnsureVivPathNotInVivDirWritePaths: File read error (strcmp)\n"); break; }
if (SCL_BITMAP_IsSet(vd->bitmap, i) == 1 && !strcmp(buf, viv_basename))
{
SCL_BITMAP_Unset(vd->bitmap, i);
++vd->null_count;
printf("Warning:EnsureVivPathNotInVivDirWritePaths: Skip file '%s' (%d) (would overwrite this archive)\n", buf, i);
}
}
}
}
/*
Rename "path/to/existing/file.ext" to "path/to/existing/file_N.ext" with N in 0..999
Returns 0 on failure, !0 on success.
Assumes path is string, sz is size of path buffer.
*/
static
int LIBNFSVIV_IncrementFile(const char * const path, int sz, const int verbose)
{
int retv = 0;
if (!path)
sz = strlen(path);
else
sz = -1;
if (0 < sz && sz < LIBNFSVIV_FilenameMaxLen - 32 && !LIBNFSVIV_IsDir(path))
{
char buf[LIBNFSVIV_FilenameMaxLen];
memcpy(buf, path, sz + 1);
{
int i;
const char *ext = strrchr(path, '.');
char *p = strrchr(buf, '.'); /* end of stem */
if (p)
p[0] = '\0';
else
{
p = buf + sz;
ext = path + sz; /* no extension, hence we need '\0' */
}
for (i = 0; i < 1000; ++i)
{
sprintf(p, "_%d%s", i, ext);
if (!LIBNFSVIV_IsFile(buf))
{
if (!rename(path, buf))
{
if (verbose) printf("IncrementFile: Incremented existing file '%s' to '%s'\n", path, buf);
retv = 1;
break;
}
}
} /* for i */
}
} /* if */
if (verbose && !retv) printf("IncrementFile: Cannot increment existing file '%s'\n", path);
return retv;
}
/* CircBuf ------------------------------------------------------------------ */
/*
struct LIBNFSVIV_CircBuf and LIBNFSVIV_CircBuf_* functions are derived from
WDL - circbuf.h
Copyright (C) 2005 Cockos Incorporated (zlib License)
*/
#ifndef __cplusplus
typedef struct LIBNFSVIV_CircBuf LIBNFSVIV_CircBuf;
#endif
struct LIBNFSVIV_CircBuf { /* treat as private members */
unsigned char *buf;
int sz;
int rd;
int wr;
};
static
int LIBNFSVIV_CircBuf_lefttoread(const LIBNFSVIV_CircBuf * const cb)
{
const int d = cb->wr - cb->rd;
if (d >= 0) return d;
return d + cb->sz;
}
/* ignores wr */
static
int LIBNFSVIV_CircBuf_readtoend(const LIBNFSVIV_CircBuf * const cb)
{
return cb->sz - cb->rd;
}
/* len is NOT upper-bounded by EOF */
static
int LIBNFSVIV_CircBuf_addFromFile(LIBNFSVIV_CircBuf *cb, FILE *file, const int filesz, int len)
{
int written = 0;
int wrlen1 = cb->sz - cb->wr;
if (len < 0 || !cb->buf) return -1;
if (len > filesz) len = filesz/* - (int)ftell(file) */;
if (len > cb->sz) len = cb->sz;
if (wrlen1 < len)
{
written += (int)fread(cb->buf + cb->wr, 1, wrlen1, file);
written += (int)fread(cb->buf, 1, len - wrlen1, file);
/* SCL_printf(" circbuf_addFromFile() stats: len: %d, written: %d, cb->wr: %d\n", len, written, cb->wr); */
if (written != len) return -1;
cb->wr = len - wrlen1;
}
else
{
written += (int)fread(cb->buf + cb->wr, 1, len, file);
/* SCL_printf(" circbuf_addFromFile() stats: len: %d, written: %d, cb->wr: %d\n", len, written, cb->wr); */
if (written != len) return -1;
cb->wr += len;
}
cb->wr %= cb->sz;
/* SCL_printf("! circbuf_addFromFile() stats: len: %d, written: %d, cb->wr: %d\n", len, written, cb->wr); */
return written;
}
/* Forwards rd, ignores wr */
static
void LIBNFSVIV_CircBuf_Fwd(LIBNFSVIV_CircBuf *cb, int len)
{
cb->rd += len;
cb->rd %= cb->sz;
}
static
int LIBNFSVIV_CircBuf_Peek(LIBNFSVIV_CircBuf *cb, void *dest, const int ofs, int len)
{
int rdlen1 = cb->sz - cb->rd - ofs;
if (len < 0 || ofs < 0 || !cb->buf) return 0;
if (len > cb->sz) len = cb->sz - ofs;
#if SCL_DEBUG > 1
if (rdlen1 < 0) SCL_printf(" circbuf_Peek(): rdlen1: %d, len: %d\n", rdlen1, len);
SCL_assert(rdlen1 >= 0);
if (rdlen1 < 0) return 0; /* Wstringop-overflow */
#endif
if (rdlen1 < len)
{
memcpy(dest, cb->buf + cb->rd + ofs, rdlen1);
memcpy((unsigned char *)dest + rdlen1, cb->buf, len - rdlen1);
}
else
{
memcpy(dest, cb->buf + cb->rd + ofs, len);
}
return len;
}
#if SCL_DEBUG > 0
void SCL_debug_printbuf(void *buf, int sz, int readat, int writeat)
{
int l = sz;
unsigned char *p = (unsigned char *)buf;
int pos = 0;
SCL_printf(" readat: %d, writeat: %d\n", readat, writeat);
if (l < 0 || !buf) return;
while (l-- > 0)
{
if (pos == readat && pos == writeat) SCL_printf("#%02x ", *p++);
else if (pos == readat) SCL_printf("r%02x ", *p++);
else if (pos == writeat) SCL_printf("w%02x ", *p++);
else SCL_printf(" %02x ", *p++);
if (++pos % 0x10 == 0) SCL_printf("\n");
}
if (pos % 0x10 != 0) SCL_printf("\n");
}
#else
#define SCL_debug_printbuf(a,b,c,d)
#endif
static
int LIBNFSVIV_CircBuf_Get(LIBNFSVIV_CircBuf *cb, void *buf, const int ofs, int len)
{
const int read = LIBNFSVIV_CircBuf_Peek(cb, buf, ofs, len);
cb->rd += read;
cb->rd %= cb->sz;
return read;
}
#if SCL_DEBUG > 2
static
unsigned char *LIBNFSVIV_CircBuf_PeekPtr(const LIBNFSVIV_CircBuf * const cb, int ofs)
{
if (ofs < 0 || !cb->buf) return NULL;
if (ofs > cb->sz) return NULL;
{
const int r2e = LIBNFSVIV_CircBuf_readtoend(cb);
ofs -= (r2e < ofs) ? r2e : 0;
return cb->buf + cb->rd + ofs;
}
}
#endif
/* ofs reduces len. unbounded by wr. */
static
void *LIBNFSVIV_CircBuf_memchr(const LIBNFSVIV_CircBuf * const cb, int c, int ofs, int len)
{
#if 1
if (len <= 0) return NULL;
if (!cb->buf || cb->sz <= 0) return NULL;
if (ofs > cb->sz) { fprintf(stderr, "warning ofs\n"); return NULL; } /* ofs %= cb->sz; */ /* really an error */
if (len > cb->sz) { fprintf(stderr, "warning len\n"); return NULL; } /* len %= cb->sz; */ /* really an error */
{
int rdlen1;
int rdofs = cb->rd + ofs;
if (rdofs > cb->sz) rdofs -= cb->sz;
len -= ofs;
rdlen1 = cb->sz - rdofs;
/* SCL_printf(" circbuf_memchr(): rdofs: %d, ofs: %d, rdlen1: %d, len: %d\n", rdofs, ofs, rdlen1, len); */
if (rdlen1 < len) /* r2e */
{
void *p = memchr(cb->buf + rdofs, c, rdlen1);
/* SCL_printf(" circbuf_memchr(): rdofs: %d, ofs: %d, rdlen1: %d, len: %d, p:'%p'\n", rdofs, ofs, rdlen1, len, p); */
return p ? p : memchr(cb->buf, c, len - rdlen1);
}
return memchr(cb->buf + rdofs, c, len);
}
#elif 0
{
int rdlen1 = cb->rd + ofs + len;
if (rdlen1 > cb->sz) rdlen1 -= cb->sz;
ofs -= cb->sz - cb->rd;
len -= ofs;
SCL_printf(" circbuf_memchr(): ofs: %d, rdlen1: %d, len: %d\n", ofs, rdlen1, len);
if (rdlen1 < len)
{
void *p = memchr(cb->buf + cb->rd + ofs, c, rdlen1);
SCL_printf(" circbuf_memchr(): p:'%p', ofs: %d, rdlen1: %d, len: %d\n", p, ofs, rdlen1, len);
return p ? p : memchr(cb->buf /* + ofs - rdlen1 */, c, len - rdlen1);
}
return memchr(cb->buf + cb->rd + ofs, c, len);
}
#endif
}
static
int __LIBNFSVIV_CircBuf_strnlen(const unsigned char * const str, const int strsz)
{
const unsigned char * const p = (const unsigned char *)memchr(str, '\0', strsz);
return p ? (int)(p - str) : strsz;
}