move help text from include/usage.src.h to archival/*.c
[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
13 /* For reference see
14  * http://www.pkware.com/company/standards/appnote/
15  * http://www.info-zip.org/pub/infozip/doc/appnote-iz-latest.zip
16  */
17
18 /* TODO
19  * Zip64 + other methods
20  */
21
22 //usage:#define unzip_trivial_usage
23 //usage:       "[-opts[modifiers]] FILE[.zip] [LIST] [-x XLIST] [-d DIR]"
24 //usage:#define unzip_full_usage "\n\n"
25 //usage:       "Extract files from ZIP archives\n"
26 //usage:     "\nOptions:"
27 //usage:     "\n        -l      List archive contents (with -q for short form)"
28 //usage:     "\n        -n      Never overwrite files (default)"
29 //usage:     "\n        -o      Overwrite"
30 //usage:     "\n        -p      Send output to stdout"
31 //usage:     "\n        -q      Quiet"
32 //usage:     "\n        -x XLST Exclude these files"
33 //usage:     "\n        -d DIR  Extract files into DIR"
34
35 #include "libbb.h"
36 #include "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 #define PEEK_FROM_END 16384
168
169 /* NB: does not preserve file position! */
170 static uint32_t find_cdf_offset(void)
171 {
172         cde_header_t cde_header;
173         unsigned char *p;
174         off_t end;
175         unsigned char *buf = xzalloc(PEEK_FROM_END);
176
177         end = xlseek(zip_fd, 0, SEEK_END);
178         end -= PEEK_FROM_END;
179         if (end < 0)
180                 end = 0;
181         xlseek(zip_fd, end, SEEK_SET);
182         full_read(zip_fd, buf, PEEK_FROM_END);
183
184         p = buf;
185         while (p <= buf + PEEK_FROM_END - CDE_HEADER_LEN - 4) {
186                 if (*p != 'P') {
187                         p++;
188                         continue;
189                 }
190                 if (*++p != 'K')
191                         continue;
192                 if (*++p != 5)
193                         continue;
194                 if (*++p != 6)
195                         continue;
196                 /* we found CDE! */
197                 memcpy(cde_header.raw, p + 1, CDE_HEADER_LEN);
198                 FIX_ENDIANNESS_CDE(cde_header);
199                 free(buf);
200                 return cde_header.formatted.cdf_offset;
201         }
202         //free(buf);
203         bb_error_msg_and_die("can't find file table");
204 };
205
206 static uint32_t read_next_cdf(uint32_t cdf_offset, cdf_header_t *cdf_ptr)
207 {
208         off_t org;
209
210         org = xlseek(zip_fd, 0, SEEK_CUR);
211
212         if (!cdf_offset)
213                 cdf_offset = find_cdf_offset();
214
215         xlseek(zip_fd, cdf_offset + 4, SEEK_SET);
216         xread(zip_fd, cdf_ptr->raw, CDF_HEADER_LEN);
217         FIX_ENDIANNESS_CDF(*cdf_ptr);
218         cdf_offset += 4 + CDF_HEADER_LEN
219                 + cdf_ptr->formatted.file_name_length
220                 + cdf_ptr->formatted.extra_field_length
221                 + cdf_ptr->formatted.file_comment_length;
222
223         xlseek(zip_fd, org, SEEK_SET);
224         return cdf_offset;
225 };
226 #endif
227
228 static void unzip_skip(off_t skip)
229 {
230         if (lseek(zip_fd, skip, SEEK_CUR) == (off_t)-1)
231                 bb_copyfd_exact_size(zip_fd, -1, skip);
232 }
233
234 static void unzip_create_leading_dirs(const char *fn)
235 {
236         /* Create all leading directories */
237         char *name = xstrdup(fn);
238         if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
239                 bb_error_msg_and_die("exiting"); /* bb_make_directory is noisy */
240         }
241         free(name);
242 }
243
244 static void unzip_extract(zip_header_t *zip_header, int dst_fd)
245 {
246         if (zip_header->formatted.method == 0) {
247                 /* Method 0 - stored (not compressed) */
248                 off_t size = zip_header->formatted.ucmpsize;
249                 if (size)
250                         bb_copyfd_exact_size(zip_fd, dst_fd, size);
251         } else {
252                 /* Method 8 - inflate */
253                 inflate_unzip_result res;
254                 if (inflate_unzip(&res, zip_header->formatted.cmpsize, zip_fd, dst_fd) < 0)
255                         bb_error_msg_and_die("inflate error");
256                 /* Validate decompression - crc */
257                 if (zip_header->formatted.crc32 != (res.crc ^ 0xffffffffL)) {
258                         bb_error_msg_and_die("crc error");
259                 }
260                 /* Validate decompression - size */
261                 if (zip_header->formatted.ucmpsize != res.bytes_out) {
262                         /* Don't die. Who knows, maybe len calculation
263                          * was botched somewhere. After all, crc matched! */
264                         bb_error_msg("bad length");
265                 }
266         }
267 }
268
269 int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
270 int unzip_main(int argc, char **argv)
271 {
272         enum { O_PROMPT, O_NEVER, O_ALWAYS };
273
274         zip_header_t zip_header;
275         smallint quiet = 0;
276         IF_NOT_DESKTOP(const) smallint verbose = 0;
277         smallint listing = 0;
278         smallint overwrite = O_PROMPT;
279 #if ENABLE_DESKTOP
280         uint32_t cdf_offset;
281 #endif
282         unsigned long total_usize;
283         unsigned long total_size;
284         unsigned total_entries;
285         int dst_fd = -1;
286         char *src_fn = NULL;
287         char *dst_fn = NULL;
288         llist_t *zaccept = NULL;
289         llist_t *zreject = NULL;
290         char *base_dir = NULL;
291         int i, opt;
292         int opt_range = 0;
293         char key_buf[80];
294         struct stat stat_buf;
295
296 /* -q, -l and -v: UnZip 5.52 of 28 February 2005, by Info-ZIP:
297  *
298  * # /usr/bin/unzip -qq -v decompress_unlzma.i.zip
299  *   204372  Defl:N    35278  83%  09-06-09 14:23  0d056252  decompress_unlzma.i
300  * # /usr/bin/unzip -q -v decompress_unlzma.i.zip
301  *  Length   Method    Size  Ratio   Date   Time   CRC-32    Name
302  * --------  ------  ------- -----   ----   ----   ------    ----
303  *   204372  Defl:N    35278  83%  09-06-09 14:23  0d056252  decompress_unlzma.i
304  * --------          -------  ---                            -------
305  *   204372            35278  83%                            1 file
306  * # /usr/bin/unzip -v decompress_unlzma.i.zip
307  * Archive:  decompress_unlzma.i.zip
308  *  Length   Method    Size  Ratio   Date   Time   CRC-32    Name
309  * --------  ------  ------- -----   ----   ----   ------    ----
310  *   204372  Defl:N    35278  83%  09-06-09 14:23  0d056252  decompress_unlzma.i
311  * --------          -------  ---                            -------
312  *   204372            35278  83%                            1 file
313  * # unzip -v decompress_unlzma.i.zip
314  * Archive:  decompress_unlzma.i.zip
315  *   Length     Date   Time    Name
316  *  --------    ----   ----    ----
317  *    204372  09-06-09 14:23   decompress_unlzma.i
318  *  --------                   -------
319  *    204372                   1 files
320  * # /usr/bin/unzip -l -qq decompress_unlzma.i.zip
321  *    204372  09-06-09 14:23   decompress_unlzma.i
322  * # /usr/bin/unzip -l -q decompress_unlzma.i.zip
323  *   Length     Date   Time    Name
324  *  --------    ----   ----    ----
325  *    204372  09-06-09 14:23   decompress_unlzma.i
326  *  --------                   -------
327  *    204372                   1 file
328  * # /usr/bin/unzip -l decompress_unlzma.i.zip
329  * Archive:  decompress_unlzma.i.zip
330  *   Length     Date   Time    Name
331  *  --------    ----   ----    ----
332  *    204372  09-06-09 14:23   decompress_unlzma.i
333  *  --------                   -------
334  *    204372                   1 file
335  */
336
337         /* '-' makes getopt return 1 for non-options */
338         while ((opt = getopt(argc, argv, "-d:lnopqxv")) != -1) {
339                 switch (opt_range) {
340                 case 0: /* Options */
341                         switch (opt) {
342                         case 'l': /* List */
343                                 listing = 1;
344                                 break;
345
346                         case 'n': /* Never overwrite existing files */
347                                 overwrite = O_NEVER;
348                                 break;
349
350                         case 'o': /* Always overwrite existing files */
351                                 overwrite = O_ALWAYS;
352                                 break;
353
354                         case 'p': /* Extract files to stdout and fall through to set verbosity */
355                                 dst_fd = STDOUT_FILENO;
356
357                         case 'q': /* Be quiet */
358                                 quiet++;
359                                 break;
360
361                         case 'v': /* Verbose list */
362                                 IF_DESKTOP(verbose++;)
363                                 listing = 1;
364                                 break;
365
366                         case 1: /* The zip file */
367                                 /* +5: space for ".zip" and NUL */
368                                 src_fn = xmalloc(strlen(optarg) + 5);
369                                 strcpy(src_fn, optarg);
370                                 opt_range++;
371                                 break;
372
373                         default:
374                                 bb_show_usage();
375                         }
376                         break;
377
378                 case 1: /* Include files */
379                         if (opt == 1) {
380                                 llist_add_to(&zaccept, optarg);
381                                 break;
382                         }
383                         if (opt == 'd') {
384                                 base_dir = optarg;
385                                 opt_range += 2;
386                                 break;
387                         }
388                         if (opt == 'x') {
389                                 opt_range++;
390                                 break;
391                         }
392                         bb_show_usage();
393
394                 case 2 : /* Exclude files */
395                         if (opt == 1) {
396                                 llist_add_to(&zreject, optarg);
397                                 break;
398                         }
399                         if (opt == 'd') { /* Extract to base directory */
400                                 base_dir = optarg;
401                                 opt_range++;
402                                 break;
403                         }
404                         /* fall through */
405
406                 default:
407                         bb_show_usage();
408                 }
409         }
410
411         if (src_fn == NULL) {
412                 bb_show_usage();
413         }
414
415         /* Open input file */
416         if (LONE_DASH(src_fn)) {
417                 xdup2(STDIN_FILENO, zip_fd);
418                 /* Cannot use prompt mode since zip data is arriving on STDIN */
419                 if (overwrite == O_PROMPT)
420                         overwrite = O_NEVER;
421         } else {
422                 static const char extn[][5] = {"", ".zip", ".ZIP"};
423                 int orig_src_fn_len = strlen(src_fn);
424                 int src_fd = -1;
425
426                 for (i = 0; (i < 3) && (src_fd == -1); i++) {
427                         strcpy(src_fn + orig_src_fn_len, extn[i]);
428                         src_fd = open(src_fn, O_RDONLY);
429                 }
430                 if (src_fd == -1) {
431                         src_fn[orig_src_fn_len] = '\0';
432                         bb_error_msg_and_die("can't open %s, %s.zip, %s.ZIP", src_fn, src_fn, src_fn);
433                 }
434                 xmove_fd(src_fd, zip_fd);
435         }
436
437         /* Change dir if necessary */
438         if (base_dir)
439                 xchdir(base_dir);
440
441         if (quiet <= 1) { /* not -qq */
442                 if (quiet == 0)
443                         printf("Archive:  %s\n", src_fn);
444                 if (listing) {
445                         puts(verbose ?
446                                 " Length   Method    Size  Ratio   Date   Time   CRC-32    Name\n"
447                                 "--------  ------  ------- -----   ----   ----   ------    ----"
448                                 :
449                                 "  Length     Date   Time    Name\n"
450                                 " --------    ----   ----    ----"
451                                 );
452                 }
453         }
454
455 /* Example of an archive with one 0-byte long file named 'z'
456  * created by Zip 2.31 on Unix:
457  * 0000 [50 4b]03 04 0a 00 00 00 00 00 42 1a b8 3c 00 00 |PK........B..<..|
458  *       sig........ vneed flags compr mtime mdate crc32>
459  * 0010  00 00 00 00 00 00 00 00 00 00 01 00 15 00 7a 55 |..............zU|
460  *      >..... csize...... usize...... fnlen exlen fn ex>
461  * 0020  54 09 00 03 cc d3 f9 4b cc d3 f9 4b 55 78 04 00 |T......K...KUx..|
462  *      >tra_field......................................
463  * 0030  00 00 00 00[50 4b]01 02 17 03 0a 00 00 00 00 00 |....PK..........|
464  *       ........... sig........ vmade vneed flags compr
465  * 0040  42 1a b8 3c 00 00 00 00 00 00 00 00 00 00 00 00 |B..<............|
466  *       mtime mdate crc32...... csize...... usize......
467  * 0050  01 00 0d 00 00 00 00 00 00 00 00 00 a4 81 00 00 |................|
468  *       fnlen exlen clen. dnum. iattr eattr...... relofs> (eattr = rw-r--r--)
469  * 0060  00 00 7a 55 54 05 00 03 cc d3 f9 4b 55 78 00 00 |..zUT......KUx..|
470  *      >..... fn extra_field...........................
471  * 0070 [50 4b]05 06 00 00 00 00 01 00 01 00 3c 00 00 00 |PK..........<...|
472  * 0080  34 00 00 00 00 00                               |4.....|
473  */
474         total_usize = 0;
475         total_size = 0;
476         total_entries = 0;
477 #if ENABLE_DESKTOP
478         cdf_offset = 0;
479 #endif
480         while (1) {
481                 uint32_t magic;
482                 mode_t dir_mode = 0777;
483 #if ENABLE_DESKTOP
484                 mode_t file_mode = 0666;
485 #endif
486
487                 /* Check magic number */
488                 xread(zip_fd, &magic, 4);
489                 /* Central directory? It's at the end, so exit */
490                 if (magic == ZIP_CDF_MAGIC)
491                         break;
492 #if ENABLE_DESKTOP
493                 /* Data descriptor? It was a streaming file, go on */
494                 if (magic == ZIP_DD_MAGIC) {
495                         /* skip over duplicate crc32, cmpsize and ucmpsize */
496                         unzip_skip(3 * 4);
497                         continue;
498                 }
499 #endif
500                 if (magic != ZIP_FILEHEADER_MAGIC)
501                         bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
502
503                 /* Read the file header */
504                 xread(zip_fd, zip_header.raw, ZIP_HEADER_LEN);
505                 FIX_ENDIANNESS_ZIP(zip_header);
506                 if ((zip_header.formatted.method != 0) && (zip_header.formatted.method != 8)) {
507                         bb_error_msg_and_die("unsupported method %d", zip_header.formatted.method);
508                 }
509 #if !ENABLE_DESKTOP
510                 if (zip_header.formatted.zip_flags & SWAP_LE16(0x0009)) {
511                         bb_error_msg_and_die("zip flags 1 and 8 are not supported");
512                 }
513 #else
514                 if (zip_header.formatted.zip_flags & SWAP_LE16(0x0001)) {
515                         /* 0x0001 - encrypted */
516                         bb_error_msg_and_die("zip flag 1 (encryption) is not supported");
517                 }
518
519                 {
520                         cdf_header_t cdf_header;
521                         cdf_offset = read_next_cdf(cdf_offset, &cdf_header);
522                         if (zip_header.formatted.zip_flags & SWAP_LE16(0x0008)) {
523                                 /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
524                                  * only from Central Directory. See unzip_doc.txt */
525                                 zip_header.formatted.crc32    = cdf_header.formatted.crc32;
526                                 zip_header.formatted.cmpsize  = cdf_header.formatted.cmpsize;
527                                 zip_header.formatted.ucmpsize = cdf_header.formatted.ucmpsize;
528                         }
529                         if ((cdf_header.formatted.version_made_by >> 8) == 3) {
530                                 /* this archive is created on Unix */
531                                 dir_mode = file_mode = (cdf_header.formatted.external_file_attributes >> 16);
532                         }
533                 }
534 #endif
535
536                 /* Read filename */
537                 free(dst_fn);
538                 dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
539                 xread(zip_fd, dst_fn, zip_header.formatted.filename_len);
540
541                 /* Skip extra header bytes */
542                 unzip_skip(zip_header.formatted.extra_len);
543
544                 /* Filter zip entries */
545                 if (find_list_entry(zreject, dst_fn)
546                  || (zaccept && !find_list_entry(zaccept, dst_fn))
547                 ) { /* Skip entry */
548                         i = 'n';
549
550                 } else { /* Extract entry */
551                         if (listing) { /* List entry */
552                                 unsigned dostime = zip_header.formatted.modtime | (zip_header.formatted.moddate << 16);
553                                 if (!verbose) {
554                                         //      "  Length     Date   Time    Name\n"
555                                         //      " --------    ----   ----    ----"
556                                         printf(       "%9u  %02u-%02u-%02u %02u:%02u   %s\n",
557                                                 (unsigned)zip_header.formatted.ucmpsize,
558                                                 (dostime & 0x01e00000) >> 21,
559                                                 (dostime & 0x001f0000) >> 16,
560                                                 (((dostime & 0xfe000000) >> 25) + 1980) % 100,
561                                                 (dostime & 0x0000f800) >> 11,
562                                                 (dostime & 0x000007e0) >> 5,
563                                                 dst_fn);
564                                         total_usize += zip_header.formatted.ucmpsize;
565                                 } else {
566                                         unsigned long percents = zip_header.formatted.ucmpsize - zip_header.formatted.cmpsize;
567                                         percents = percents * 100;
568                                         if (zip_header.formatted.ucmpsize)
569                                                 percents /= zip_header.formatted.ucmpsize;
570                                         //      " Length   Method    Size  Ratio   Date   Time   CRC-32    Name\n"
571                                         //      "--------  ------  ------- -----   ----   ----   ------    ----"
572                                         printf(      "%8u  Defl:N"    "%9u%4u%%  %02u-%02u-%02u %02u:%02u  %08x  %s\n",
573                                                 (unsigned)zip_header.formatted.ucmpsize,
574                                                 (unsigned)zip_header.formatted.cmpsize,
575                                                 (unsigned)percents,
576                                                 (dostime & 0x01e00000) >> 21,
577                                                 (dostime & 0x001f0000) >> 16,
578                                                 (((dostime & 0xfe000000) >> 25) + 1980) % 100,
579                                                 (dostime & 0x0000f800) >> 11,
580                                                 (dostime & 0x000007e0) >> 5,
581                                                 zip_header.formatted.crc32,
582                                                 dst_fn);
583                                         total_usize += zip_header.formatted.ucmpsize;
584                                         total_size += zip_header.formatted.cmpsize;
585                                 }
586                                 i = 'n';
587                         } else if (dst_fd == STDOUT_FILENO) { /* Extracting to STDOUT */
588                                 i = -1;
589                         } else if (last_char_is(dst_fn, '/')) { /* Extract directory */
590                                 if (stat(dst_fn, &stat_buf) == -1) {
591                                         if (errno != ENOENT) {
592                                                 bb_perror_msg_and_die("can't stat '%s'", dst_fn);
593                                         }
594                                         if (!quiet) {
595                                                 printf("   creating: %s\n", dst_fn);
596                                         }
597                                         unzip_create_leading_dirs(dst_fn);
598                                         if (bb_make_directory(dst_fn, dir_mode, 0)) {
599                                                 bb_error_msg_and_die("exiting");
600                                         }
601                                 } else {
602                                         if (!S_ISDIR(stat_buf.st_mode)) {
603                                                 bb_error_msg_and_die("'%s' exists but is not directory", dst_fn);
604                                         }
605                                 }
606                                 i = 'n';
607
608                         } else {  /* Extract file */
609  check_file:
610                                 if (stat(dst_fn, &stat_buf) == -1) { /* File does not exist */
611                                         if (errno != ENOENT) {
612                                                 bb_perror_msg_and_die("can't stat '%s'", dst_fn);
613                                         }
614                                         i = 'y';
615                                 } else { /* File already exists */
616                                         if (overwrite == O_NEVER) {
617                                                 i = 'n';
618                                         } else if (S_ISREG(stat_buf.st_mode)) { /* File is regular file */
619                                                 if (overwrite == O_ALWAYS) {
620                                                         i = 'y';
621                                                 } else {
622                                                         printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
623                                                         if (!fgets(key_buf, sizeof(key_buf), stdin)) {
624                                                                 bb_perror_msg_and_die("can't read input");
625                                                         }
626                                                         i = key_buf[0];
627                                                 }
628                                         } else { /* File is not regular file */
629                                                 bb_error_msg_and_die("'%s' exists but is not regular file", dst_fn);
630                                         }
631                                 }
632                         }
633                 }
634
635                 switch (i) {
636                 case 'A':
637                         overwrite = O_ALWAYS;
638                 case 'y': /* Open file and fall into unzip */
639                         unzip_create_leading_dirs(dst_fn);
640 #if ENABLE_DESKTOP
641                         dst_fd = xopen3(dst_fn, O_WRONLY | O_CREAT | O_TRUNC, file_mode);
642 #else
643                         dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
644 #endif
645                 case -1: /* Unzip */
646                         if (!quiet) {
647                                 printf("  inflating: %s\n", dst_fn);
648                         }
649                         unzip_extract(&zip_header, dst_fd);
650                         if (dst_fd != STDOUT_FILENO) {
651                                 /* closing STDOUT is potentially bad for future business */
652                                 close(dst_fd);
653                         }
654                         break;
655
656                 case 'N':
657                         overwrite = O_NEVER;
658                 case 'n':
659                         /* Skip entry data */
660                         unzip_skip(zip_header.formatted.cmpsize);
661                         break;
662
663                 case 'r':
664                         /* Prompt for new name */
665                         printf("new name: ");
666                         if (!fgets(key_buf, sizeof(key_buf), stdin)) {
667                                 bb_perror_msg_and_die("can't read input");
668                         }
669                         free(dst_fn);
670                         dst_fn = xstrdup(key_buf);
671                         chomp(dst_fn);
672                         goto check_file;
673
674                 default:
675                         printf("error: invalid response [%c]\n", (char)i);
676                         goto check_file;
677                 }
678
679                 total_entries++;
680         }
681
682         if (listing && quiet <= 1) {
683                 if (!verbose) {
684                         //      "  Length     Date   Time    Name\n"
685                         //      " --------    ----   ----    ----"
686                         printf( " --------                   -------\n"
687                                 "%9lu"   "                   %u files\n",
688                                 total_usize, total_entries);
689                 } else {
690                         unsigned long percents = total_usize - total_size;
691                         percents = percents * 100;
692                         if (total_usize)
693                                 percents /= total_usize;
694                         //      " Length   Method    Size  Ratio   Date   Time   CRC-32    Name\n"
695                         //      "--------  ------  ------- -----   ----   ----   ------    ----"
696                         printf( "--------          -------  ---                            -------\n"
697                                 "%8lu"              "%17lu%4u%%                            %u files\n",
698                                 total_usize, total_size, (unsigned)percents,
699                                 total_entries);
700                 }
701         }
702
703         return 0;
704 }