Initial integration, lots of broken stuff
[supertux.git] / src / unison / physfs-1.1.1 / 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_sint32 i = 0;
379     PHYSFS_sint64 filelen;
380     PHYSFS_sint64 filepos;
381     PHYSFS_sint32 maxread;
382     PHYSFS_sint32 totalread = 0;
383     int found = 0;
384     PHYSFS_uint32 extra = 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             *((PHYSFS_uint32 *) (&buf[maxread - 4])) = 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         extra = *((PHYSFS_uint32 *) (&buf[0]));
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     } /* while */
451
452     BAIL_IF_MACRO(!found, ERR_NOT_AN_ARCHIVE, -1);
453
454     if (len != NULL)
455         *len = filelen;
456
457     return(filepos + i);
458 } /* zip_find_end_of_central_dir */
459
460
461 static int ZIP_isArchive(const char *filename, int forWriting)
462 {
463     PHYSFS_uint32 sig;
464     int retval = 0;
465     void *in;
466
467     in = __PHYSFS_platformOpenRead(filename);
468     BAIL_IF_MACRO(in == NULL, NULL, 0);
469
470     /*
471      * The first thing in a zip file might be the signature of the
472      *  first local file record, so it makes for a quick determination.
473      */
474     if (readui32(in, &sig))
475     {
476         retval = (sig == ZIP_LOCAL_FILE_SIG);
477         if (!retval)
478         {
479             /*
480              * No sig...might be a ZIP with data at the start
481              *  (a self-extracting executable, etc), so we'll have to do
482              *  it the hard way...
483              */
484             retval = (zip_find_end_of_central_dir(in, NULL) != -1);
485         } /* if */
486     } /* if */
487
488     __PHYSFS_platformClose(in);
489     return(retval);
490 } /* ZIP_isArchive */
491
492
493 static void zip_free_entries(ZIPentry *entries, PHYSFS_uint32 max)
494 {
495     PHYSFS_uint32 i;
496     for (i = 0; i < max; i++)
497     {
498         ZIPentry *entry = &entries[i];
499         if (entry->name != NULL)
500             allocator.Free(entry->name);
501     } /* for */
502
503     allocator.Free(entries);
504 } /* zip_free_entries */
505
506
507 /*
508  * This will find the ZIPentry associated with a path in platform-independent
509  *  notation. Directories don't have ZIPentries associated with them, but 
510  *  (*isDir) will be set to non-zero if a dir was hit.
511  */
512 static ZIPentry *zip_find_entry(ZIPinfo *info, const char *path, int *isDir)
513 {
514     ZIPentry *a = info->entries;
515     PHYSFS_sint32 pathlen = strlen(path);
516     PHYSFS_sint32 lo = 0;
517     PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
518     PHYSFS_sint32 middle;
519     const char *thispath = NULL;
520     int rc;
521
522     while (lo <= hi)
523     {
524         middle = lo + ((hi - lo) / 2);
525         thispath = a[middle].name;
526         rc = strncmp(path, thispath, pathlen);
527
528         if (rc > 0)
529             lo = middle + 1;
530
531         else if (rc < 0)
532             hi = middle - 1;
533
534         else /* substring match...might be dir or entry or nothing. */
535         {
536             if (isDir != NULL)
537             {
538                 *isDir = (thispath[pathlen] == '/');
539                 if (*isDir)
540                     return(NULL);
541             } /* if */
542
543             if (thispath[pathlen] == '\0') /* found entry? */
544                 return(&a[middle]);
545             else
546                 hi = middle - 1;  /* adjust search params, try again. */
547         } /* if */
548     } /* while */
549
550     if (isDir != NULL)
551         *isDir = 0;
552
553     BAIL_MACRO(ERR_NO_SUCH_FILE, NULL);
554 } /* zip_find_entry */
555
556
557 /* Convert paths from old, buggy DOS zippers... */
558 static void zip_convert_dos_path(ZIPentry *entry, char *path)
559 {
560     PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((entry->version >> 8) & 0xFF);
561     if (hosttype == 0)  /* FS_FAT_ */
562     {
563         while (*path)
564         {
565             if (*path == '\\')
566                 *path = '/';
567             path++;
568         } /* while */
569     } /* if */
570 } /* zip_convert_dos_path */
571
572
573 static void zip_expand_symlink_path(char *path)
574 {
575     char *ptr = path;
576     char *prevptr = path;
577
578     while (1)
579     {
580         ptr = strchr(ptr, '/');
581         if (ptr == NULL)
582             break;
583
584         if (*(ptr + 1) == '.')
585         {
586             if (*(ptr + 2) == '/')
587             {
588                 /* current dir in middle of string: ditch it. */
589                 memmove(ptr, ptr + 2, strlen(ptr + 2) + 1);
590             } /* else if */
591
592             else if (*(ptr + 2) == '\0')
593             {
594                 /* current dir at end of string: ditch it. */
595                 *ptr = '\0';
596             } /* else if */
597
598             else if (*(ptr + 2) == '.')
599             {
600                 if (*(ptr + 3) == '/')
601                 {
602                     /* parent dir in middle: move back one, if possible. */
603                     memmove(prevptr, ptr + 4, strlen(ptr + 4) + 1);
604                     ptr = prevptr;
605                     while (prevptr != path)
606                     {
607                         prevptr--;
608                         if (*prevptr == '/')
609                         {
610                             prevptr++;
611                             break;
612                         } /* if */
613                     } /* while */
614                 } /* if */
615
616                 if (*(ptr + 3) == '\0')
617                 {
618                     /* parent dir at end: move back one, if possible. */
619                     *prevptr = '\0';
620                 } /* if */
621             } /* if */
622         } /* if */
623         else
624         {
625             prevptr = ptr;
626         } /* else */
627     } /* while */
628 } /* zip_expand_symlink_path */
629
630 /* (forward reference: zip_follow_symlink and zip_resolve call each other.) */
631 static int zip_resolve(void *in, ZIPinfo *info, ZIPentry *entry);
632
633 /*
634  * Look for the entry named by (path). If it exists, resolve it, and return
635  *  a pointer to that entry. If it's another symlink, keep resolving until you
636  *  hit a real file and then return a pointer to the final non-symlink entry.
637  *  If there's a problem, return NULL. (path) is always free()'d by this
638  *  function.
639  */
640 static ZIPentry *zip_follow_symlink(void *in, ZIPinfo *info, char *path)
641 {
642     ZIPentry *entry;
643
644     zip_expand_symlink_path(path);
645     entry = zip_find_entry(info, path, NULL);
646     if (entry != NULL)
647     {
648         if (!zip_resolve(in, info, entry))  /* recursive! */
649             entry = NULL;
650         else
651         {
652             if (entry->symlink != NULL)
653                 entry = entry->symlink;
654         } /* else */
655     } /* if */
656
657     allocator.Free(path);
658     return(entry);
659 } /* zip_follow_symlink */
660
661
662 static int zip_resolve_symlink(void *in, ZIPinfo *info, ZIPentry *entry)
663 {
664     char *path;
665     PHYSFS_uint32 size = entry->uncompressed_size;
666     int rc = 0;
667
668     /*
669      * We've already parsed the local file header of the symlink at this
670      *  point. Now we need to read the actual link from the file data and
671      *  follow it.
672      */
673
674     BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, entry->offset), NULL, 0);
675
676     path = (char *) allocator.Malloc(size + 1);
677     BAIL_IF_MACRO(path == NULL, ERR_OUT_OF_MEMORY, 0);
678     
679     if (entry->compression_method == COMPMETH_NONE)
680         rc = (__PHYSFS_platformRead(in, path, size, 1) == 1);
681
682     else  /* symlink target path is compressed... */
683     {
684         z_stream stream;
685         PHYSFS_uint32 complen = entry->compressed_size;
686         PHYSFS_uint8 *compressed = (PHYSFS_uint8*) __PHYSFS_smallAlloc(complen);
687         if (compressed != NULL)
688         {
689             if (__PHYSFS_platformRead(in, compressed, complen, 1) == 1)
690             {
691                 initializeZStream(&stream);
692                 stream.next_in = compressed;
693                 stream.avail_in = complen;
694                 stream.next_out = (unsigned char *) path;
695                 stream.avail_out = size;
696                 if (zlib_err(inflateInit2(&stream, -MAX_WBITS)) == Z_OK)
697                 {
698                     rc = zlib_err(inflate(&stream, Z_FINISH));
699                     inflateEnd(&stream);
700
701                     /* both are acceptable outcomes... */
702                     rc = ((rc == Z_OK) || (rc == Z_STREAM_END));
703                 } /* if */
704             } /* if */
705             __PHYSFS_smallFree(compressed);
706         } /* if */
707     } /* else */
708
709     if (!rc)
710         allocator.Free(path);
711     else
712     {
713         path[entry->uncompressed_size] = '\0';    /* null-terminate it. */
714         zip_convert_dos_path(entry, path);
715         entry->symlink = zip_follow_symlink(in, info, path);
716     } /* else */
717
718     return(entry->symlink != NULL);
719 } /* zip_resolve_symlink */
720
721
722 /*
723  * Parse the local file header of an entry, and update entry->offset.
724  */
725 static int zip_parse_local(void *in, ZIPentry *entry)
726 {
727     PHYSFS_uint32 ui32;
728     PHYSFS_uint16 ui16;
729     PHYSFS_uint16 fnamelen;
730     PHYSFS_uint16 extralen;
731
732     /*
733      * crc and (un)compressed_size are always zero if this is a "JAR"
734      *  archive created with Sun's Java tools, apparently. We only
735      *  consider this archive corrupted if those entries don't match and
736      *  aren't zero. That seems to work well.
737      */
738
739     BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, entry->offset), NULL, 0);
740     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
741     BAIL_IF_MACRO(ui32 != ZIP_LOCAL_FILE_SIG, ERR_CORRUPTED, 0);
742     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
743     BAIL_IF_MACRO(ui16 != entry->version_needed, ERR_CORRUPTED, 0);
744     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);  /* general bits. */
745     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
746     BAIL_IF_MACRO(ui16 != entry->compression_method, ERR_CORRUPTED, 0);
747     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);  /* date/time */
748     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
749     BAIL_IF_MACRO(ui32 && (ui32 != entry->crc), ERR_CORRUPTED, 0);
750     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
751     BAIL_IF_MACRO(ui32 && (ui32 != entry->compressed_size), ERR_CORRUPTED, 0);
752     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
753     BAIL_IF_MACRO(ui32 && (ui32 != entry->uncompressed_size),ERR_CORRUPTED,0);
754     BAIL_IF_MACRO(!readui16(in, &fnamelen), NULL, 0);
755     BAIL_IF_MACRO(!readui16(in, &extralen), NULL, 0);
756
757     entry->offset += fnamelen + extralen + 30;
758     return(1);
759 } /* zip_parse_local */
760
761
762 static int zip_resolve(void *in, ZIPinfo *info, ZIPentry *entry)
763 {
764     int retval = 1;
765     ZipResolveType resolve_type = entry->resolved;
766
767     /* Don't bother if we've failed to resolve this entry before. */
768     BAIL_IF_MACRO(resolve_type == ZIP_BROKEN_FILE, ERR_CORRUPTED, 0);
769     BAIL_IF_MACRO(resolve_type == ZIP_BROKEN_SYMLINK, ERR_CORRUPTED, 0);
770
771     /* uhoh...infinite symlink loop! */
772     BAIL_IF_MACRO(resolve_type == ZIP_RESOLVING, ERR_SYMLINK_LOOP, 0);
773
774     /*
775      * We fix up the offset to point to the actual data on the
776      *  first open, since we don't want to seek across the whole file on
777      *  archive open (can be SLOW on large, CD-stored files), but we
778      *  need to check the local file header...not just for corruption,
779      *  but since it stores offset info the central directory does not.
780      */
781     if (resolve_type != ZIP_RESOLVED)
782     {
783         entry->resolved = ZIP_RESOLVING;
784
785         retval = zip_parse_local(in, entry);
786         if (retval)
787         {
788             /*
789              * If it's a symlink, find the original file. This will cause
790              *  resolution of other entries (other symlinks and, eventually,
791              *  the real file) if all goes well.
792              */
793             if (resolve_type == ZIP_UNRESOLVED_SYMLINK)
794                 retval = zip_resolve_symlink(in, info, entry);
795         } /* if */
796
797         if (resolve_type == ZIP_UNRESOLVED_SYMLINK)
798             entry->resolved = ((retval) ? ZIP_RESOLVED : ZIP_BROKEN_SYMLINK);
799         else if (resolve_type == ZIP_UNRESOLVED_FILE)
800             entry->resolved = ((retval) ? ZIP_RESOLVED : ZIP_BROKEN_FILE);
801     } /* if */
802
803     return(retval);
804 } /* zip_resolve */
805
806
807 static int zip_version_does_symlinks(PHYSFS_uint32 version)
808 {
809     int retval = 0;
810     PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((version >> 8) & 0xFF);
811
812     switch (hosttype)
813     {
814             /*
815              * These are the platforms that can NOT build an archive with
816              *  symlinks, according to the Info-ZIP project.
817              */
818         case 0:  /* FS_FAT_  */
819         case 1:  /* AMIGA_   */
820         case 2:  /* VMS_     */
821         case 4:  /* VM_CSM_  */
822         case 6:  /* FS_HPFS_ */
823         case 11: /* FS_NTFS_ */
824         case 14: /* FS_VFAT_ */
825         case 13: /* ACORN_   */
826         case 15: /* MVS_     */
827         case 18: /* THEOS_   */
828             break;  /* do nothing. */
829
830         default:  /* assume the rest to be unix-like. */
831             retval = 1;
832             break;
833     } /* switch */
834
835     return(retval);
836 } /* zip_version_does_symlinks */
837
838
839 static int zip_entry_is_symlink(ZIPentry *entry)
840 {
841     return((entry->resolved == ZIP_UNRESOLVED_SYMLINK) ||
842            (entry->resolved == ZIP_BROKEN_SYMLINK) ||
843            (entry->symlink));
844 } /* zip_entry_is_symlink */
845
846
847 static int zip_has_symlink_attr(ZIPentry *entry, PHYSFS_uint32 extern_attr)
848 {
849     PHYSFS_uint16 xattr = ((extern_attr >> 16) & 0xFFFF);
850
851     return (
852               (zip_version_does_symlinks(entry->version)) &&
853               (entry->uncompressed_size > 0) &&
854               ((xattr & UNIX_FILETYPE_MASK) == UNIX_FILETYPE_SYMLINK)
855            );
856 } /* zip_has_symlink_attr */
857
858
859 static PHYSFS_sint64 zip_dos_time_to_physfs_time(PHYSFS_uint32 dostime)
860 {
861 #ifdef _WIN32_WCE
862     /* We have no struct tm and no mktime right now.
863        FIXME: This should probably be fixed at some point.
864     */
865     return -1;
866 #else
867     PHYSFS_uint32 dosdate;
868     struct tm unixtime;
869     memset(&unixtime, '\0', sizeof (unixtime));
870
871     dosdate = (PHYSFS_uint32) ((dostime >> 16) & 0xFFFF);
872     dostime &= 0xFFFF;
873
874     /* dissect date */
875     unixtime.tm_year = ((dosdate >> 9) & 0x7F) + 80;
876     unixtime.tm_mon  = ((dosdate >> 5) & 0x0F) - 1;
877     unixtime.tm_mday = ((dosdate     ) & 0x1F);
878
879     /* dissect time */
880     unixtime.tm_hour = ((dostime >> 11) & 0x1F);
881     unixtime.tm_min  = ((dostime >>  5) & 0x3F);
882     unixtime.tm_sec  = ((dostime <<  1) & 0x3E);
883
884     /* let mktime calculate daylight savings time. */
885     unixtime.tm_isdst = -1;
886
887     return((PHYSFS_sint64) mktime(&unixtime));
888 #endif
889 } /* zip_dos_time_to_physfs_time */
890
891
892 static int zip_load_entry(void *in, ZIPentry *entry, PHYSFS_uint32 ofs_fixup)
893 {
894     PHYSFS_uint16 fnamelen, extralen, commentlen;
895     PHYSFS_uint32 external_attr;
896     PHYSFS_uint16 ui16;
897     PHYSFS_uint32 ui32;
898     PHYSFS_sint64 si64;
899
900     /* sanity check with central directory signature... */
901     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
902     BAIL_IF_MACRO(ui32 != ZIP_CENTRAL_DIR_SIG, ERR_CORRUPTED, 0);
903
904     /* Get the pertinent parts of the record... */
905     BAIL_IF_MACRO(!readui16(in, &entry->version), NULL, 0);
906     BAIL_IF_MACRO(!readui16(in, &entry->version_needed), NULL, 0);
907     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);  /* general bits */
908     BAIL_IF_MACRO(!readui16(in, &entry->compression_method), NULL, 0);
909     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
910     entry->last_mod_time = zip_dos_time_to_physfs_time(ui32);
911     BAIL_IF_MACRO(!readui32(in, &entry->crc), NULL, 0);
912     BAIL_IF_MACRO(!readui32(in, &entry->compressed_size), NULL, 0);
913     BAIL_IF_MACRO(!readui32(in, &entry->uncompressed_size), NULL, 0);
914     BAIL_IF_MACRO(!readui16(in, &fnamelen), NULL, 0);
915     BAIL_IF_MACRO(!readui16(in, &extralen), NULL, 0);
916     BAIL_IF_MACRO(!readui16(in, &commentlen), NULL, 0);
917     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);  /* disk number start */
918     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);  /* internal file attribs */
919     BAIL_IF_MACRO(!readui32(in, &external_attr), NULL, 0);
920     BAIL_IF_MACRO(!readui32(in, &entry->offset), NULL, 0);
921     entry->offset += ofs_fixup;
922
923     entry->symlink = NULL;  /* will be resolved later, if necessary. */
924     entry->resolved = (zip_has_symlink_attr(entry, external_attr)) ?
925                             ZIP_UNRESOLVED_SYMLINK : ZIP_UNRESOLVED_FILE;
926
927     entry->name = (char *) allocator.Malloc(fnamelen + 1);
928     BAIL_IF_MACRO(entry->name == NULL, ERR_OUT_OF_MEMORY, 0);
929     if (__PHYSFS_platformRead(in, entry->name, fnamelen, 1) != 1)
930         goto zip_load_entry_puked;
931
932     entry->name[fnamelen] = '\0';  /* null-terminate the filename. */
933     zip_convert_dos_path(entry, entry->name);
934
935     si64 = __PHYSFS_platformTell(in);
936     if (si64 == -1)
937         goto zip_load_entry_puked;
938
939         /* seek to the start of the next entry in the central directory... */
940     if (!__PHYSFS_platformSeek(in, si64 + extralen + commentlen))
941         goto zip_load_entry_puked;
942
943     return(1);  /* success. */
944
945 zip_load_entry_puked:
946     allocator.Free(entry->name);
947     return(0);  /* failure. */
948 } /* zip_load_entry */
949
950
951 static int zip_entry_cmp(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
952 {
953     ZIPentry *a = (ZIPentry *) _a;
954     return(strcmp(a[one].name, a[two].name));
955 } /* zip_entry_cmp */
956
957
958 static void zip_entry_swap(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
959 {
960     ZIPentry tmp;
961     ZIPentry *first = &(((ZIPentry *) _a)[one]);
962     ZIPentry *second = &(((ZIPentry *) _a)[two]);
963     memcpy(&tmp, first, sizeof (ZIPentry));
964     memcpy(first, second, sizeof (ZIPentry));
965     memcpy(second, &tmp, sizeof (ZIPentry));
966 } /* zip_entry_swap */
967
968
969 static int zip_load_entries(void *in, ZIPinfo *info,
970                             PHYSFS_uint32 data_ofs, PHYSFS_uint32 central_ofs)
971 {
972     PHYSFS_uint32 max = info->entryCount;
973     PHYSFS_uint32 i;
974
975     BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, central_ofs), NULL, 0);
976
977     info->entries = (ZIPentry *) allocator.Malloc(sizeof (ZIPentry) * max);
978     BAIL_IF_MACRO(info->entries == NULL, ERR_OUT_OF_MEMORY, 0);
979
980     for (i = 0; i < max; i++)
981     {
982         if (!zip_load_entry(in, &info->entries[i], data_ofs))
983         {
984             zip_free_entries(info->entries, i);
985             return(0);
986         } /* if */
987     } /* for */
988
989     __PHYSFS_sort(info->entries, max, zip_entry_cmp, zip_entry_swap);
990     return(1);
991 } /* zip_load_entries */
992
993
994 static int zip_parse_end_of_central_dir(void *in, ZIPinfo *info,
995                                         PHYSFS_uint32 *data_start,
996                                         PHYSFS_uint32 *central_dir_ofs)
997 {
998     PHYSFS_uint32 ui32;
999     PHYSFS_uint16 ui16;
1000     PHYSFS_sint64 len;
1001     PHYSFS_sint64 pos;
1002
1003     /* find the end-of-central-dir record, and seek to it. */
1004     pos = zip_find_end_of_central_dir(in, &len);
1005     BAIL_IF_MACRO(pos == -1, NULL, 0);
1006     BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, pos), NULL, 0);
1007
1008     /* check signature again, just in case. */
1009     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
1010     BAIL_IF_MACRO(ui32 != ZIP_END_OF_CENTRAL_DIR_SIG, ERR_NOT_AN_ARCHIVE, 0);
1011
1012     /* number of this disk */
1013     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1014     BAIL_IF_MACRO(ui16 != 0, ERR_UNSUPPORTED_ARCHIVE, 0);
1015
1016     /* number of the disk with the start of the central directory */
1017     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1018     BAIL_IF_MACRO(ui16 != 0, ERR_UNSUPPORTED_ARCHIVE, 0);
1019
1020     /* total number of entries in the central dir on this disk */
1021     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1022
1023     /* total number of entries in the central dir */
1024     BAIL_IF_MACRO(!readui16(in, &info->entryCount), NULL, 0);
1025     BAIL_IF_MACRO(ui16 != info->entryCount, ERR_UNSUPPORTED_ARCHIVE, 0);
1026
1027     /* size of the central directory */
1028     BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
1029
1030     /* offset of central directory */
1031     BAIL_IF_MACRO(!readui32(in, central_dir_ofs), NULL, 0);
1032     BAIL_IF_MACRO(pos < *central_dir_ofs + ui32, ERR_UNSUPPORTED_ARCHIVE, 0);
1033
1034     /*
1035      * For self-extracting archives, etc, there's crapola in the file
1036      *  before the zipfile records; we calculate how much data there is
1037      *  prepended by determining how far the central directory offset is
1038      *  from where it is supposed to be (start of end-of-central-dir minus
1039      *  sizeof central dir)...the difference in bytes is how much arbitrary
1040      *  data is at the start of the physical file.
1041      */
1042     *data_start = (PHYSFS_uint32) (pos - (*central_dir_ofs + ui32));
1043
1044     /* Now that we know the difference, fix up the central dir offset... */
1045     *central_dir_ofs += *data_start;
1046
1047     /* zipfile comment length */
1048     BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1049
1050     /*
1051      * Make sure that the comment length matches to the end of file...
1052      *  If it doesn't, we're either in the wrong part of the file, or the
1053      *  file is corrupted, but we give up either way.
1054      */
1055     BAIL_IF_MACRO((pos + 22 + ui16) != len, ERR_UNSUPPORTED_ARCHIVE, 0);
1056
1057     return(1);  /* made it. */
1058 } /* zip_parse_end_of_central_dir */
1059
1060
1061 static ZIPinfo *zip_create_zipinfo(const char *name)
1062 {
1063     char *ptr;
1064     ZIPinfo *info = (ZIPinfo *) allocator.Malloc(sizeof (ZIPinfo));
1065     BAIL_IF_MACRO(info == NULL, ERR_OUT_OF_MEMORY, 0);
1066     memset(info, '\0', sizeof (ZIPinfo));
1067
1068     ptr = (char *) allocator.Malloc(strlen(name) + 1);
1069     if (ptr == NULL)
1070     {
1071         allocator.Free(info);
1072         BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1073     } /* if */
1074
1075     info->archiveName = ptr;
1076     strcpy(info->archiveName, name);
1077     return(info);
1078 } /* zip_create_zipinfo */
1079
1080
1081 static void *ZIP_openArchive(const char *name, int forWriting)
1082 {
1083     void *in = NULL;
1084     ZIPinfo *info = NULL;
1085     PHYSFS_uint32 data_start;
1086     PHYSFS_uint32 cent_dir_ofs;
1087
1088     BAIL_IF_MACRO(forWriting, ERR_ARC_IS_READ_ONLY, NULL);
1089
1090     if ((in = __PHYSFS_platformOpenRead(name)) == NULL)
1091         goto zip_openarchive_failed;
1092     
1093     if ((info = zip_create_zipinfo(name)) == NULL)
1094         goto zip_openarchive_failed;
1095
1096     if (!zip_parse_end_of_central_dir(in, info, &data_start, &cent_dir_ofs))
1097         goto zip_openarchive_failed;
1098
1099     if (!zip_load_entries(in, info, data_start, cent_dir_ofs))
1100         goto zip_openarchive_failed;
1101
1102     __PHYSFS_platformClose(in);
1103     return(info);
1104
1105 zip_openarchive_failed:
1106     if (info != NULL)
1107     {
1108         if (info->archiveName != NULL)
1109             allocator.Free(info->archiveName);
1110         allocator.Free(info);
1111     } /* if */
1112
1113     if (in != NULL)
1114         __PHYSFS_platformClose(in);
1115
1116     return(NULL);
1117 } /* ZIP_openArchive */
1118
1119
1120 static PHYSFS_sint32 zip_find_start_of_dir(ZIPinfo *info, const char *path,
1121                                             int stop_on_first_find)
1122 {
1123     PHYSFS_sint32 lo = 0;
1124     PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
1125     PHYSFS_sint32 middle;
1126     PHYSFS_uint32 dlen = strlen(path);
1127     PHYSFS_sint32 retval = -1;
1128     const char *name;
1129     int rc;
1130
1131     if (*path == '\0')  /* root dir? */
1132         return(0);
1133
1134     if ((dlen > 0) && (path[dlen - 1] == '/')) /* ignore trailing slash. */
1135         dlen--;
1136
1137     while (lo <= hi)
1138     {
1139         middle = lo + ((hi - lo) / 2);
1140         name = info->entries[middle].name;
1141         rc = strncmp(path, name, dlen);
1142         if (rc == 0)
1143         {
1144             char ch = name[dlen];
1145             if ('/' < ch) /* make sure this isn't just a substr match. */
1146                 rc = -1;
1147             else if ('/' > ch)
1148                 rc = 1;
1149             else 
1150             {
1151                 if (stop_on_first_find) /* Just checking dir's existance? */
1152                     return(middle);
1153
1154                 if (name[dlen + 1] == '\0') /* Skip initial dir entry. */
1155                     return(middle + 1);
1156
1157                 /* there might be more entries earlier in the list. */
1158                 retval = middle;
1159                 hi = middle - 1;
1160             } /* else */
1161         } /* if */
1162
1163         if (rc > 0)
1164             lo = middle + 1;
1165         else
1166             hi = middle - 1;
1167     } /* while */
1168
1169     return(retval);
1170 } /* zip_find_start_of_dir */
1171
1172
1173 /*
1174  * Moved to seperate function so we can use alloca then immediately throw
1175  *  away the allocated stack space...
1176  */
1177 static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
1178                            const char *odir, const char *str, PHYSFS_sint32 ln)
1179 {
1180     char *newstr = __PHYSFS_smallAlloc(ln + 1);
1181     if (newstr == NULL)
1182         return;
1183
1184     memcpy(newstr, str, ln);
1185     newstr[ln] = '\0';
1186     cb(callbackdata, odir, newstr);
1187     __PHYSFS_smallFree(newstr);
1188 } /* doEnumCallback */
1189
1190
1191 static void ZIP_enumerateFiles(dvoid *opaque, const char *dname,
1192                                int omitSymLinks, PHYSFS_EnumFilesCallback cb,
1193                                const char *origdir, void *callbackdata)
1194 {
1195     ZIPinfo *info = ((ZIPinfo *) opaque);
1196     PHYSFS_sint32 dlen, dlen_inc, max, i;
1197
1198     i = zip_find_start_of_dir(info, dname, 0);
1199     if (i == -1)  /* no such directory. */
1200         return;
1201
1202     dlen = strlen(dname);
1203     if ((dlen > 0) && (dname[dlen - 1] == '/')) /* ignore trailing slash. */
1204         dlen--;
1205
1206     dlen_inc = ((dlen > 0) ? 1 : 0) + dlen;
1207     max = (PHYSFS_sint32) info->entryCount;
1208     while (i < max)
1209     {
1210         char *e = info->entries[i].name;
1211         if ((dlen) && ((strncmp(e, dname, dlen) != 0) || (e[dlen] != '/')))
1212             break;  /* past end of this dir; we're done. */
1213
1214         if ((omitSymLinks) && (zip_entry_is_symlink(&info->entries[i])))
1215             i++;
1216         else
1217         {
1218             char *add = e + dlen_inc;
1219             char *ptr = strchr(add, '/');
1220             PHYSFS_sint32 ln = (PHYSFS_sint32) ((ptr) ? ptr-add : strlen(add));
1221             doEnumCallback(cb, callbackdata, origdir, add, ln);
1222             ln += dlen_inc;  /* point past entry to children... */
1223
1224             /* increment counter and skip children of subdirs... */
1225             while ((++i < max) && (ptr != NULL))
1226             {
1227                 char *e_new = info->entries[i].name;
1228                 if ((strncmp(e, e_new, ln) != 0) || (e_new[ln] != '/'))
1229                     break;
1230             } /* while */
1231         } /* else */
1232     } /* while */
1233 } /* ZIP_enumerateFiles */
1234
1235
1236 static int ZIP_exists(dvoid *opaque, const char *name)
1237 {
1238     int isDir;    
1239     ZIPinfo *info = (ZIPinfo *) opaque;
1240     ZIPentry *entry = zip_find_entry(info, name, &isDir);
1241     return((entry != NULL) || (isDir));
1242 } /* ZIP_exists */
1243
1244
1245 static PHYSFS_sint64 ZIP_getLastModTime(dvoid *opaque,
1246                                         const char *name,
1247                                         int *fileExists)
1248 {
1249     int isDir;
1250     ZIPinfo *info = (ZIPinfo *) opaque;
1251     ZIPentry *entry = zip_find_entry(info, name, &isDir);
1252
1253     *fileExists = ((isDir) || (entry != NULL));
1254     if (isDir)
1255         return(1);  /* Best I can do for a dir... */
1256
1257     BAIL_IF_MACRO(entry == NULL, NULL, -1);
1258     return(entry->last_mod_time);
1259 } /* ZIP_getLastModTime */
1260
1261
1262 static int ZIP_isDirectory(dvoid *opaque, const char *name, int *fileExists)
1263 {
1264     ZIPinfo *info = (ZIPinfo *) opaque;
1265     int isDir;
1266     ZIPentry *entry = zip_find_entry(info, name, &isDir);
1267
1268     *fileExists = ((isDir) || (entry != NULL));
1269     if (isDir)
1270         return(1); /* definitely a dir. */
1271
1272     /* Follow symlinks. This means we might need to resolve entries. */
1273     BAIL_IF_MACRO(entry == NULL, ERR_NO_SUCH_FILE, 0);
1274
1275     if (entry->resolved == ZIP_UNRESOLVED_SYMLINK) /* gotta resolve it. */
1276     {
1277         int rc;
1278         void *in = __PHYSFS_platformOpenRead(info->archiveName);
1279         BAIL_IF_MACRO(in == NULL, NULL, 0);
1280         rc = zip_resolve(in, info, entry);
1281         __PHYSFS_platformClose(in);
1282         if (!rc)
1283             return(0);
1284     } /* if */
1285
1286     BAIL_IF_MACRO(entry->resolved == ZIP_BROKEN_SYMLINK, NULL, 0);
1287     BAIL_IF_MACRO(entry->symlink == NULL, ERR_NOT_A_DIR, 0);
1288
1289     return(zip_find_start_of_dir(info, entry->symlink->name, 1) >= 0);
1290 } /* ZIP_isDirectory */
1291
1292
1293 static int ZIP_isSymLink(dvoid *opaque, const char *name, int *fileExists)
1294 {
1295     int isDir;
1296     ZIPentry *entry = zip_find_entry((ZIPinfo *) opaque, name, &isDir);
1297     *fileExists = ((isDir) || (entry != NULL));
1298     BAIL_IF_MACRO(entry == NULL, NULL, 0);
1299     return(zip_entry_is_symlink(entry));
1300 } /* ZIP_isSymLink */
1301
1302
1303 static void *zip_get_file_handle(const char *fn, ZIPinfo *inf, ZIPentry *entry)
1304 {
1305     int success;
1306     void *retval = __PHYSFS_platformOpenRead(fn);
1307     BAIL_IF_MACRO(retval == NULL, NULL, NULL);
1308
1309     success = zip_resolve(retval, inf, entry);
1310     if (success)
1311     {
1312         PHYSFS_sint64 offset;
1313         offset = ((entry->symlink) ? entry->symlink->offset : entry->offset);
1314         success = __PHYSFS_platformSeek(retval, offset);
1315     } /* if */
1316
1317     if (!success)
1318     {
1319         __PHYSFS_platformClose(retval);
1320         retval = NULL;
1321     } /* if */
1322
1323     return(retval);
1324 } /* zip_get_file_handle */
1325
1326
1327 static fvoid *ZIP_openRead(dvoid *opaque, const char *fnm, int *fileExists)
1328 {
1329     ZIPinfo *info = (ZIPinfo *) opaque;
1330     ZIPentry *entry = zip_find_entry(info, fnm, NULL);
1331     ZIPfileinfo *finfo = NULL;
1332     void *in;
1333
1334     *fileExists = (entry != NULL);
1335     BAIL_IF_MACRO(entry == NULL, NULL, NULL);
1336
1337     in = zip_get_file_handle(info->archiveName, info, entry);
1338     BAIL_IF_MACRO(in == NULL, NULL, NULL);
1339
1340     finfo = (ZIPfileinfo *) allocator.Malloc(sizeof (ZIPfileinfo));
1341     if (finfo == NULL)
1342     {
1343         __PHYSFS_platformClose(in);
1344         BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1345     } /* if */
1346
1347     memset(finfo, '\0', sizeof (ZIPfileinfo));
1348     finfo->handle = in;
1349     finfo->entry = ((entry->symlink != NULL) ? entry->symlink : entry);
1350     initializeZStream(&finfo->stream);
1351     if (finfo->entry->compression_method != COMPMETH_NONE)
1352     {
1353         if (zlib_err(inflateInit2(&finfo->stream, -MAX_WBITS)) != Z_OK)
1354         {
1355             ZIP_fileClose(finfo);
1356             return(NULL);
1357         } /* if */
1358
1359         finfo->buffer = (PHYSFS_uint8 *) allocator.Malloc(ZIP_READBUFSIZE);
1360         if (finfo->buffer == NULL)
1361         {
1362             ZIP_fileClose(finfo);
1363             BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1364         } /* if */
1365     } /* if */
1366
1367     return(finfo);
1368 } /* ZIP_openRead */
1369
1370
1371 static fvoid *ZIP_openWrite(dvoid *opaque, const char *filename)
1372 {
1373     BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
1374 } /* ZIP_openWrite */
1375
1376
1377 static fvoid *ZIP_openAppend(dvoid *opaque, const char *filename)
1378 {
1379     BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
1380 } /* ZIP_openAppend */
1381
1382
1383 static void ZIP_dirClose(dvoid *opaque)
1384 {
1385     ZIPinfo *zi = (ZIPinfo *) (opaque);
1386     zip_free_entries(zi->entries, zi->entryCount);
1387     allocator.Free(zi->archiveName);
1388     allocator.Free(zi);
1389 } /* ZIP_dirClose */
1390
1391
1392 static int ZIP_remove(dvoid *opaque, const char *name)
1393 {
1394     BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
1395 } /* ZIP_remove */
1396
1397
1398 static int ZIP_mkdir(dvoid *opaque, const char *name)
1399 {
1400     BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
1401 } /* ZIP_mkdir */
1402
1403
1404 const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_ZIP =
1405 {
1406     "ZIP",
1407     ZIP_ARCHIVE_DESCRIPTION,
1408     "Ryan C. Gordon <icculus@icculus.org>",
1409     "http://icculus.org/physfs/",
1410 };
1411
1412
1413 const PHYSFS_Archiver __PHYSFS_Archiver_ZIP =
1414 {
1415     &__PHYSFS_ArchiveInfo_ZIP,
1416     ZIP_isArchive,          /* isArchive() method      */
1417     ZIP_openArchive,        /* openArchive() method    */
1418     ZIP_enumerateFiles,     /* enumerateFiles() method */
1419     ZIP_exists,             /* exists() method         */
1420     ZIP_isDirectory,        /* isDirectory() method    */
1421     ZIP_isSymLink,          /* isSymLink() method      */
1422     ZIP_getLastModTime,     /* getLastModTime() method */
1423     ZIP_openRead,           /* openRead() method       */
1424     ZIP_openWrite,          /* openWrite() method      */
1425     ZIP_openAppend,         /* openAppend() method     */
1426     ZIP_remove,             /* remove() method         */
1427     ZIP_mkdir,              /* mkdir() method          */
1428     ZIP_dirClose,           /* dirClose() method       */
1429     ZIP_read,               /* read() method           */
1430     ZIP_write,              /* write() method          */
1431     ZIP_eof,                /* eof() method            */
1432     ZIP_tell,               /* tell() method           */
1433     ZIP_seek,               /* seek() method           */
1434     ZIP_fileLength,         /* fileLength() method     */
1435     ZIP_fileClose           /* fileClose() method      */
1436 };
1437
1438 #endif  /* defined PHYSFS_SUPPORTS_ZIP */
1439
1440 /* end of zip.c ... */
1441