1 /* vi: set sw=4 ts=4: */
3 * Mini unzip implementation for busybox
5 * Copyright (C) 2004 by Ed Clark
7 * Loosely based on original busybox unzip applet by Laurence Anderson.
8 * All options and features should work in this version.
10 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14 * http://www.pkware.com/company/standards/appnote/
15 * http://www.info-zip.org/pub/infozip/doc/appnote-iz-latest.zip
19 * Zip64 + other methods
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"
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"
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,
45 ZIP_FILEHEADER_MAGIC = 0x04034b50,
46 ZIP_CDF_MAGIC = 0x02014b50,
47 ZIP_CDE_MAGIC = 0x06054b50,
48 ZIP_DD_MAGIC = 0x08074b50,
52 #define ZIP_HEADER_LEN 26
55 uint8_t raw[ZIP_HEADER_LEN];
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 */
68 } zip_header_t; /* PACKED - gcc 4.2.1 doesn't like it (spews warning) */
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.
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];
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 ); \
92 #define CDF_HEADER_LEN 42
95 uint8_t raw[CDF_HEADER_LEN];
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 */
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];
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); \
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); \
136 #define CDE_HEADER_LEN 16
139 uint8_t raw[CDE_HEADER_LEN];
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;
148 /* uint16_t file_comment_length; */
149 /* .ZIP file comment (variable size) */
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];
158 #define FIX_ENDIANNESS_CDE(cde_header) do { \
159 (cde_header).formatted.cdf_offset = SWAP_LE32((cde_header).formatted.cdf_offset); \
167 #define PEEK_FROM_END 16384
169 /* NB: does not preserve file position! */
170 static uint32_t find_cdf_offset(void)
172 cde_header_t cde_header;
175 unsigned char *buf = xzalloc(PEEK_FROM_END);
177 end = xlseek(zip_fd, 0, SEEK_END);
178 end -= PEEK_FROM_END;
181 xlseek(zip_fd, end, SEEK_SET);
182 full_read(zip_fd, buf, PEEK_FROM_END);
185 while (p <= buf + PEEK_FROM_END - CDE_HEADER_LEN - 4) {
197 memcpy(cde_header.raw, p + 1, CDE_HEADER_LEN);
198 FIX_ENDIANNESS_CDE(cde_header);
200 return cde_header.formatted.cdf_offset;
203 bb_error_msg_and_die("can't find file table");
206 static uint32_t read_next_cdf(uint32_t cdf_offset, cdf_header_t *cdf_ptr)
210 org = xlseek(zip_fd, 0, SEEK_CUR);
213 cdf_offset = find_cdf_offset();
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;
223 xlseek(zip_fd, org, SEEK_SET);
228 static void unzip_skip(off_t skip)
230 if (lseek(zip_fd, skip, SEEK_CUR) == (off_t)-1)
231 bb_copyfd_exact_size(zip_fd, -1, skip);
234 static void unzip_create_leading_dirs(const char *fn)
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 */
244 static void unzip_extract(zip_header_t *zip_header, int dst_fd)
246 if (zip_header->formatted.method == 0) {
247 /* Method 0 - stored (not compressed) */
248 off_t size = zip_header->formatted.ucmpsize;
250 bb_copyfd_exact_size(zip_fd, dst_fd, size);
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");
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");
269 int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
270 int unzip_main(int argc, char **argv)
272 enum { O_PROMPT, O_NEVER, O_ALWAYS };
274 zip_header_t zip_header;
276 IF_NOT_DESKTOP(const) smallint verbose = 0;
277 smallint listing = 0;
278 smallint overwrite = O_PROMPT;
282 unsigned long total_usize;
283 unsigned long total_size;
284 unsigned total_entries;
288 llist_t *zaccept = NULL;
289 llist_t *zreject = NULL;
290 char *base_dir = NULL;
294 struct stat stat_buf;
296 /* -q, -l and -v: UnZip 5.52 of 28 February 2005, by Info-ZIP:
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
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
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
337 /* '-' makes getopt return 1 for non-options */
338 while ((opt = getopt(argc, argv, "-d:lnopqxv")) != -1) {
340 case 0: /* Options */
346 case 'n': /* Never overwrite existing files */
350 case 'o': /* Always overwrite existing files */
351 overwrite = O_ALWAYS;
354 case 'p': /* Extract files to stdout and fall through to set verbosity */
355 dst_fd = STDOUT_FILENO;
357 case 'q': /* Be quiet */
361 case 'v': /* Verbose list */
362 IF_DESKTOP(verbose++;)
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);
378 case 1: /* Include files */
380 llist_add_to(&zaccept, optarg);
394 case 2 : /* Exclude files */
396 llist_add_to(&zreject, optarg);
399 if (opt == 'd') { /* Extract to base directory */
411 if (src_fn == NULL) {
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)
422 static const char extn[][5] = {"", ".zip", ".ZIP"};
423 int orig_src_fn_len = strlen(src_fn);
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);
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);
434 xmove_fd(src_fd, zip_fd);
437 /* Change dir if necessary */
441 if (quiet <= 1) { /* not -qq */
443 printf("Archive: %s\n", src_fn);
446 " Length Method Size Ratio Date Time CRC-32 Name\n"
447 "-------- ------ ------- ----- ---- ---- ------ ----"
449 " Length Date Time Name\n"
450 " -------- ---- ---- ----"
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.....|
482 mode_t dir_mode = 0777;
484 mode_t file_mode = 0666;
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)
493 /* Data descriptor? It was a streaming file, go on */
494 if (magic == ZIP_DD_MAGIC) {
495 /* skip over duplicate crc32, cmpsize and ucmpsize */
500 if (magic != ZIP_FILEHEADER_MAGIC)
501 bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
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);
510 if (zip_header.formatted.zip_flags & SWAP_LE16(0x0009)) {
511 bb_error_msg_and_die("zip flags 1 and 8 are not supported");
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");
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;
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);
538 dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
539 xread(zip_fd, dst_fn, zip_header.formatted.filename_len);
541 /* Skip extra header bytes */
542 unzip_skip(zip_header.formatted.extra_len);
544 /* Filter zip entries */
545 if (find_list_entry(zreject, dst_fn)
546 || (zaccept && !find_list_entry(zaccept, dst_fn))
550 } else { /* Extract entry */
551 if (listing) { /* List entry */
552 unsigned dostime = zip_header.formatted.modtime | (zip_header.formatted.moddate << 16);
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,
564 total_usize += zip_header.formatted.ucmpsize;
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,
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,
583 total_usize += zip_header.formatted.ucmpsize;
584 total_size += zip_header.formatted.cmpsize;
587 } else if (dst_fd == STDOUT_FILENO) { /* Extracting to STDOUT */
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);
595 printf(" creating: %s\n", dst_fn);
597 unzip_create_leading_dirs(dst_fn);
598 if (bb_make_directory(dst_fn, dir_mode, 0)) {
599 bb_error_msg_and_die("exiting");
602 if (!S_ISDIR(stat_buf.st_mode)) {
603 bb_error_msg_and_die("'%s' exists but is not directory", dst_fn);
608 } else { /* Extract 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);
615 } else { /* File already exists */
616 if (overwrite == O_NEVER) {
618 } else if (S_ISREG(stat_buf.st_mode)) { /* File is regular file */
619 if (overwrite == O_ALWAYS) {
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");
628 } else { /* File is not regular file */
629 bb_error_msg_and_die("'%s' exists but is not regular file", dst_fn);
637 overwrite = O_ALWAYS;
638 case 'y': /* Open file and fall into unzip */
639 unzip_create_leading_dirs(dst_fn);
641 dst_fd = xopen3(dst_fn, O_WRONLY | O_CREAT | O_TRUNC, file_mode);
643 dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
647 printf(" inflating: %s\n", dst_fn);
649 unzip_extract(&zip_header, dst_fd);
650 if (dst_fd != STDOUT_FILENO) {
651 /* closing STDOUT is potentially bad for future business */
659 /* Skip entry data */
660 unzip_skip(zip_header.formatted.cmpsize);
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");
670 dst_fn = xstrdup(key_buf);
675 printf("error: invalid response [%c]\n", (char)i);
682 if (listing && quiet <= 1) {
684 // " Length Date Time Name\n"
685 // " -------- ---- ---- ----"
686 printf( " -------- -------\n"
687 "%9lu" " %u files\n",
688 total_usize, total_entries);
690 unsigned long percents = total_usize - total_size;
691 percents = percents * 100;
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,