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