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