]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - lib/libarchive/archive_read_support_format_zip.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / lib / 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$");
28
29 #ifdef HAVE_ERRNO_H
30 #include <errno.h>
31 #endif
32 #include <stdio.h>
33 #ifdef HAVE_STDLIB_H
34 #include <stdlib.h>
35 #endif
36 #include <time.h>
37 #ifdef HAVE_ZLIB_H
38 #include <zlib.h>
39 #endif
40
41 #include "archive.h"
42 #include "archive_entry.h"
43 #include "archive_private.h"
44 #include "archive_read_private.h"
45 #include "archive_endian.h"
46
47 struct zip {
48         /* entry_bytes_remaining is the number of bytes we expect. */
49         int64_t                 entry_bytes_remaining;
50         int64_t                 entry_offset;
51
52         /* These count the number of bytes actually read for the entry. */
53         int64_t                 entry_compressed_bytes_read;
54         int64_t                 entry_uncompressed_bytes_read;
55
56         /* Running CRC32 of the decompressed data */
57         unsigned long           entry_crc32;
58
59         unsigned                version;
60         unsigned                system;
61         unsigned                flags;
62         unsigned                compression;
63         const char *            compression_name;
64         time_t                  mtime;
65         time_t                  ctime;
66         time_t                  atime;
67         mode_t                  mode;
68         uid_t                   uid;
69         gid_t                   gid;
70
71         /* Flags to mark progress of decompression. */
72         char                    decompress_init;
73         char                    end_of_entry;
74         char                    end_of_entry_cleanup;
75
76         unsigned long           crc32;
77         ssize_t                 filename_length;
78         ssize_t                 extra_length;
79         int64_t                 uncompressed_size;
80         int64_t                 compressed_size;
81
82         unsigned char           *uncompressed_buffer;
83         size_t                  uncompressed_buffer_size;
84 #ifdef HAVE_ZLIB_H
85         z_stream                stream;
86         char                    stream_valid;
87 #endif
88
89         struct archive_string   pathname;
90         struct archive_string   extra;
91         char    format_name[64];
92 };
93
94 #define ZIP_LENGTH_AT_END       8
95
96 struct zip_file_header {
97         char    signature[4];
98         char    version[2];
99         char    flags[2];
100         char    compression[2];
101         char    timedate[4];
102         char    crc32[4];
103         char    compressed_size[4];
104         char    uncompressed_size[4];
105         char    filename_length[2];
106         char    extra_length[2];
107 };
108
109 static const char *compression_names[] = {
110         "uncompressed",
111         "shrinking",
112         "reduced-1",
113         "reduced-2",
114         "reduced-3",
115         "reduced-4",
116         "imploded",
117         "reserved",
118         "deflation"
119 };
120
121 static int      archive_read_format_zip_bid(struct archive_read *);
122 static int      archive_read_format_zip_cleanup(struct archive_read *);
123 static int      archive_read_format_zip_read_data(struct archive_read *,
124                     const void **, size_t *, off_t *);
125 static int      archive_read_format_zip_read_data_skip(struct archive_read *a);
126 static int      archive_read_format_zip_read_header(struct archive_read *,
127                     struct archive_entry *);
128 static int      zip_read_data_deflate(struct archive_read *a, const void **buff,
129                     size_t *size, off_t *offset);
130 static int      zip_read_data_none(struct archive_read *a, const void **buff,
131                     size_t *size, off_t *offset);
132 static int      zip_read_file_header(struct archive_read *a,
133                     struct archive_entry *entry, struct zip *zip);
134 static time_t   zip_time(const char *);
135 static void process_extra(const void* extra, struct zip* zip);
136
137 int
138 archive_read_support_format_zip(struct archive *_a)
139 {
140         struct archive_read *a = (struct archive_read *)_a;
141         struct zip *zip;
142         int r;
143
144         zip = (struct zip *)malloc(sizeof(*zip));
145         if (zip == NULL) {
146                 archive_set_error(&a->archive, ENOMEM, "Can't allocate zip data");
147                 return (ARCHIVE_FATAL);
148         }
149         memset(zip, 0, sizeof(*zip));
150
151         r = __archive_read_register_format(a,
152             zip,
153             archive_read_format_zip_bid,
154             archive_read_format_zip_read_header,
155             archive_read_format_zip_read_data,
156             archive_read_format_zip_read_data_skip,
157             archive_read_format_zip_cleanup);
158
159         if (r != ARCHIVE_OK)
160                 free(zip);
161         return (ARCHIVE_OK);
162 }
163
164
165 static int
166 archive_read_format_zip_bid(struct archive_read *a)
167 {
168         const char *p;
169         const void *buff;
170         size_t bytes_avail;
171
172         if ((p = __archive_read_ahead(a, 4)) == NULL)
173                 return (-1);
174
175         /*
176          * Bid of 30 here is: 16 bits for "PK",
177          * next 16-bit field has four options (-2 bits).
178          * 16 + 16-2 = 30.
179          */
180         if (p[0] == 'P' && p[1] == 'K') {
181                 if ((p[2] == '\001' && p[3] == '\002')
182                     || (p[2] == '\003' && p[3] == '\004')
183                     || (p[2] == '\005' && p[3] == '\006')
184                     || (p[2] == '\007' && p[3] == '\010')
185                     || (p[2] == '0' && p[3] == '0'))
186                         return (30);
187         }
188
189         /*
190          * Attempt to handle self-extracting archives
191          * by noting a PE header and searching forward
192          * up to 64k for a 'PK\003\004' marker.
193          */
194         if (p[0] == 'M' && p[1] == 'Z') {
195                 /*
196                  * TODO: Additional checks that this really is a PE
197                  * file before we invoke the 128k lookahead below.
198                  * No point in allocating a bigger lookahead buffer
199                  * if we don't need to.
200                  */
201                 /*
202                  * TODO: Of course, the compression layer lookahead
203                  * buffers aren't dynamically sized yet; they should be.
204                  */
205                 bytes_avail = (a->decompressor->read_ahead)(a, &buff, 128*1024);
206                 p = (const char *)buff;
207
208                 /*
209                  * TODO: Optimize by jumping forward based on values
210                  * in the PE header.  Note that we don't need to be
211                  * exact, but we mustn't skip too far.  The search
212                  * below will compensate if we undershoot.  Skipping
213                  * will also reduce the chance of false positives
214                  * (which is not really all that high to begin with,
215                  * so maybe skipping isn't really necessary).
216                  */
217
218                 while (p < bytes_avail + (const char *)buff) {
219                         if (p[0] == 'P' && p[1] == 'K' /* "PK" signature */
220                             && p[2] == 3 && p[3] == 4 /* File entry */
221                             && p[8] == 8 /* compression == deflate */
222                             && p[9] == 0 /* High byte of compression */
223                                 )
224                         {
225                                 return (30);
226                         }
227                         ++p;
228                 }
229         }
230
231         return (0);
232 }
233
234 /*
235  * Search forward for a "PK\003\004" file header.  This handles the
236  * case of self-extracting archives, where there is an executable
237  * prepended to the ZIP archive.
238  */
239 static int
240 skip_sfx(struct archive_read *a)
241 {
242         const void *h;
243         const char *p, *q;
244         size_t skip, bytes;
245
246         /*
247          * TODO: We should be able to skip forward by a bunch
248          * by lifting some values from the PE header.  We don't
249          * need to be exact (we're still going to search forward
250          * to find the header), but it will speed things up and
251          * reduce the chance of a false positive.
252          */
253         for (;;) {
254                 bytes = (a->decompressor->read_ahead)(a, &h, 4096);
255                 if (bytes < 4)
256                         return (ARCHIVE_FATAL);
257                 p = h;
258                 q = p + bytes;
259
260                 /*
261                  * Scan ahead until we find something that looks
262                  * like the zip header.
263                  */
264                 while (p + 4 < q) {
265                         switch (p[3]) {
266                         case '\004':
267                                 /* TODO: Additional verification here. */
268                                 if (memcmp("PK\003\004", p, 4) == 0) {
269                                         skip = p - (const char *)h;
270                                         (a->decompressor->consume)(a, skip);
271                                         return (ARCHIVE_OK);
272                                 }
273                                 p += 4;
274                                 break;
275                         case '\003': p += 1; break;
276                         case 'K': p += 2; break;
277                         case 'P': p += 3; break;
278                         default: p += 4; break;
279                         }
280                 }
281                 skip = p - (const char *)h;
282                 (a->decompressor->consume)(a, skip);
283         }
284 }
285
286 static int
287 archive_read_format_zip_read_header(struct archive_read *a,
288     struct archive_entry *entry)
289 {
290         const void *h;
291         const char *signature;
292         struct zip *zip;
293         int r = ARCHIVE_OK, r1;
294
295         a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
296         if (a->archive.archive_format_name == NULL)
297                 a->archive.archive_format_name = "ZIP";
298
299         zip = (struct zip *)(a->format->data);
300         zip->decompress_init = 0;
301         zip->end_of_entry = 0;
302         zip->end_of_entry_cleanup = 0;
303         zip->entry_uncompressed_bytes_read = 0;
304         zip->entry_compressed_bytes_read = 0;
305         zip->entry_crc32 = crc32(0, NULL, 0);
306         if ((h = __archive_read_ahead(a, 4)) == NULL)
307                 return (ARCHIVE_FATAL);
308
309         signature = (const char *)h;
310         if (signature[0] == 'M' && signature[1] == 'Z') {
311                 /* This is an executable?  Must be self-extracting... */
312                 r = skip_sfx(a);
313                 if (r < ARCHIVE_WARN)
314                         return (r);
315                 if ((h = __archive_read_ahead(a, 4)) == NULL)
316                         return (ARCHIVE_FATAL);
317                 signature = (const char *)h;
318         }
319
320         if (signature[0] != 'P' || signature[1] != 'K') {
321                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
322                     "Bad ZIP file");
323                 return (ARCHIVE_FATAL);
324         }
325
326         /*
327          * "PK00" signature is used for "split" archives that
328          * only have a single segment.  This means we can just
329          * skip the PK00; the first real file header should follow.
330          */
331         if (signature[2] == '0' && signature[3] == '0') {
332                 (a->decompressor->consume)(a, 4);
333                 if ((h = __archive_read_ahead(a, 4)) == NULL)
334                         return (ARCHIVE_FATAL);
335                 signature = (const char *)h;
336                 if (signature[0] != 'P' || signature[1] != 'K') {
337                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
338                             "Bad ZIP file");
339                         return (ARCHIVE_FATAL);
340                 }
341         }
342
343         if (signature[2] == '\001' && signature[3] == '\002') {
344                 /* Beginning of central directory. */
345                 return (ARCHIVE_EOF);
346         }
347
348         if (signature[2] == '\003' && signature[3] == '\004') {
349                 /* Regular file entry. */
350                 r1 = zip_read_file_header(a, entry, zip);
351                 if (r1 != ARCHIVE_OK)
352                         return (r1);
353                 return (r);
354         }
355
356         if (signature[2] == '\005' && signature[3] == '\006') {
357                 /* End-of-archive record. */
358                 return (ARCHIVE_EOF);
359         }
360
361         if (signature[2] == '\007' && signature[3] == '\010') {
362                 /*
363                  * We should never encounter this record here;
364                  * see ZIP_LENGTH_AT_END handling below for details.
365                  */
366                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
367                     "Bad ZIP file: Unexpected end-of-entry record");
368                 return (ARCHIVE_FATAL);
369         }
370
371         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
372             "Damaged ZIP file or unsupported format variant (%d,%d)",
373             signature[2], signature[3]);
374         return (ARCHIVE_FATAL);
375 }
376
377 int
378 zip_read_file_header(struct archive_read *a, struct archive_entry *entry,
379     struct zip *zip)
380 {
381         const struct zip_file_header *p;
382         const void *h;
383
384         if ((p = __archive_read_ahead(a, sizeof *p)) == NULL) {
385                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
386                     "Truncated ZIP file header");
387                 return (ARCHIVE_FATAL);
388         }
389
390         zip->version = p->version[0];
391         zip->system = p->version[1];
392         zip->flags = archive_le16dec(p->flags);
393         zip->compression = archive_le16dec(p->compression);
394         if (zip->compression <
395             sizeof(compression_names)/sizeof(compression_names[0]))
396                 zip->compression_name = compression_names[zip->compression];
397         else
398                 zip->compression_name = "??";
399         zip->mtime = zip_time(p->timedate);
400         zip->ctime = 0;
401         zip->atime = 0;
402         zip->mode = 0;
403         zip->uid = 0;
404         zip->gid = 0;
405         zip->crc32 = archive_le32dec(p->crc32);
406         zip->filename_length = archive_le16dec(p->filename_length);
407         zip->extra_length = archive_le16dec(p->extra_length);
408         zip->uncompressed_size = archive_le32dec(p->uncompressed_size);
409         zip->compressed_size = archive_le32dec(p->compressed_size);
410
411         (a->decompressor->consume)(a, sizeof(struct zip_file_header));
412
413
414         /* Read the filename. */
415         if ((h = __archive_read_ahead(a, zip->filename_length)) == NULL) {
416                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
417                     "Truncated ZIP file header");
418                 return (ARCHIVE_FATAL);
419         }
420         if (archive_string_ensure(&zip->pathname, zip->filename_length) == NULL)
421                 __archive_errx(1, "Out of memory");
422         archive_strncpy(&zip->pathname, h, zip->filename_length);
423         (a->decompressor->consume)(a, zip->filename_length);
424         archive_entry_set_pathname(entry, zip->pathname.s);
425
426         if (zip->pathname.s[archive_strlen(&zip->pathname) - 1] == '/')
427                 zip->mode = AE_IFDIR | 0777;
428         else
429                 zip->mode = AE_IFREG | 0777;
430
431         /* Read the extra data. */
432         if ((h = __archive_read_ahead(a, zip->extra_length)) == NULL) {
433                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
434                     "Truncated ZIP file header");
435                 return (ARCHIVE_FATAL);
436         }
437         process_extra(h, zip);
438         (a->decompressor->consume)(a, zip->extra_length);
439
440         /* Populate some additional entry fields: */
441         archive_entry_set_mode(entry, zip->mode);
442         archive_entry_set_uid(entry, zip->uid);
443         archive_entry_set_gid(entry, zip->gid);
444         archive_entry_set_mtime(entry, zip->mtime, 0);
445         archive_entry_set_ctime(entry, zip->ctime, 0);
446         archive_entry_set_atime(entry, zip->atime, 0);
447         /* Set the size only if it's meaningful. */
448         if (0 == (zip->flags & ZIP_LENGTH_AT_END))
449                 archive_entry_set_size(entry, zip->uncompressed_size);
450
451         zip->entry_bytes_remaining = zip->compressed_size;
452         zip->entry_offset = 0;
453
454         /* If there's no body, force read_data() to return EOF immediately. */
455         if (0 == (zip->flags & ZIP_LENGTH_AT_END)
456             && zip->entry_bytes_remaining < 1)
457                 zip->end_of_entry = 1;
458
459         /* Set up a more descriptive format name. */
460         sprintf(zip->format_name, "ZIP %d.%d (%s)",
461             zip->version / 10, zip->version % 10,
462             zip->compression_name);
463         a->archive.archive_format_name = zip->format_name;
464
465         return (ARCHIVE_OK);
466 }
467
468 /* Convert an MSDOS-style date/time into Unix-style time. */
469 static time_t
470 zip_time(const char *p)
471 {
472         int msTime, msDate;
473         struct tm ts;
474
475         msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
476         msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
477
478         memset(&ts, 0, sizeof(ts));
479         ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
480         ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
481         ts.tm_mday = msDate & 0x1f; /* Day of month. */
482         ts.tm_hour = (msTime >> 11) & 0x1f;
483         ts.tm_min = (msTime >> 5) & 0x3f;
484         ts.tm_sec = (msTime << 1) & 0x3e;
485         ts.tm_isdst = -1;
486         return mktime(&ts);
487 }
488
489 static int
490 archive_read_format_zip_read_data(struct archive_read *a,
491     const void **buff, size_t *size, off_t *offset)
492 {
493         int r;
494         struct zip *zip;
495
496         zip = (struct zip *)(a->format->data);
497
498         /*
499          * If we hit end-of-entry last time, clean up and return
500          * ARCHIVE_EOF this time.
501          */
502         if (zip->end_of_entry) {
503                 if (!zip->end_of_entry_cleanup) {
504                         if (zip->flags & ZIP_LENGTH_AT_END) {
505                                 const char *p;
506
507                                 if ((p = __archive_read_ahead(a, 16)) == NULL) {
508                                         archive_set_error(&a->archive,
509                                             ARCHIVE_ERRNO_FILE_FORMAT,
510                                             "Truncated ZIP end-of-file record");
511                                         return (ARCHIVE_FATAL);
512                                 }
513                                 zip->crc32 = archive_le32dec(p + 4);
514                                 zip->compressed_size = archive_le32dec(p + 8);
515                                 zip->uncompressed_size = archive_le32dec(p + 12);
516                                 (a->decompressor->consume)(a, 16);
517                         }
518
519                         /* Check file size, CRC against these values. */
520                         if (zip->compressed_size != zip->entry_compressed_bytes_read) {
521                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
522                                     "ZIP compressed data is wrong size");
523                                 return (ARCHIVE_WARN);
524                         }
525                         /* Size field only stores the lower 32 bits of the actual size. */
526                         if ((zip->uncompressed_size & UINT32_MAX)
527                             != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
528                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
529                                     "ZIP uncompressed data is wrong size");
530                                 return (ARCHIVE_WARN);
531                         }
532                         /* Check computed CRC against header */
533                         if (zip->crc32 != zip->entry_crc32) {
534                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
535                                     "ZIP bad CRC: 0x%lx should be 0x%lx",
536                                     zip->entry_crc32, zip->crc32);
537                                 return (ARCHIVE_WARN);
538                         }
539                         /* End-of-entry cleanup done. */
540                         zip->end_of_entry_cleanup = 1;
541                 }
542                 *offset = zip->entry_uncompressed_bytes_read;
543                 *size = 0;
544                 *buff = NULL;
545                 return (ARCHIVE_EOF);
546         }
547
548         switch(zip->compression) {
549         case 0:  /* No compression. */
550                 r =  zip_read_data_none(a, buff, size, offset);
551                 break;
552         case 8: /* Deflate compression. */
553                 r =  zip_read_data_deflate(a, buff, size, offset);
554                 break;
555         default: /* Unsupported compression. */
556                 *buff = NULL;
557                 *size = 0;
558                 *offset = 0;
559                 /* Return a warning. */
560                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
561                     "Unsupported ZIP compression method (%s)",
562                     zip->compression_name);
563                 if (zip->flags & ZIP_LENGTH_AT_END) {
564                         /*
565                          * ZIP_LENGTH_AT_END requires us to
566                          * decompress the entry in order to
567                          * skip it, but we don't know this
568                          * compression method, so we give up.
569                          */
570                         r = ARCHIVE_FATAL;
571                 } else {
572                         /* We can't decompress this entry, but we will
573                          * be able to skip() it and try the next entry. */
574                         r = ARCHIVE_WARN;
575                 }
576                 break;
577         }
578         if (r != ARCHIVE_OK)
579                 return (r);
580         /* Update checksum */
581         if (*size)
582                 zip->entry_crc32 =
583                     crc32(zip->entry_crc32, *buff, *size);
584         /* Return EOF immediately if this is a non-regular file. */
585         if (AE_IFREG != (zip->mode & AE_IFMT))
586                 return (ARCHIVE_EOF);
587         return (ARCHIVE_OK);
588 }
589
590 /*
591  * Read "uncompressed" data.  According to the current specification,
592  * if ZIP_LENGTH_AT_END is specified, then the size fields in the
593  * initial file header are supposed to be set to zero.  This would, of
594  * course, make it impossible for us to read the archive, since we
595  * couldn't determine the end of the file data.  Info-ZIP seems to
596  * include the real size fields both before and after the data in this
597  * case (the CRC only appears afterwards), so this works as you would
598  * expect.
599  *
600  * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
601  * zip->end_of_entry if it consumes all of the data.
602  */
603 static int
604 zip_read_data_none(struct archive_read *a, const void **buff,
605     size_t *size, off_t *offset)
606 {
607         struct zip *zip;
608         ssize_t bytes_avail;
609
610         zip = (struct zip *)(a->format->data);
611
612         if (zip->entry_bytes_remaining == 0) {
613                 *buff = NULL;
614                 *size = 0;
615                 *offset = zip->entry_offset;
616                 zip->end_of_entry = 1;
617                 return (ARCHIVE_OK);
618         }
619         /*
620          * Note: '1' here is a performance optimization.
621          * Recall that the decompression layer returns a count of
622          * available bytes; asking for more than that forces the
623          * decompressor to combine reads by copying data.
624          */
625         bytes_avail = (a->decompressor->read_ahead)(a, buff, 1);
626         if (bytes_avail <= 0) {
627                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
628                     "Truncated ZIP file data");
629                 return (ARCHIVE_FATAL);
630         }
631         if (bytes_avail > zip->entry_bytes_remaining)
632                 bytes_avail = zip->entry_bytes_remaining;
633         (a->decompressor->consume)(a, bytes_avail);
634         *size = bytes_avail;
635         *offset = zip->entry_offset;
636         zip->entry_offset += *size;
637         zip->entry_bytes_remaining -= *size;
638         zip->entry_uncompressed_bytes_read += *size;
639         zip->entry_compressed_bytes_read += *size;
640         return (ARCHIVE_OK);
641 }
642
643 #ifdef HAVE_ZLIB_H
644 static int
645 zip_read_data_deflate(struct archive_read *a, const void **buff,
646     size_t *size, off_t *offset)
647 {
648         struct zip *zip;
649         ssize_t bytes_avail;
650         const void *compressed_buff;
651         int r;
652
653         zip = (struct zip *)(a->format->data);
654
655         /* If the buffer hasn't been allocated, allocate it now. */
656         if (zip->uncompressed_buffer == NULL) {
657                 zip->uncompressed_buffer_size = 32 * 1024;
658                 zip->uncompressed_buffer
659                     = (unsigned char *)malloc(zip->uncompressed_buffer_size);
660                 if (zip->uncompressed_buffer == NULL) {
661                         archive_set_error(&a->archive, ENOMEM,
662                             "No memory for ZIP decompression");
663                         return (ARCHIVE_FATAL);
664                 }
665         }
666
667         /* If we haven't yet read any data, initialize the decompressor. */
668         if (!zip->decompress_init) {
669                 if (zip->stream_valid)
670                         r = inflateReset(&zip->stream);
671                 else
672                         r = inflateInit2(&zip->stream,
673                             -15 /* Don't check for zlib header */);
674                 if (r != Z_OK) {
675                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
676                             "Can't initialize ZIP decompression.");
677                         return (ARCHIVE_FATAL);
678                 }
679                 /* Stream structure has been set up. */
680                 zip->stream_valid = 1;
681                 /* We've initialized decompression for this stream. */
682                 zip->decompress_init = 1;
683         }
684
685         /*
686          * Note: '1' here is a performance optimization.
687          * Recall that the decompression layer returns a count of
688          * available bytes; asking for more than that forces the
689          * decompressor to combine reads by copying data.
690          */
691         bytes_avail = (a->decompressor->read_ahead)(a, &compressed_buff, 1);
692         if (bytes_avail <= 0) {
693                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
694                     "Truncated ZIP file body");
695                 return (ARCHIVE_FATAL);
696         }
697
698         /*
699          * A bug in zlib.h: stream.next_in should be marked 'const'
700          * but isn't (the library never alters data through the
701          * next_in pointer, only reads it).  The result: this ugly
702          * cast to remove 'const'.
703          */
704         zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
705         zip->stream.avail_in = bytes_avail;
706         zip->stream.total_in = 0;
707         zip->stream.next_out = zip->uncompressed_buffer;
708         zip->stream.avail_out = zip->uncompressed_buffer_size;
709         zip->stream.total_out = 0;
710
711         r = inflate(&zip->stream, 0);
712         switch (r) {
713         case Z_OK:
714                 break;
715         case Z_STREAM_END:
716                 zip->end_of_entry = 1;
717                 break;
718         case Z_MEM_ERROR:
719                 archive_set_error(&a->archive, ENOMEM,
720                     "Out of memory for ZIP decompression");
721                 return (ARCHIVE_FATAL);
722         default:
723                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
724                     "ZIP decompression failed (%d)", r);
725                 return (ARCHIVE_FATAL);
726         }
727
728         /* Consume as much as the compressor actually used. */
729         bytes_avail = zip->stream.total_in;
730         (a->decompressor->consume)(a, bytes_avail);
731         zip->entry_bytes_remaining -= bytes_avail;
732         zip->entry_compressed_bytes_read += bytes_avail;
733
734         *offset = zip->entry_offset;
735         *size = zip->stream.total_out;
736         zip->entry_uncompressed_bytes_read += *size;
737         *buff = zip->uncompressed_buffer;
738         zip->entry_offset += *size;
739         return (ARCHIVE_OK);
740 }
741 #else
742 static int
743 zip_read_data_deflate(struct archive_read *a, const void **buff,
744     size_t *size, off_t *offset)
745 {
746         *buff = NULL;
747         *size = 0;
748         *offset = 0;
749         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
750             "libarchive compiled without deflate support (no libz)");
751         return (ARCHIVE_FATAL);
752 }
753 #endif
754
755 static int
756 archive_read_format_zip_read_data_skip(struct archive_read *a)
757 {
758         struct zip *zip;
759         const void *buff = NULL;
760         off_t bytes_skipped;
761
762         zip = (struct zip *)(a->format->data);
763
764         /* If we've already read to end of data, we're done. */
765         if (zip->end_of_entry_cleanup)
766                 return (ARCHIVE_OK);
767
768         /*
769          * If the length is at the end, we have no choice but
770          * to decompress all the data to find the end marker.
771          */
772         if (zip->flags & ZIP_LENGTH_AT_END) {
773                 size_t size;
774                 off_t offset;
775                 int r;
776                 do {
777                         r = archive_read_format_zip_read_data(a, &buff,
778                             &size, &offset);
779                 } while (r == ARCHIVE_OK);
780                 return (r);
781         }
782
783         /*
784          * If the length is at the beginning, we can skip the
785          * compressed data much more quickly.
786          */
787         bytes_skipped = (a->decompressor->skip)(a, zip->entry_bytes_remaining);
788         if (bytes_skipped < 0)
789                 return (ARCHIVE_FATAL);
790
791         /* This entry is finished and done. */
792         zip->end_of_entry_cleanup = zip->end_of_entry = 1;
793         return (ARCHIVE_OK);
794 }
795
796 static int
797 archive_read_format_zip_cleanup(struct archive_read *a)
798 {
799         struct zip *zip;
800
801         zip = (struct zip *)(a->format->data);
802 #ifdef HAVE_ZLIB_H
803         if (zip->stream_valid)
804                 inflateEnd(&zip->stream);
805 #endif
806         free(zip->uncompressed_buffer);
807         archive_string_free(&(zip->pathname));
808         archive_string_free(&(zip->extra));
809         free(zip);
810         (a->format->data) = NULL;
811         return (ARCHIVE_OK);
812 }
813
814 /*
815  * The extra data is stored as a list of
816  *      id1+size1+data1 + id2+size2+data2 ...
817  *  triplets.  id and size are 2 bytes each.
818  */
819 static void
820 process_extra(const void* extra, struct zip* zip)
821 {
822         int offset = 0;
823         const char *p = (const char *)extra;
824         while (offset < zip->extra_length - 4)
825         {
826                 unsigned short headerid = archive_le16dec(p + offset);
827                 unsigned short datasize = archive_le16dec(p + offset + 2);
828                 offset += 4;
829                 if (offset + datasize > zip->extra_length)
830                         break;
831 #ifdef DEBUG
832                 fprintf(stderr, "Header id 0x%04x, length %d\n",
833                     headerid, datasize);
834 #endif
835                 switch (headerid) {
836                 case 0x0001:
837                         /* Zip64 extended information extra field. */
838                         if (datasize >= 8)
839                                 zip->uncompressed_size = archive_le64dec(p + offset);
840                         if (datasize >= 16)
841                                 zip->compressed_size = archive_le64dec(p + offset + 8);
842                         break;
843                 case 0x5455:
844                 {
845                         /* Extended time field "UT". */
846                         int flags = p[offset];
847                         offset++;
848                         datasize--;
849                         /* Flag bits indicate which dates are present. */
850                         if (flags & 0x01)
851                         {
852 #ifdef DEBUG
853                                 fprintf(stderr, "mtime: %lld -> %d\n",
854                                     (long long)zip->mtime,
855                                     archive_le32dec(p + offset));
856 #endif
857                                 if (datasize < 4)
858                                         break;
859                                 zip->mtime = archive_le32dec(p + offset);
860                                 offset += 4;
861                                 datasize -= 4;
862                         }
863                         if (flags & 0x02)
864                         {
865                                 if (datasize < 4)
866                                         break;
867                                 zip->atime = archive_le32dec(p + offset);
868                                 offset += 4;
869                                 datasize -= 4;
870                         }
871                         if (flags & 0x04)
872                         {
873                                 if (datasize < 4)
874                                         break;
875                                 zip->ctime = archive_le32dec(p + offset);
876                                 offset += 4;
877                                 datasize -= 4;
878                         }
879                         break;
880                 }
881                 case 0x7855:
882                         /* Info-ZIP Unix Extra Field (type 2) "Ux". */
883 #ifdef DEBUG
884                         fprintf(stderr, "uid %d gid %d\n",
885                             archive_le16dec(p + offset),
886                             archive_le16dec(p + offset + 2));
887 #endif
888                         if (datasize >= 2)
889                                 zip->uid = archive_le16dec(p + offset);
890                         if (datasize >= 4)
891                                 zip->gid = archive_le16dec(p + offset + 2);
892                         break;
893                 default:
894                         break;
895                 }
896                 offset += datasize;
897         }
898 #ifdef DEBUG
899         if (offset != zip->extra_length)
900         {
901                 fprintf(stderr,
902                     "Extra data field contents do not match reported size!");
903         }
904 #endif
905 }