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