Upload 2.0.2
[physicsfs] / archivers / zip.c
1 /*
2  * ZIP support routines for PhysicsFS.
3  *
4  * Please see the file LICENSE.txt in the source's root directory.
5  *
6  *  This file written by Ryan C. Gordon, with some peeking at "unzip.c"
7  *   by Gilles Vollant.
8  */
9
10 #if (defined PHYSFS_SUPPORTS_ZIP)
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #ifndef _WIN32_WCE
16 #include <errno.h>
17 #include <time.h>
18 #endif
19 #include "physfs.h"
20 #include "zlib.h"
21
22 #define __PHYSICSFS_INTERNAL__
23 #include "physfs_internal.h"
24
25 /*
26  * A buffer of ZIP_READBUFSIZE is allocated for each compressed file opened,
27  *  and is freed when you close the file; compressed data is read into
28  *  this buffer, and then is decompressed into the buffer passed to
29  *  PHYSFS_read().
30  *
31  * Uncompressed entries in a zipfile do not allocate this buffer; they just
32  *  read data directly into the buffer passed to PHYSFS_read().
33  *
34  * Depending on your speed and memory requirements, you should tweak this
35  *  value.
36  */
37 #define ZIP_READBUFSIZE   (16 * 1024)
38
39
40 /*
41  * Entries are "unresolved" until they are first opened. At that time,
42  *  local file headers parsed/validated, data offsets will be updated to look
43  *  at the actual file data instead of the header, and symlinks will be
44  *  followed and optimized. This means that we don't seek and read around the
45  *  archive until forced to do so, and after the first time, we had to do
46  *  less reading and parsing, which is very CD-ROM friendly.
47  */
48 typedef enum
49 {
50     ZIP_UNRESOLVED_FILE,
51     ZIP_UNRESOLVED_SYMLINK,
52     ZIP_RESOLVING,
53     ZIP_RESOLVED,
54     ZIP_BROKEN_FILE,
55     ZIP_BROKEN_SYMLINK
56 } ZipResolveType;
57
58
59 /*
60  * One ZIPentry is kept for each file in an open ZIP archive.
61  */
62 typedef struct _ZIPentry
63 {
64     char *name;                         /* Name of file in archive        */
65     struct _ZIPentry *symlink;          /* NULL or file we symlink to     */
66     ZipResolveType resolved;            /* Have we resolved file/symlink? */
67     PHYSFS_uint32 offset;               /* offset of data in archive      */
68     PHYSFS_uint16 version;              /* version made by                */
69     PHYSFS_uint16 version_needed;       /* version needed to extract      */
70     PHYSFS_uint16 compression_method;   /* compression method             */
71     PHYSFS_uint32 crc;                  /* crc-32                         */
72     PHYSFS_uint32 compressed_size;      /* compressed size                */
73     PHYSFS_uint32 uncompressed_size;    /* uncompressed size              */
74     PHYSFS_sint64 last_mod_time;        /* last file mod time             */
75 } ZIPentry;
76
77 /*
78  * One ZIPinfo is kept for each open ZIP archive.
79  */
80 typedef struct
81 {
82     char *archiveName;        /* path to ZIP in platform-dependent notation. */
83     PHYSFS_uint16 entryCount; /* Number of files in ZIP.                     */
84     ZIPentry *entries;        /* info on all files in ZIP.                   */
85 } ZIPinfo;
86
87 /*
88  * One ZIPfileinfo is kept for each open file in a ZIP archive.
89  */
90 typedef struct
91 {
92     ZIPentry *entry;                      /* Info on file.              */
93     void *handle;                         /* physical file handle.      */
94     PHYSFS_uint32 compressed_position;    /* offset in compressed data. */
95     PHYSFS_uint32 uncompressed_position;  /* tell() position.           */
96     PHYSFS_uint8 *buffer;                 /* decompression buffer.      */
97     z_stream stream;                      /* zlib stream state.         */
98 } ZIPfileinfo;
99
100
101 /* Magic numbers... */
102 #define ZIP_LOCAL_FILE_SIG          0x04034b50
103 #define ZIP_CENTRAL_DIR_SIG         0x02014b50
104 #define ZIP_END_OF_CENTRAL_DIR_SIG  0x06054b50
105
106 /* compression methods... */
107 #define COMPMETH_NONE 0
108 /* ...and others... */
109
110
111 #define UNIX_FILETYPE_MASK    0170000
112 #define UNIX_FILETYPE_SYMLINK 0120000
113
114
115 /*
116  * Bridge physfs allocation functions to zlib's format...
117  */
118 static voidpf zlibPhysfsAlloc(voidpf opaque, uInt items, uInt size)
119 {
120     return(((PHYSFS_Allocator *) opaque)->Malloc(items * size));
121 } /* zlibPhysfsAlloc */
122
123 /*
124  * Bridge physfs allocation functions to zlib's format...
125  */
126 static void zlibPhysfsFree(voidpf opaque, voidpf address)
127 {
128     ((PHYSFS_Allocator *) opaque)->Free(address);
129 } /* zlibPhysfsFree */
130
131
132 /*
133  * Construct a new z_stream to a sane state.
134  */
135 static void initializeZStream(z_stream *pstr)
136 {
137     memset(pstr, '\0', sizeof (z_stream));
138     pstr->zalloc = zlibPhysfsAlloc;
139     pstr->zfree = zlibPhysfsFree;
140     pstr->opaque = &allocator;
141 } /* initializeZStream */
142
143
144 static const char *zlib_error_string(int rc)
145 {
146     switch (rc)
147     {
148         case Z_OK: return(NULL);  /* not an error. */
149         case Z_STREAM_END: return(NULL); /* not an error. */
150 #ifndef _WIN32_WCE
151         case Z_ERRNO: return(strerror(errno));
152 #endif
153         case Z_NEED_DICT: return(ERR_NEED_DICT);
154         case Z_DATA_ERROR: return(ERR_DATA_ERROR);
155         case Z_MEM_ERROR: return(ERR_MEMORY_ERROR);
156         case Z_BUF_ERROR: return(ERR_BUFFER_ERROR);
157         case Z_VERSION_ERROR: return(ERR_VERSION_ERROR);
158         default: return(ERR_UNKNOWN_ERROR);
159     } /* switch */
160
161     return(NULL);
162 } /* zlib_error_string */
163
164
165 /*
166  * Wrap all zlib calls in this, so the physfs error state is set appropriately.
167  */
168 static int zlib_err(int rc)
169 {
170     const char *str = zlib_error_string(rc);
171     if (str != NULL)
172         __PHYSFS_setError(str);
173     return(rc);
174 } /* zlib_err */
175
176
177 /*
178  * Read an unsigned 32-bit int and swap to native byte order.
179  */
180 static int readui32(void *in, PHYSFS_uint32 *val)
181 {
182     PHYSFS_uint32 v;
183     BAIL_IF_MACRO(__PHYSFS_platformRead(in, &v, sizeof (v), 1) != 1, NULL, 0);
184     *val = PHYSFS_swapULE32(v);
185     return(1);
186 } /* readui32 */
187
188
189 /*
190  * Read an unsigned 16-bit int and swap to native byte order.
191  */
192 static int readui16(void *in, PHYSFS_uint16 *val)
193 {
194     PHYSFS_uint16 v;
195     BAIL_IF_MACRO(__PHYSFS_platformRead(in, &v, sizeof (v), 1) != 1, NULL, 0);
196     *val = PHYSFS_swapULE16(v);
197     return(1);
198 } /* readui16 */
199
200
201 static PHYSFS_sint64 ZIP_read(fvoid *opaque, void *buf,
202                               PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
203 {
204     ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
205     ZIPentry *entry = finfo->entry;
206     PHYSFS_sint64 retval = 0;
207     PHYSFS_sint64 maxread = ((PHYSFS_sint64) objSize) * objCount;
208     PHYSFS_sint64 avail = entry->uncompressed_size -
209                           finfo->uncompressed_position;
210
211     BAIL_IF_MACRO(maxread == 0, NULL, 0);    /* quick rejection. */
212
213     if (avail < maxread)
214     {
215         maxread = avail - (avail % objSize);
216         objCount = (PHYSFS_uint32) (maxread / objSize);
217         BAIL_IF_MACRO(objCount == 0, ERR_PAST_EOF, 0);  /* quick rejection. */
218         __PHYSFS_setError(ERR_PAST_EOF);   /* this is always true here. */
219     } /* if */
220
221     if (entry->compression_method == COMPMETH_NONE)
222     {
223         retval = __PHYSFS_platformRead(finfo->handle, buf, objSize, objCount);
224     } /* if */
225
226     else
227     {
228         finfo->stream.next_out = buf;
229         finfo->stream.avail_out = objSize * objCount;
230
231         while (retval < maxread)
232         {
233             PHYSFS_uint32 before = finfo->stream.total_out;
234             int rc;
235
236             if (finfo->stream.avail_in == 0)
237             {
238                 PHYSFS_sint64 br;
239
240                 br = entry->compressed_size - finfo->compressed_position;
241                 if (br > 0)
242                 {
243                     if (br > ZIP_READBUFSIZE)
244                         br = ZIP_READBUFSIZE;
245
246                     br = __PHYSFS_platformRead(finfo->handle,
247                                                finfo->buffer,
248                                                1, (PHYSFS_uint32) br);
249                     if (br <= 0)
250                         break;
251
252                     finfo->compressed_position += (PHYSFS_uint32) br;
253                     finfo->stream.next_in = finfo->buffer;
254                     finfo->stream.avail_in = (PHYSFS_uint32) br;
255                 } /* if */
256             } /* if */
257
258             rc = zlib_err(inflate(&finfo->stream, Z_SYNC_FLUSH));
259             retval += (finfo->stream.total_out - before);
260
261             if (rc != Z_OK)
262                 break;
263         } /* while */
264
265         retval /= objSize;
266     } /* else */
267
268     if (retval > 0)
269         finfo->uncompressed_position += (PHYSFS_uint32) (retval * objSize);
270
271     return(retval);
272 } /* ZIP_read */
273
274
275 static PHYSFS_sint64 ZIP_write(fvoid *opaque, const void *buf,
276                                PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
277 {
278     BAIL_MACRO(ERR_NOT_SUPPORTED, -1);
279 } /* ZIP_write */
280
281
282 static int ZIP_eof(fvoid *opaque)
283 {
284     ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
285     return(finfo->uncompressed_position >= finfo->entry->uncompressed_size);
286 } /* ZIP_eof */
287
288
289 static PHYSFS_sint64 ZIP_tell(fvoid *opaque)
290 {
291     return(((ZIPfileinfo *) opaque)->uncompressed_position);
292 } /* ZIP_tell */
293
294
295 static int ZIP_seek(fvoid *opaque, PHYSFS_uint64 offset)
296 {
297     ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
298     ZIPentry *entry = finfo->entry;
299     void *in = finfo->handle;
300
301     BAIL_IF_MACRO(offset > entry->uncompressed_size, ERR_PAST_EOF, 0);
302
303     if (entry->compression_method == COMPMETH_NONE)
304     {
305         PHYSFS_sint64 newpos = offset + entry->offset;
306         BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, newpos), NULL, 0);
307         finfo->uncompressed_position = (PHYSFS_uint32) offset;
308     } /* if */
309
310     else
311     {
312         /*
313          * If seeking backwards, we need to redecode the file
314          *  from the start and throw away the compressed bits until we hit
315          *  the offset we need. If seeking forward, we still need to
316          *  decode, but we don't rewind first.
317          */
318         if (offset < finfo->uncompressed_position)
319         {
320             /* we do a copy so state is sane if inflateInit2() fails. */
321             z_stream str;
322             initializeZStream(&str);
323             if (zlib_err(inflateInit2(&str, -MAX_WBITS)) != Z_OK)
324                 return(0);
325
326             if (!__PHYSFS_platformSeek(in, entry->offset))
327                 return(0);
328
329             inflateEnd(&finfo->stream);
330             memcpy(&finfo->stream, &str, sizeof (z_stream));
331             finfo->uncompressed_position = finfo->compressed_position = 0;
332         } /* if */
333
334         while (finfo->uncompressed_position != offset)
335         {
336             PHYSFS_uint8 buf[512];
337             PHYSFS_uint32 maxread;
338
339             maxread = (PHYSFS_uint32) (offset - finfo->uncompressed_position);
340             if (maxread > sizeof (buf))
341                 maxread = sizeof (buf);
342
343             if (ZIP_read(finfo, buf, maxread, 1) != 1)
344                 return(0);
345         } /* while */
346     } /* else */
347
348     return(1);
349 } /* ZIP_seek */
350
351
352 static PHYSFS_sint64 ZIP_fileLength(fvoid *opaque)
353 {
354     ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
355     return(finfo->entry->uncompressed_size);
356 } /* ZIP_fileLength */
357
358
359 static int ZIP_fileClose(fvoid *opaque)
360 {
361     ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
362     BAIL_IF_MACRO(!__PHYSFS_platformClose(finfo->handle), NULL, 0);
363
364     if (finfo->entry->compression_method != COMPMETH_NONE)
365         inflateEnd(&finfo->stream);
366
367     if (finfo->buffer != NULL)
368         allocator.Free(finfo->buffer);
369
370     allocator.Free(finfo);
371     return(1);
372 } /* ZIP_fileClose */
373
374
375 static PHYSFS_sint64 zip_find_end_of_central_dir(void *in, PHYSFS_sint64 *len)
376 {
377     PHYSFS_uint8 buf[256];
378     PHYSFS_uint8 extra[4] = { 0, 0, 0, 0 };
379     PHYSFS_sint32 i = 0;
380     PHYSFS_sint64 filelen;
381     PHYSFS_sint64 filepos;
382     PHYSFS_sint32 maxread;
383     PHYSFS_sint32 totalread = 0;
384     int found = 0;
385
386     filelen = __PHYSFS_platformFileLength(in);
387     BAIL_IF_MACRO(filelen == -1, NULL, 0);  /* !!! FIXME: unlocalized string */
388     BAIL_IF_MACRO(filelen > 0xFFFFFFFF, "ZIP bigger than 2 gigs?!", 0);
389
390     /*
391      * Jump to the end of the file and start reading backwards.
392      *  The last thing in the file is the zipfile comment, which is variable
393      *  length, and the field that specifies its size is before it in the
394      *  file (argh!)...this means that we need to scan backwards until we
395      *  hit the end-of-central-dir signature. We can then sanity check that
396      *  the comment was as big as it should be to make sure we're in the
397      *  right place. The comment length field is 16 bits, so we can stop
398      *  searching for that signature after a little more than 64k at most,
399      *  and call it a corrupted zipfile.
400      */
401
402     if (sizeof (buf) < filelen)
403     {
404         filepos = filelen - sizeof (buf);
405         maxread = sizeof (buf);
406     } /* if */
407     else
408     {
409         filepos = 0;
410         maxread = (PHYSFS_uint32) filelen;
411     } /* else */
412
413     while ((totalread < filelen) && (totalread < 65557))
414     {
415         BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, filepos), NULL, -1);
416
417         /* make sure we catch a signature between buffers. */
418         if (totalread != 0)
419         {
420             if (__PHYSFS_platformRead(in, buf, maxread - 4, 1) != 1)
421                 return(-1);
422             memcpy(&buf[maxread - 4], &extra, sizeof (extra));
423             totalread += maxread - 4;
424         } /* if */
425         else
426         {
427             if (__PHYSFS_platformRead(in, buf, maxread, 1) != 1)
428                 return(-1);
429             totalread += maxread;
430         } /* else */
431
432         memcpy(&extra, buf, sizeof (extra));
433
434         for (i = maxread - 4; i > 0; i--)
435         {
436             if ((buf[i + 0] == 0x50) &&
437                 (buf[i + 1] == 0x4B) &&
438                 (buf[i + 2] == 0x05) &&
439                 (buf[i + 3] == 0x06) )
440             {
441                 found = 1;  /* that's the signature! */
442                 break;  
443             } /* if */
444         } /* for */
445
446         if (found)
447             break;
448
449         filepos -= (maxread - 4);
450         if (filepos < 0)
451             filepos = 0;
452     } /* while */
453
454     BAIL_IF_MACRO(!found, ERR_NOT_AN_ARCHIVE, -1);
455
456     if (len != NULL)
457         *len = filelen;
458
459     return(filepos + i);
460 } /* zip_find_end_of_central_dir */
461
462
463 static int ZIP_isArchive(const char *filename, int forWriting)
464 {
465     PHYSFS_uint32 sig;
466     int retval = 0;
467     void *in;
468
469     in = __PHYSFS_platformOpenRead(filename);
470     BAIL_IF_MACRO(in == NULL, NULL, 0);
471
472     /*
473      * The first thing in a zip file might be the signature of the
474      *  first local file record, so it makes for a quick determination.
475      */
476     if (readui32(in, &sig))
477     {
478         retval = (sig == ZIP_LOCAL_FILE_SIG);
479         if (!retval)
480         {
481             /*
482              * No sig...might be a ZIP with data at the start
483              *  (a self-extracting executable, etc), so we'll have to do
484              *  it the hard way...
485              */
486             retval = (zip_find_end_of_central_dir(in, NULL) != -1);
487         } /* if */
488     } /* if */
489
490     __PHYSFS_platformClose(in);
491     return(retval);
492 } /* ZIP_isArchive */
493
494
495 static void zip_free_entries(ZIPentry *entries, PHYSFS_uint32 max)
496 {
497     PHYSFS_uint32 i;
498     for (i = 0; i < max; i++)
499     {
500         ZIPentry *entry = &entries[i];
501         if (entry->name != NULL)
502             allocator.Free(entry->name);
503     } /* for */
504
505     allocator.Free(entries);
506 } /* zip_free_entries */
507
508
509 /*
510  * This will find the ZIPentry associated with a path in platform-independent
511  *  notation. Directories don't have ZIPentries associated with them, but 
512  *  (*isDir) will be set to non-zero if a dir was hit.
513  */
514 static ZIPentry *zip_find_entry(ZIPinfo *info, const char *path, int *isDir)
515 {
516     ZIPentry *a = info->entries;
517     PHYSFS_sint32 pathlen = strlen(path);
518     PHYSFS_sint32 lo = 0;
519     PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
520     PHYSFS_sint32 middle;
521     const char *thispath = NULL;
522     int rc;
523
524     while (lo <= hi)
525     {
526         middle = lo + ((hi - lo) / 2);
527         thispath = a[middle].name;
528         rc = strncmp(path, thispath, pathlen);
529
530         if (rc > 0)
531             lo = middle + 1;
532
533         else if (rc < 0)
534             hi = middle - 1;
535
536         else /* substring match...might be dir or entry or nothing. */
537         {
538             if (isDir != NULL)
539             {
540                 *isDir = (thispath[pathlen] == '/');
541                 if (*isDir)
542                     return(NULL);
543             } /* if */
544
545             if (thispath[pathlen] == '\0') /* found entry? */
546                 return(&a[middle]);
547             /* adjust search params, try again. */
548             else if (thispath[pathlen] > '/')
549                 hi = middle - 1;
550             else
551                 lo = middle + 1;
552         } /* if */
553     } /* while */
554
555     if (isDir != NULL)
556         *isDir = 0;
557
558     BAIL_MACRO(ERR_NO_SUCH_FILE, NULL);
559 } /* zip_find_entry */
560
561
562 /* Convert paths from old, buggy DOS zippers... */
563 static void zip_convert_dos_path(ZIPentry *entry, char *path)
564 {
565     PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((entry->version >> 8) & 0xFF);
566     if (hosttype == 0)  /* FS_FAT_ */
567     {
568         while (*path)
569         {
570             if (*path == '\\')
571                 *path = '/';
572             path++;
573         } /* while */
574     } /* if */
575 } /* zip_convert_dos_path */
576
577
578 static void zip_expand_symlink_path(char *path)
579 {
580     char *ptr = path;
581     char *prevptr = path;
582
583     while (1)
584     {
585         ptr = strchr(ptr, '/');
586         if (ptr == NULL)
587             break;
588
589         if (*(ptr + 1) == '.')
590         {
591             if (*(ptr + 2) == '/')
592             {
593                 /* current dir in middle of string: ditch it. */
594                 memmove(ptr, ptr + 2, strlen(ptr + 2) + 1);
595             } /* else if */
596
597             else if (*(ptr + 2) == '\0')
598             {
599                 /* current dir at end of string: ditch it. */
600                 *ptr = '\0';
601             } /* else if */
602
603             else if (*(ptr + 2) == '.')
604             {
605                 if (*(ptr + 3) == '/')
606                 {
607                     /* parent dir in middle: move back one, if possible. */
608                     memmove(prevptr, ptr + 4, strlen(ptr + 4) + 1);
609                     ptr = prevptr;
610                     while (prevptr != path)
611                     {
612                         prevptr--;
613                         if (*prevptr == '/')
614                         {
615                             prevptr++;
616                             break;
617                         } /* if */
618                     } /* while */
619                 } /* if */
620
621                 if (*(ptr + 3) == '\0')
622                 {
623                     /* parent dir at end: move back one, if possible. */
624                     *prevptr = '\0';
625                 } /* if */
626             } /* if */
627         } /* if */
628         else
629         {
630             prevptr = ptr;
631         } /* else */
632     } /* while */
633 } /* zip_expand_symlink_path */
634
635 /* (forward reference: zip_follow_symlink and zip_resolve call each other.) */
636 static int zip_resolve(void *in, ZIPinfo *info, ZIPentry *entry);
637
638 /*
639  * Look for the entry named by (path). If it exists, resolve it, and return
640  *  a pointer to that entry. If it's another symlink, keep resolving until you
641  *  hit a real file and then return a pointer to the final non-symlink entry.
642  *  If there's a problem, return NULL. (path) is always free()'d by this
643  *  function.
644  */
645 static ZIPentry *zip_follow_symlink(void *in, ZIPinfo *info, char *path)
646 {
647     ZIPentry *entry;
648
649     zip_expand_symlink_path(path);
650     entry = zip_find_entry(info, path, NULL);
651     if (entry != NULL)
652     {
653         if (!zip_resolve(in, info, entry))  /* recursive! */
654             entry = NULL;
655         else
656         {
657             if (entry->symlink != NULL)
658                 entry = entry->symlink;
659         } /* else */
660     } /* if */
661
662     allocator.Free(path);
663     return(entry);
664 } /* zip_follow_symlink */
665
666
667 static int zip_resolve_symlink(void *in, ZIPinfo *info, ZIPentry *entry)
668 {
669     char *path;
670     PHYSFS_uint32 size = entry->uncompressed_size;
671     int rc = 0;
672
673     /*
674      * We've already parsed the local file header of the symlink at this
675      *  point. Now we need to read the actual link from the file data and
676      *  follow it.
677      */
678
679     BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, entry->offset), NULL, 0);
680
681     path = (char *) allocator.Malloc(size + 1);
682     BAIL_IF_MACRO(path == NULL, ERR_OUT_OF_MEMORY, 0);
683     
684     if (entry->compression_method == COMPMETH_NONE)
685         rc = (__PHYSFS_platformRead(in, path, size, 1) == 1);
686
687     else  /* symlink target path is compressed... */
688     {
689         z_stream stream;
690         PHYSFS_uint32 complen = entry->compressed_size;
691         PHYSFS_uint8 *compressed = (PHYSFS_uint8*) __PHYSFS_smallAlloc(complen);
692         if (compressed != NULL)
693         {
694             if (__PHYSFS_platformRead(in, compressed, complen, 1) == 1)
695             {
696                 initializeZStream(&stream);
697                 stream.next_in = compressed;
698                 stream.avail_in = complen;
699                 stream.next_out = (unsigned char *) path;
700                 stream.avail_out = size;
701                 if (zlib_err(inflateInit2(&stream, -MAX_WBITS)) == Z_OK)
702                 {
703                     rc = zlib_err(inflate(&stream, Z_FINISH));
704                     inflateEnd(&stream);
705
706                     /* both are acceptable outcomes... */
707                     rc = ((rc == Z_OK) || (rc == Z_STREAM_END));
708                 } /* if */
709             } /* if */
710             __PHYSFS_smallFree(compressed);
711         } /* if */
712     } /* else */
713
714     if (!rc)
715         allocator.Free(path);
716     else
717     {
718         path[entry->uncompressed_size] = '\0';    /* null-terminate it. */
719         zip_convert_dos_path(entry, path);
720         entry->symlink = zip_follow_symlink(in, info, path);
721     } /* else */
722
723     return(entry->symlink != NULL);
724 } /* zip_resolve_symlink */
725
726
727 /*
728  * Parse the local file header of an entry, and update entry->offset.
729  */
730 static int zip_parse_local(void *in, ZIPentry *entry)
731 {
732     PHYSFS_uint32 ui32;
733     PHYSFS_uint16 ui16;
734     PHYSFS_uint16 fnamelen;
735     PHYSFS_uint16 extralen;
736
737     /*
738      * crc and (un)compressed_size are always zero if this is a "JAR"
739      *  archive created with Sun's Java tools, apparently. We only
740      *  consider this archive corrupted if those entries don't match and
741      *  aren't zero. That seems to work well.
742      */
743
744     BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, entry->offset), NULL, 0);
745     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
746     BAIL_IF_MACRO(ui32 != ZIP_LOCAL_FILE_SIG, ERR_CORRUPTED, 0);
747     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
748     BAIL_IF_MACRO(ui16 != entry->version_needed, ERR_CORRUPTED, 0);
749     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);  /* general bits. */
750     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
751     BAIL_IF_MACRO(ui16 != entry->compression_method, ERR_CORRUPTED, 0);
752     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);  /* date/time */
753     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
754     BAIL_IF_MACRO(ui32 && (ui32 != entry->crc), ERR_CORRUPTED, 0);
755     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
756     BAIL_IF_MACRO(ui32 && (ui32 != entry->compressed_size), ERR_CORRUPTED, 0);
757     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
758     BAIL_IF_MACRO(ui32 && (ui32 != entry->uncompressed_size),ERR_CORRUPTED,0);
759     BAIL_IF_MACRO(!readui16(in, &fnamelen), NULL, 0);
760     BAIL_IF_MACRO(!readui16(in, &extralen), NULL, 0);
761
762     entry->offset += fnamelen + extralen + 30;
763     return(1);
764 } /* zip_parse_local */
765
766
767 static int zip_resolve(void *in, ZIPinfo *info, ZIPentry *entry)
768 {
769     int retval = 1;
770     ZipResolveType resolve_type = entry->resolved;
771
772     /* Don't bother if we've failed to resolve this entry before. */
773     BAIL_IF_MACRO(resolve_type == ZIP_BROKEN_FILE, ERR_CORRUPTED, 0);
774     BAIL_IF_MACRO(resolve_type == ZIP_BROKEN_SYMLINK, ERR_CORRUPTED, 0);
775
776     /* uhoh...infinite symlink loop! */
777     BAIL_IF_MACRO(resolve_type == ZIP_RESOLVING, ERR_SYMLINK_LOOP, 0);
778
779     /*
780      * We fix up the offset to point to the actual data on the
781      *  first open, since we don't want to seek across the whole file on
782      *  archive open (can be SLOW on large, CD-stored files), but we
783      *  need to check the local file header...not just for corruption,
784      *  but since it stores offset info the central directory does not.
785      */
786     if (resolve_type != ZIP_RESOLVED)
787     {
788         entry->resolved = ZIP_RESOLVING;
789
790         retval = zip_parse_local(in, entry);
791         if (retval)
792         {
793             /*
794              * If it's a symlink, find the original file. This will cause
795              *  resolution of other entries (other symlinks and, eventually,
796              *  the real file) if all goes well.
797              */
798             if (resolve_type == ZIP_UNRESOLVED_SYMLINK)
799                 retval = zip_resolve_symlink(in, info, entry);
800         } /* if */
801
802         if (resolve_type == ZIP_UNRESOLVED_SYMLINK)
803             entry->resolved = ((retval) ? ZIP_RESOLVED : ZIP_BROKEN_SYMLINK);
804         else if (resolve_type == ZIP_UNRESOLVED_FILE)
805             entry->resolved = ((retval) ? ZIP_RESOLVED : ZIP_BROKEN_FILE);
806     } /* if */
807
808     return(retval);
809 } /* zip_resolve */
810
811
812 static int zip_version_does_symlinks(PHYSFS_uint32 version)
813 {
814     int retval = 0;
815     PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((version >> 8) & 0xFF);
816
817     switch (hosttype)
818     {
819             /*
820              * These are the platforms that can NOT build an archive with
821              *  symlinks, according to the Info-ZIP project.
822              */
823         case 0:  /* FS_FAT_  */
824         case 1:  /* AMIGA_   */
825         case 2:  /* VMS_     */
826         case 4:  /* VM_CSM_  */
827         case 6:  /* FS_HPFS_ */
828         case 11: /* FS_NTFS_ */
829         case 14: /* FS_VFAT_ */
830         case 13: /* ACORN_   */
831         case 15: /* MVS_     */
832         case 18: /* THEOS_   */
833             break;  /* do nothing. */
834
835         default:  /* assume the rest to be unix-like. */
836             retval = 1;
837             break;
838     } /* switch */
839
840     return(retval);
841 } /* zip_version_does_symlinks */
842
843
844 static int zip_entry_is_symlink(const ZIPentry *entry)
845 {
846     return((entry->resolved == ZIP_UNRESOLVED_SYMLINK) ||
847            (entry->resolved == ZIP_BROKEN_SYMLINK) ||
848            (entry->symlink));
849 } /* zip_entry_is_symlink */
850
851
852 static int zip_has_symlink_attr(ZIPentry *entry, PHYSFS_uint32 extern_attr)
853 {
854     PHYSFS_uint16 xattr = ((extern_attr >> 16) & 0xFFFF);
855
856     return (
857               (zip_version_does_symlinks(entry->version)) &&
858               (entry->uncompressed_size > 0) &&
859               ((xattr & UNIX_FILETYPE_MASK) == UNIX_FILETYPE_SYMLINK)
860            );
861 } /* zip_has_symlink_attr */
862
863
864 static PHYSFS_sint64 zip_dos_time_to_physfs_time(PHYSFS_uint32 dostime)
865 {
866 #ifdef _WIN32_WCE
867     /* We have no struct tm and no mktime right now.
868        FIXME: This should probably be fixed at some point.
869     */
870     return -1;
871 #else
872     PHYSFS_uint32 dosdate;
873     struct tm unixtime;
874     memset(&unixtime, '\0', sizeof (unixtime));
875
876     dosdate = (PHYSFS_uint32) ((dostime >> 16) & 0xFFFF);
877     dostime &= 0xFFFF;
878
879     /* dissect date */
880     unixtime.tm_year = ((dosdate >> 9) & 0x7F) + 80;
881     unixtime.tm_mon  = ((dosdate >> 5) & 0x0F) - 1;
882     unixtime.tm_mday = ((dosdate     ) & 0x1F);
883
884     /* dissect time */
885     unixtime.tm_hour = ((dostime >> 11) & 0x1F);
886     unixtime.tm_min  = ((dostime >>  5) & 0x3F);
887     unixtime.tm_sec  = ((dostime <<  1) & 0x3E);
888
889     /* let mktime calculate daylight savings time. */
890     unixtime.tm_isdst = -1;
891
892     return((PHYSFS_sint64) mktime(&unixtime));
893 #endif
894 } /* zip_dos_time_to_physfs_time */
895
896
897 static int zip_load_entry(void *in, ZIPentry *entry, PHYSFS_uint32 ofs_fixup)
898 {
899     PHYSFS_uint16 fnamelen, extralen, commentlen;
900     PHYSFS_uint32 external_attr;
901     PHYSFS_uint16 ui16;
902     PHYSFS_uint32 ui32;
903     PHYSFS_sint64 si64;
904
905     /* sanity check with central directory signature... */
906     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
907     BAIL_IF_MACRO(ui32 != ZIP_CENTRAL_DIR_SIG, ERR_CORRUPTED, 0);
908
909     /* Get the pertinent parts of the record... */
910     BAIL_IF_MACRO(!readui16(in, &entry->version), NULL, 0);
911     BAIL_IF_MACRO(!readui16(in, &entry->version_needed), NULL, 0);
912     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);  /* general bits */
913     BAIL_IF_MACRO(!readui16(in, &entry->compression_method), NULL, 0);
914     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
915     entry->last_mod_time = zip_dos_time_to_physfs_time(ui32);
916     BAIL_IF_MACRO(!readui32(in, &entry->crc), NULL, 0);
917     BAIL_IF_MACRO(!readui32(in, &entry->compressed_size), NULL, 0);
918     BAIL_IF_MACRO(!readui32(in, &entry->uncompressed_size), NULL, 0);
919     BAIL_IF_MACRO(!readui16(in, &fnamelen), NULL, 0);
920     BAIL_IF_MACRO(!readui16(in, &extralen), NULL, 0);
921     BAIL_IF_MACRO(!readui16(in, &commentlen), NULL, 0);
922     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);  /* disk number start */
923     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);  /* internal file attribs */
924     BAIL_IF_MACRO(!readui32(in, &external_attr), NULL, 0);
925     BAIL_IF_MACRO(!readui32(in, &entry->offset), NULL, 0);
926     entry->offset += ofs_fixup;
927
928     entry->symlink = NULL;  /* will be resolved later, if necessary. */
929     entry->resolved = (zip_has_symlink_attr(entry, external_attr)) ?
930                             ZIP_UNRESOLVED_SYMLINK : ZIP_UNRESOLVED_FILE;
931
932     entry->name = (char *) allocator.Malloc(fnamelen + 1);
933     BAIL_IF_MACRO(entry->name == NULL, ERR_OUT_OF_MEMORY, 0);
934     if (__PHYSFS_platformRead(in, entry->name, fnamelen, 1) != 1)
935         goto zip_load_entry_puked;
936
937     entry->name[fnamelen] = '\0';  /* null-terminate the filename. */
938     zip_convert_dos_path(entry, entry->name);
939
940     si64 = __PHYSFS_platformTell(in);
941     if (si64 == -1)
942         goto zip_load_entry_puked;
943
944         /* seek to the start of the next entry in the central directory... */
945     if (!__PHYSFS_platformSeek(in, si64 + extralen + commentlen))
946         goto zip_load_entry_puked;
947
948     return(1);  /* success. */
949
950 zip_load_entry_puked:
951     allocator.Free(entry->name);
952     return(0);  /* failure. */
953 } /* zip_load_entry */
954
955
956 static int zip_entry_cmp(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
957 {
958     if (one != two)
959     {
960         const ZIPentry *a = (const ZIPentry *) _a;
961         return(strcmp(a[one].name, a[two].name));
962     } /* if */
963
964     return 0;
965 } /* zip_entry_cmp */
966
967
968 static void zip_entry_swap(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
969 {
970     if (one != two)
971     {
972         ZIPentry tmp;
973         ZIPentry *first = &(((ZIPentry *) _a)[one]);
974         ZIPentry *second = &(((ZIPentry *) _a)[two]);
975         memcpy(&tmp, first, sizeof (ZIPentry));
976         memcpy(first, second, sizeof (ZIPentry));
977         memcpy(second, &tmp, sizeof (ZIPentry));
978     } /* if */
979 } /* zip_entry_swap */
980
981
982 static int zip_load_entries(void *in, ZIPinfo *info,
983                             PHYSFS_uint32 data_ofs, PHYSFS_uint32 central_ofs)
984 {
985     PHYSFS_uint32 max = info->entryCount;
986     PHYSFS_uint32 i;
987
988     BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, central_ofs), NULL, 0);
989
990     info->entries = (ZIPentry *) allocator.Malloc(sizeof (ZIPentry) * max);
991     BAIL_IF_MACRO(info->entries == NULL, ERR_OUT_OF_MEMORY, 0);
992
993     for (i = 0; i < max; i++)
994     {
995         if (!zip_load_entry(in, &info->entries[i], data_ofs))
996         {
997             zip_free_entries(info->entries, i);
998             return(0);
999         } /* if */
1000     } /* for */
1001
1002     __PHYSFS_sort(info->entries, max, zip_entry_cmp, zip_entry_swap);
1003     return(1);
1004 } /* zip_load_entries */
1005
1006
1007 static int zip_parse_end_of_central_dir(void *in, ZIPinfo *info,
1008                                         PHYSFS_uint32 *data_start,
1009                                         PHYSFS_uint32 *central_dir_ofs)
1010 {
1011     PHYSFS_uint32 ui32;
1012     PHYSFS_uint16 ui16;
1013     PHYSFS_sint64 len;
1014     PHYSFS_sint64 pos;
1015
1016     /* find the end-of-central-dir record, and seek to it. */
1017     pos = zip_find_end_of_central_dir(in, &len);
1018     BAIL_IF_MACRO(pos == -1, NULL, 0);
1019     BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, pos), NULL, 0);
1020
1021     /* check signature again, just in case. */
1022     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
1023     BAIL_IF_MACRO(ui32 != ZIP_END_OF_CENTRAL_DIR_SIG, ERR_NOT_AN_ARCHIVE, 0);
1024
1025     /* number of this disk */
1026     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1027     BAIL_IF_MACRO(ui16 != 0, ERR_UNSUPPORTED_ARCHIVE, 0);
1028
1029     /* number of the disk with the start of the central directory */
1030     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1031     BAIL_IF_MACRO(ui16 != 0, ERR_UNSUPPORTED_ARCHIVE, 0);
1032
1033     /* total number of entries in the central dir on this disk */
1034     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1035
1036     /* total number of entries in the central dir */
1037     BAIL_IF_MACRO(!readui16(in, &info->entryCount), NULL, 0);
1038     BAIL_IF_MACRO(ui16 != info->entryCount, ERR_UNSUPPORTED_ARCHIVE, 0);
1039
1040     /* size of the central directory */
1041     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
1042
1043     /* offset of central directory */
1044     BAIL_IF_MACRO(!readui32(in, central_dir_ofs), NULL, 0);
1045     BAIL_IF_MACRO(pos < *central_dir_ofs + ui32, ERR_UNSUPPORTED_ARCHIVE, 0);
1046
1047     /*
1048      * For self-extracting archives, etc, there's crapola in the file
1049      *  before the zipfile records; we calculate how much data there is
1050      *  prepended by determining how far the central directory offset is
1051      *  from where it is supposed to be (start of end-of-central-dir minus
1052      *  sizeof central dir)...the difference in bytes is how much arbitrary
1053      *  data is at the start of the physical file.
1054      */
1055     *data_start = (PHYSFS_uint32) (pos - (*central_dir_ofs + ui32));
1056
1057     /* Now that we know the difference, fix up the central dir offset... */
1058     *central_dir_ofs += *data_start;
1059
1060     /* zipfile comment length */
1061     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1062
1063     /*
1064      * Make sure that the comment length matches to the end of file...
1065      *  If it doesn't, we're either in the wrong part of the file, or the
1066      *  file is corrupted, but we give up either way.
1067      */
1068     BAIL_IF_MACRO((pos + 22 + ui16) != len, ERR_UNSUPPORTED_ARCHIVE, 0);
1069
1070     return(1);  /* made it. */
1071 } /* zip_parse_end_of_central_dir */
1072
1073
1074 static ZIPinfo *zip_create_zipinfo(const char *name)
1075 {
1076     char *ptr;
1077     ZIPinfo *info = (ZIPinfo *) allocator.Malloc(sizeof (ZIPinfo));
1078     BAIL_IF_MACRO(info == NULL, ERR_OUT_OF_MEMORY, 0);
1079     memset(info, '\0', sizeof (ZIPinfo));
1080
1081     ptr = (char *) allocator.Malloc(strlen(name) + 1);
1082     if (ptr == NULL)
1083     {
1084         allocator.Free(info);
1085         BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1086     } /* if */
1087
1088     info->archiveName = ptr;
1089     strcpy(info->archiveName, name);
1090     return(info);
1091 } /* zip_create_zipinfo */
1092
1093
1094 static void *ZIP_openArchive(const char *name, int forWriting)
1095 {
1096     void *in = NULL;
1097     ZIPinfo *info = NULL;
1098     PHYSFS_uint32 data_start;
1099     PHYSFS_uint32 cent_dir_ofs;
1100
1101     BAIL_IF_MACRO(forWriting, ERR_ARC_IS_READ_ONLY, NULL);
1102
1103     if ((in = __PHYSFS_platformOpenRead(name)) == NULL)
1104         goto zip_openarchive_failed;
1105     
1106     if ((info = zip_create_zipinfo(name)) == NULL)
1107         goto zip_openarchive_failed;
1108
1109     if (!zip_parse_end_of_central_dir(in, info, &data_start, &cent_dir_ofs))
1110         goto zip_openarchive_failed;
1111
1112     if (!zip_load_entries(in, info, data_start, cent_dir_ofs))
1113         goto zip_openarchive_failed;
1114
1115     __PHYSFS_platformClose(in);
1116     return(info);
1117
1118 zip_openarchive_failed:
1119     if (info != NULL)
1120     {
1121         if (info->archiveName != NULL)
1122             allocator.Free(info->archiveName);
1123         allocator.Free(info);
1124     } /* if */
1125
1126     if (in != NULL)
1127         __PHYSFS_platformClose(in);
1128
1129     return(NULL);
1130 } /* ZIP_openArchive */
1131
1132
1133 static PHYSFS_sint32 zip_find_start_of_dir(ZIPinfo *info, const char *path,
1134                                             int stop_on_first_find)
1135 {
1136     PHYSFS_sint32 lo = 0;
1137     PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
1138     PHYSFS_sint32 middle;
1139     PHYSFS_uint32 dlen = strlen(path);
1140     PHYSFS_sint32 retval = -1;
1141     const char *name;
1142     int rc;
1143
1144     if (*path == '\0')  /* root dir? */
1145         return(0);
1146
1147     if ((dlen > 0) && (path[dlen - 1] == '/')) /* ignore trailing slash. */
1148         dlen--;
1149
1150     while (lo <= hi)
1151     {
1152         middle = lo + ((hi - lo) / 2);
1153         name = info->entries[middle].name;
1154         rc = strncmp(path, name, dlen);
1155         if (rc == 0)
1156         {
1157             char ch = name[dlen];
1158             if ('/' < ch) /* make sure this isn't just a substr match. */
1159                 rc = -1;
1160             else if ('/' > ch)
1161                 rc = 1;
1162             else 
1163             {
1164                 if (stop_on_first_find) /* Just checking dir's existance? */
1165                     return(middle);
1166
1167                 if (name[dlen + 1] == '\0') /* Skip initial dir entry. */
1168                     return(middle + 1);
1169
1170                 /* there might be more entries earlier in the list. */
1171                 retval = middle;
1172                 hi = middle - 1;
1173             } /* else */
1174         } /* if */
1175
1176         if (rc > 0)
1177             lo = middle + 1;
1178         else
1179             hi = middle - 1;
1180     } /* while */
1181
1182     return(retval);
1183 } /* zip_find_start_of_dir */
1184
1185
1186 /*
1187  * Moved to seperate function so we can use alloca then immediately throw
1188  *  away the allocated stack space...
1189  */
1190 static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
1191                            const char *odir, const char *str, PHYSFS_sint32 ln)
1192 {
1193     char *newstr = __PHYSFS_smallAlloc(ln + 1);
1194     if (newstr == NULL)
1195         return;
1196
1197     memcpy(newstr, str, ln);
1198     newstr[ln] = '\0';
1199     cb(callbackdata, odir, newstr);
1200     __PHYSFS_smallFree(newstr);
1201 } /* doEnumCallback */
1202
1203
1204 static void ZIP_enumerateFiles(dvoid *opaque, const char *dname,
1205                                int omitSymLinks, PHYSFS_EnumFilesCallback cb,
1206                                const char *origdir, void *callbackdata)
1207 {
1208     ZIPinfo *info = ((ZIPinfo *) opaque);
1209     PHYSFS_sint32 dlen, dlen_inc, max, i;
1210
1211     i = zip_find_start_of_dir(info, dname, 0);
1212     if (i == -1)  /* no such directory. */
1213         return;
1214
1215     dlen = strlen(dname);
1216     if ((dlen > 0) && (dname[dlen - 1] == '/')) /* ignore trailing slash. */
1217         dlen--;
1218
1219     dlen_inc = ((dlen > 0) ? 1 : 0) + dlen;
1220     max = (PHYSFS_sint32) info->entryCount;
1221     while (i < max)
1222     {
1223         char *e = info->entries[i].name;
1224         if ((dlen) && ((strncmp(e, dname, dlen) != 0) || (e[dlen] != '/')))
1225             break;  /* past end of this dir; we're done. */
1226
1227         if ((omitSymLinks) && (zip_entry_is_symlink(&info->entries[i])))
1228             i++;
1229         else
1230         {
1231             char *add = e + dlen_inc;
1232             char *ptr = strchr(add, '/');
1233             PHYSFS_sint32 ln = (PHYSFS_sint32) ((ptr) ? ptr-add : strlen(add));
1234             doEnumCallback(cb, callbackdata, origdir, add, ln);
1235             ln += dlen_inc;  /* point past entry to children... */
1236
1237             /* increment counter and skip children of subdirs... */
1238             while ((++i < max) && (ptr != NULL))
1239             {
1240                 char *e_new = info->entries[i].name;
1241                 if ((strncmp(e, e_new, ln) != 0) || (e_new[ln] != '/'))
1242                     break;
1243             } /* while */
1244         } /* else */
1245     } /* while */
1246 } /* ZIP_enumerateFiles */
1247
1248
1249 static int ZIP_exists(dvoid *opaque, const char *name)
1250 {
1251     int isDir;    
1252     ZIPinfo *info = (ZIPinfo *) opaque;
1253     ZIPentry *entry = zip_find_entry(info, name, &isDir);
1254     return((entry != NULL) || (isDir));
1255 } /* ZIP_exists */
1256
1257
1258 static PHYSFS_sint64 ZIP_getLastModTime(dvoid *opaque,
1259                                         const char *name,
1260                                         int *fileExists)
1261 {
1262     int isDir;
1263     ZIPinfo *info = (ZIPinfo *) opaque;
1264     ZIPentry *entry = zip_find_entry(info, name, &isDir);
1265
1266     *fileExists = ((isDir) || (entry != NULL));
1267     if (isDir)
1268         return(1);  /* Best I can do for a dir... */
1269
1270     BAIL_IF_MACRO(entry == NULL, NULL, -1);
1271     return(entry->last_mod_time);
1272 } /* ZIP_getLastModTime */
1273
1274
1275 static int ZIP_isDirectory(dvoid *opaque, const char *name, int *fileExists)
1276 {
1277     ZIPinfo *info = (ZIPinfo *) opaque;
1278     int isDir;
1279     ZIPentry *entry = zip_find_entry(info, name, &isDir);
1280
1281     *fileExists = ((isDir) || (entry != NULL));
1282     if (isDir)
1283         return(1); /* definitely a dir. */
1284
1285     /* Follow symlinks. This means we might need to resolve entries. */
1286     BAIL_IF_MACRO(entry == NULL, ERR_NO_SUCH_FILE, 0);
1287
1288     if (entry->resolved == ZIP_UNRESOLVED_SYMLINK) /* gotta resolve it. */
1289     {
1290         int rc;
1291         void *in = __PHYSFS_platformOpenRead(info->archiveName);
1292         BAIL_IF_MACRO(in == NULL, NULL, 0);
1293         rc = zip_resolve(in, info, entry);
1294         __PHYSFS_platformClose(in);
1295         if (!rc)
1296             return(0);
1297     } /* if */
1298
1299     BAIL_IF_MACRO(entry->resolved == ZIP_BROKEN_SYMLINK, NULL, 0);
1300     BAIL_IF_MACRO(entry->symlink == NULL, ERR_NOT_A_DIR, 0);
1301
1302     return(zip_find_start_of_dir(info, entry->symlink->name, 1) >= 0);
1303 } /* ZIP_isDirectory */
1304
1305
1306 static int ZIP_isSymLink(dvoid *opaque, const char *name, int *fileExists)
1307 {
1308     int isDir;
1309     const ZIPentry *entry = zip_find_entry((ZIPinfo *) opaque, name, &isDir);
1310     *fileExists = ((isDir) || (entry != NULL));
1311     BAIL_IF_MACRO(entry == NULL, NULL, 0);
1312     return(zip_entry_is_symlink(entry));
1313 } /* ZIP_isSymLink */
1314
1315
1316 static void *zip_get_file_handle(const char *fn, ZIPinfo *inf, ZIPentry *entry)
1317 {
1318     int success;
1319     void *retval = __PHYSFS_platformOpenRead(fn);
1320     BAIL_IF_MACRO(retval == NULL, NULL, NULL);
1321
1322     success = zip_resolve(retval, inf, entry);
1323     if (success)
1324     {
1325         PHYSFS_sint64 offset;
1326         offset = ((entry->symlink) ? entry->symlink->offset : entry->offset);
1327         success = __PHYSFS_platformSeek(retval, offset);
1328     } /* if */
1329
1330     if (!success)
1331     {
1332         __PHYSFS_platformClose(retval);
1333         retval = NULL;
1334     } /* if */
1335
1336     return(retval);
1337 } /* zip_get_file_handle */
1338
1339
1340 static fvoid *ZIP_openRead(dvoid *opaque, const char *fnm, int *fileExists)
1341 {
1342     ZIPinfo *info = (ZIPinfo *) opaque;
1343     ZIPentry *entry = zip_find_entry(info, fnm, NULL);
1344     ZIPfileinfo *finfo = NULL;
1345     void *in;
1346
1347     *fileExists = (entry != NULL);
1348     BAIL_IF_MACRO(entry == NULL, NULL, NULL);
1349
1350     in = zip_get_file_handle(info->archiveName, info, entry);
1351     BAIL_IF_MACRO(in == NULL, NULL, NULL);
1352
1353     finfo = (ZIPfileinfo *) allocator.Malloc(sizeof (ZIPfileinfo));
1354     if (finfo == NULL)
1355     {
1356         __PHYSFS_platformClose(in);
1357         BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1358     } /* if */
1359
1360     memset(finfo, '\0', sizeof (ZIPfileinfo));
1361     finfo->handle = in;
1362     finfo->entry = ((entry->symlink != NULL) ? entry->symlink : entry);
1363     initializeZStream(&finfo->stream);
1364     if (finfo->entry->compression_method != COMPMETH_NONE)
1365     {
1366         if (zlib_err(inflateInit2(&finfo->stream, -MAX_WBITS)) != Z_OK)
1367         {
1368             ZIP_fileClose(finfo);
1369             return(NULL);
1370         } /* if */
1371
1372         finfo->buffer = (PHYSFS_uint8 *) allocator.Malloc(ZIP_READBUFSIZE);
1373         if (finfo->buffer == NULL)
1374         {
1375             ZIP_fileClose(finfo);
1376             BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1377         } /* if */
1378     } /* if */
1379
1380     return(finfo);
1381 } /* ZIP_openRead */
1382
1383
1384 static fvoid *ZIP_openWrite(dvoid *opaque, const char *filename)
1385 {
1386     BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
1387 } /* ZIP_openWrite */
1388
1389
1390 static fvoid *ZIP_openAppend(dvoid *opaque, const char *filename)
1391 {
1392     BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
1393 } /* ZIP_openAppend */
1394
1395
1396 static void ZIP_dirClose(dvoid *opaque)
1397 {
1398     ZIPinfo *zi = (ZIPinfo *) (opaque);
1399     zip_free_entries(zi->entries, zi->entryCount);
1400     allocator.Free(zi->archiveName);
1401     allocator.Free(zi);
1402 } /* ZIP_dirClose */
1403
1404
1405 static int ZIP_remove(dvoid *opaque, const char *name)
1406 {
1407     BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
1408 } /* ZIP_remove */
1409
1410
1411 static int ZIP_mkdir(dvoid *opaque, const char *name)
1412 {
1413     BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
1414 } /* ZIP_mkdir */
1415
1416
1417 const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_ZIP =
1418 {
1419     "ZIP",
1420     ZIP_ARCHIVE_DESCRIPTION,
1421     "Ryan C. Gordon <icculus@icculus.org>",
1422     "http://icculus.org/physfs/",
1423 };
1424
1425
1426 const PHYSFS_Archiver __PHYSFS_Archiver_ZIP =
1427 {
1428     &__PHYSFS_ArchiveInfo_ZIP,
1429     ZIP_isArchive,          /* isArchive() method      */
1430     ZIP_openArchive,        /* openArchive() method    */
1431     ZIP_enumerateFiles,     /* enumerateFiles() method */
1432     ZIP_exists,             /* exists() method         */
1433     ZIP_isDirectory,        /* isDirectory() method    */
1434     ZIP_isSymLink,          /* isSymLink() method      */
1435     ZIP_getLastModTime,     /* getLastModTime() method */
1436     ZIP_openRead,           /* openRead() method       */
1437     ZIP_openWrite,          /* openWrite() method      */
1438     ZIP_openAppend,         /* openAppend() method     */
1439     ZIP_remove,             /* remove() method         */
1440     ZIP_mkdir,              /* mkdir() method          */
1441     ZIP_dirClose,           /* dirClose() method       */
1442     ZIP_read,               /* read() method           */
1443     ZIP_write,              /* write() method          */
1444     ZIP_eof,                /* eof() method            */
1445     ZIP_tell,               /* tell() method           */
1446     ZIP_seek,               /* seek() method           */
1447     ZIP_fileLength,         /* fileLength() method     */
1448     ZIP_fileClose           /* fileClose() method      */
1449 };
1450
1451 #endif  /* defined PHYSFS_SUPPORTS_ZIP */
1452
1453 /* end of zip.c ... */
1454