forked from madler/sunzip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sunzip.c
1828 lines (1627 loc) · 62 KB
/
sunzip.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
/* sunzip.c -- streaming unzip for reading a zip file from stdin
Copyright (C) 2006, 2014, 2016, 2021 Mark Adler
version 0.5 6 Jan 2021
This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Mark Adler [email protected]
*/
/* Version history:
0.1 3 Jun 2006 First version -- verifies deflated and stored entries
0.2 4 Jun 2006 Add more PK signatures to reject or ignore
Allow for an Info-ZIP zip data descriptor signature
as well as a PKWare appnote data descriptor (no signature)
0.3 4 Jul 2006 Handle (by skipping) digital sig and zip64 end fields
Use read() from stdin for speed (unbuffered)
Use inflateBack() instead of inflate() for speed
Handle deflate64 entries with inflateBack9()
Add quiet (-q) and really quiet (-qq) options
If stdin not redirected, give command help
Write out files, add -t option to just test
Add -o option to overwrite existing files
Decode and apply MS-DOS timestamp
Decode and apply Unix timestamp extra fields
Allow for several different types of data descriptors
Handle bzip2 (method 12) decompression
Process zip64 local headers and use full lengths
Use central directory for names to allow conversion
Apply external attributes from central directory
Detect and create symbolic links
Catch user interrupt and delete temporary junk
0.31 7 Jul 2006 Get name from UTF-8 extra field if present
Fix zip64central offset bug
Change null-replacement character to underscore
Fix bad() error message mid-line handling
Fix stored length corruption bug
Verify that stored lengths are equal
Use larger input buffer when int type is large
Don't use calloc() when int type is large
0.32 14 Jul 2006 Consolidate and simplify extra field processing
Use more portable stat() structure definitions
Allow use of mktemp() when mkdtemp() is not available
0.33 23 Jul 2006 Replace futimes() with utimes() for portability
Fix bug in bzip2 decoding
Do two passes on command options to allow any order
Change pathbrk() return value to simplify usage
Protect against parent references ("..") in file names
Move name processing to after possibly getting UTF-8 name
0.34 15 Jan 2014 Add option to change the replacement character for ..
Fix bug in the handling of extended timestamps
Allow bit 11 to be set in general purpose flags
0.4 11 Jul 2016 Use blast for DCL imploded entries (method 10)
Add zlib license
0.5 6 Jan 2021 Add -r option to retain temporary files in the event of
an error.
*/
/* Notes:
- Compile and link sunzip with zlib 1.2.3 or later, infback9.c and
inftree9.c (found in the zlib source distribution in contrib/infback9),
blast.c from zlib 1.2.9 or later (found in contrib/blast), and libbzip2.
*/
/* To-do:
- Set EIGHTDOT3 for file systems that so restrict the file names
- Tailor path name operations for different operating systems
- Set the long data descriptor signature once it's specified by PKWare
(looks like that will never happen)
- Handle the entry name "-" differently? (Created by piped zip.)
*/
/* ----- External Functions, Types, and Constants Definitions ----- */
#include <stdio.h> /* printf(), fprintf(), fflush(), rename(), puts(), */
/* fopen(), fread(), fclose() */
#include <stdlib.h> /* exit(), malloc(), calloc(), free() */
#include <string.h> /* memcpy(), strcpy(), strlen(), strcmp() */
#include <ctype.h> /* tolower() */
#include <limits.h> /* LONG_MIN */
#include <time.h> /* mktime() */
#include <sys/time.h> /* utimes() */
#include <assert.h> /* assert() */
#include <signal.h> /* signal() */
#include <unistd.h> /* read(), close(), isatty(), chdir(), mkdtemp() or */
/* mktemp(), unlink(), rmdir(), symlink() */
#include <fcntl.h> /* open(), write(), O_WRONLY, O_CREAT, O_EXCL */
#include <sys/types.h> /* for mkdir(), stat() */
#include <sys/stat.h> /* mkdir(), stat() */
#include <errno.h> /* errno, EEXIST */
#include <dirent.h> /* opendir(), readdir(), closedir() */
#include "zlib.h" /* crc32(), z_stream, inflateBackInit(), */
/* inflateBack(), inflateBackEnd() */
#ifndef JUST_DEFLATE
#include "infback9.h" /* inflateBack9Init(), inflate9Back(), */
/* inflateBack9End() */
#include "blast.h" /* blast() */
#include "bzlib.h" /* BZ2_bzDecompressInit(), BZ2_bzDecompress(), */
/* BZ2_bzDecompressEnd() */
#endif
/* ----- Language Readability Enhancements (sez me) ----- */
#define local static
#define until(c) while(!(c))
/* ----- Operating System Configuration and Tailoring ----- */
/* hack to avoid end-of-line conversions */
#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
/* # include <fcntl.h> */
# include <io.h>
# define SET_BINARY_MODE(file) setmode(file, O_BINARY)
#else
# define SET_BINARY_MODE(file)
#endif
/* defines for the lengths of the integer types -- assure that longs are either
four bytes or greater than or equal to eight bytes in length */
#if UINT_MAX > 0xffff
# define BIGINT
#endif
#if ULONG_MAX >= 0xffffffffffffffffUL
# define BIGLONG
# if ULONG_MAX > 0xffffffffffffffffUL
# define GIANTLONG
# endif
#else
# if ULONG_MAX != 0xffffffffUL
# error Unexpected size of long data type
# endif
#endif
/* systems for which mkdtemp() is not provided */
#ifdef VMS
# define NOMKDTEMP
#endif
/* %% need to #define EIGHTDOT3 if limited to 8.3 names, e.g. DOS FAT */
/* ----- Operating System Specific Path Name Operations ----- */
/* %% This entire section should be tailored for various operating system
conventions for path name syntax -- currently set up for Unix */
/* Safe file name character to replace nulls with */
#define SAFESEP '_'
/* Unix path delimiter */
#define PATHDELIM '/'
/* Unix parent reference and replacement character (repeated) */
#define PARENT ".."
local int parrepl = '_';
/* convert a block into a string -- replace any zeros and terminate with a
zero; this assumes that blk is at least len+1 long */
local void tostr(char *blk, unsigned len)
{
while (len--) {
if (*blk == 0)
*blk = SAFESEP;
blk++;
}
*blk = 0;
}
/* see if it's a directory */
local int isdir(char *path)
{
size_t len;
len = strlen(path);
return len && path[len - 1] == PATHDELIM;
}
/* add a delimiter to a path and return a pointer to where to put the next
name (assumes that space is available) */
local char *pathcat(char *path)
{
size_t len;
len = strlen(path);
path += len;
if (len && path[-1] != PATHDELIM) {
*path++ = PATHDELIM;
*path = 0;
}
return path;
}
/* given a path, find the next path delimiter and return a pointer to the start
of it, or return a pointer to the end of the string if the name has no path
delimiter after it */
local char *pathbrk(char *path)
{
while (*path && *path != PATHDELIM)
path++;
return path;
}
/* given a path, skip over path delimiters, if any, to get to the start of the
next level name */
local char *pathtok(char *path)
{
while (*path == PATHDELIM)
path++;
return path;
}
/* secure the path name by removing root or device references, and any parent
directory references */
local char *guard(char *path)
{
int was;
char *left, *prev, *name, *cut;
/* skip leading path delimiters */
path = pathtok(path);
/* remove parent references */
left = path;
while (*left) {
/* if have a leading parent reference, replace it with safe separators
and then prevent deletion of that by moving past it */
cut = pathbrk(left);
was = *cut;
*cut = 0;
if (strcmp(left, PARENT) == 0) {
while (*left)
*left++ = parrepl;
*cut = was;
left = pathtok(cut);
continue;
}
*cut = was;
/* find non-leading parent reference, if any */
prev = left;
while (*(name = pathtok(cut))) {
cut = pathbrk(name);
was = *cut;
*cut = 0;
if (strcmp(name, PARENT) == 0) {
*cut = was;
break;
}
*cut = was;
prev = name;
}
if (*name == 0)
break; /* no more parent references, all done */
/* delete parent and parent reference and start over */
strcpy(prev, pathtok(cut));
}
/* return secured path */
return path;
}
/* convert name from source to current operating system, using the information
in the madeby value from the central directory -- name updated in place or
name is freed and a new malloc'ed space returned */
local char *tohere(char *name, unsigned madeby)
{
(void)madeby;
return name;
}
/* ----- Utility Operations ----- */
/* mkdtemp() template for temporary directory (if changed, adjust size of
tempdir[] below) */
#define TEMPDIR "_zXXXXXX"
/* temporary directory and possibly name -- big enough to hold TEMPDIR,
delimiter, the to36() result which is up to 13 characters, and the
null terminator (that's 12 + 1 + 13 + 1 == 27), adjust as needed for
path delimiters that are more than one character */
local char tempdir[27];
/* make a temporary directory (avoid race condition if mkdtemp available) */
local char *mktempdir(char *template)
{
#ifdef NOMKDTEMP
template = mktemp(template);
if (template != NULL && mkdir(template, 0700))
template = NULL;
return template;
#else
return mkdtemp(template);
#endif
}
/* remove temporary directory and contents */
local void rmtempdir(void)
{
char *temp;
DIR *dir;
struct dirent *ent;
/* if already removed or never made, then done */
if (tempdir[0] == 0)
return;
/* get just the directory name */
temp = pathbrk(tempdir);
*temp = 0;
/* scan the directory and remove its contents */
dir = opendir(tempdir);
if (dir != NULL) {
temp = pathcat(tempdir);
while ((ent = readdir(dir)) != NULL) {
strcpy(temp, ent->d_name);
unlink(tempdir);
}
closedir(dir);
}
/* remove the empty directory */
temp = pathbrk(tempdir);
*temp = 0;
rmdir(tempdir);
/* mark it as gone */
tempdir[0] = 0;
}
/* relocate the temporary directory contents */
local void mvtempdir(char *newtemp)
{
char *temp, *dest;
DIR *dir;
struct dirent *ent;
/* get just the temporary directory name */
temp = pathbrk(tempdir);
*temp = 0;
/* scan it and move the contents to newtemp */
dir = opendir(tempdir);
if (dir == NULL)
return;
temp = pathcat(tempdir);
dest = pathcat(newtemp);
while ((ent = readdir(dir)) != NULL) {
strcpy(temp, ent->d_name);
strcpy(dest, ent->d_name);
rename(tempdir, newtemp);
}
closedir(dir);
/* remove path delimiters from names */
temp = pathbrk(tempdir);
*temp = 0;
dest = pathbrk(newtemp);
*dest = 0;
}
/* true if in the middle of a line on stdout */
local int midline = 0;
/* true to retain temporary files in the event of an error */
local int retain = 0;
/* abort with an error message */
local int bye(char *why)
{
if (!retain)
rmtempdir(); /* don't leave a mess behind */
putchar(midline ? '\n' : '\r');
fflush(stdout);
fprintf(stderr, "sunzip abort: %s\n", why);
exit(1);
return 0; /* to make compiler happy -- will never get here */
}
/* convert an unsigned 32-bit integer to signed, even if long > 32 bits */
local long tolong(unsigned long val)
{
return (long)(val & 0x7fffffffUL) - (long)(val & 0x80000000UL);
}
/* allocate memory and abort on failure */
local void *alloc(size_t size)
{
void *got;
got = malloc(size);
if (got == NULL)
bye("out of memory");
return got;
}
/* allocate memory and duplicate a string */
local char *strnew(char *str)
{
char *ret;
ret = alloc(strlen(str) + 1);
strcpy(ret, str);
return ret;
}
/* Convert an 8-byte unsigned integer into a base 36 number using 0-9 and A-Z
for the digits -- the digits are written least to most significant with no
trailing zeros; if EIGHTDOT3 defined, put the digits in the 8.3 file name
format, and fail if the offset is too large to fit in 11 digits (~ 10^17) */
local char *to36(unsigned long low, unsigned long high)
{
unsigned rem;
#ifndef BIGLONG
unsigned tmp;
#endif
char *next;
static char num[14]; /* good for up to 2^64 - 1 */
/* check type lengths and input to protect num[] array */
#ifdef BIGLONG
#ifdef GIANTLONG
assert(low <= (1UL << 64) - 1);
#endif
assert(high == 0);
#endif
/* convert to base 36 */
next = num;
do {
#ifdef BIGLONG
/* use 64-bit division */
rem = low % 36;
low /= 36;
#else
/* divide 8-byte value by 36 (assumes 4-byte integers) */
/* special values are 2^32 div 36 == 119304647, 2^32 mod 36 == 4 */
rem = (unsigned)(high % 36);
high /= 36;
tmp = (unsigned)(low % 36);
low /= 36;
low += 119304647UL * rem; /* can't overflow */
tmp += rem << 2; /* rem times (2^32 mod 36) */
rem = tmp % 36;
tmp /= 36;
low += tmp; /* can't overflow here either */
#endif
#ifdef EIGHTDOT3
/* insert a dot for 8.3 names, and fail if more than 11 digits */
if (next - num == 8)
*next++ = '.';
if (next - num == 12)
bye("zip file too big for FAT file system names");
#endif
/* write a digit and divide again until nothing left */
*next++ = rem < 10 ? '0' + rem : 'A' + rem - 10;
} while (low || high);
/* terminate and return string */
*next = 0;
return num;
}
/* ----- Input/Output Operations ----- */
/* structure for output processing */
struct out {
int file; /* output file or -1 to not write */
unsigned long crc; /* accumulated CRC-32 of output */
unsigned long count; /* output byte count */
unsigned long count_hi; /* count overflow */
};
/* process inflate output, writing if requested */
local int put(void *out_desc, unsigned char *buf, unsigned len)
{
int wrote;
unsigned try;
struct out *out = (struct out *)out_desc;
#ifndef BIGINT
/* handle special inflateBack9() case for 64K len */
if (len == 0) {
len = 32768U;
put(out, buf, len);
buf += len;
}
#endif
/* update crc and output byte count */
out->crc = crc32(out->crc, buf, len);
out->count += len;
if (out->count < len)
out->count_hi++;
if (out->file != -1)
while (len) { /* loop since write() may not complete request */
try = len >= 32768U ? 16384 : len;
wrote = write(out->file, buf, try);
if (wrote == -1)
bye("write error");
len -= wrote;
buf += wrote;
}
return 0;
}
/* structure for input acquisition and processing */
struct in {
int file; /* input file */
unsigned char *buf; /* input buffer */
unsigned long count; /* input byte count */
unsigned long count_hi; /* count overflow */
unsigned long offset; /* input stream offset of end of buffer */
unsigned long offset_hi; /* input stream offset overflow */
};
/* Input buffer size (must fit in signed int) */
#ifdef BIGINT
# define CHUNK 131072
#else
# define CHUNK 16384
#endif
/* Load input buffer, assumed to be empty, and return bytes loaded and a
pointer to them. read() is called until the buffer is full, or until it
returns end-of-file or error. Abort program on error using bye(). */
local unsigned get(void *in_desc, unsigned char **buf)
{
int got;
unsigned want, len;
unsigned char *next;
struct in *in = (struct in *)in_desc;
next = in->buf;
if (buf != NULL)
*buf = next;
want = CHUNK;
do { /* loop since read() not assured to return request */
got = (int)read(in->file, next, want);
if (got == -1)
bye("zip file read error");
next += got;
want -= got;
} until (got == 0 || want == 0);
len = CHUNK - want; /* how much is in buffer */
in->count += len;
if (in->count < len)
in->count_hi++;
in->offset += len;
if (in->offset < len)
in->offset_hi++;
return len;
}
/* load input buffer, abort if EOF */
#define load(in) ((left = get(in, NULL)) == 0 ? \
bye("unexpected end of zip file") : (next = in->buf, left))
/* get one, two, or four bytes little-endian from the buffer, abort if EOF */
#define get1(in) (left == 0 ? load(in) : 0, left--, *next++)
#define get2(in) (tmp2 = get1(in), tmp2 + (get1(in) << 8))
#define get4(in) (tmp4 = get2(in), tmp4 + ((unsigned long)get2(in) << 16))
/* skip len bytes, abort if EOF */
#define skip(len, in) \
do { \
tmp4 = len; \
while (tmp4 > left) { \
tmp4 -= left; \
load(in); \
} \
left -= (unsigned)tmp4; \
next += (unsigned)tmp4; \
} while (0)
/* read header field into output buffer */
#define field(len, in) \
do { \
tmp2 = len; \
tmpp = outbuf; \
while (tmp2 > left) { \
memcpy(tmpp, next, left); \
tmp2 -= left; \
tmpp += left; \
load(in); \
} \
memcpy(tmpp, next, tmp2); \
left -= tmp2; \
next += tmp2; \
} while (0)
/* ----- File and Directory Operations ----- */
/* structure for directory cache, also saves times and pre-existence */
struct tree {
char *name; /* name of this directory */
int new; /* true if directory didn't already exist */
long acc; /* last access time */
long mod; /* last modification time */
struct tree *subs; /* list of subdirectories */
struct tree *next; /* next directory at this level */
};
/* directory cache */
local struct tree *root = NULL; /* linked list of top-level directories */
/* add a path to the cache -- if file true, then whatever comes after the last
delimiter is a file name, so don't make a directory with that name nor use
the access and modify times; note if the directory already existed or not */
local void graft(char *path, int file, long acc, long mod)
{
int ret, was = 0;
char *name, *cut;
struct tree **branch;
/* make the path safe before creating it */
path = guard(path);
if (*path == 0) /* if no name, nothing to do */
return;
/* process each name in the provided path */
name = path;
branch = &root;
for (;;) {
/* cut out next name in path */
cut = pathbrk(name);
was = *cut;
*cut = 0;
if (was == 0 && file)
break; /* don't do last name for a file */
/* search for that name in the list */
while (*branch != NULL) {
if (strcmp((*branch)->name, name) == 0)
break;
branch = &((*branch)->next);
}
/* if it's not in the list, add it and create */
if (*branch == NULL) {
*branch = alloc(sizeof(struct tree));
(*branch)->name = strnew(name);
(*branch)->acc = LONG_MIN;
(*branch)->mod = LONG_MIN;
(*branch)->subs = NULL;
(*branch)->next = NULL;
ret = mkdir(path, 0777);
if (ret && errno != EEXIST)
bye("write error");
(*branch)->new = ret == 0;
}
/* see if there's more path -- if not, then done */
if (was == 0)
break;
*cut = was; /* restore delimiter */
name = pathtok(cut); /* next name, skipping delimiters */
if (*name == 0) /* ended with a delimiter */
break;
/* go down a level for the next name */
branch = &((*branch)->subs);
}
/* if a directory, set the directory times for the last leaf */
if (!file && acc != LONG_MIN) {
(*branch)->acc = acc;
(*branch)->mod = mod;
}
return;
}
/* apply the saved directory times to the directories */
local void setdirtimes(struct tree *branch)
{
struct timeval times[2]; /* access and modify times */
while (branch != NULL) {
/* update the times for all the subdirectories of this directory */
if (branch->subs != NULL) {
if (chdir(branch->name) == 0) {
setdirtimes(branch->subs);
chdir("..");
}
}
/* then update the times for this directory if new and we have times */
if (branch->new && branch->acc != LONG_MIN) {
times[0].tv_sec = branch->acc;
times[0].tv_usec = 0;
times[1].tv_sec = branch->mod;
times[1].tv_usec = 0;
utimes(branch->name, times);
}
/* go to the next directory in the list */
branch = branch->next;
}
}
/* release the memory used by the branch (prune(&root) frees it all) */
local void prune(struct tree **branch)
{
struct tree *here, *next;
/* snip from the tree */
here = *branch;
*branch = NULL;
/* prune and then free each of the branches in the list */
while (here != NULL) {
prune(&(here->subs));
free(here->name);
next = here->next;
free(here);
here = next;
}
}
/* create a path if it doesn't exist (root paths allowed here) */
local void mkpath(char *path)
{
int was;
char *dir, *next;
/* scan path */
dir = pathtok(path); /* go to first name */
while ((was = *(next = pathbrk(dir))) != 0) {
*next = 0;
if (mkdir(path, 0777) && errno != EEXIST)
bye("write error");
*next = was;
dir = pathtok(next + 1); /* go to next name */
}
if (*dir && mkdir(path, 0777) && errno != EEXIST)
bye("write error");
}
/* see if the name exists and what it is */
local int ftype(char *name)
{
struct stat st;
if (lstat(name, &st))
return 0;
switch (st.st_mode & S_IFMT) {
case S_IFREG: return 1;
case S_IFDIR: return 2;
case S_IFLNK: return 3;
default: return 4;
}
}
/* ----- Time Operations ----- */
/* convert MS-DOS date and time to a Unix time, assuming current timezone
(you got a better idea?) */
local long dos2time(unsigned long dos)
{
struct tm tm;
if (dos == 0)
return (unsigned long)time(NULL);
tm.tm_year = ((int)(dos >> 25) & 0x7f) + 80;
tm.tm_mon = ((int)(dos >> 21) & 0xf) - 1;
tm.tm_mday = (int)(dos >> 16) & 0x1f;
tm.tm_hour = (int)(dos >> 11) & 0x1f;
tm.tm_min = (int)(dos >> 5) & 0x3f;
tm.tm_sec = (int)(dos << 1) & 0x3e;
tm.tm_isdst = -1; /* figure out if DST or not */
return (long)mktime(&tm);
}
/* ----- Zip Format Operations ----- */
/* list of local header offsets of skipped entries (encrypted or old method) */
unsigned long skipped; /* number of entries in list */
unsigned long skiplen; /* how many the list can hold */
unsigned long *skiplist; /* skipped entry list (allocated) */
/* add an entry to the skip list */
local void skipadd(unsigned long here, unsigned long here_hi)
{
unsigned long size;
#ifdef BIGLONG
(void)here_hi;
#endif
/* allocate or resize list if needed */
if (skipped == skiplen) {
skiplen = skiplen ? skiplen << 1 : 512;
#ifdef BIGLONG
size = skiplen * sizeof(unsigned long);
#else
size = skiplen << 3;
#endif
skiplist = skiplist == NULL ? malloc(size) : realloc(skiplist, size);
if (skiplist == NULL)
bye("out of memory");
}
/* add entry to list */
#ifdef BIGLONG
skiplist[skipped++] = here;
#else
skiplist[skipped << 1] = here;
skiplist[(skipped << 1) + 1] = here_hi;
skipped++;
#endif
}
/* binary search for entry in skip list (assumes ordered), return true if it's
there */
local int skipfind(unsigned long here, unsigned long here_hi)
{
unsigned long left, right, mid, low;
#ifndef BIGLONG
unsigned long high;
#else
(void)here_hi;
#endif
left = 1;
right = skipped;
while (left <= right) {
mid = left + ((right - left) >> 2);
#ifdef BIGLONG
low = skiplist[mid - 1];
#else
low = skiplist[(mid - 1) << 1];
high = skiplist[((mid - 1) << 1) + 1];
if (here_hi == high) {
#endif
if (here < low)
right = mid - 1;
else if (here > low)
left = mid + 1;
else
return 1;
#ifndef BIGLONG
}
else {
if (here_hi < high)
right = mid - 1;
else
left = mid + 1;
}
#endif
}
return 0;
}
/* pull two and four-byte little-endian integers from buffer */
#define little2(ptr) ((ptr)[0] + ((ptr)[1] << 8))
#define little4(ptr) (little2(ptr) + ((unsigned long)(little2(ptr + 2)) << 16))
/* find and return a specific extra block in an extra field */
local int getblock(unsigned id, unsigned char *extra, unsigned xlen,
unsigned char **block, unsigned *len)
{
unsigned thisid, size;
/* scan extra blocks */
while (xlen) {
/* get extra block id and data size */
if (xlen < 4)
return 0; /* invalid block */
thisid = little2(extra);
size = little2(extra + 2);
extra += 4;
xlen -= 4;
if (xlen < size)
return 0; /* invalid block */
/* check for requested id */
if (thisid == id) {
*block = extra;
*len = size;
return 1; /* got it! */
}
/* go to the next block */
extra += size;
xlen -= size;
}
return 0; /* wasn't there */
}
/* extract Unix access and modification times from extra field */
local void xtimes(unsigned char *extra, unsigned xlen, long *acc, long *mod)
{
unsigned len;
unsigned char *block;
/* process Extended Timestamp block */
if (getblock(0x5455, extra, xlen, &block, &len) && len &&
(*block & 1) == 1 && len >= ((unsigned)(*block & 2) << 1) + 5) {
*mod = tolong(little4(block + 1));
*acc = *block & 2 ? tolong(little4(block + 5)) : *mod;
return;
}
/* process PKWare Unix or Info-ZIP Type 1 Unix block */
if ((getblock(0x5855, extra, xlen, &block, &len) ||
getblock(0x000d, extra, xlen, &block, &len)) &&
len >= 8) {
*acc = tolong(little4(block));
*mod = tolong(little4(block + 4));
}
}
/* look for a zip64 block in the local header and update lengths, return
true if got 8-byte lengths */
local int zip64local(unsigned char *extra, unsigned xlen,
unsigned long *clen, unsigned long *clen_hi,
unsigned long *ulen, unsigned long *ulen_hi)
{
unsigned len;
unsigned char *block;
/* process zip64 Extended Information block */
if (getblock(0x0001, extra, xlen, &block, &len) && len >= 16) {
*ulen = little4(block);
*ulen_hi = little4(block + 4);
*clen = little4(block + 8);
*clen_hi = little4(block + 12);
return 1; /* got 8-byte lengths */
}
return 0; /* didn't get 8-byte lengths */
}
/* 32-bit marker for presence of 64-bit lengths */
#define LOW4 0xffffffffUL
/* look for a zip64 block in the central header and update offset */
local void zip64central(unsigned char *extra, unsigned xlen,
unsigned long clen, unsigned long ulen,
unsigned long *offset, unsigned long *offset_hi)
{
unsigned len;
unsigned char *block;
/* process zip64 Extended Information block */
if (getblock(0x0001, extra, xlen, &block, &len) && len >= 16) {
if (ulen == LOW4) {
block += 8;
len -= 8;
}
if (clen == LOW4) {
block += 8;
len -= 8;
}
if (len >= 8) {
*offset = little4(block);
*offset_hi = little4(block + 4);
}
}
}
/* look for a UTF-8 name in the central header */
local char *utf8name(unsigned char *extra, unsigned xlen,
unsigned long namecrc, char *name)
{
unsigned len;
unsigned char *block;
/* process and copy utf-8 name, discard old name */
if (getblock(0x7075, extra, xlen, &block, &len) && len > 5 &&
*block == 1 && little4(block + 1) == namecrc) {
free(name);
name = (char *)(block + 5);
tostr(name, len - 5);
name = strnew(name);
}
return name;
}
#ifndef JUST_DEFLATE
/* ----- BZip2 Decompression Operation ----- */
#define BZOUTSIZE 32768U /* passed outbuf better be this big */
/* decompress and write a bzip2 compressed entry */