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