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 the GPL v2 or later, see the file LICENSE in this tarball.
14 * http://www.pkware.com/company/standards/appnote/
15 * http://www.info-zip.org/pub/infozip/doc/appnote-iz-latest.zip
20 * Zip64 + other methods
21 * Improve handling of zip format, ie.
22 * - deferred CRC, comp. & uncomp. lengths (zip header flags bit 3)
23 * - unix file permissions, etc.
28 #include "unarchive.h"
32 ZIP_FILEHEADER_MAGIC = 0x504b0304,
33 ZIP_CDS_MAGIC = 0x504b0102,
34 ZIP_CDS_END_MAGIC = 0x504b0506,
35 ZIP_DD_MAGIC = 0x504b0708,
37 ZIP_FILEHEADER_MAGIC = 0x04034b50,
38 ZIP_CDS_MAGIC = 0x02014b50,
39 ZIP_CDS_END_MAGIC = 0x06054b50,
40 ZIP_DD_MAGIC = 0x08074b50,
44 #define ZIP_HEADER_LEN 26
47 uint8_t raw[ZIP_HEADER_LEN];
49 uint16_t version; /* 0-1 */
50 uint16_t flags; /* 2-3 */
51 uint16_t method; /* 4-5 */
52 uint16_t modtime; /* 6-7 */
53 uint16_t moddate; /* 8-9 */
54 uint32_t crc32 PACKED; /* 10-13 */
55 uint32_t cmpsize PACKED; /* 14-17 */
56 uint32_t ucmpsize PACKED; /* 18-21 */
57 uint16_t filename_len; /* 22-23 */
58 uint16_t extra_len; /* 24-25 */
60 } zip_header_t; /* PACKED - gcc 4.2.1 doesn't like it (spews warning) */
62 /* Check the offset of the last element, not the length. This leniency
63 * allows for poor packing, whereby the overall struct may be too long,
64 * even though the elements are all in the right place.
66 struct BUG_zip_header_must_be_26_bytes {
67 char BUG_zip_header_must_be_26_bytes[
68 offsetof(zip_header_t, formatted.extra_len) + 2 ==
69 ZIP_HEADER_LEN ? 1 : -1];
72 #define FIX_ENDIANNESS(zip_header) do { \
73 (zip_header).formatted.version = SWAP_LE16((zip_header).formatted.version ); \
74 (zip_header).formatted.flags = SWAP_LE16((zip_header).formatted.flags ); \
75 (zip_header).formatted.method = SWAP_LE16((zip_header).formatted.method ); \
76 (zip_header).formatted.modtime = SWAP_LE16((zip_header).formatted.modtime ); \
77 (zip_header).formatted.moddate = SWAP_LE16((zip_header).formatted.moddate ); \
78 (zip_header).formatted.crc32 = SWAP_LE32((zip_header).formatted.crc32 ); \
79 (zip_header).formatted.cmpsize = SWAP_LE32((zip_header).formatted.cmpsize ); \
80 (zip_header).formatted.ucmpsize = SWAP_LE32((zip_header).formatted.ucmpsize ); \
81 (zip_header).formatted.filename_len = SWAP_LE16((zip_header).formatted.filename_len); \
82 (zip_header).formatted.extra_len = SWAP_LE16((zip_header).formatted.extra_len ); \
85 static void unzip_skip(int fd, off_t skip)
87 bb_copyfd_exact_size(fd, -1, skip);
90 static void unzip_create_leading_dirs(const char *fn)
92 /* Create all leading directories */
93 char *name = xstrdup(fn);
94 if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
95 bb_error_msg_and_die("exiting"); /* bb_make_directory is noisy */
100 static void unzip_extract(zip_header_t *zip_header, int src_fd, int dst_fd)
102 if (zip_header->formatted.method == 0) {
103 /* Method 0 - stored (not compressed) */
104 off_t size = zip_header->formatted.ucmpsize;
106 bb_copyfd_exact_size(src_fd, dst_fd, size);
108 /* Method 8 - inflate */
109 inflate_unzip_result res;
110 if (inflate_unzip(&res, zip_header->formatted.cmpsize, src_fd, dst_fd) < 0)
111 bb_error_msg_and_die("inflate error");
112 /* Validate decompression - crc */
113 if (zip_header->formatted.crc32 != (res.crc ^ 0xffffffffL)) {
114 bb_error_msg_and_die("crc error");
116 /* Validate decompression - size */
117 if (zip_header->formatted.ucmpsize != res.bytes_out) {
118 /* Don't die. Who knows, maybe len calculation
119 * was botched somewhere. After all, crc matched! */
120 bb_error_msg("bad length");
125 int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
126 int unzip_main(int argc, char **argv)
128 enum { O_PROMPT, O_NEVER, O_ALWAYS };
130 zip_header_t zip_header;
131 smallint verbose = 1;
132 smallint listing = 0;
133 smallint overwrite = O_PROMPT;
135 unsigned total_entries;
140 llist_t *zaccept = NULL;
141 llist_t *zreject = NULL;
142 char *base_dir = NULL;
146 struct stat stat_buf;
148 /* '-' makes getopt return 1 for non-options */
149 while ((opt = getopt(argc, argv, "-d:lnopqx")) != -1) {
151 case 0: /* Options */
157 case 'n': /* Never overwrite existing files */
161 case 'o': /* Always overwrite existing files */
162 overwrite = O_ALWAYS;
165 case 'p': /* Extract files to stdout and fall through to set verbosity */
166 dst_fd = STDOUT_FILENO;
168 case 'q': /* Be quiet */
172 case 1: /* The zip file */
173 /* +5: space for ".zip" and NUL */
174 src_fn = xmalloc(strlen(optarg) + 5);
175 strcpy(src_fn, optarg);
185 case 1: /* Include files */
187 llist_add_to(&zaccept, optarg);
201 case 2 : /* Exclude files */
203 llist_add_to(&zreject, optarg);
206 if (opt == 'd') { /* Extract to base directory */
218 if (src_fn == NULL) {
222 /* Open input file */
223 if (LONE_DASH(src_fn)) {
224 src_fd = STDIN_FILENO;
225 /* Cannot use prompt mode since zip data is arriving on STDIN */
226 if (overwrite == O_PROMPT)
229 static const char extn[][5] = {"", ".zip", ".ZIP"};
230 int orig_src_fn_len = strlen(src_fn);
232 for (i = 0; (i < 3) && (src_fd == -1); i++) {
233 strcpy(src_fn + orig_src_fn_len, extn[i]);
234 src_fd = open(src_fn, O_RDONLY);
237 src_fn[orig_src_fn_len] = '\0';
238 bb_error_msg_and_die("can't open %s, %s.zip, %s.ZIP", src_fn, src_fn, src_fn);
242 /* Change dir if necessary */
247 printf("Archive: %s\n", src_fn);
249 puts(" Length Date Time Name\n"
250 " -------- ---- ---- ----");
259 /* Check magic number */
260 xread(src_fd, &magic, 4);
261 /* Central directory? It's at the end, so exit */
262 if (magic == ZIP_CDS_MAGIC)
264 if (magic != ZIP_FILEHEADER_MAGIC)
265 bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
267 /* Read the file header */
268 xread(src_fd, zip_header.raw, ZIP_HEADER_LEN);
269 FIX_ENDIANNESS(zip_header);
270 if ((zip_header.formatted.method != 0) && (zip_header.formatted.method != 8)) {
271 bb_error_msg_and_die("unsupported method %d", zip_header.formatted.method);
273 if (zip_header.formatted.flags & (0x0008|0x0001)) {
274 /* 0x0001 - encrypted */
275 /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
276 * only from Central Directory. See unzip_doc.txt */
277 bb_error_msg_and_die("zip flags 8 and 1 are not supported");
282 dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
283 xread(src_fd, dst_fn, zip_header.formatted.filename_len);
285 /* Skip extra header bytes */
286 unzip_skip(src_fd, zip_header.formatted.extra_len);
288 /* Filter zip entries */
289 if (find_list_entry(zreject, dst_fn)
290 || (zaccept && !find_list_entry(zaccept, dst_fn))
294 } else { /* Extract entry */
295 if (listing) { /* List entry */
297 unsigned dostime = zip_header.formatted.modtime | (zip_header.formatted.moddate << 16);
298 printf("%9u %02u-%02u-%02u %02u:%02u %s\n",
299 zip_header.formatted.ucmpsize,
300 (dostime & 0x01e00000) >> 21,
301 (dostime & 0x001f0000) >> 16,
302 (((dostime & 0xfe000000) >> 25) + 1980) % 100,
303 (dostime & 0x0000f800) >> 11,
304 (dostime & 0x000007e0) >> 5,
306 total_size += zip_header.formatted.ucmpsize;
309 /* short listing -- filenames only */
313 } else if (dst_fd == STDOUT_FILENO) { /* Extracting to STDOUT */
315 } else if (last_char_is(dst_fn, '/')) { /* Extract directory */
316 if (stat(dst_fn, &stat_buf) == -1) {
317 if (errno != ENOENT) {
318 bb_perror_msg_and_die("cannot stat '%s'", dst_fn);
321 printf(" creating: %s\n", dst_fn);
323 unzip_create_leading_dirs(dst_fn);
324 if (bb_make_directory(dst_fn, 0777, 0)) {
325 bb_error_msg_and_die("exiting");
328 if (!S_ISDIR(stat_buf.st_mode)) {
329 bb_error_msg_and_die("'%s' exists but is not directory", dst_fn);
334 } else { /* Extract file */
336 if (stat(dst_fn, &stat_buf) == -1) { /* File does not exist */
337 if (errno != ENOENT) {
338 bb_perror_msg_and_die("cannot stat '%s'", dst_fn);
341 } else { /* File already exists */
342 if (overwrite == O_NEVER) {
344 } else if (S_ISREG(stat_buf.st_mode)) { /* File is regular file */
345 if (overwrite == O_ALWAYS) {
348 printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
349 if (!fgets(key_buf, sizeof(key_buf), stdin)) {
350 bb_perror_msg_and_die("cannot read input");
354 } else { /* File is not regular file */
355 bb_error_msg_and_die("'%s' exists but is not regular file", dst_fn);
363 overwrite = O_ALWAYS;
364 case 'y': /* Open file and fall into unzip */
365 unzip_create_leading_dirs(dst_fn);
366 dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
369 printf(" inflating: %s\n", dst_fn);
371 unzip_extract(&zip_header, src_fd, dst_fd);
372 if (dst_fd != STDOUT_FILENO) {
373 /* closing STDOUT is potentially bad for future business */
381 /* Skip entry data */
382 unzip_skip(src_fd, zip_header.formatted.cmpsize);
386 /* Prompt for new name */
387 printf("new name: ");
388 if (!fgets(key_buf, sizeof(key_buf), stdin)) {
389 bb_perror_msg_and_die("cannot read input");
392 dst_fn = xstrdup(key_buf);
397 printf("error: invalid response [%c]\n",(char)i);
401 // Looks like bug (data descriptor cannot be identified this way)
402 // /* Data descriptor section */
403 // if (zip_header.formatted.flags & 4) {
404 // /* skip over duplicate crc, compressed size and uncompressed size */
405 // unzip_skip(src_fd, 12);
409 if (listing && verbose) {
410 printf(" -------- -------\n"
412 total_size, total_entries);