unzip: give better error message when presented with unsupported
[oweals/busybox.git] / archival / unzip.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini unzip implementation for busybox
4  *
5  * Copyright (C) 2004 by Ed Clark
6  *
7  * Loosely based on original busybox unzip applet by Laurence Anderson.
8  * All options and features should work in this version.
9  *
10  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
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  * Endian issues
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.
24  * - central directory
25  */
26
27 #include "libbb.h"
28 #include "unarchive.h"
29
30 enum {
31 #if BB_BIG_ENDIAN
32         ZIP_FILEHEADER_MAGIC = 0x504b0304,
33         ZIP_CDS_MAGIC        = 0x504b0102,
34         ZIP_CDS_END_MAGIC    = 0x504b0506,
35         ZIP_DD_MAGIC         = 0x504b0708,
36 #else
37         ZIP_FILEHEADER_MAGIC = 0x04034b50,
38         ZIP_CDS_MAGIC        = 0x02014b50,
39         ZIP_CDS_END_MAGIC    = 0x06054b50,
40         ZIP_DD_MAGIC         = 0x08074b50,
41 #endif
42 };
43
44 #define ZIP_HEADER_LEN 26
45
46 typedef union {
47         uint8_t raw[ZIP_HEADER_LEN];
48         struct {
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 */
59         } formatted PACKED;
60 } zip_header_t; /* PACKED - gcc 4.2.1 doesn't like it (spews warning) */
61
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.
65  */
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];
70 };
71
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   ); \
83 } while (0)
84
85 static void unzip_skip(int fd, off_t skip)
86 {
87         bb_copyfd_exact_size(fd, -1, skip);
88 }
89
90 static void unzip_create_leading_dirs(const char *fn)
91 {
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 */
96         }
97         free(name);
98 }
99
100 static void unzip_extract(zip_header_t *zip_header, int src_fd, int dst_fd)
101 {
102         if (zip_header->formatted.flags & (0x0008|0x0001)) {
103                 /* 0x0001 - encrypted */
104                 /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
105                  * only from Central Directory. See unzip_doc.txt */
106                 bb_error_msg_and_die("zip flags 8 and 1 are not supported");
107         }
108         if (zip_header->formatted.method == 0) {
109                 /* Method 0 - stored (not compressed) */
110                 off_t size = zip_header->formatted.ucmpsize;
111                 if (size)
112                         bb_copyfd_exact_size(src_fd, dst_fd, size);
113         } else {
114                 /* Method 8 - inflate */
115                 inflate_unzip_result res;
116                 if (inflate_unzip(&res, zip_header->formatted.cmpsize, src_fd, dst_fd) < 0)
117                         bb_error_msg_and_die("inflate error");
118                 /* Validate decompression - crc */
119                 if (zip_header->formatted.crc32 != (res.crc ^ 0xffffffffL)) {
120                         bb_error_msg_and_die("crc error");
121                 }
122                 /* Validate decompression - size */
123                 if (zip_header->formatted.ucmpsize != res.bytes_out) {
124                         /* Don't die. Who knows, maybe len calculation
125                          * was botched somewhere. After all, crc matched! */
126                         bb_error_msg("bad length");
127                 }
128         }
129 }
130
131 int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
132 int unzip_main(int argc, char **argv)
133 {
134         enum { O_PROMPT, O_NEVER, O_ALWAYS };
135
136         zip_header_t zip_header;
137         smallint verbose = 1;
138         smallint listing = 0;
139         smallint overwrite = O_PROMPT;
140         unsigned total_size;
141         unsigned total_entries;
142         int src_fd = -1;
143         int dst_fd = -1;
144         char *src_fn = NULL;
145         char *dst_fn = NULL;
146         llist_t *zaccept = NULL;
147         llist_t *zreject = NULL;
148         char *base_dir = NULL;
149         int i, opt;
150         int opt_range = 0;
151         char key_buf[80];
152         struct stat stat_buf;
153
154         /* '-' makes getopt return 1 for non-options */
155         while ((opt = getopt(argc, argv, "-d:lnopqx")) != -1) {
156                 switch (opt_range) {
157                 case 0: /* Options */
158                         switch (opt) {
159                         case 'l': /* List */
160                                 listing = 1;
161                                 break;
162
163                         case 'n': /* Never overwrite existing files */
164                                 overwrite = O_NEVER;
165                                 break;
166
167                         case 'o': /* Always overwrite existing files */
168                                 overwrite = O_ALWAYS;
169                                 break;
170
171                         case 'p': /* Extract files to stdout and fall through to set verbosity */
172                                 dst_fd = STDOUT_FILENO;
173
174                         case 'q': /* Be quiet */
175                                 verbose = 0;
176                                 break;
177
178                         case 1: /* The zip file */
179                                 /* +5: space for ".zip" and NUL */
180                                 src_fn = xmalloc(strlen(optarg) + 5);
181                                 strcpy(src_fn, optarg);
182                                 opt_range++;
183                                 break;
184
185                         default:
186                                 bb_show_usage();
187
188                         }
189                         break;
190
191                 case 1: /* Include files */
192                         if (opt == 1) {
193                                 llist_add_to(&zaccept, optarg);
194                                 break;
195                         }
196                         if (opt == 'd') {
197                                 base_dir = optarg;
198                                 opt_range += 2;
199                                 break;
200                         }
201                         if (opt == 'x') {
202                                 opt_range++;
203                                 break;
204                         }
205                         bb_show_usage();
206
207                 case 2 : /* Exclude files */
208                         if (opt == 1) {
209                                 llist_add_to(&zreject, optarg);
210                                 break;
211                         }
212                         if (opt == 'd') { /* Extract to base directory */
213                                 base_dir = optarg;
214                                 opt_range++;
215                                 break;
216                         }
217                         /* fall through */
218
219                 default:
220                         bb_show_usage();
221                 }
222         }
223
224         if (src_fn == NULL) {
225                 bb_show_usage();
226         }
227
228         /* Open input file */
229         if (LONE_DASH(src_fn)) {
230                 src_fd = STDIN_FILENO;
231                 /* Cannot use prompt mode since zip data is arriving on STDIN */
232                 if (overwrite == O_PROMPT)
233                         overwrite = O_NEVER;
234         } else {
235                 static const char extn[][5] = {"", ".zip", ".ZIP"};
236                 int orig_src_fn_len = strlen(src_fn);
237
238                 for (i = 0; (i < 3) && (src_fd == -1); i++) {
239                         strcpy(src_fn + orig_src_fn_len, extn[i]);
240                         src_fd = open(src_fn, O_RDONLY);
241                 }
242                 if (src_fd == -1) {
243                         src_fn[orig_src_fn_len] = '\0';
244                         bb_error_msg_and_die("can't open %s, %s.zip, %s.ZIP", src_fn, src_fn, src_fn);
245                 }
246         }
247
248         /* Change dir if necessary */
249         if (base_dir)
250                 xchdir(base_dir);
251
252         if (verbose) {
253                 printf("Archive:  %s\n", src_fn);
254                 if (listing){
255                         puts("  Length     Date   Time    Name\n"
256                              " --------    ----   ----    ----");
257                 }
258         }
259
260         total_size = 0;
261         total_entries = 0;
262         while (1) {
263                 uint32_t magic;
264
265                 /* Check magic number */
266                 xread(src_fd, &magic, 4);
267                 if (magic == ZIP_CDS_MAGIC)
268                         break;
269                 if (magic != ZIP_FILEHEADER_MAGIC)
270                         bb_error_msg_and_die("invalid zip magic %08X", magic);
271
272                 /* Read the file header */
273                 xread(src_fd, zip_header.raw, ZIP_HEADER_LEN);
274                 FIX_ENDIANNESS(zip_header);
275                 if ((zip_header.formatted.method != 0) && (zip_header.formatted.method != 8)) {
276                         bb_error_msg_and_die("unsupported method %d", zip_header.formatted.method);
277                 }
278
279                 /* Read filename */
280                 free(dst_fn);
281                 dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
282                 xread(src_fd, dst_fn, zip_header.formatted.filename_len);
283
284                 /* Skip extra header bytes */
285                 unzip_skip(src_fd, zip_header.formatted.extra_len);
286
287                 /* Filter zip entries */
288                 if (find_list_entry(zreject, dst_fn)
289                  || (zaccept && !find_list_entry(zaccept, dst_fn))
290                 ) { /* Skip entry */
291                         i = 'n';
292
293                 } else { /* Extract entry */
294                         if (listing) { /* List entry */
295                                 if (verbose) {
296                                         unsigned dostime = zip_header.formatted.modtime | (zip_header.formatted.moddate << 16);
297                                         printf("%9u  %02u-%02u-%02u %02u:%02u   %s\n",
298                                            zip_header.formatted.ucmpsize,
299                                            (dostime & 0x01e00000) >> 21,
300                                            (dostime & 0x001f0000) >> 16,
301                                            (((dostime & 0xfe000000) >> 25) + 1980) % 100,
302                                            (dostime & 0x0000f800) >> 11,
303                                            (dostime & 0x000007e0) >> 5,
304                                            dst_fn);
305                                         total_size += zip_header.formatted.ucmpsize;
306                                         total_entries++;
307                                 } else {
308                                         /* short listing -- filenames only */
309                                         puts(dst_fn);
310                                 }
311                                 i = 'n';
312                         } else if (dst_fd == STDOUT_FILENO) { /* Extracting to STDOUT */
313                                 i = -1;
314                         } else if (last_char_is(dst_fn, '/')) { /* Extract directory */
315                                 if (stat(dst_fn, &stat_buf) == -1) {
316                                         if (errno != ENOENT) {
317                                                 bb_perror_msg_and_die("cannot stat '%s'", dst_fn);
318                                         }
319                                         if (verbose) {
320                                                 printf("   creating: %s\n", dst_fn);
321                                         }
322                                         unzip_create_leading_dirs(dst_fn);
323                                         if (bb_make_directory(dst_fn, 0777, 0)) {
324                                                 bb_error_msg_and_die("exiting");
325                                         }
326                                 } else {
327                                         if (!S_ISDIR(stat_buf.st_mode)) {
328                                                 bb_error_msg_and_die("'%s' exists but is not directory", dst_fn);
329                                         }
330                                 }
331                                 i = 'n';
332
333                         } else {  /* Extract file */
334  _check_file:
335                                 if (stat(dst_fn, &stat_buf) == -1) { /* File does not exist */
336                                         if (errno != ENOENT) {
337                                                 bb_perror_msg_and_die("cannot stat '%s'", dst_fn);
338                                         }
339                                         i = 'y';
340                                 } else { /* File already exists */
341                                         if (overwrite == O_NEVER) {
342                                                 i = 'n';
343                                         } else if (S_ISREG(stat_buf.st_mode)) { /* File is regular file */
344                                                 if (overwrite == O_ALWAYS) {
345                                                         i = 'y';
346                                                 } else {
347                                                         printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
348                                                         if (!fgets(key_buf, sizeof(key_buf), stdin)) {
349                                                                 bb_perror_msg_and_die("cannot read input");
350                                                         }
351                                                         i = key_buf[0];
352                                                 }
353                                         } else { /* File is not regular file */
354                                                 bb_error_msg_and_die("'%s' exists but is not regular file", dst_fn);
355                                         }
356                                 }
357                         }
358                 }
359
360                 switch (i) {
361                 case 'A':
362                         overwrite = O_ALWAYS;
363                 case 'y': /* Open file and fall into unzip */
364                         unzip_create_leading_dirs(dst_fn);
365                         dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
366                 case -1: /* Unzip */
367                         if (verbose) {
368                                 printf("  inflating: %s\n", dst_fn);
369                         }
370                         unzip_extract(&zip_header, src_fd, dst_fd);
371                         if (dst_fd != STDOUT_FILENO) {
372                                 /* closing STDOUT is potentially bad for future business */
373                                 close(dst_fd);
374                         }
375                         break;
376
377                 case 'N':
378                         overwrite = O_NEVER;
379                 case 'n':
380                         /* Skip entry data */
381                         unzip_skip(src_fd, zip_header.formatted.cmpsize);
382                         break;
383
384                 case 'r':
385                         /* Prompt for new name */
386                         printf("new name: ");
387                         if (!fgets(key_buf, sizeof(key_buf), stdin)) {
388                                 bb_perror_msg_and_die("cannot read input");
389                         }
390                         free(dst_fn);
391                         dst_fn = xstrdup(key_buf);
392                         chomp(dst_fn);
393                         goto _check_file;
394
395                 default:
396                         printf("error: invalid response [%c]\n",(char)i);
397                         goto _check_file;
398                 }
399
400                 /* Data descriptor section */
401                 if (zip_header.formatted.flags & 4) {
402                         /* skip over duplicate crc, compressed size and uncompressed size */
403                         unzip_skip(src_fd, 12);
404                 }
405         }
406
407         if (listing && verbose) {
408                 printf(" --------                   -------\n"
409                        "%9d                   %d files\n",
410                        total_size, total_entries);
411         }
412
413         return 0;
414 }