Import libarchive 2.0.28.
[dragonfly.git] / contrib / libarchive-2.0 / libarchive / archive_read_support_format_zip.c
1 /*-
2  * Copyright (c) 2004 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "archive_platform.h"
27 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_format_zip.c,v 1.11 2007/03/03 07:37:36 kientzle Exp $");
28
29 #ifdef HAVE_SYS_STAT_H
30 #include <sys/stat.h>
31 #endif
32 #ifdef HAVE_ERRNO_H
33 #include <errno.h>
34 #endif
35 #include <stdio.h>
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 #include <time.h>
40 #ifdef HAVE_ZLIB_H
41 #include <zlib.h>
42 #endif
43
44 #include "archive.h"
45 #include "archive_entry.h"
46 #include "archive_private.h"
47 #include "archive_read_private.h"
48
49 struct zip {
50         /* entry_bytes_remaining is the number of bytes we expect. */
51         int64_t                 entry_bytes_remaining;
52         int64_t                 entry_offset;
53
54         /* These count the number of bytes actually read for the entry. */
55         int64_t                 entry_compressed_bytes_read;
56         int64_t                 entry_uncompressed_bytes_read;
57
58         unsigned                version;
59         unsigned                system;
60         unsigned                flags;
61         unsigned                compression;
62         const char *            compression_name;
63         time_t                  mtime;
64         time_t                  ctime;
65         time_t                  atime;
66         mode_t                  mode;
67         uid_t                   uid;
68         gid_t                   gid;
69
70         /* Flags to mark progress of decompression. */
71         char                    decompress_init;
72         char                    end_of_entry;
73         char                    end_of_entry_cleanup;
74
75         long                    crc32;
76         ssize_t                 filename_length;
77         ssize_t                 extra_length;
78         int64_t                 uncompressed_size;
79         int64_t                 compressed_size;
80
81         unsigned char           *uncompressed_buffer;
82         size_t                  uncompressed_buffer_size;
83 #ifdef HAVE_ZLIB_H
84         z_stream                stream;
85 #endif
86
87         struct archive_string   pathname;
88         struct archive_string   extra;
89         char    format_name[64];
90 };
91
92 #define ZIP_LENGTH_AT_END       8
93
94 struct zip_file_header {
95         char    signature[4];
96         char    version[2];
97         char    flags[2];
98         char    compression[2];
99         char    timedate[4];
100         char    crc32[4];
101         char    compressed_size[4];
102         char    uncompressed_size[4];
103         char    filename_length[2];
104         char    extra_length[2];
105 };
106
107 static const char *compression_names[] = {
108         "uncompressed",
109         "shrinking",
110         "reduced-1",
111         "reduced-2",
112         "reduced-3",
113         "reduced-4",
114         "imploded",
115         "reserved",
116         "deflation"
117 };
118
119 static int      archive_read_format_zip_bid(struct archive_read *);
120 static int      archive_read_format_zip_cleanup(struct archive_read *);
121 static int      archive_read_format_zip_read_data(struct archive_read *,
122                     const void **, size_t *, off_t *);
123 static int      archive_read_format_zip_read_data_skip(struct archive_read *a);
124 static int      archive_read_format_zip_read_header(struct archive_read *,
125                     struct archive_entry *);
126 static int      i2(const char *);
127 static int      i4(const char *);
128 static unsigned int     u2(const char *);
129 static unsigned int     u4(const char *);
130 static uint64_t u8(const char *);
131 static int      zip_read_data_deflate(struct archive_read *a, const void **buff,
132                     size_t *size, off_t *offset);
133 static int      zip_read_data_none(struct archive_read *a, const void **buff,
134                     size_t *size, off_t *offset);
135 static int      zip_read_file_header(struct archive_read *a,
136                     struct archive_entry *entry, struct zip *zip);
137 static time_t   zip_time(const char *);
138 static void process_extra(const void* extra, struct zip* zip);
139
140 /* Largest 32-bit unsigned value, stored in a 64-bit constant. */
141 static const uint64_t max_uint32 = (((uint64_t)1) << 32) - 1;
142
143 int
144 archive_read_support_format_zip(struct archive *_a)
145 {
146         struct archive_read *a = (struct archive_read *)_a;
147         struct zip *zip;
148         int r;
149
150         zip = (struct zip *)malloc(sizeof(*zip));
151         if (zip == NULL) {
152                 archive_set_error(&a->archive, ENOMEM, "Can't allocate zip data");
153                 return (ARCHIVE_FATAL);
154         }
155         memset(zip, 0, sizeof(*zip));
156
157         r = __archive_read_register_format(a,
158             zip,
159             archive_read_format_zip_bid,
160             archive_read_format_zip_read_header,
161             archive_read_format_zip_read_data,
162             archive_read_format_zip_read_data_skip,
163             archive_read_format_zip_cleanup);
164
165         if (r != ARCHIVE_OK)
166                 free(zip);
167         return (ARCHIVE_OK);
168 }
169
170
171 static int
172 archive_read_format_zip_bid(struct archive_read *a)
173 {
174         int bytes_read;
175         int bid = 0;
176         const void *h;
177         const char *p;
178
179         if (a->archive.archive_format == ARCHIVE_FORMAT_ZIP)
180                 bid += 1;
181
182         bytes_read = (a->compression_read_ahead)(a, &h, 4);
183         if (bytes_read < 4)
184             return (-1);
185         p = (const char *)h;
186
187         if (p[0] == 'P' && p[1] == 'K') {
188                 bid += 16;
189                 if (p[2] == '\001' && p[3] == '\002')
190                         bid += 16;
191                 else if (p[2] == '\003' && p[3] == '\004')
192                         bid += 16;
193                 else if (p[2] == '\005' && p[3] == '\006')
194                         bid += 16;
195                 else if (p[2] == '\007' && p[3] == '\010')
196                         bid += 16;
197         }
198         return (bid);
199 }
200
201 static int
202 archive_read_format_zip_read_header(struct archive_read *a,
203     struct archive_entry *entry)
204 {
205         int bytes_read;
206         const void *h;
207         const char *signature;
208         struct zip *zip;
209
210         a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
211         if (a->archive.archive_format_name == NULL)
212                 a->archive.archive_format_name = "ZIP";
213
214         zip = (struct zip *)*(a->pformat_data);
215         zip->decompress_init = 0;
216         zip->end_of_entry = 0;
217         zip->end_of_entry_cleanup = 0;
218         zip->entry_uncompressed_bytes_read = 0;
219         zip->entry_compressed_bytes_read = 0;
220         bytes_read = (a->compression_read_ahead)(a, &h, 4);
221         if (bytes_read < 4)
222                 return (ARCHIVE_FATAL);
223
224         signature = (const char *)h;
225         if (signature[0] != 'P' || signature[1] != 'K') {
226                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
227                     "Bad ZIP file");
228                 return (ARCHIVE_FATAL);
229         }
230
231         if (signature[2] == '\001' && signature[3] == '\002') {
232                 /* Beginning of central directory. */
233                 return (ARCHIVE_EOF);
234         }
235
236         if (signature[2] == '\003' && signature[3] == '\004') {
237                 /* Regular file entry. */
238                 return (zip_read_file_header(a, entry, zip));
239         }
240
241         if (signature[2] == '\005' && signature[3] == '\006') {
242                 /* End-of-archive record. */
243                 return (ARCHIVE_EOF);
244         }
245
246         if (signature[2] == '\007' && signature[3] == '\010') {
247                 /*
248                  * We should never encounter this record here;
249                  * see ZIP_LENGTH_AT_END handling below for details.
250                  */
251                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
252                     "Bad ZIP file: Unexpected end-of-entry record");
253                 return (ARCHIVE_FATAL);
254         }
255
256         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
257             "Damaged ZIP file or unsupported format variant (%d,%d)",
258             signature[2], signature[3]);
259         return (ARCHIVE_FATAL);
260 }
261
262 int
263 zip_read_file_header(struct archive_read *a, struct archive_entry *entry,
264     struct zip *zip)
265 {
266         const struct zip_file_header *p;
267         const void *h;
268         int bytes_read;
269         struct stat st;
270
271         bytes_read =
272             (a->compression_read_ahead)(a, &h, sizeof(struct zip_file_header));
273         if (bytes_read < (int)sizeof(struct zip_file_header)) {
274                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
275                     "Truncated ZIP file header");
276                 return (ARCHIVE_FATAL);
277         }
278         p = (const struct zip_file_header *)h;
279
280         zip->version = p->version[0];
281         zip->system = p->version[1];
282         zip->flags = i2(p->flags);
283         zip->compression = i2(p->compression);
284         if (zip->compression <
285             sizeof(compression_names)/sizeof(compression_names[0]))
286                 zip->compression_name = compression_names[zip->compression];
287         else
288                 zip->compression_name = "??";
289         zip->mtime = zip_time(p->timedate);
290         zip->ctime = 0;
291         zip->atime = 0;
292         zip->mode = 0;
293         zip->uid = 0;
294         zip->gid = 0;
295         zip->crc32 = i4(p->crc32);
296         zip->filename_length = i2(p->filename_length);
297         zip->extra_length = i2(p->extra_length);
298         zip->uncompressed_size = u4(p->uncompressed_size);
299         zip->compressed_size = u4(p->compressed_size);
300
301         (a->compression_read_consume)(a, sizeof(struct zip_file_header));
302
303
304         /* Read the filename. */
305         bytes_read = (a->compression_read_ahead)(a, &h, zip->filename_length);
306         if (bytes_read < zip->filename_length) {
307                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
308                     "Truncated ZIP file header");
309                 return (ARCHIVE_FATAL);
310         }
311         archive_string_ensure(&zip->pathname, zip->filename_length);
312         archive_strncpy(&zip->pathname, (const char *)h, zip->filename_length);
313         (a->compression_read_consume)(a, zip->filename_length);
314         archive_entry_set_pathname(entry, zip->pathname.s);
315
316         if (zip->pathname.s[archive_strlen(&zip->pathname) - 1] == '/')
317                 zip->mode = S_IFDIR | 0777;
318         else
319                 zip->mode = S_IFREG | 0777;
320
321         /* Read the extra data. */
322         bytes_read = (a->compression_read_ahead)(a, &h, zip->extra_length);
323         if (bytes_read < zip->extra_length) {
324                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
325                     "Truncated ZIP file header");
326                 return (ARCHIVE_FATAL);
327         }
328         process_extra(h, zip);
329         (a->compression_read_consume)(a, zip->extra_length);
330
331         /* Populate some additional entry fields: */
332         memset(&st, 0, sizeof(st));
333         st.st_mode = zip->mode;
334         st.st_uid = zip->uid;
335         st.st_gid = zip->gid;
336         st.st_mtime = zip->mtime;
337         st.st_ctime = zip->ctime;
338         st.st_atime = zip->atime;
339         st.st_size = zip->uncompressed_size;
340         archive_entry_copy_stat(entry, &st);
341
342         zip->entry_bytes_remaining = zip->compressed_size;
343         zip->entry_offset = 0;
344
345         /* Set up a more descriptive format name. */
346         sprintf(zip->format_name, "ZIP %d.%d (%s)",
347             zip->version / 10, zip->version % 10,
348             zip->compression_name);
349         a->archive.archive_format_name = zip->format_name;
350
351         return (ARCHIVE_OK);
352 }
353
354 /* Convert an MSDOS-style date/time into Unix-style time. */
355 static time_t
356 zip_time(const char *p)
357 {
358         int msTime, msDate;
359         struct tm ts;
360
361         msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
362         msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
363
364         memset(&ts, 0, sizeof(ts));
365         ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
366         ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
367         ts.tm_mday = msDate & 0x1f; /* Day of month. */
368         ts.tm_hour = (msTime >> 11) & 0x1f;
369         ts.tm_min = (msTime >> 5) & 0x3f;
370         ts.tm_sec = (msTime << 1) & 0x3e;
371         ts.tm_isdst = -1;
372         return mktime(&ts);
373 }
374
375 static int
376 archive_read_format_zip_read_data(struct archive_read *a,
377     const void **buff, size_t *size, off_t *offset)
378 {
379         int r;
380         struct zip *zip;
381
382         zip = (struct zip *)*(a->pformat_data);
383
384         /*
385          * If we hit end-of-entry last time, clean up and return
386          * ARCHIVE_EOF this time.
387          */
388         if (zip->end_of_entry) {
389                 if (!zip->end_of_entry_cleanup) {
390                         if (zip->flags & ZIP_LENGTH_AT_END) {
391                                 const void *h;
392                                 const char *p;
393                                 int bytes_read =
394                                     (a->compression_read_ahead)(a, &h, 16);
395                                 if (bytes_read < 16) {
396                                         archive_set_error(&a->archive,
397                                             ARCHIVE_ERRNO_FILE_FORMAT,
398                                             "Truncated ZIP end-of-file record");
399                                         return (ARCHIVE_FATAL);
400                                 }
401                                 p = (const char *)h;
402                                 zip->crc32 = i4(p + 4);
403                                 zip->compressed_size = u4(p + 8);
404                                 zip->uncompressed_size = u4(p + 12);
405                                 bytes_read = (a->compression_read_consume)(a, 16);
406                         }
407
408                         /* Check file size, CRC against these values. */
409                         if (zip->compressed_size != zip->entry_compressed_bytes_read) {
410                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
411                                     "ZIP compressed data is wrong size");
412                                 return (ARCHIVE_WARN);
413                         }
414                         /* Size field only stores the lower 32 bits of the actual size. */
415                         if ((zip->uncompressed_size & max_uint32)
416                             != (zip->entry_uncompressed_bytes_read & max_uint32)) {
417                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
418                                     "ZIP uncompressed data is wrong size");
419                                 return (ARCHIVE_WARN);
420                         }
421 /* TODO: Compute CRC. */
422 /*
423                         if (zip->crc32 != zip->entry_crc32_calculated) {
424                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
425                                     "ZIP data CRC error");
426                                 return (ARCHIVE_WARN);
427                         }
428 */
429                         /* End-of-entry cleanup done. */
430                         zip->end_of_entry_cleanup = 1;
431                 }
432                 return (ARCHIVE_EOF);
433         }
434
435         switch(zip->compression) {
436         case 0:  /* No compression. */
437                 r =  zip_read_data_none(a, buff, size, offset);
438                 break;
439         case 8: /* Deflate compression. */
440                 r =  zip_read_data_deflate(a, buff, size, offset);
441                 break;
442         default: /* Unsupported compression. */
443                 *buff = NULL;
444                 *size = 0;
445                 *offset = 0;
446                 /* Return a warning. */
447                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
448                     "Unsupported ZIP compression method (%s)",
449                     zip->compression_name);
450                 if (zip->flags & ZIP_LENGTH_AT_END) {
451                         /*
452                          * ZIP_LENGTH_AT_END requires us to
453                          * decompress the entry in order to
454                          * skip it, but we don't know this
455                          * compression method, so we give up.
456                          */
457                         r = ARCHIVE_FATAL;
458                 } else {
459                         /* We know compressed size; just skip it. */
460                         archive_read_format_zip_read_data_skip(a);
461                         r = ARCHIVE_WARN;
462                 }
463                 break;
464         }
465         return (r);
466 }
467
468 /*
469  * Read "uncompressed" data.  According to the current specification,
470  * if ZIP_LENGTH_AT_END is specified, then the size fields in the
471  * initial file header are supposed to be set to zero.  This would, of
472  * course, make it impossible for us to read the archive, since we
473  * couldn't determine the end of the file data.  Info-ZIP seems to
474  * include the real size fields both before and after the data in this
475  * case (the CRC only appears afterwards), so this works as you would
476  * expect.
477  *
478  * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
479  * zip->end_of_entry if it consumes all of the data.
480  */
481 static int
482 zip_read_data_none(struct archive_read *a, const void **buff,
483     size_t *size, off_t *offset)
484 {
485         struct zip *zip;
486         ssize_t bytes_avail;
487
488         zip = (struct zip *)*(a->pformat_data);
489
490         if (zip->entry_bytes_remaining == 0) {
491                 *buff = NULL;
492                 *size = 0;
493                 *offset = zip->entry_offset;
494                 zip->end_of_entry = 1;
495                 return (ARCHIVE_OK);
496         }
497         /*
498          * Note: '1' here is a performance optimization.
499          * Recall that the decompression layer returns a count of
500          * available bytes; asking for more than that forces the
501          * decompressor to combine reads by copying data.
502          */
503         bytes_avail = (a->compression_read_ahead)(a, buff, 1);
504         if (bytes_avail <= 0) {
505                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
506                     "Truncated ZIP file data");
507                 return (ARCHIVE_FATAL);
508         }
509         if (bytes_avail > zip->entry_bytes_remaining)
510                 bytes_avail = zip->entry_bytes_remaining;
511         (a->compression_read_consume)(a, bytes_avail);
512         *size = bytes_avail;
513         *offset = zip->entry_offset;
514         zip->entry_offset += *size;
515         zip->entry_bytes_remaining -= *size;
516         zip->entry_uncompressed_bytes_read += *size;
517         zip->entry_compressed_bytes_read += *size;
518         return (ARCHIVE_OK);
519 }
520
521 #ifdef HAVE_ZLIB_H
522 static int
523 zip_read_data_deflate(struct archive_read *a, const void **buff,
524     size_t *size, off_t *offset)
525 {
526         struct zip *zip;
527         ssize_t bytes_avail;
528         const void *compressed_buff;
529         int r;
530
531         zip = (struct zip *)*(a->pformat_data);
532
533         /* If the buffer hasn't been allocated, allocate it now. */
534         if (zip->uncompressed_buffer == NULL) {
535                 zip->uncompressed_buffer_size = 32 * 1024;
536                 zip->uncompressed_buffer
537                     = (unsigned char *)malloc(zip->uncompressed_buffer_size);
538                 if (zip->uncompressed_buffer == NULL) {
539                         archive_set_error(&a->archive, ENOMEM,
540                             "No memory for ZIP decompression");
541                         return (ARCHIVE_FATAL);
542                 }
543         }
544
545         /* If we haven't yet read any data, initialize the decompressor. */
546         if (!zip->decompress_init) {
547                 r = inflateInit2(&zip->stream,
548                     -15 /* Don't check for zlib header */);
549                 if (r != Z_OK) {
550                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
551                             "Can't initialize ZIP decompression.");
552                         return (ARCHIVE_FATAL);
553                 }
554                 zip->decompress_init = 1;
555         }
556
557         /*
558          * Note: '1' here is a performance optimization.
559          * Recall that the decompression layer returns a count of
560          * available bytes; asking for more than that forces the
561          * decompressor to combine reads by copying data.
562          */
563         bytes_avail = (a->compression_read_ahead)(a, &compressed_buff, 1);
564         if (bytes_avail <= 0) {
565                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
566                     "Truncated ZIP file body");
567                 return (ARCHIVE_FATAL);
568         }
569
570         /*
571          * A bug in zlib.h: stream.next_in should be marked 'const'
572          * but isn't (the library never alters data through the
573          * next_in pointer, only reads it).  The result: this ugly
574          * cast to remove 'const'.
575          */
576         zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
577         zip->stream.avail_in = bytes_avail;
578         zip->stream.total_in = 0;
579         zip->stream.next_out = zip->uncompressed_buffer;
580         zip->stream.avail_out = zip->uncompressed_buffer_size;
581         zip->stream.total_out = 0;
582
583         r = inflate(&zip->stream, 0);
584         switch (r) {
585         case Z_OK:
586                 break;
587         case Z_STREAM_END:
588                 zip->end_of_entry = 1;
589                 break;
590         case Z_MEM_ERROR:
591                 archive_set_error(&a->archive, ENOMEM,
592                     "Out of memory for ZIP decompression");
593                 return (ARCHIVE_FATAL);
594         default:
595                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
596                     "ZIP decompression failed (%d)", r);
597                 return (ARCHIVE_FATAL);
598         }
599
600         /* Consume as much as the compressor actually used. */
601         bytes_avail = zip->stream.total_in;
602         (a->compression_read_consume)(a, bytes_avail);
603         zip->entry_bytes_remaining -= bytes_avail;
604         zip->entry_compressed_bytes_read += bytes_avail;
605
606         *offset = zip->entry_offset;
607         *size = zip->stream.total_out;
608         zip->entry_uncompressed_bytes_read += *size;
609         *buff = zip->uncompressed_buffer;
610         zip->entry_offset += *size;
611         return (ARCHIVE_OK);
612 }
613 #else
614 static int
615 zip_read_data_deflate(struct archive_read *a, const void **buff,
616     size_t *size, off_t *offset)
617 {
618         *buff = NULL;
619         *size = 0;
620         *offset = 0;
621         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
622             "libarchive compiled without deflate support (no libz)");
623         return (ARCHIVE_FATAL);
624 }
625 #endif
626
627 static int
628 archive_read_format_zip_read_data_skip(struct archive_read *a)
629 {
630         struct zip *zip;
631         const void *buff = NULL;
632         ssize_t bytes_avail;
633
634         zip = (struct zip *)*(a->pformat_data);
635
636         /*
637          * If the length is at the end, we have no choice but
638          * to decompress all the data to find the end marker.
639          */
640         if (zip->flags & ZIP_LENGTH_AT_END) {
641                 size_t size;
642                 off_t offset;
643                 int r;
644                 do {
645                         r = archive_read_format_zip_read_data(a, &buff,
646                             &size, &offset);
647                 } while (r == ARCHIVE_OK);
648                 return (r);
649         }
650
651         /*
652          * If the length is at the beginning, we can skip the
653          * compressed data much more quickly.
654          */
655         while (zip->entry_bytes_remaining > 0) {
656                 bytes_avail = (a->compression_read_ahead)(a, &buff, 1);
657                 if (bytes_avail <= 0) {
658                         archive_set_error(&a->archive,
659                             ARCHIVE_ERRNO_FILE_FORMAT,
660                             "Truncated ZIP file body");
661                         return (ARCHIVE_FATAL);
662                 }
663                 if (bytes_avail > zip->entry_bytes_remaining)
664                         bytes_avail = zip->entry_bytes_remaining;
665                 (a->compression_read_consume)(a, bytes_avail);
666                 zip->entry_bytes_remaining -= bytes_avail;
667         }
668         /* This entry is finished and done. */
669         zip->end_of_entry_cleanup = zip->end_of_entry = 1;
670         return (ARCHIVE_OK);
671 }
672
673 static int
674 archive_read_format_zip_cleanup(struct archive_read *a)
675 {
676         struct zip *zip;
677
678         zip = (struct zip *)*(a->pformat_data);
679         if (zip->uncompressed_buffer != NULL)
680                 free(zip->uncompressed_buffer);
681         archive_string_free(&(zip->pathname));
682         archive_string_free(&(zip->extra));
683         free(zip);
684         *(a->pformat_data) = NULL;
685         return (ARCHIVE_OK);
686 }
687
688 static int
689 i2(const char *p)
690 {
691         return ((0xff & (int)p[0]) + 256 * (0xff & (int)p[1]));
692 }
693
694
695 static int
696 i4(const char *p)
697 {
698         return ((0xffff & i2(p)) + 0x10000 * (0xffff & i2(p+2)));
699 }
700
701 static unsigned int
702 u2(const char *p)
703 {
704         return ((0xff & (unsigned int)p[0]) + 256 * (0xff & (unsigned int)p[1]));
705 }
706
707 static unsigned int
708 u4(const char *p)
709 {
710         return u2(p) + 0x10000 * u2(p+2);
711 }
712
713 static uint64_t
714 u8(const char *p)
715 {
716         return u4(p) + 0x100000000LL * u4(p+4);
717 }
718
719 /*
720  * The extra data is stored as a list of
721  *      id1+size1+data1 + id2+size2+data2 ...
722  *  triplets.  id and size are 2 bytes each.
723  */
724 static void
725 process_extra(const void* extra, struct zip* zip)
726 {
727         int offset = 0;
728         const char *p = (const char *)extra;
729         while (offset < zip->extra_length - 4)
730         {
731                 unsigned short headerid = u2(p + offset);
732                 unsigned short datasize = u2(p + offset + 2);
733                 offset += 4;
734                 if (offset + datasize > zip->extra_length)
735                         break;
736 #ifdef DEBUG
737                 fprintf(stderr, "Header id 0x%04x, length %d\n",
738                     headerid, datasize);
739 #endif
740                 switch (headerid) {
741                 case 0x0001:
742                         /* Zip64 extended information extra field. */
743                         if (datasize >= 8)
744                                 zip->uncompressed_size = u8(p + offset);
745                         if (datasize >= 16)
746                                 zip->compressed_size = u8(p + offset + 8);
747                         break;
748                 case 0x5455:
749                 {
750                         /* Extended time field "UT". */
751                         int flags = p[offset];
752                         offset++;
753                         datasize--;
754                         /* Flag bits indicate which dates are present. */
755                         if (flags & 0x01)
756                         {
757 #ifdef DEBUG
758                                 fprintf(stderr, "mtime: %d -> %d\n",
759                                     zip->mtime, i4(p + offset));
760 #endif
761                                 if (datasize < 4)
762                                         break;
763                                 zip->mtime = i4(p + offset);
764                                 offset += 4;
765                                 datasize -= 4;
766                         }
767                         if (flags & 0x02)
768                         {
769                                 if (datasize < 4)
770                                         break;
771                                 zip->atime = i4(p + offset);
772                                 offset += 4;
773                                 datasize -= 4;
774                         }
775                         if (flags & 0x04)
776                         {
777                                 if (datasize < 4)
778                                         break;
779                                 zip->ctime = i4(p + offset);
780                                 offset += 4;
781                                 datasize -= 4;
782                         }
783                         break;
784                 }
785                 case 0x7855:
786                         /* Info-ZIP Unix Extra Field (type 2) "Ux". */
787 #ifdef DEBUG
788                         fprintf(stderr, "uid %d gid %d\n",
789                             i2(p + offset), i2(p + offset + 2));
790 #endif
791                         if (datasize >= 2)
792                                 zip->uid = i2(p + offset);
793                         if (datasize >= 4)
794                                 zip->gid = i2(p + offset + 2);
795                         break;
796                 default:
797                         break;
798                 }
799                 offset += datasize;
800         }
801 #ifdef DEBUG
802         if (offset != zip->extra_length)
803         {
804                 fprintf(stderr,
805                     "Extra data field contents do not match reported size!");
806         }
807 #endif
808 }