ensure that corrupted file extraction causes both a message and
[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 <fcntl.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include "unarchive.h"
33 #include "busybox.h"
34
35 #if BB_BIG_ENDIAN
36 static inline unsigned short
37 __swap16(unsigned short x) {
38         return (((uint16_t)(x) & 0xFF) << 8) | (((uint16_t)(x) & 0xFF00) >> 8);
39 }
40
41 static inline uint32_t
42 __swap32(uint32_t x) {
43          return (((x & 0xFF) << 24) |
44                 ((x & 0xFF00) << 8) |
45                 ((x & 0xFF0000) >> 8) |
46                 ((x & 0xFF000000) >> 24));
47 }
48 #else /* it's little-endian */
49 # define __swap16(x) (x)
50 # define __swap32(x) (x)
51 #endif /* BB_BIG_ENDIAN */
52
53 #define ZIP_FILEHEADER_MAGIC            __swap32(0x04034b50)
54 #define ZIP_CDS_MAGIC                   __swap32(0x02014b50)
55 #define ZIP_CDS_END_MAGIC               __swap32(0x06054b50)
56 #define ZIP_DD_MAGIC                    __swap32(0x08074b50)
57
58 extern unsigned int gunzip_crc;
59 extern unsigned int gunzip_bytes_out;
60
61 typedef union {
62         unsigned char raw[26];
63         struct {
64                 unsigned short version; /* 0-1 */
65                 unsigned short flags;   /* 2-3 */
66                 unsigned short method;  /* 4-5 */
67                 unsigned short modtime; /* 6-7 */
68                 unsigned short moddate; /* 8-9 */
69                 unsigned int crc32 ATTRIBUTE_PACKED;    /* 10-13 */
70                 unsigned int cmpsize ATTRIBUTE_PACKED;  /* 14-17 */
71                 unsigned int ucmpsize ATTRIBUTE_PACKED; /* 18-21 */
72                 unsigned short filename_len;    /* 22-23 */
73                 unsigned short extra_len;               /* 24-25 */
74         } formated ATTRIBUTE_PACKED;
75 } zip_header_t;
76
77 static void unzip_skip(int fd, off_t skip)
78 {
79         if (lseek(fd, skip, SEEK_CUR) == (off_t)-1) {
80                 if ((errno != ESPIPE) || (bb_copyfd_size(fd, -1, skip) != skip)) {
81                         bb_error_msg_and_die("Seek failure");
82                 }
83         }
84 }
85
86 static void unzip_read(int fd, void *buf, size_t count)
87 {
88         if (bb_xread(fd, buf, count) != count) {
89                 bb_error_msg_and_die("Read failure");
90         }
91 }
92
93 static void unzip_create_leading_dirs(char *fn)
94 {
95         /* Create all leading directories */
96         char *name = bb_xstrdup(fn);
97         if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
98                 bb_error_msg_and_die("Failed to create directory");
99         }
100         free(name);
101 }
102
103 static int unzip_extract(zip_header_t *zip_header, int src_fd, int dst_fd)
104 {
105         if (zip_header->formated.method == 0) {
106                 /* Method 0 - stored (not compressed) */
107                 int size = zip_header->formated.ucmpsize;
108                 if (size && (bb_copyfd_size(src_fd, dst_fd, size) != size)) {
109                         bb_error_msg_and_die("Cannot complete extraction");
110                 }
111
112         } else {
113                 /* Method 8 - inflate */
114                 inflate_init(zip_header->formated.cmpsize);
115                 inflate_unzip(src_fd, dst_fd);
116                 inflate_cleanup();
117                 /* Validate decompression - crc */
118                 if (zip_header->formated.crc32 != (gunzip_crc ^ 0xffffffffL)) {
119                         bb_error_msg("Invalid compressed data--crc error");
120                         return 1;
121                 }
122                 /* Validate decompression - size */
123                 if (zip_header->formated.ucmpsize != gunzip_bytes_out) {
124                         bb_error_msg("Invalid compressed data--length error");
125                         return 1;
126                 }
127         }
128         return 0;
129 }
130
131 int unzip_main(int argc, char **argv)
132 {
133         zip_header_t zip_header;
134         enum {v_silent, v_normal, v_list} verbosity = v_normal;
135         enum {o_prompt, o_never, o_always} overwrite = o_prompt;
136         unsigned int total_size = 0;
137         unsigned int total_entries = 0;
138         int src_fd = -1, dst_fd = -1;
139         char *src_fn = NULL, *dst_fn = NULL;
140         llist_t *zaccept = NULL;
141         llist_t *zreject = NULL;
142         char *base_dir = NULL;
143         int failed, i, opt, opt_range = 0, list_header_done = 0;
144         char key_buf[512];
145         struct stat stat_buf;
146
147         while((opt = getopt(argc, argv, "-d:lnopqx")) != -1) {
148                 switch(opt_range) {
149                 case 0: /* Options */
150                         switch(opt) {
151                         case 'l': /* List */
152                                 verbosity = v_list;
153                                 break;
154
155                         case 'n': /* Never overwrite existing files */
156                                 overwrite = o_never;
157                                 break;
158
159                         case 'o': /* Always overwrite existing files */
160                                 overwrite = o_always;
161                                 break;
162
163                         case 'p': /* Extract files to stdout and fall through to set verbosity */
164                                 dst_fd = STDOUT_FILENO;
165
166                         case 'q': /* Be quiet */
167                                 verbosity = (verbosity == v_normal) ? v_silent : verbosity;
168                                 break;
169
170                         case 1 : /* The zip file */
171                                 src_fn = bb_xstrndup(optarg, strlen(optarg)+4);
172                                 opt_range++;
173                                 break;
174
175                         default:
176                                 bb_show_usage();
177
178                         }
179                         break;
180
181                 case 1: /* Include files */
182                         if (opt == 1) {
183                                 zaccept = llist_add_to(zaccept, optarg);
184
185                         } else if (opt == 'd') {
186                                 base_dir = optarg;
187                                 opt_range += 2;
188
189                         } else if (opt == 'x') {
190                                 opt_range++;
191
192                         } else {
193                                 bb_show_usage();
194                         }
195                         break;
196
197                 case 2 : /* Exclude files */
198                         if (opt == 1) {
199                                 zreject = llist_add_to(zreject, optarg);
200
201                         } else if (opt == 'd') { /* Extract to base directory */
202                                 base_dir = optarg;
203                                 opt_range++;
204
205                         } else {
206                                 bb_show_usage();
207                         }
208                         break;
209
210                 default:
211                         bb_show_usage();
212                 }
213         }
214
215         if (src_fn == NULL) {
216                 bb_show_usage();
217         }
218
219         /* Open input file */
220         if (strcmp("-", src_fn) == 0) {
221                 src_fd = STDIN_FILENO;
222                 /* Cannot use prompt mode since zip data is arriving on STDIN */
223                 overwrite = (overwrite == o_prompt) ? o_never : overwrite;
224
225         } else {
226                 static const char *const extn[] = {"", ".zip", ".ZIP"};
227                 int orig_src_fn_len = strlen(src_fn);
228                 for(i = 0; (i < 3) && (src_fd == -1); i++) {
229                         strcpy(src_fn + orig_src_fn_len, extn[i]);
230                         src_fd = open(src_fn, O_RDONLY);
231                 }
232                 if (src_fd == -1) {
233                         src_fn[orig_src_fn_len] = 0;
234                         bb_error_msg_and_die("Cannot open %s, %s.zip, %s.ZIP", src_fn, src_fn, src_fn);
235                 }
236         }
237
238         /* Change dir if necessary */
239         if (base_dir && chdir(base_dir)) {
240                 bb_perror_msg_and_die("Cannot chdir");
241         }
242
243         if (verbosity != v_silent)
244                 printf("Archive:  %s\n", src_fn);
245
246         failed = 0;
247
248         while (1) {
249                 unsigned int magic;
250
251                 /* Check magic number */
252                 unzip_read(src_fd, &magic, 4);
253                 if (magic == ZIP_CDS_MAGIC) {
254                         break;
255                 } else if (magic != ZIP_FILEHEADER_MAGIC) {
256                         bb_error_msg_and_die("Invalid zip magic %08X", magic);
257                 }
258
259                 /* Read the file header */
260                 unzip_read(src_fd, zip_header.raw, 26);
261 #if BB_BIG_ENDIAN
262                 zip_header.formated.version = __swap16(zip_header.formated.version);
263                 zip_header.formated.flags = __swap16(zip_header.formated.flags);
264                 zip_header.formated.method = __swap16(zip_header.formated.method);
265                 zip_header.formated.modtime = __swap16(zip_header.formated.modtime);
266                 zip_header.formated.moddate = __swap16(zip_header.formated.moddate);
267                 zip_header.formated.crc32 = __swap32(zip_header.formated.crc32);
268                 zip_header.formated.cmpsize = __swap32(zip_header.formated.cmpsize);
269                 zip_header.formated.ucmpsize = __swap32(zip_header.formated.ucmpsize);
270                 zip_header.formated.filename_len = __swap16(zip_header.formated.filename_len);
271                 zip_header.formated.extra_len = __swap16(zip_header.formated.extra_len);
272 #endif /* BB_BIG_ENDIAN */
273                 if ((zip_header.formated.method != 0) && (zip_header.formated.method != 8)) {
274                         bb_error_msg_and_die("Unsupported compression method %d", zip_header.formated.method);
275                 }
276
277                 /* Read filename */
278                 free(dst_fn);
279                 dst_fn = xmalloc(zip_header.formated.filename_len + 1);
280                 unzip_read(src_fd, dst_fn, zip_header.formated.filename_len);
281                 dst_fn[zip_header.formated.filename_len] = 0;
282
283                 /* Skip extra header bytes */
284                 unzip_skip(src_fd, zip_header.formated.extra_len);
285
286                 if ((verbosity == v_list) && !list_header_done){
287                         printf("  Length     Date   Time    Name\n");
288                         printf(" --------    ----   ----    ----\n");
289                         list_header_done = 1;
290                 }
291
292                 /* Filter zip entries */
293                 if (find_list_entry(zreject, dst_fn) ||
294                         (zaccept && !find_list_entry(zaccept, dst_fn))) { /* Skip entry */
295                         i = 'n';
296
297                 } else { /* Extract entry */
298                         total_size += zip_header.formated.ucmpsize;
299
300                         if (verbosity == v_list) { /* List entry */
301                                 unsigned int dostime = zip_header.formated.modtime | (zip_header.formated.moddate << 16);
302                                 printf("%9u  %02u-%02u-%02u %02u:%02u   %s\n",
303                                            zip_header.formated.ucmpsize,
304                                            (dostime & 0x01e00000) >> 21,
305                                            (dostime & 0x001f0000) >> 16,
306                                            (((dostime & 0xfe000000) >> 25) + 1980) % 100,
307                                            (dostime & 0x0000f800) >> 11,
308                                            (dostime & 0x000007e0) >> 5,
309                                            dst_fn);
310                                 total_entries++;
311                                 i = 'n';
312
313                         } else if (dst_fd == STDOUT_FILENO) { /* Extracting to STDOUT */
314                                 i = -1;
315
316                         } else if (last_char_is(dst_fn, '/')) { /* Extract directory */
317                                 if (stat(dst_fn, &stat_buf) == -1) {
318                                         if (errno != ENOENT) {
319                                                 bb_perror_msg_and_die("Cannot stat '%s'",dst_fn);
320                                         }
321                                         if (verbosity == v_normal) {
322                                                 printf("   creating: %s\n", dst_fn);
323                                         }
324                                         unzip_create_leading_dirs(dst_fn);
325                                         if (bb_make_directory(dst_fn, 0777, 0)) {
326                                                 bb_error_msg_and_die("Failed to create directory");
327                                         }
328                                 } else {
329                                         if (!S_ISDIR(stat_buf.st_mode)) {
330                                                 bb_error_msg_and_die("'%s' exists but is not directory", dst_fn);
331                                         }
332                                 }
333                                 i = 'n';
334
335                         } else {  /* Extract file */
336                         _check_file:
337                                 if (stat(dst_fn, &stat_buf) == -1) { /* File does not exist */
338                                         if (errno != ENOENT) {
339                                                 bb_perror_msg_and_die("Cannot stat '%s'",dst_fn);
340                                         }
341                                         i = 'y';
342
343                                 } else { /* File already exists */
344                                         if (overwrite == o_never) {
345                                                 i = 'n';
346
347                                         } else if (S_ISREG(stat_buf.st_mode)) { /* File is regular file */
348                                                 if (overwrite == o_always) {
349                                                         i = 'y';
350                                                 } else {
351                                                         printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
352                                                         if (!fgets(key_buf, 512, stdin)) {
353                                                                 bb_perror_msg_and_die("Cannot read input");
354                                                         }
355                                                         i = key_buf[0];
356                                                 }
357
358                                         } else { /* File is not regular file */
359                                                 bb_error_msg_and_die("'%s' exists but is not regular file",dst_fn);
360                                         }
361                                 }
362                         }
363                 }
364
365                 switch (i) {
366                 case 'A':
367                         overwrite = o_always;
368                 case 'y': /* Open file and fall into unzip */
369                         unzip_create_leading_dirs(dst_fn);
370                         dst_fd = bb_xopen(dst_fn, O_WRONLY | O_CREAT);
371                 case -1: /* Unzip */
372                         if (verbosity == v_normal) {
373                                 printf("  inflating: %s\n", dst_fn);
374                         }
375                         if (unzip_extract(&zip_header, src_fd, dst_fd)) {
376                             failed = 1;
377                         }
378                         if (dst_fd != STDOUT_FILENO) {
379                                 /* closing STDOUT is potentially bad for future business */
380                                 close(dst_fd);
381                         }
382                         break;
383
384                 case 'N':
385                         overwrite = o_never;
386                 case 'n':
387                         /* Skip entry data */
388                         unzip_skip(src_fd, zip_header.formated.cmpsize);
389                         break;
390
391                 case 'r':
392                         /* Prompt for new name */
393                         printf("new name: ");
394                         if (!fgets(key_buf, 512, stdin)) {
395                                 bb_perror_msg_and_die("Cannot read input");
396                         }
397                         free(dst_fn);
398                         dst_fn = bb_xstrdup(key_buf);
399                         chomp(dst_fn);
400                         goto _check_file;
401
402                 default:
403                         printf("error: invalid response [%c]\n",(char)i);
404                         goto _check_file;
405                 }
406
407                 /* Data descriptor section */
408                 if (zip_header.formated.flags & 4) {
409                         /* skip over duplicate crc, compressed size and uncompressed size */
410                         unzip_skip(src_fd, 12);
411                 }
412         }
413
414         if (verbosity == v_list) {
415                 printf(" --------                   -------\n"
416                        "%9d                   %d files\n", total_size, total_entries);
417         }
418
419         return failed;
420 }
421
422 /* END CODE */
423 /*
424 Local Variables:
425 c-file-style: "linux"
426 c-basic-offset: 4
427 tab-width: 4
428 End:
429 */