unzip: fix a case where we find wrong CDE. Closes 8821
[oweals/busybox.git] / archival / unzip.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini unzip implementation for busybox
4  *
5  * Copyright (C) 2004 by Ed Clark
6  *
7  * Loosely based on original busybox unzip applet by Laurence Anderson.
8  * All options and features should work in this version.
9  *
10  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
11  */
12 /* For reference see
13  * http://www.pkware.com/company/standards/appnote/
14  * http://www.info-zip.org/pub/infozip/doc/appnote-iz-latest.zip
15  *
16  * TODO
17  * Zip64 + other methods
18  */
19
20 //config:config UNZIP
21 //config:       bool "unzip"
22 //config:       default y
23 //config:       help
24 //config:         unzip will list or extract files from a ZIP archive,
25 //config:         commonly found on DOS/WIN systems. The default behavior
26 //config:         (with no options) is to extract the archive into the
27 //config:         current directory. Use the `-d' option to extract to a
28 //config:         directory of your choice.
29
30 //applet:IF_UNZIP(APPLET(unzip, BB_DIR_USR_BIN, BB_SUID_DROP))
31 //kbuild:lib-$(CONFIG_UNZIP) += unzip.o
32
33 //usage:#define unzip_trivial_usage
34 //usage:       "[-lnopq] FILE[.zip] [FILE]... [-x FILE...] [-d DIR]"
35 //usage:#define unzip_full_usage "\n\n"
36 //usage:       "Extract FILEs from ZIP archive\n"
37 //usage:     "\n        -l      List contents (with -q for short form)"
38 //usage:     "\n        -n      Never overwrite files (default: ask)"
39 //usage:     "\n        -o      Overwrite"
40 //usage:     "\n        -p      Print to stdout"
41 //usage:     "\n        -q      Quiet"
42 //usage:     "\n        -x FILE Exclude FILEs"
43 //usage:     "\n        -d DIR  Extract into DIR"
44
45 #include "libbb.h"
46 #include "bb_archive.h"
47
48 #if 0
49 # define dbg(...) bb_error_msg(__VA_ARGS__)
50 #else
51 # define dbg(...) ((void)0)
52 #endif
53
54 enum {
55 #if BB_BIG_ENDIAN
56         ZIP_FILEHEADER_MAGIC = 0x504b0304,
57         ZIP_CDF_MAGIC        = 0x504b0102, /* central directory's file header */
58         ZIP_CDE_MAGIC        = 0x504b0506, /* "end of central directory" record */
59         ZIP_DD_MAGIC         = 0x504b0708,
60 #else
61         ZIP_FILEHEADER_MAGIC = 0x04034b50,
62         ZIP_CDF_MAGIC        = 0x02014b50,
63         ZIP_CDE_MAGIC        = 0x06054b50,
64         ZIP_DD_MAGIC         = 0x08074b50,
65 #endif
66 };
67
68 #define ZIP_HEADER_LEN 26
69
70 typedef union {
71         uint8_t raw[ZIP_HEADER_LEN];
72         struct {
73                 uint16_t version;               /* 0-1 */
74                 uint16_t zip_flags;             /* 2-3 */
75                 uint16_t method;                /* 4-5 */
76                 uint16_t modtime;               /* 6-7 */
77                 uint16_t moddate;               /* 8-9 */
78                 uint32_t crc32 PACKED;          /* 10-13 */
79                 uint32_t cmpsize PACKED;        /* 14-17 */
80                 uint32_t ucmpsize PACKED;       /* 18-21 */
81                 uint16_t filename_len;          /* 22-23 */
82                 uint16_t extra_len;             /* 24-25 */
83         } formatted PACKED;
84 } zip_header_t; /* PACKED - gcc 4.2.1 doesn't like it (spews warning) */
85
86 /* Check the offset of the last element, not the length.  This leniency
87  * allows for poor packing, whereby the overall struct may be too long,
88  * even though the elements are all in the right place.
89  */
90 struct BUG_zip_header_must_be_26_bytes {
91         char BUG_zip_header_must_be_26_bytes[
92                 offsetof(zip_header_t, formatted.extra_len) + 2
93                         == ZIP_HEADER_LEN ? 1 : -1];
94 };
95
96 #define FIX_ENDIANNESS_ZIP(zip_header) do { \
97         (zip_header).formatted.version      = SWAP_LE16((zip_header).formatted.version     ); \
98         (zip_header).formatted.method       = SWAP_LE16((zip_header).formatted.method      ); \
99         (zip_header).formatted.modtime      = SWAP_LE16((zip_header).formatted.modtime     ); \
100         (zip_header).formatted.moddate      = SWAP_LE16((zip_header).formatted.moddate     ); \
101         (zip_header).formatted.crc32        = SWAP_LE32((zip_header).formatted.crc32       ); \
102         (zip_header).formatted.cmpsize      = SWAP_LE32((zip_header).formatted.cmpsize     ); \
103         (zip_header).formatted.ucmpsize     = SWAP_LE32((zip_header).formatted.ucmpsize    ); \
104         (zip_header).formatted.filename_len = SWAP_LE16((zip_header).formatted.filename_len); \
105         (zip_header).formatted.extra_len    = SWAP_LE16((zip_header).formatted.extra_len   ); \
106 } while (0)
107
108 #define CDF_HEADER_LEN 42
109
110 typedef union {
111         uint8_t raw[CDF_HEADER_LEN];
112         struct {
113                 /* uint32_t signature; 50 4b 01 02 */
114                 uint16_t version_made_by;       /* 0-1 */
115                 uint16_t version_needed;        /* 2-3 */
116                 uint16_t cdf_flags;             /* 4-5 */
117                 uint16_t method;                /* 6-7 */
118                 uint16_t mtime;                 /* 8-9 */
119                 uint16_t mdate;                 /* 10-11 */
120                 uint32_t crc32;                 /* 12-15 */
121                 uint32_t cmpsize;               /* 16-19 */
122                 uint32_t ucmpsize;              /* 20-23 */
123                 uint16_t file_name_length;      /* 24-25 */
124                 uint16_t extra_field_length;    /* 26-27 */
125                 uint16_t file_comment_length;   /* 28-29 */
126                 uint16_t disk_number_start;     /* 30-31 */
127                 uint16_t internal_file_attributes; /* 32-33 */
128                 uint32_t external_file_attributes PACKED; /* 34-37 */
129                 uint32_t relative_offset_of_local_header PACKED; /* 38-41 */
130         } formatted PACKED;
131 } cdf_header_t;
132
133 struct BUG_cdf_header_must_be_42_bytes {
134         char BUG_cdf_header_must_be_42_bytes[
135                 offsetof(cdf_header_t, formatted.relative_offset_of_local_header) + 4
136                         == CDF_HEADER_LEN ? 1 : -1];
137 };
138
139 #define FIX_ENDIANNESS_CDF(cdf_header) do { \
140         (cdf_header).formatted.crc32        = SWAP_LE32((cdf_header).formatted.crc32       ); \
141         (cdf_header).formatted.cmpsize      = SWAP_LE32((cdf_header).formatted.cmpsize     ); \
142         (cdf_header).formatted.ucmpsize     = SWAP_LE32((cdf_header).formatted.ucmpsize    ); \
143         (cdf_header).formatted.file_name_length = SWAP_LE16((cdf_header).formatted.file_name_length); \
144         (cdf_header).formatted.extra_field_length = SWAP_LE16((cdf_header).formatted.extra_field_length); \
145         (cdf_header).formatted.file_comment_length = SWAP_LE16((cdf_header).formatted.file_comment_length); \
146         IF_DESKTOP( \
147         (cdf_header).formatted.version_made_by = SWAP_LE16((cdf_header).formatted.version_made_by); \
148         (cdf_header).formatted.external_file_attributes = SWAP_LE32((cdf_header).formatted.external_file_attributes); \
149         ) \
150 } while (0)
151
152 #define CDE_HEADER_LEN 16
153
154 typedef union {
155         uint8_t raw[CDE_HEADER_LEN];
156         struct {
157                 /* uint32_t signature; 50 4b 05 06 */
158                 uint16_t this_disk_no;
159                 uint16_t disk_with_cdf_no;
160                 uint16_t cdf_entries_on_this_disk;
161                 uint16_t cdf_entries_total;
162                 uint32_t cdf_size;
163                 uint32_t cdf_offset;
164                 /* uint16_t file_comment_length; */
165                 /* .ZIP file comment (variable size) */
166         } formatted PACKED;
167 } cde_header_t;
168
169 struct BUG_cde_header_must_be_16_bytes {
170         char BUG_cde_header_must_be_16_bytes[
171                 sizeof(cde_header_t) == CDE_HEADER_LEN ? 1 : -1];
172 };
173
174 #define FIX_ENDIANNESS_CDE(cde_header) do { \
175         (cde_header).formatted.cdf_offset = SWAP_LE32((cde_header).formatted.cdf_offset); \
176 } while (0)
177
178 enum { zip_fd = 3 };
179
180
181 #if ENABLE_DESKTOP
182
183 /* Seen in the wild:
184  * Self-extracting PRO2K3XP_32.exe contains 19078464 byte zip archive,
185  * where CDE was nearly 48 kbytes before EOF.
186  * (Surprisingly, it also apparently has *another* CDE structure
187  * closer to the end, with bogus cdf_offset).
188  * To make extraction work, bumped PEEK_FROM_END from 16k to 64k.
189  */
190 #define PEEK_FROM_END (64*1024)
191
192 /* This value means that we failed to find CDF */
193 #define BAD_CDF_OFFSET ((uint32_t)0xffffffff)
194
195 /* NB: does not preserve file position! */
196 static uint32_t find_cdf_offset(void)
197 {
198         cde_header_t cde_header;
199         unsigned char *p;
200         off_t end;
201         unsigned char *buf = xzalloc(PEEK_FROM_END);
202         uint32_t found;
203
204         end = xlseek(zip_fd, 0, SEEK_END);
205         end -= PEEK_FROM_END;
206         if (end < 0)
207                 end = 0;
208         dbg("Looking for cdf_offset starting from 0x%"OFF_FMT"x", end);
209         xlseek(zip_fd, end, SEEK_SET);
210         full_read(zip_fd, buf, PEEK_FROM_END);
211
212         found = BAD_CDF_OFFSET;
213         p = buf;
214         while (p <= buf + PEEK_FROM_END - CDE_HEADER_LEN - 4) {
215                 if (*p != 'P') {
216                         p++;
217                         continue;
218                 }
219                 if (*++p != 'K')
220                         continue;
221                 if (*++p != 5)
222                         continue;
223                 if (*++p != 6)
224                         continue;
225                 /* we found CDE! */
226                 memcpy(cde_header.raw, p + 1, CDE_HEADER_LEN);
227                 FIX_ENDIANNESS_CDE(cde_header);
228                 /*
229                  * I've seen .ZIP files with seemingly valid CDEs
230                  * where cdf_offset points past EOF - ??
231                  * This check ignores such CDEs:
232                  */
233                 if (cde_header.formatted.cdf_offset < end + (p - buf)) {
234                         found = cde_header.formatted.cdf_offset;
235                         dbg("Possible cdf_offset:0x%x at 0x%"OFF_FMT"x",
236                                 (unsigned)found, end + (p-3 - buf));
237                         dbg("  cdf_offset+cdf_size:0x%x",
238                                 (unsigned)(found + SWAP_LE32(cde_header.formatted.cdf_size)));
239                         /*
240                          * We do not "break" here because only the last CDE is valid.
241                          * I've seen a .zip archive which contained a .zip file,
242                          * uncompressed, and taking the first CDE was using
243                          * the CDE inside that file!
244                          */
245                 }
246         }
247         free(buf);
248         dbg("Found cdf_offset:0x%x", (unsigned)found);
249         return found;
250 };
251
252 static uint32_t read_next_cdf(uint32_t cdf_offset, cdf_header_t *cdf_ptr)
253 {
254         off_t org;
255
256         org = xlseek(zip_fd, 0, SEEK_CUR);
257
258         if (!cdf_offset)
259                 cdf_offset = find_cdf_offset();
260
261         if (cdf_offset != BAD_CDF_OFFSET) {
262                 dbg("Reading CDF at 0x%x", (unsigned)cdf_offset);
263                 xlseek(zip_fd, cdf_offset + 4, SEEK_SET);
264                 xread(zip_fd, cdf_ptr->raw, CDF_HEADER_LEN);
265                 FIX_ENDIANNESS_CDF(*cdf_ptr);
266                 dbg("file_name_length:%u", (unsigned)cdf_ptr->formatted.file_name_length);
267                 dbg("extra_field_length:%u", (unsigned)cdf_ptr->formatted.extra_field_length);
268                 dbg("file_comment_length:%u", (unsigned)cdf_ptr->formatted.file_comment_length);
269                 cdf_offset += 4 + CDF_HEADER_LEN
270                         + cdf_ptr->formatted.file_name_length
271                         + cdf_ptr->formatted.extra_field_length
272                         + cdf_ptr->formatted.file_comment_length;
273         }
274
275         xlseek(zip_fd, org, SEEK_SET);
276         return cdf_offset;
277 };
278 #endif
279
280 static void unzip_skip(off_t skip)
281 {
282         if (skip != 0)
283                 if (lseek(zip_fd, skip, SEEK_CUR) == (off_t)-1)
284                         bb_copyfd_exact_size(zip_fd, -1, skip);
285 }
286
287 static void unzip_create_leading_dirs(const char *fn)
288 {
289         /* Create all leading directories */
290         char *name = xstrdup(fn);
291         if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
292                 xfunc_die(); /* bb_make_directory is noisy */
293         }
294         free(name);
295 }
296
297 static void unzip_extract(zip_header_t *zip_header, int dst_fd)
298 {
299         if (zip_header->formatted.method == 0) {
300                 /* Method 0 - stored (not compressed) */
301                 off_t size = zip_header->formatted.ucmpsize;
302                 if (size)
303                         bb_copyfd_exact_size(zip_fd, dst_fd, size);
304         } else {
305                 /* Method 8 - inflate */
306                 transformer_state_t xstate;
307                 init_transformer_state(&xstate);
308                 xstate.bytes_in = zip_header->formatted.cmpsize;
309                 xstate.src_fd = zip_fd;
310                 xstate.dst_fd = dst_fd;
311                 if (inflate_unzip(&xstate) < 0)
312                         bb_error_msg_and_die("inflate error");
313                 /* Validate decompression - crc */
314                 if (zip_header->formatted.crc32 != (xstate.crc32 ^ 0xffffffffL)) {
315                         bb_error_msg_and_die("crc error");
316                 }
317                 /* Validate decompression - size */
318                 if (zip_header->formatted.ucmpsize != xstate.bytes_out) {
319                         /* Don't die. Who knows, maybe len calculation
320                          * was botched somewhere. After all, crc matched! */
321                         bb_error_msg("bad length");
322                 }
323         }
324 }
325
326 static void my_fgets80(char *buf80)
327 {
328         fflush_all();
329         if (!fgets(buf80, 80, stdin)) {
330                 bb_perror_msg_and_die("can't read standard input");
331         }
332 }
333
334 int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
335 int unzip_main(int argc, char **argv)
336 {
337         enum { O_PROMPT, O_NEVER, O_ALWAYS };
338
339         zip_header_t zip_header;
340         smallint quiet = 0;
341         IF_NOT_DESKTOP(const) smallint verbose = 0;
342         smallint listing = 0;
343         smallint overwrite = O_PROMPT;
344         smallint x_opt_seen;
345 #if ENABLE_DESKTOP
346         uint32_t cdf_offset;
347 #endif
348         unsigned long total_usize;
349         unsigned long total_size;
350         unsigned total_entries;
351         int dst_fd = -1;
352         char *src_fn = NULL;
353         char *dst_fn = NULL;
354         llist_t *zaccept = NULL;
355         llist_t *zreject = NULL;
356         char *base_dir = NULL;
357         int i, opt;
358         char key_buf[80]; /* must match size used by my_fgets80 */
359         struct stat stat_buf;
360
361 /* -q, -l and -v: UnZip 5.52 of 28 February 2005, by Info-ZIP:
362  *
363  * # /usr/bin/unzip -qq -v decompress_unlzma.i.zip
364  *   204372  Defl:N    35278  83%  09-06-09 14:23  0d056252  decompress_unlzma.i
365  * # /usr/bin/unzip -q -v decompress_unlzma.i.zip
366  *  Length   Method    Size  Ratio   Date   Time   CRC-32    Name
367  * --------  ------  ------- -----   ----   ----   ------    ----
368  *   204372  Defl:N    35278  83%  09-06-09 14:23  0d056252  decompress_unlzma.i
369  * --------          -------  ---                            -------
370  *   204372            35278  83%                            1 file
371  * # /usr/bin/unzip -v decompress_unlzma.i.zip
372  * Archive:  decompress_unlzma.i.zip
373  *  Length   Method    Size  Ratio   Date   Time   CRC-32    Name
374  * --------  ------  ------- -----   ----   ----   ------    ----
375  *   204372  Defl:N    35278  83%  09-06-09 14:23  0d056252  decompress_unlzma.i
376  * --------          -------  ---                            -------
377  *   204372            35278  83%                            1 file
378  * # unzip -v decompress_unlzma.i.zip
379  * Archive:  decompress_unlzma.i.zip
380  *   Length     Date   Time    Name
381  *  --------    ----   ----    ----
382  *    204372  09-06-09 14:23   decompress_unlzma.i
383  *  --------                   -------
384  *    204372                   1 files
385  * # /usr/bin/unzip -l -qq decompress_unlzma.i.zip
386  *    204372  09-06-09 14:23   decompress_unlzma.i
387  * # /usr/bin/unzip -l -q decompress_unlzma.i.zip
388  *   Length     Date   Time    Name
389  *  --------    ----   ----    ----
390  *    204372  09-06-09 14:23   decompress_unlzma.i
391  *  --------                   -------
392  *    204372                   1 file
393  * # /usr/bin/unzip -l decompress_unlzma.i.zip
394  * Archive:  decompress_unlzma.i.zip
395  *   Length     Date   Time    Name
396  *  --------    ----   ----    ----
397  *    204372  09-06-09 14:23   decompress_unlzma.i
398  *  --------                   -------
399  *    204372                   1 file
400  */
401
402         x_opt_seen = 0;
403         /* '-' makes getopt return 1 for non-options */
404         while ((opt = getopt(argc, argv, "-d:lnopqxv")) != -1) {
405                 switch (opt) {
406                 case 'd':  /* Extract to base directory */
407                         base_dir = optarg;
408                         break;
409
410                 case 'l': /* List */
411                         listing = 1;
412                         break;
413
414                 case 'n': /* Never overwrite existing files */
415                         overwrite = O_NEVER;
416                         break;
417
418                 case 'o': /* Always overwrite existing files */
419                         overwrite = O_ALWAYS;
420                         break;
421
422                 case 'p': /* Extract files to stdout and fall through to set verbosity */
423                         dst_fd = STDOUT_FILENO;
424
425                 case 'q': /* Be quiet */
426                         quiet++;
427                         break;
428
429                 case 'v': /* Verbose list */
430                         IF_DESKTOP(verbose++;)
431                         listing = 1;
432                         break;
433
434                 case 'x':
435                         x_opt_seen = 1;
436                         break;
437
438                 case 1:
439                         if (!src_fn) {
440                                 /* The zip file */
441                                 /* +5: space for ".zip" and NUL */
442                                 src_fn = xmalloc(strlen(optarg) + 5);
443                                 strcpy(src_fn, optarg);
444                         } else if (!x_opt_seen) {
445                                 /* Include files */
446                                 llist_add_to(&zaccept, optarg);
447                         } else {
448                                 /* Exclude files */
449                                 llist_add_to(&zreject, optarg);
450                         }
451                         break;
452
453                 default:
454                         bb_show_usage();
455                 }
456         }
457
458 #ifndef __GLIBC__
459         /*
460          * This code is needed for non-GNU getopt
461          * which doesn't understand "-" in option string.
462          * The -x option won't work properly in this case:
463          * "unzip a.zip q -x w e" will be interpreted as
464          * "unzip a.zip q w e -x" = "unzip a.zip q w e"
465          */
466         argv += optind;
467         if (argv[0]) {
468                 /* +5: space for ".zip" and NUL */
469                 src_fn = xmalloc(strlen(argv[0]) + 5);
470                 strcpy(src_fn, argv[0]);
471                 while (*++argv)
472                         llist_add_to(&zaccept, *argv);
473         }
474 #endif
475
476         if (!src_fn) {
477                 bb_show_usage();
478         }
479
480         /* Open input file */
481         if (LONE_DASH(src_fn)) {
482                 xdup2(STDIN_FILENO, zip_fd);
483                 /* Cannot use prompt mode since zip data is arriving on STDIN */
484                 if (overwrite == O_PROMPT)
485                         overwrite = O_NEVER;
486         } else {
487                 static const char extn[][5] = { ".zip", ".ZIP" };
488                 char *ext = src_fn + strlen(src_fn);
489                 int src_fd;
490
491                 i = 0;
492                 for (;;) {
493                         src_fd = open(src_fn, O_RDONLY);
494                         if (src_fd >= 0)
495                                 break;
496                         if (++i > 2) {
497                                 *ext = '\0';
498                                 bb_error_msg_and_die("can't open %s[.zip]", src_fn);
499                         }
500                         strcpy(ext, extn[i - 1]);
501                 }
502                 xmove_fd(src_fd, zip_fd);
503         }
504
505         /* Change dir if necessary */
506         if (base_dir)
507                 xchdir(base_dir);
508
509         if (quiet <= 1) { /* not -qq */
510                 if (quiet == 0)
511                         printf("Archive:  %s\n", src_fn);
512                 if (listing) {
513                         puts(verbose ?
514                                 " Length   Method    Size  Ratio   Date   Time   CRC-32    Name\n"
515                                 "--------  ------  ------- -----   ----   ----   ------    ----"
516                                 :
517                                 "  Length     Date   Time    Name\n"
518                                 " --------    ----   ----    ----"
519                                 );
520                 }
521         }
522
523 /* Example of an archive with one 0-byte long file named 'z'
524  * created by Zip 2.31 on Unix:
525  * 0000 [50 4b]03 04 0a 00 00 00 00 00 42 1a b8 3c 00 00 |PK........B..<..|
526  *       sig........ vneed flags compr mtime mdate crc32>
527  * 0010  00 00 00 00 00 00 00 00 00 00 01 00 15 00 7a 55 |..............zU|
528  *      >..... csize...... usize...... fnlen exlen fn ex>
529  * 0020  54 09 00 03 cc d3 f9 4b cc d3 f9 4b 55 78 04 00 |T......K...KUx..|
530  *      >tra_field......................................
531  * 0030  00 00 00 00[50 4b]01 02 17 03 0a 00 00 00 00 00 |....PK..........|
532  *       ........... sig........ vmade vneed flags compr
533  * 0040  42 1a b8 3c 00 00 00 00 00 00 00 00 00 00 00 00 |B..<............|
534  *       mtime mdate crc32...... csize...... usize......
535  * 0050  01 00 0d 00 00 00 00 00 00 00 00 00 a4 81 00 00 |................|
536  *       fnlen exlen clen. dnum. iattr eattr...... relofs> (eattr = rw-r--r--)
537  * 0060  00 00 7a 55 54 05 00 03 cc d3 f9 4b 55 78 00 00 |..zUT......KUx..|
538  *      >..... fn extra_field...........................
539  * 0070 [50 4b]05 06 00 00 00 00 01 00 01 00 3c 00 00 00 |PK..........<...|
540  * 0080  34 00 00 00 00 00                               |4.....|
541  */
542         total_usize = 0;
543         total_size = 0;
544         total_entries = 0;
545 #if ENABLE_DESKTOP
546         cdf_offset = 0;
547 #endif
548         while (1) {
549                 uint32_t magic;
550                 mode_t dir_mode = 0777;
551 #if ENABLE_DESKTOP
552                 mode_t file_mode = 0666;
553 #endif
554
555                 /* Check magic number */
556                 xread(zip_fd, &magic, 4);
557                 /* Central directory? It's at the end, so exit */
558                 if (magic == ZIP_CDF_MAGIC) {
559                         dbg("got ZIP_CDF_MAGIC");
560                         break;
561                 }
562 #if ENABLE_DESKTOP
563                 /* Data descriptor? It was a streaming file, go on */
564                 if (magic == ZIP_DD_MAGIC) {
565                         dbg("got ZIP_DD_MAGIC");
566                         /* skip over duplicate crc32, cmpsize and ucmpsize */
567                         unzip_skip(3 * 4);
568                         continue;
569                 }
570 #endif
571                 if (magic != ZIP_FILEHEADER_MAGIC)
572                         bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
573                 dbg("got ZIP_FILEHEADER_MAGIC");
574
575                 /* Read the file header */
576                 xread(zip_fd, zip_header.raw, ZIP_HEADER_LEN);
577                 FIX_ENDIANNESS_ZIP(zip_header);
578                 if ((zip_header.formatted.method != 0) && (zip_header.formatted.method != 8)) {
579                         bb_error_msg_and_die("unsupported method %d", zip_header.formatted.method);
580                 }
581 #if !ENABLE_DESKTOP
582                 if (zip_header.formatted.zip_flags & SWAP_LE16(0x0009)) {
583                         bb_error_msg_and_die("zip flags 1 and 8 are not supported");
584                 }
585 #else
586                 if (zip_header.formatted.zip_flags & SWAP_LE16(0x0001)) {
587                         /* 0x0001 - encrypted */
588                         bb_error_msg_and_die("zip flag 1 (encryption) is not supported");
589                 }
590
591                 if (cdf_offset != BAD_CDF_OFFSET) {
592                         cdf_header_t cdf_header;
593                         cdf_offset = read_next_cdf(cdf_offset, &cdf_header);
594                         /*
595                          * Note: cdf_offset can become BAD_CDF_OFFSET after the above call.
596                          */
597                         if (zip_header.formatted.zip_flags & SWAP_LE16(0x0008)) {
598                                 /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
599                                  * only from Central Directory. See unzip_doc.txt
600                                  */
601                                 zip_header.formatted.crc32    = cdf_header.formatted.crc32;
602                                 zip_header.formatted.cmpsize  = cdf_header.formatted.cmpsize;
603                                 zip_header.formatted.ucmpsize = cdf_header.formatted.ucmpsize;
604                         }
605                         if ((cdf_header.formatted.version_made_by >> 8) == 3) {
606                                 /* This archive is created on Unix */
607                                 dir_mode = file_mode = (cdf_header.formatted.external_file_attributes >> 16);
608                         }
609                 }
610                 if (cdf_offset == BAD_CDF_OFFSET
611                  && (zip_header.formatted.zip_flags & SWAP_LE16(0x0008))
612                 ) {
613                         /* If it's a streaming zip, we _require_ CDF */
614                         bb_error_msg_and_die("can't find file table");
615                 }
616 #endif
617
618                 /* Read filename */
619                 free(dst_fn);
620                 dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
621                 xread(zip_fd, dst_fn, zip_header.formatted.filename_len);
622
623                 /* Skip extra header bytes */
624                 unzip_skip(zip_header.formatted.extra_len);
625
626                 /* Guard against "/abspath", "/../" and similar attacks */
627                 overlapping_strcpy(dst_fn, strip_unsafe_prefix(dst_fn));
628
629                 /* Filter zip entries */
630                 if (find_list_entry(zreject, dst_fn)
631                  || (zaccept && !find_list_entry(zaccept, dst_fn))
632                 ) { /* Skip entry */
633                         i = 'n';
634                 } else {
635                         if (listing) {
636                                 /* List entry */
637                                 unsigned dostime = zip_header.formatted.modtime | (zip_header.formatted.moddate << 16);
638                                 if (!verbose) {
639                                         //      "  Length     Date   Time    Name\n"
640                                         //      " --------    ----   ----    ----"
641                                         printf(       "%9u  %02u-%02u-%02u %02u:%02u   %s\n",
642                                                 (unsigned)zip_header.formatted.ucmpsize,
643                                                 (dostime & 0x01e00000) >> 21,
644                                                 (dostime & 0x001f0000) >> 16,
645                                                 (((dostime & 0xfe000000) >> 25) + 1980) % 100,
646                                                 (dostime & 0x0000f800) >> 11,
647                                                 (dostime & 0x000007e0) >> 5,
648                                                 dst_fn);
649                                         total_usize += zip_header.formatted.ucmpsize;
650                                 } else {
651                                         unsigned long percents = zip_header.formatted.ucmpsize - zip_header.formatted.cmpsize;
652                                         percents = percents * 100;
653                                         if (zip_header.formatted.ucmpsize)
654                                                 percents /= zip_header.formatted.ucmpsize;
655                                         //      " Length   Method    Size  Ratio   Date   Time   CRC-32    Name\n"
656                                         //      "--------  ------  ------- -----   ----   ----   ------    ----"
657                                         printf(      "%8u  Defl:N"    "%9u%4u%%  %02u-%02u-%02u %02u:%02u  %08x  %s\n",
658                                                 (unsigned)zip_header.formatted.ucmpsize,
659                                                 (unsigned)zip_header.formatted.cmpsize,
660                                                 (unsigned)percents,
661                                                 (dostime & 0x01e00000) >> 21,
662                                                 (dostime & 0x001f0000) >> 16,
663                                                 (((dostime & 0xfe000000) >> 25) + 1980) % 100,
664                                                 (dostime & 0x0000f800) >> 11,
665                                                 (dostime & 0x000007e0) >> 5,
666                                                 zip_header.formatted.crc32,
667                                                 dst_fn);
668                                         total_usize += zip_header.formatted.ucmpsize;
669                                         total_size += zip_header.formatted.cmpsize;
670                                 }
671                                 i = 'n';
672                         } else if (dst_fd == STDOUT_FILENO) {
673                                 /* Extracting to STDOUT */
674                                 i = -1;
675                         } else if (last_char_is(dst_fn, '/')) {
676                                 /* Extract directory */
677                                 if (stat(dst_fn, &stat_buf) == -1) {
678                                         if (errno != ENOENT) {
679                                                 bb_perror_msg_and_die("can't stat '%s'", dst_fn);
680                                         }
681                                         if (!quiet) {
682                                                 printf("   creating: %s\n", dst_fn);
683                                         }
684                                         unzip_create_leading_dirs(dst_fn);
685                                         if (bb_make_directory(dst_fn, dir_mode, FILEUTILS_IGNORE_CHMOD_ERR)) {
686                                                 xfunc_die();
687                                         }
688                                 } else {
689                                         if (!S_ISDIR(stat_buf.st_mode)) {
690                                                 bb_error_msg_and_die("'%s' exists but is not a %s",
691                                                         dst_fn, "directory");
692                                         }
693                                 }
694                                 i = 'n';
695                         } else {
696                                 /* Extract file */
697  check_file:
698                                 if (stat(dst_fn, &stat_buf) == -1) {
699                                         /* File does not exist */
700                                         if (errno != ENOENT) {
701                                                 bb_perror_msg_and_die("can't stat '%s'", dst_fn);
702                                         }
703                                         i = 'y';
704                                 } else {
705                                         /* File already exists */
706                                         if (overwrite == O_NEVER) {
707                                                 i = 'n';
708                                         } else if (S_ISREG(stat_buf.st_mode)) {
709                                                 /* File is regular file */
710                                                 if (overwrite == O_ALWAYS) {
711                                                         i = 'y';
712                                                 } else {
713                                                         printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
714                                                         my_fgets80(key_buf);
715                                                         i = key_buf[0];
716                                                 }
717                                         } else {
718                                                 /* File is not regular file */
719                                                 bb_error_msg_and_die("'%s' exists but is not a %s",
720                                                         dst_fn, "regular file");
721                                         }
722                                 }
723                         }
724                 }
725
726                 switch (i) {
727                 case 'A':
728                         overwrite = O_ALWAYS;
729                 case 'y': /* Open file and fall into unzip */
730                         unzip_create_leading_dirs(dst_fn);
731 #if ENABLE_DESKTOP
732                         dst_fd = xopen3(dst_fn, O_WRONLY | O_CREAT | O_TRUNC, file_mode);
733 #else
734                         dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
735 #endif
736                 case -1: /* Unzip */
737                         if (!quiet) {
738                                 printf("  inflating: %s\n", dst_fn);
739                         }
740                         unzip_extract(&zip_header, dst_fd);
741                         if (dst_fd != STDOUT_FILENO) {
742                                 /* closing STDOUT is potentially bad for future business */
743                                 close(dst_fd);
744                         }
745                         break;
746
747                 case 'N':
748                         overwrite = O_NEVER;
749                 case 'n':
750                         /* Skip entry data */
751                         unzip_skip(zip_header.formatted.cmpsize);
752                         break;
753
754                 case 'r':
755                         /* Prompt for new name */
756                         printf("new name: ");
757                         my_fgets80(key_buf);
758                         free(dst_fn);
759                         dst_fn = xstrdup(key_buf);
760                         chomp(dst_fn);
761                         goto check_file;
762
763                 default:
764                         printf("error: invalid response [%c]\n", (char)i);
765                         goto check_file;
766                 }
767
768                 total_entries++;
769         }
770
771         if (listing && quiet <= 1) {
772                 if (!verbose) {
773                         //      "  Length     Date   Time    Name\n"
774                         //      " --------    ----   ----    ----"
775                         printf( " --------                   -------\n"
776                                 "%9lu"   "                   %u files\n",
777                                 total_usize, total_entries);
778                 } else {
779                         unsigned long percents = total_usize - total_size;
780                         percents = percents * 100;
781                         if (total_usize)
782                                 percents /= total_usize;
783                         //      " Length   Method    Size  Ratio   Date   Time   CRC-32    Name\n"
784                         //      "--------  ------  ------- -----   ----   ----   ------    ----"
785                         printf( "--------          -------  ---                            -------\n"
786                                 "%8lu"              "%17lu%4u%%                            %u files\n",
787                                 total_usize, total_size, (unsigned)percents,
788                                 total_entries);
789                 }
790         }
791
792         return 0;
793 }