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