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];
378 PHYSFS_uint8 extra[4] = { 0, 0, 0, 0 };
380 PHYSFS_sint64 filelen;
381 PHYSFS_sint64 filepos;
382 PHYSFS_sint32 maxread;
383 PHYSFS_sint32 totalread = 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 memcpy(&buf[maxread - 4], &extra, sizeof (extra));
423 totalread += maxread - 4;
427 if (__PHYSFS_platformRead(in, buf, maxread, 1) != 1)
429 totalread += maxread;
432 memcpy(&extra, buf, sizeof (extra));
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);
454 BAIL_IF_MACRO(!found, ERR_NOT_AN_ARCHIVE, -1);
460 } /* zip_find_end_of_central_dir */
463 static int ZIP_isArchive(const char *filename, int forWriting)
469 in = __PHYSFS_platformOpenRead(filename);
470 BAIL_IF_MACRO(in == NULL, NULL, 0);
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.
476 if (readui32(in, &sig))
478 retval = (sig == ZIP_LOCAL_FILE_SIG);
482 * No sig...might be a ZIP with data at the start
483 * (a self-extracting executable, etc), so we'll have to do
486 retval = (zip_find_end_of_central_dir(in, NULL) != -1);
490 __PHYSFS_platformClose(in);
492 } /* ZIP_isArchive */
495 static void zip_free_entries(ZIPentry *entries, PHYSFS_uint32 max)
498 for (i = 0; i < max; i++)
500 ZIPentry *entry = &entries[i];
501 if (entry->name != NULL)
502 allocator.Free(entry->name);
505 allocator.Free(entries);
506 } /* zip_free_entries */
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.
514 static ZIPentry *zip_find_entry(ZIPinfo *info, const char *path, int *isDir)
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;
526 middle = lo + ((hi - lo) / 2);
527 thispath = a[middle].name;
528 rc = strncmp(path, thispath, pathlen);
536 else /* substring match...might be dir or entry or nothing. */
540 *isDir = (thispath[pathlen] == '/');
545 if (thispath[pathlen] == '\0') /* found entry? */
547 /* adjust search params, try again. */
548 else if (thispath[pathlen] > '/')
558 BAIL_MACRO(ERR_NO_SUCH_FILE, NULL);
559 } /* zip_find_entry */
562 /* Convert paths from old, buggy DOS zippers... */
563 static void zip_convert_dos_path(ZIPentry *entry, char *path)
565 PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((entry->version >> 8) & 0xFF);
566 if (hosttype == 0) /* FS_FAT_ */
575 } /* zip_convert_dos_path */
578 static void zip_expand_symlink_path(char *path)
581 char *prevptr = path;
585 ptr = strchr(ptr, '/');
589 if (*(ptr + 1) == '.')
591 if (*(ptr + 2) == '/')
593 /* current dir in middle of string: ditch it. */
594 memmove(ptr, ptr + 2, strlen(ptr + 2) + 1);
597 else if (*(ptr + 2) == '\0')
599 /* current dir at end of string: ditch it. */
603 else if (*(ptr + 2) == '.')
605 if (*(ptr + 3) == '/')
607 /* parent dir in middle: move back one, if possible. */
608 memmove(prevptr, ptr + 4, strlen(ptr + 4) + 1);
610 while (prevptr != path)
621 if (*(ptr + 3) == '\0')
623 /* parent dir at end: move back one, if possible. */
633 } /* zip_expand_symlink_path */
635 /* (forward reference: zip_follow_symlink and zip_resolve call each other.) */
636 static int zip_resolve(void *in, ZIPinfo *info, ZIPentry *entry);
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
645 static ZIPentry *zip_follow_symlink(void *in, ZIPinfo *info, char *path)
649 zip_expand_symlink_path(path);
650 entry = zip_find_entry(info, path, NULL);
653 if (!zip_resolve(in, info, entry)) /* recursive! */
657 if (entry->symlink != NULL)
658 entry = entry->symlink;
662 allocator.Free(path);
664 } /* zip_follow_symlink */
667 static int zip_resolve_symlink(void *in, ZIPinfo *info, ZIPentry *entry)
670 PHYSFS_uint32 size = entry->uncompressed_size;
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
679 BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, entry->offset), NULL, 0);
681 path = (char *) allocator.Malloc(size + 1);
682 BAIL_IF_MACRO(path == NULL, ERR_OUT_OF_MEMORY, 0);
684 if (entry->compression_method == COMPMETH_NONE)
685 rc = (__PHYSFS_platformRead(in, path, size, 1) == 1);
687 else /* symlink target path is compressed... */
690 PHYSFS_uint32 complen = entry->compressed_size;
691 PHYSFS_uint8 *compressed = (PHYSFS_uint8*) __PHYSFS_smallAlloc(complen);
692 if (compressed != NULL)
694 if (__PHYSFS_platformRead(in, compressed, complen, 1) == 1)
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)
703 rc = zlib_err(inflate(&stream, Z_FINISH));
706 /* both are acceptable outcomes... */
707 rc = ((rc == Z_OK) || (rc == Z_STREAM_END));
710 __PHYSFS_smallFree(compressed);
715 allocator.Free(path);
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);
723 return(entry->symlink != NULL);
724 } /* zip_resolve_symlink */
728 * Parse the local file header of an entry, and update entry->offset.
730 static int zip_parse_local(void *in, ZIPentry *entry)
734 PHYSFS_uint16 fnamelen;
735 PHYSFS_uint16 extralen;
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.
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);
762 entry->offset += fnamelen + extralen + 30;
764 } /* zip_parse_local */
767 static int zip_resolve(void *in, ZIPinfo *info, ZIPentry *entry)
770 ZipResolveType resolve_type = entry->resolved;
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);
776 /* uhoh...infinite symlink loop! */
777 BAIL_IF_MACRO(resolve_type == ZIP_RESOLVING, ERR_SYMLINK_LOOP, 0);
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.
786 if (resolve_type != ZIP_RESOLVED)
788 entry->resolved = ZIP_RESOLVING;
790 retval = zip_parse_local(in, entry);
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.
798 if (resolve_type == ZIP_UNRESOLVED_SYMLINK)
799 retval = zip_resolve_symlink(in, info, entry);
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);
812 static int zip_version_does_symlinks(PHYSFS_uint32 version)
815 PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((version >> 8) & 0xFF);
820 * These are the platforms that can NOT build an archive with
821 * symlinks, according to the Info-ZIP project.
823 case 0: /* FS_FAT_ */
826 case 4: /* VM_CSM_ */
827 case 6: /* FS_HPFS_ */
828 case 11: /* FS_NTFS_ */
829 case 14: /* FS_VFAT_ */
830 case 13: /* ACORN_ */
832 case 18: /* THEOS_ */
833 break; /* do nothing. */
835 default: /* assume the rest to be unix-like. */
841 } /* zip_version_does_symlinks */
844 static int zip_entry_is_symlink(const ZIPentry *entry)
846 return((entry->resolved == ZIP_UNRESOLVED_SYMLINK) ||
847 (entry->resolved == ZIP_BROKEN_SYMLINK) ||
849 } /* zip_entry_is_symlink */
852 static int zip_has_symlink_attr(ZIPentry *entry, PHYSFS_uint32 extern_attr)
854 PHYSFS_uint16 xattr = ((extern_attr >> 16) & 0xFFFF);
857 (zip_version_does_symlinks(entry->version)) &&
858 (entry->uncompressed_size > 0) &&
859 ((xattr & UNIX_FILETYPE_MASK) == UNIX_FILETYPE_SYMLINK)
861 } /* zip_has_symlink_attr */
864 static PHYSFS_sint64 zip_dos_time_to_physfs_time(PHYSFS_uint32 dostime)
867 /* We have no struct tm and no mktime right now.
868 FIXME: This should probably be fixed at some point.
872 PHYSFS_uint32 dosdate;
874 memset(&unixtime, '\0', sizeof (unixtime));
876 dosdate = (PHYSFS_uint32) ((dostime >> 16) & 0xFFFF);
880 unixtime.tm_year = ((dosdate >> 9) & 0x7F) + 80;
881 unixtime.tm_mon = ((dosdate >> 5) & 0x0F) - 1;
882 unixtime.tm_mday = ((dosdate ) & 0x1F);
885 unixtime.tm_hour = ((dostime >> 11) & 0x1F);
886 unixtime.tm_min = ((dostime >> 5) & 0x3F);
887 unixtime.tm_sec = ((dostime << 1) & 0x3E);
889 /* let mktime calculate daylight savings time. */
890 unixtime.tm_isdst = -1;
892 return((PHYSFS_sint64) mktime(&unixtime));
894 } /* zip_dos_time_to_physfs_time */
897 static int zip_load_entry(void *in, ZIPentry *entry, PHYSFS_uint32 ofs_fixup)
899 PHYSFS_uint16 fnamelen, extralen, commentlen;
900 PHYSFS_uint32 external_attr;
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);
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;
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;
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;
937 entry->name[fnamelen] = '\0'; /* null-terminate the filename. */
938 zip_convert_dos_path(entry, entry->name);
940 si64 = __PHYSFS_platformTell(in);
942 goto zip_load_entry_puked;
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;
948 return(1); /* success. */
950 zip_load_entry_puked:
951 allocator.Free(entry->name);
952 return(0); /* failure. */
953 } /* zip_load_entry */
956 static int zip_entry_cmp(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
960 const ZIPentry *a = (const ZIPentry *) _a;
961 return(strcmp(a[one].name, a[two].name));
965 } /* zip_entry_cmp */
968 static void zip_entry_swap(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
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));
979 } /* zip_entry_swap */
982 static int zip_load_entries(void *in, ZIPinfo *info,
983 PHYSFS_uint32 data_ofs, PHYSFS_uint32 central_ofs)
985 PHYSFS_uint32 max = info->entryCount;
988 BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, central_ofs), NULL, 0);
990 info->entries = (ZIPentry *) allocator.Malloc(sizeof (ZIPentry) * max);
991 BAIL_IF_MACRO(info->entries == NULL, ERR_OUT_OF_MEMORY, 0);
993 for (i = 0; i < max; i++)
995 if (!zip_load_entry(in, &info->entries[i], data_ofs))
997 zip_free_entries(info->entries, i);
1002 __PHYSFS_sort(info->entries, max, zip_entry_cmp, zip_entry_swap);
1004 } /* zip_load_entries */
1007 static int zip_parse_end_of_central_dir(void *in, ZIPinfo *info,
1008 PHYSFS_uint32 *data_start,
1009 PHYSFS_uint32 *central_dir_ofs)
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);
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);
1025 /* number of this disk */
1026 BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
1027 BAIL_IF_MACRO(ui16 != 0, ERR_UNSUPPORTED_ARCHIVE, 0);
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);
1033 /* total number of entries in the central dir on this disk */
1034 BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
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);
1040 /* size of the central directory */
1041 BAIL_IF_MACRO(!readui32(in, &ui32), NULL, 0);
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);
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.
1055 *data_start = (PHYSFS_uint32) (pos - (*central_dir_ofs + ui32));
1057 /* Now that we know the difference, fix up the central dir offset... */
1058 *central_dir_ofs += *data_start;
1060 /* zipfile comment length */
1061 BAIL_IF_MACRO(!readui16(in, &ui16), NULL, 0);
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.
1068 BAIL_IF_MACRO((pos + 22 + ui16) != len, ERR_UNSUPPORTED_ARCHIVE, 0);
1070 return(1); /* made it. */
1071 } /* zip_parse_end_of_central_dir */
1074 static ZIPinfo *zip_create_zipinfo(const char *name)
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));
1081 ptr = (char *) allocator.Malloc(strlen(name) + 1);
1084 allocator.Free(info);
1085 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1088 info->archiveName = ptr;
1089 strcpy(info->archiveName, name);
1091 } /* zip_create_zipinfo */
1094 static void *ZIP_openArchive(const char *name, int forWriting)
1097 ZIPinfo *info = NULL;
1098 PHYSFS_uint32 data_start;
1099 PHYSFS_uint32 cent_dir_ofs;
1101 BAIL_IF_MACRO(forWriting, ERR_ARC_IS_READ_ONLY, NULL);
1103 if ((in = __PHYSFS_platformOpenRead(name)) == NULL)
1104 goto zip_openarchive_failed;
1106 if ((info = zip_create_zipinfo(name)) == NULL)
1107 goto zip_openarchive_failed;
1109 if (!zip_parse_end_of_central_dir(in, info, &data_start, ¢_dir_ofs))
1110 goto zip_openarchive_failed;
1112 if (!zip_load_entries(in, info, data_start, cent_dir_ofs))
1113 goto zip_openarchive_failed;
1115 __PHYSFS_platformClose(in);
1118 zip_openarchive_failed:
1121 if (info->archiveName != NULL)
1122 allocator.Free(info->archiveName);
1123 allocator.Free(info);
1127 __PHYSFS_platformClose(in);
1130 } /* ZIP_openArchive */
1133 static PHYSFS_sint32 zip_find_start_of_dir(ZIPinfo *info, const char *path,
1134 int stop_on_first_find)
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;
1144 if (*path == '\0') /* root dir? */
1147 if ((dlen > 0) && (path[dlen - 1] == '/')) /* ignore trailing slash. */
1152 middle = lo + ((hi - lo) / 2);
1153 name = info->entries[middle].name;
1154 rc = strncmp(path, name, dlen);
1157 char ch = name[dlen];
1158 if ('/' < ch) /* make sure this isn't just a substr match. */
1164 if (stop_on_first_find) /* Just checking dir's existance? */
1167 if (name[dlen + 1] == '\0') /* Skip initial dir entry. */
1170 /* there might be more entries earlier in the list. */
1183 } /* zip_find_start_of_dir */
1187 * Moved to seperate function so we can use alloca then immediately throw
1188 * away the allocated stack space...
1190 static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
1191 const char *odir, const char *str, PHYSFS_sint32 ln)
1193 char *newstr = __PHYSFS_smallAlloc(ln + 1);
1197 memcpy(newstr, str, ln);
1199 cb(callbackdata, odir, newstr);
1200 __PHYSFS_smallFree(newstr);
1201 } /* doEnumCallback */
1204 static void ZIP_enumerateFiles(dvoid *opaque, const char *dname,
1205 int omitSymLinks, PHYSFS_EnumFilesCallback cb,
1206 const char *origdir, void *callbackdata)
1208 ZIPinfo *info = ((ZIPinfo *) opaque);
1209 PHYSFS_sint32 dlen, dlen_inc, max, i;
1211 i = zip_find_start_of_dir(info, dname, 0);
1212 if (i == -1) /* no such directory. */
1215 dlen = strlen(dname);
1216 if ((dlen > 0) && (dname[dlen - 1] == '/')) /* ignore trailing slash. */
1219 dlen_inc = ((dlen > 0) ? 1 : 0) + dlen;
1220 max = (PHYSFS_sint32) info->entryCount;
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. */
1227 if ((omitSymLinks) && (zip_entry_is_symlink(&info->entries[i])))
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... */
1237 /* increment counter and skip children of subdirs... */
1238 while ((++i < max) && (ptr != NULL))
1240 char *e_new = info->entries[i].name;
1241 if ((strncmp(e, e_new, ln) != 0) || (e_new[ln] != '/'))
1246 } /* ZIP_enumerateFiles */
1249 static int ZIP_exists(dvoid *opaque, const char *name)
1252 ZIPinfo *info = (ZIPinfo *) opaque;
1253 ZIPentry *entry = zip_find_entry(info, name, &isDir);
1254 return((entry != NULL) || (isDir));
1258 static PHYSFS_sint64 ZIP_getLastModTime(dvoid *opaque,
1263 ZIPinfo *info = (ZIPinfo *) opaque;
1264 ZIPentry *entry = zip_find_entry(info, name, &isDir);
1266 *fileExists = ((isDir) || (entry != NULL));
1268 return(1); /* Best I can do for a dir... */
1270 BAIL_IF_MACRO(entry == NULL, NULL, -1);
1271 return(entry->last_mod_time);
1272 } /* ZIP_getLastModTime */
1275 static int ZIP_isDirectory(dvoid *opaque, const char *name, int *fileExists)
1277 ZIPinfo *info = (ZIPinfo *) opaque;
1279 ZIPentry *entry = zip_find_entry(info, name, &isDir);
1281 *fileExists = ((isDir) || (entry != NULL));
1283 return(1); /* definitely a dir. */
1285 /* Follow symlinks. This means we might need to resolve entries. */
1286 BAIL_IF_MACRO(entry == NULL, ERR_NO_SUCH_FILE, 0);
1288 if (entry->resolved == ZIP_UNRESOLVED_SYMLINK) /* gotta resolve it. */
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);
1299 BAIL_IF_MACRO(entry->resolved == ZIP_BROKEN_SYMLINK, NULL, 0);
1300 BAIL_IF_MACRO(entry->symlink == NULL, ERR_NOT_A_DIR, 0);
1302 return(zip_find_start_of_dir(info, entry->symlink->name, 1) >= 0);
1303 } /* ZIP_isDirectory */
1306 static int ZIP_isSymLink(dvoid *opaque, const char *name, int *fileExists)
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 */
1316 static void *zip_get_file_handle(const char *fn, ZIPinfo *inf, ZIPentry *entry)
1319 void *retval = __PHYSFS_platformOpenRead(fn);
1320 BAIL_IF_MACRO(retval == NULL, NULL, NULL);
1322 success = zip_resolve(retval, inf, entry);
1325 PHYSFS_sint64 offset;
1326 offset = ((entry->symlink) ? entry->symlink->offset : entry->offset);
1327 success = __PHYSFS_platformSeek(retval, offset);
1332 __PHYSFS_platformClose(retval);
1337 } /* zip_get_file_handle */
1340 static fvoid *ZIP_openRead(dvoid *opaque, const char *fnm, int *fileExists)
1342 ZIPinfo *info = (ZIPinfo *) opaque;
1343 ZIPentry *entry = zip_find_entry(info, fnm, NULL);
1344 ZIPfileinfo *finfo = NULL;
1347 *fileExists = (entry != NULL);
1348 BAIL_IF_MACRO(entry == NULL, NULL, NULL);
1350 in = zip_get_file_handle(info->archiveName, info, entry);
1351 BAIL_IF_MACRO(in == NULL, NULL, NULL);
1353 finfo = (ZIPfileinfo *) allocator.Malloc(sizeof (ZIPfileinfo));
1356 __PHYSFS_platformClose(in);
1357 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1360 memset(finfo, '\0', sizeof (ZIPfileinfo));
1362 finfo->entry = ((entry->symlink != NULL) ? entry->symlink : entry);
1363 initializeZStream(&finfo->stream);
1364 if (finfo->entry->compression_method != COMPMETH_NONE)
1366 if (zlib_err(inflateInit2(&finfo->stream, -MAX_WBITS)) != Z_OK)
1368 ZIP_fileClose(finfo);
1372 finfo->buffer = (PHYSFS_uint8 *) allocator.Malloc(ZIP_READBUFSIZE);
1373 if (finfo->buffer == NULL)
1375 ZIP_fileClose(finfo);
1376 BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
1381 } /* ZIP_openRead */
1384 static fvoid *ZIP_openWrite(dvoid *opaque, const char *filename)
1386 BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
1387 } /* ZIP_openWrite */
1390 static fvoid *ZIP_openAppend(dvoid *opaque, const char *filename)
1392 BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
1393 } /* ZIP_openAppend */
1396 static void ZIP_dirClose(dvoid *opaque)
1398 ZIPinfo *zi = (ZIPinfo *) (opaque);
1399 zip_free_entries(zi->entries, zi->entryCount);
1400 allocator.Free(zi->archiveName);
1402 } /* ZIP_dirClose */
1405 static int ZIP_remove(dvoid *opaque, const char *name)
1407 BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
1411 static int ZIP_mkdir(dvoid *opaque, const char *name)
1413 BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
1417 const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_ZIP =
1420 ZIP_ARCHIVE_DESCRIPTION,
1421 "Ryan C. Gordon <icculus@icculus.org>",
1422 "http://icculus.org/physfs/",
1426 const PHYSFS_Archiver __PHYSFS_Archiver_ZIP =
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 */
1451 #endif /* defined PHYSFS_SUPPORTS_ZIP */
1453 /* end of zip.c ... */