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