2 * ZIP support routines for PhysicsFS.
4 * Please see the file LICENSE.txt in the source's root directory.
6 * This file written by Ryan C. Gordon, with some peeking at "unzip.c"
10 #if (defined PHYSFS_SUPPORTS_ZIP)
22 #define __PHYSICSFS_INTERNAL__
23 #include "physfs_internal.h"
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
31 * Uncompressed entries in a zipfile do not allocate this buffer; they just
32 * read data directly into the buffer passed to PHYSFS_read().
34 * Depending on your speed and memory requirements, you should tweak this
37 #define ZIP_READBUFSIZE (16 * 1024)
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.
51 ZIP_UNRESOLVED_SYMLINK,
60 * One ZIPentry is kept for each file in an open ZIP archive.
62 typedef struct _ZIPentry
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 */
78 * One ZIPinfo is kept for each open ZIP archive.
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. */
88 * One ZIPfileinfo is kept for each open file in a ZIP archive.
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. */
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
106 /* compression methods... */
107 #define COMPMETH_NONE 0
108 /* ...and others... */
111 #define UNIX_FILETYPE_MASK 0170000
112 #define UNIX_FILETYPE_SYMLINK 0120000
116 * Bridge physfs allocation functions to zlib's format...
118 static voidpf zlibPhysfsAlloc(voidpf opaque, uInt items, uInt size)
120 return(((PHYSFS_Allocator *) opaque)->Malloc(items * size));
121 } /* zlibPhysfsAlloc */
124 * Bridge physfs allocation functions to zlib's format...
126 static void zlibPhysfsFree(voidpf opaque, voidpf address)
128 ((PHYSFS_Allocator *) opaque)->Free(address);
129 } /* zlibPhysfsFree */
133 * Construct a new z_stream to a sane state.
135 static void initializeZStream(z_stream *pstr)
137 memset(pstr, '\0', sizeof (z_stream));
138 pstr->zalloc = zlibPhysfsAlloc;
139 pstr->zfree = zlibPhysfsFree;
140 pstr->opaque = &allocator;
141 } /* initializeZStream */
144 static const char *zlib_error_string(int rc)
148 case Z_OK: return(NULL); /* not an error. */
149 case Z_STREAM_END: return(NULL); /* not an error. */
151 case Z_ERRNO: return(strerror(errno));
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);
162 } /* zlib_error_string */
166 * Wrap all zlib calls in this, so the physfs error state is set appropriately.
168 static int zlib_err(int rc)
170 const char *str = zlib_error_string(rc);
172 __PHYSFS_setError(str);
178 * Read an unsigned 32-bit int and swap to native byte order.
180 static int readui32(void *in, PHYSFS_uint32 *val)
183 BAIL_IF_MACRO(__PHYSFS_platformRead(in, &v, sizeof (v), 1) != 1, NULL, 0);
184 *val = PHYSFS_swapULE32(v);
190 * Read an unsigned 16-bit int and swap to native byte order.
192 static int readui16(void *in, PHYSFS_uint16 *val)
195 BAIL_IF_MACRO(__PHYSFS_platformRead(in, &v, sizeof (v), 1) != 1, NULL, 0);
196 *val = PHYSFS_swapULE16(v);
201 static PHYSFS_sint64 ZIP_read(fvoid *opaque, void *buf,
202 PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
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;
211 BAIL_IF_MACRO(maxread == 0, NULL, 0); /* quick rejection. */
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. */
221 if (entry->compression_method == COMPMETH_NONE)
223 retval = __PHYSFS_platformRead(finfo->handle, buf, objSize, objCount);
228 finfo->stream.next_out = buf;
229 finfo->stream.avail_out = objSize * objCount;
231 while (retval < maxread)
233 PHYSFS_uint32 before = finfo->stream.total_out;
236 if (finfo->stream.avail_in == 0)
240 br = entry->compressed_size - finfo->compressed_position;
243 if (br > ZIP_READBUFSIZE)
244 br = ZIP_READBUFSIZE;
246 br = __PHYSFS_platformRead(finfo->handle,
248 1, (PHYSFS_uint32) br);
252 finfo->compressed_position += (PHYSFS_uint32) br;
253 finfo->stream.next_in = finfo->buffer;
254 finfo->stream.avail_in = (PHYSFS_uint32) br;
258 rc = zlib_err(inflate(&finfo->stream, Z_SYNC_FLUSH));
259 retval += (finfo->stream.total_out - before);
269 finfo->uncompressed_position += (PHYSFS_uint32) (retval * objSize);
275 static PHYSFS_sint64 ZIP_write(fvoid *opaque, const void *buf,
276 PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
278 BAIL_MACRO(ERR_NOT_SUPPORTED, -1);
282 static int ZIP_eof(fvoid *opaque)
284 ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
285 return(finfo->uncompressed_position >= finfo->entry->uncompressed_size);
289 static PHYSFS_sint64 ZIP_tell(fvoid *opaque)
291 return(((ZIPfileinfo *) opaque)->uncompressed_position);
295 static int ZIP_seek(fvoid *opaque, PHYSFS_uint64 offset)
297 ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
298 ZIPentry *entry = finfo->entry;
299 void *in = finfo->handle;
301 BAIL_IF_MACRO(offset > entry->uncompressed_size, ERR_PAST_EOF, 0);
303 if (entry->compression_method == COMPMETH_NONE)
305 PHYSFS_sint64 newpos = offset + entry->offset;
306 BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, newpos), NULL, 0);
307 finfo->uncompressed_position = (PHYSFS_uint32) offset;
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.
318 if (offset < finfo->uncompressed_position)
320 /* we do a copy so state is sane if inflateInit2() fails. */
322 initializeZStream(&str);
323 if (zlib_err(inflateInit2(&str, -MAX_WBITS)) != Z_OK)
326 if (!__PHYSFS_platformSeek(in, entry->offset))
329 inflateEnd(&finfo->stream);
330 memcpy(&finfo->stream, &str, sizeof (z_stream));
331 finfo->uncompressed_position = finfo->compressed_position = 0;
334 while (finfo->uncompressed_position != offset)
336 PHYSFS_uint8 buf[512];
337 PHYSFS_uint32 maxread;
339 maxread = (PHYSFS_uint32) (offset - finfo->uncompressed_position);
340 if (maxread > sizeof (buf))
341 maxread = sizeof (buf);
343 if (ZIP_read(finfo, buf, maxread, 1) != 1)
352 static PHYSFS_sint64 ZIP_fileLength(fvoid *opaque)
354 ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
355 return(finfo->entry->uncompressed_size);
356 } /* ZIP_fileLength */
359 static int ZIP_fileClose(fvoid *opaque)
361 ZIPfileinfo *finfo = (ZIPfileinfo *) opaque;
362 BAIL_IF_MACRO(!__PHYSFS_platformClose(finfo->handle), NULL, 0);
364 if (finfo->entry->compression_method != COMPMETH_NONE)
365 inflateEnd(&finfo->stream);
367 if (finfo->buffer != NULL)
368 allocator.Free(finfo->buffer);
370 allocator.Free(finfo);
372 } /* ZIP_fileClose */
375 static PHYSFS_sint64 zip_find_end_of_central_dir(void *in, PHYSFS_sint64 *len)
377 PHYSFS_uint8 buf[256];
379 PHYSFS_sint64 filelen;
380 PHYSFS_sint64 filepos;
381 PHYSFS_sint32 maxread;
382 PHYSFS_sint32 totalread = 0;
384 PHYSFS_uint32 extra = 0;
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);
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.
402 if (sizeof (buf) < filelen)
404 filepos = filelen - sizeof (buf);
405 maxread = sizeof (buf);
410 maxread = (PHYSFS_uint32) filelen;
413 while ((totalread < filelen) && (totalread < 65557))
415 BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, filepos), NULL, -1);
417 /* make sure we catch a signature between buffers. */
420 if (__PHYSFS_platformRead(in, buf, maxread - 4, 1) != 1)
422 *((PHYSFS_uint32 *) (&buf[maxread - 4])) = extra;
423 totalread += maxread - 4;
427 if (__PHYSFS_platformRead(in, buf, maxread, 1) != 1)
429 totalread += maxread;
432 extra = *((PHYSFS_uint32 *) (&buf[0]));
434 for (i = maxread - 4; i > 0; i--)
436 if ((buf[i + 0] == 0x50) &&
437 (buf[i + 1] == 0x4B) &&
438 (buf[i + 2] == 0x05) &&
439 (buf[i + 3] == 0x06) )
441 found = 1; /* that's the signature! */
449 filepos -= (maxread - 4);
452 BAIL_IF_MACRO(!found, ERR_NOT_AN_ARCHIVE, -1);
458 } /* zip_find_end_of_central_dir */
461 static int ZIP_isArchive(const char *filename, int forWriting)
467 in = __PHYSFS_platformOpenRead(filename);
468 BAIL_IF_MACRO(in == NULL, NULL, 0);
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.
474 if (readui32(in, &sig))
476 retval = (sig == ZIP_LOCAL_FILE_SIG);
480 * No sig...might be a ZIP with data at the start
481 * (a self-extracting executable, etc), so we'll have to do
484 retval = (zip_find_end_of_central_dir(in, NULL) != -1);
488 __PHYSFS_platformClose(in);
490 } /* ZIP_isArchive */
493 static void zip_free_entries(ZIPentry *entries, PHYSFS_uint32 max)
496 for (i = 0; i < max; i++)
498 ZIPentry *entry = &entries[i];
499 if (entry->name != NULL)
500 allocator.Free(entry->name);
503 allocator.Free(entries);
504 } /* zip_free_entries */
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.
512 static ZIPentry *zip_find_entry(ZIPinfo *info, const char *path, int *isDir)
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;
524 middle = lo + ((hi - lo) / 2);
525 thispath = a[middle].name;
526 rc = strncmp(path, thispath, pathlen);
534 else /* substring match...might be dir or entry or nothing. */
538 *isDir = (thispath[pathlen] == '/');
543 if (thispath[pathlen] == '\0') /* found entry? */
546 hi = middle - 1; /* adjust search params, try again. */
553 BAIL_MACRO(ERR_NO_SUCH_FILE, NULL);
554 } /* zip_find_entry */
557 /* Convert paths from old, buggy DOS zippers... */
558 static void zip_convert_dos_path(ZIPentry *entry, char *path)
560 PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((entry->version >> 8) & 0xFF);
561 if (hosttype == 0) /* FS_FAT_ */
570 } /* zip_convert_dos_path */
573 static void zip_expand_symlink_path(char *path)
576 char *prevptr = path;
580 ptr = strchr(ptr, '/');
584 if (*(ptr + 1) == '.')
586 if (*(ptr + 2) == '/')
588 /* current dir in middle of string: ditch it. */
589 memmove(ptr, ptr + 2, strlen(ptr + 2) + 1);
592 else if (*(ptr + 2) == '\0')
594 /* current dir at end of string: ditch it. */
598 else if (*(ptr + 2) == '.')
600 if (*(ptr + 3) == '/')
602 /* parent dir in middle: move back one, if possible. */
603 memmove(prevptr, ptr + 4, strlen(ptr + 4) + 1);
605 while (prevptr != path)
616 if (*(ptr + 3) == '\0')
618 /* parent dir at end: move back one, if possible. */
628 } /* zip_expand_symlink_path */
630 /* (forward reference: zip_follow_symlink and zip_resolve call each other.) */
631 static int zip_resolve(void *in, ZIPinfo *info, ZIPentry *entry);
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
640 static ZIPentry *zip_follow_symlink(void *in, ZIPinfo *info, char *path)
644 zip_expand_symlink_path(path);
645 entry = zip_find_entry(info, path, NULL);
648 if (!zip_resolve(in, info, entry)) /* recursive! */
652 if (entry->symlink != NULL)
653 entry = entry->symlink;
657 allocator.Free(path);
659 } /* zip_follow_symlink */
662 static int zip_resolve_symlink(void *in, ZIPinfo *info, ZIPentry *entry)
665 PHYSFS_uint32 size = entry->uncompressed_size;
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
674 BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, entry->offset), NULL, 0);
676 path = (char *) allocator.Malloc(size + 1);
677 BAIL_IF_MACRO(path == NULL, ERR_OUT_OF_MEMORY, 0);
679 if (entry->compression_method == COMPMETH_NONE)
680 rc = (__PHYSFS_platformRead(in, path, size, 1) == 1);
682 else /* symlink target path is compressed... */
685 PHYSFS_uint32 complen = entry->compressed_size;
686 PHYSFS_uint8 *compressed = (PHYSFS_uint8*) __PHYSFS_smallAlloc(complen);
687 if (compressed != NULL)
689 if (__PHYSFS_platformRead(in, compressed, complen, 1) == 1)
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)
698 rc = zlib_err(inflate(&stream, Z_FINISH));
701 /* both are acceptable outcomes... */
702 rc = ((rc == Z_OK) || (rc == Z_STREAM_END));
705 __PHYSFS_smallFree(compressed);
710 allocator.Free(path);
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);
718 return(entry->symlink != NULL);
719 } /* zip_resolve_symlink */
723 * Parse the local file header of an entry, and update entry->offset.
725 static int zip_parse_local(void *in, ZIPentry *entry)
729 PHYSFS_uint16 fnamelen;
730 PHYSFS_uint16 extralen;
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.
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);
757 entry->offset += fnamelen + extralen + 30;
759 } /* zip_parse_local */
762 static int zip_resolve(void *in, ZIPinfo *info, ZIPentry *entry)
765 ZipResolveType resolve_type = entry->resolved;
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);
771 /* uhoh...infinite symlink loop! */
772 BAIL_IF_MACRO(resolve_type == ZIP_RESOLVING, ERR_SYMLINK_LOOP, 0);
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.
781 if (resolve_type != ZIP_RESOLVED)
783 entry->resolved = ZIP_RESOLVING;
785 retval = zip_parse_local(in, entry);
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.
793 if (resolve_type == ZIP_UNRESOLVED_SYMLINK)
794 retval = zip_resolve_symlink(in, info, entry);
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);
807 static int zip_version_does_symlinks(PHYSFS_uint32 version)
810 PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((version >> 8) & 0xFF);
815 * These are the platforms that can NOT build an archive with
816 * symlinks, according to the Info-ZIP project.
818 case 0: /* FS_FAT_ */
821 case 4: /* VM_CSM_ */
822 case 6: /* FS_HPFS_ */
823 case 11: /* FS_NTFS_ */
824 case 14: /* FS_VFAT_ */
825 case 13: /* ACORN_ */
827 case 18: /* THEOS_ */
828 break; /* do nothing. */
830 default: /* assume the rest to be unix-like. */
836 } /* zip_version_does_symlinks */
839 static int zip_entry_is_symlink(ZIPentry *entry)
841 return((entry->resolved == ZIP_UNRESOLVED_SYMLINK) ||
842 (entry->resolved == ZIP_BROKEN_SYMLINK) ||
844 } /* zip_entry_is_symlink */
847 static int zip_has_symlink_attr(ZIPentry *entry, PHYSFS_uint32 extern_attr)
849 PHYSFS_uint16 xattr = ((extern_attr >> 16) & 0xFFFF);
852 (zip_version_does_symlinks(entry->version)) &&
853 (entry->uncompressed_size > 0) &&
854 ((xattr & UNIX_FILETYPE_MASK) == UNIX_FILETYPE_SYMLINK)
856 } /* zip_has_symlink_attr */
859 static PHYSFS_sint64 zip_dos_time_to_physfs_time(PHYSFS_uint32 dostime)
862 /* We have no struct tm and no mktime right now.
863 FIXME: This should probably be fixed at some point.
867 PHYSFS_uint32 dosdate;
869 memset(&unixtime, '\0', sizeof (unixtime));
871 dosdate = (PHYSFS_uint32) ((dostime >> 16) & 0xFFFF);
875 unixtime.tm_year = ((dosdate >> 9) & 0x7F) + 80;
876 unixtime.tm_mon = ((dosdate >> 5) & 0x0F) - 1;
877 unixtime.tm_mday = ((dosdate ) & 0x1F);
880 unixtime.tm_hour = ((dostime >> 11) & 0x1F);
881 unixtime.tm_min = ((dostime >> 5) & 0x3F);
882 unixtime.tm_sec = ((dostime << 1) & 0x3E);
884 /* let mktime calculate daylight savings time. */
885 unixtime.tm_isdst = -1;
887 return((PHYSFS_sint64) mktime(&unixtime));
889 } /* zip_dos_time_to_physfs_time */
892 static int zip_load_entry(void *in, ZIPentry *entry, PHYSFS_uint32 ofs_fixup)
894 PHYSFS_uint16 fnamelen, extralen, commentlen;
895 PHYSFS_uint32 external_attr;
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);
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;
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;
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;
932 entry->name[fnamelen] = '\0'; /* null-terminate the filename. */
933 zip_convert_dos_path(entry, entry->name);
935 si64 = __PHYSFS_platformTell(in);
937 goto zip_load_entry_puked;
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;
943 return(1); /* success. */
945 zip_load_entry_puked:
946 allocator.Free(entry->name);
947 return(0); /* failure. */
948 } /* zip_load_entry */
951 static int zip_entry_cmp(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
953 ZIPentry *a = (ZIPentry *) _a;
954 return(strcmp(a[one].name, a[two].name));
955 } /* zip_entry_cmp */
958 static void zip_entry_swap(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
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 */
969 static int zip_load_entries(void *in, ZIPinfo *info,
970 PHYSFS_uint32 data_ofs, PHYSFS_uint32 central_ofs)
972 PHYSFS_uint32 max = info->entryCount;
975 BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, central_ofs), NULL, 0);
977 info->entries = (ZIPentry *) allocator.Malloc(sizeof (ZIPentry) * max);
978 BAIL_IF_MACRO(info->entries == NULL, ERR_OUT_OF_MEMORY, 0);
980 for (i = 0; i < max; i++)
982 if (!zip_load_entry(in, &info->entries[i], data_ofs))
984 zip_free_entries(info->entries, i);
989 __PHYSFS_sort(info->entries, max, zip_entry_cmp, zip_entry_swap);
991 } /* zip_load_entries */
994 static int zip_parse_end_of_central_dir(void *in, ZIPinfo *info,
995 PHYSFS_uint32 *data_start,
996 PHYSFS_uint32 *central_dir_ofs)
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);
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);
1012 /* number of this disk */
1013 BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1014 BAIL_IF_MACRO(ui16 != 0, ERR_UNSUPPORTED_ARCHIVE, 0);
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);
1020 /* total number of entries in the central dir on this disk */
1021 BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
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);
1027 /* size of the central directory */
1028 BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
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);
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.
1042 *data_start = (PHYSFS_uint32) (pos - (*central_dir_ofs + ui32));
1044 /* Now that we know the difference, fix up the central dir offset... */
1045 *central_dir_ofs += *data_start;
1047 /* zipfile comment length */
1048 BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
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.
1055 BAIL_IF_MACRO((pos + 22 + ui16) != len, ERR_UNSUPPORTED_ARCHIVE, 0);
1057 return(1); /* made it. */
1058 } /* zip_parse_end_of_central_dir */
1061 static ZIPinfo *zip_create_zipinfo(const char *name)
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));
1068 ptr = (char *) allocator.Malloc(strlen(name) + 1);
1071 allocator.Free(info);
1072 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1075 info->archiveName = ptr;
1076 strcpy(info->archiveName, name);
1078 } /* zip_create_zipinfo */
1081 static void *ZIP_openArchive(const char *name, int forWriting)
1084 ZIPinfo *info = NULL;
1085 PHYSFS_uint32 data_start;
1086 PHYSFS_uint32 cent_dir_ofs;
1088 BAIL_IF_MACRO(forWriting, ERR_ARC_IS_READ_ONLY, NULL);
1090 if ((in = __PHYSFS_platformOpenRead(name)) == NULL)
1091 goto zip_openarchive_failed;
1093 if ((info = zip_create_zipinfo(name)) == NULL)
1094 goto zip_openarchive_failed;
1096 if (!zip_parse_end_of_central_dir(in, info, &data_start, ¢_dir_ofs))
1097 goto zip_openarchive_failed;
1099 if (!zip_load_entries(in, info, data_start, cent_dir_ofs))
1100 goto zip_openarchive_failed;
1102 __PHYSFS_platformClose(in);
1105 zip_openarchive_failed:
1108 if (info->archiveName != NULL)
1109 allocator.Free(info->archiveName);
1110 allocator.Free(info);
1114 __PHYSFS_platformClose(in);
1117 } /* ZIP_openArchive */
1120 static PHYSFS_sint32 zip_find_start_of_dir(ZIPinfo *info, const char *path,
1121 int stop_on_first_find)
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;
1131 if (*path == '\0') /* root dir? */
1134 if ((dlen > 0) && (path[dlen - 1] == '/')) /* ignore trailing slash. */
1139 middle = lo + ((hi - lo) / 2);
1140 name = info->entries[middle].name;
1141 rc = strncmp(path, name, dlen);
1144 char ch = name[dlen];
1145 if ('/' < ch) /* make sure this isn't just a substr match. */
1151 if (stop_on_first_find) /* Just checking dir's existance? */
1154 if (name[dlen + 1] == '\0') /* Skip initial dir entry. */
1157 /* there might be more entries earlier in the list. */
1170 } /* zip_find_start_of_dir */
1174 * Moved to seperate function so we can use alloca then immediately throw
1175 * away the allocated stack space...
1177 static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
1178 const char *odir, const char *str, PHYSFS_sint32 ln)
1180 char *newstr = __PHYSFS_smallAlloc(ln + 1);
1184 memcpy(newstr, str, ln);
1186 cb(callbackdata, odir, newstr);
1187 __PHYSFS_smallFree(newstr);
1188 } /* doEnumCallback */
1191 static void ZIP_enumerateFiles(dvoid *opaque, const char *dname,
1192 int omitSymLinks, PHYSFS_EnumFilesCallback cb,
1193 const char *origdir, void *callbackdata)
1195 ZIPinfo *info = ((ZIPinfo *) opaque);
1196 PHYSFS_sint32 dlen, dlen_inc, max, i;
1198 i = zip_find_start_of_dir(info, dname, 0);
1199 if (i == -1) /* no such directory. */
1202 dlen = strlen(dname);
1203 if ((dlen > 0) && (dname[dlen - 1] == '/')) /* ignore trailing slash. */
1206 dlen_inc = ((dlen > 0) ? 1 : 0) + dlen;
1207 max = (PHYSFS_sint32) info->entryCount;
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. */
1214 if ((omitSymLinks) && (zip_entry_is_symlink(&info->entries[i])))
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... */
1224 /* increment counter and skip children of subdirs... */
1225 while ((++i < max) && (ptr != NULL))
1227 char *e_new = info->entries[i].name;
1228 if ((strncmp(e, e_new, ln) != 0) || (e_new[ln] != '/'))
1233 } /* ZIP_enumerateFiles */
1236 static int ZIP_exists(dvoid *opaque, const char *name)
1239 ZIPinfo *info = (ZIPinfo *) opaque;
1240 ZIPentry *entry = zip_find_entry(info, name, &isDir);
1241 return((entry != NULL) || (isDir));
1245 static PHYSFS_sint64 ZIP_getLastModTime(dvoid *opaque,
1250 ZIPinfo *info = (ZIPinfo *) opaque;
1251 ZIPentry *entry = zip_find_entry(info, name, &isDir);
1253 *fileExists = ((isDir) || (entry != NULL));
1255 return(1); /* Best I can do for a dir... */
1257 BAIL_IF_MACRO(entry == NULL, NULL, -1);
1258 return(entry->last_mod_time);
1259 } /* ZIP_getLastModTime */
1262 static int ZIP_isDirectory(dvoid *opaque, const char *name, int *fileExists)
1264 ZIPinfo *info = (ZIPinfo *) opaque;
1266 ZIPentry *entry = zip_find_entry(info, name, &isDir);
1268 *fileExists = ((isDir) || (entry != NULL));
1270 return(1); /* definitely a dir. */
1272 /* Follow symlinks. This means we might need to resolve entries. */
1273 BAIL_IF_MACRO(entry == NULL, ERR_NO_SUCH_FILE, 0);
1275 if (entry->resolved == ZIP_UNRESOLVED_SYMLINK) /* gotta resolve it. */
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);
1286 BAIL_IF_MACRO(entry->resolved == ZIP_BROKEN_SYMLINK, NULL, 0);
1287 BAIL_IF_MACRO(entry->symlink == NULL, ERR_NOT_A_DIR, 0);
1289 return(zip_find_start_of_dir(info, entry->symlink->name, 1) >= 0);
1290 } /* ZIP_isDirectory */
1293 static int ZIP_isSymLink(dvoid *opaque, const char *name, int *fileExists)
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 */
1303 static void *zip_get_file_handle(const char *fn, ZIPinfo *inf, ZIPentry *entry)
1306 void *retval = __PHYSFS_platformOpenRead(fn);
1307 BAIL_IF_MACRO(retval == NULL, NULL, NULL);
1309 success = zip_resolve(retval, inf, entry);
1312 PHYSFS_sint64 offset;
1313 offset = ((entry->symlink) ? entry->symlink->offset : entry->offset);
1314 success = __PHYSFS_platformSeek(retval, offset);
1319 __PHYSFS_platformClose(retval);
1324 } /* zip_get_file_handle */
1327 static fvoid *ZIP_openRead(dvoid *opaque, const char *fnm, int *fileExists)
1329 ZIPinfo *info = (ZIPinfo *) opaque;
1330 ZIPentry *entry = zip_find_entry(info, fnm, NULL);
1331 ZIPfileinfo *finfo = NULL;
1334 *fileExists = (entry != NULL);
1335 BAIL_IF_MACRO(entry == NULL, NULL, NULL);
1337 in = zip_get_file_handle(info->archiveName, info, entry);
1338 BAIL_IF_MACRO(in == NULL, NULL, NULL);
1340 finfo = (ZIPfileinfo *) allocator.Malloc(sizeof (ZIPfileinfo));
1343 __PHYSFS_platformClose(in);
1344 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1347 memset(finfo, '\0', sizeof (ZIPfileinfo));
1349 finfo->entry = ((entry->symlink != NULL) ? entry->symlink : entry);
1350 initializeZStream(&finfo->stream);
1351 if (finfo->entry->compression_method != COMPMETH_NONE)
1353 if (zlib_err(inflateInit2(&finfo->stream, -MAX_WBITS)) != Z_OK)
1355 ZIP_fileClose(finfo);
1359 finfo->buffer = (PHYSFS_uint8 *) allocator.Malloc(ZIP_READBUFSIZE);
1360 if (finfo->buffer == NULL)
1362 ZIP_fileClose(finfo);
1363 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1368 } /* ZIP_openRead */
1371 static fvoid *ZIP_openWrite(dvoid *opaque, const char *filename)
1373 BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
1374 } /* ZIP_openWrite */
1377 static fvoid *ZIP_openAppend(dvoid *opaque, const char *filename)
1379 BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
1380 } /* ZIP_openAppend */
1383 static void ZIP_dirClose(dvoid *opaque)
1385 ZIPinfo *zi = (ZIPinfo *) (opaque);
1386 zip_free_entries(zi->entries, zi->entryCount);
1387 allocator.Free(zi->archiveName);
1389 } /* ZIP_dirClose */
1392 static int ZIP_remove(dvoid *opaque, const char *name)
1394 BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
1398 static int ZIP_mkdir(dvoid *opaque, const char *name)
1400 BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
1404 const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_ZIP =
1407 ZIP_ARCHIVE_DESCRIPTION,
1408 "Ryan C. Gordon <icculus@icculus.org>",
1409 "http://icculus.org/physfs/",
1413 const PHYSFS_Archiver __PHYSFS_Archiver_ZIP =
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 */
1438 #endif /* defined PHYSFS_SUPPORTS_ZIP */
1440 /* end of zip.c ... */