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