2 // ZIP file support (mostly ripped from MAME)
4 // Added by James L. Hammons
18 int gUnzipQuiet = 0; /* flag controls error messages */
21 #define ERROR_CORRUPT "The zipfile seems to be corrupt, please check it"
22 #define ERROR_FILESYSTEM "Your filesystem seems to be corrupt, please check it"
23 #define ERROR_UNSUPPORTED "The format of this zipfile is not supported, please recompress it"
25 #define INFLATE_INPUT_BUFFER_MAX 16384
27 #define MIN(x,y) ((x)<(y)?(x):(y))
30 /* Print a error message */
31 void errormsg(const char * extmsg, const char * usermsg, const char * zipname)
33 /* Output to the user with no internal detail */
35 printf("Error in zipfile %s\n%s\n", zipname, usermsg);
36 /* Output to log file with all informations */
37 WriteLog("Error in zipfile %s: %s\n", zipname, extmsg);
40 /* -------------------------------------------------------------------------
42 ------------------------------------------------------------------------- */
44 /* Use these to avoid structure padding and byte-ordering problems */
45 static UINT16 read_word (char *buf) {
46 unsigned char *ubuf = (unsigned char *) buf;
48 return ((UINT16)ubuf[1] << 8) | (UINT16)ubuf[0];
51 /* Use these to avoid structure padding and byte-ordering problems */
52 static UINT32 read_dword (char *buf) {
53 unsigned char *ubuf = (unsigned char *) buf;
55 return ((UINT32)ubuf[3] << 24) | ((UINT32)ubuf[2] << 16) | ((UINT32)ubuf[1] << 8) | (UINT32)ubuf[0];
58 /* Locate end-of-central-dir sig in buffer and return offset
60 *offset offset of cent dir start in buffer
63 !=0 found, *offset valid
65 static int ecd_find_sig (char *buffer, int buflen, int *offset)
67 static char ecdsig[] = { 'P', 'K', 0x05, 0x06 };
69 for (i=buflen-22; i>=0; i--) {
70 if (memcmp(buffer+i, ecdsig, 4) == 0) {
78 /* Read ecd data in zip structure
80 zip->fp, zip->length zip file
82 zip->ecd, zip->ecd_length ecd data
84 static int ecd_read(ZIP * zip)
87 int buf_length = 1024; /* initial buffer length */
93 if (buf_length > zip->length)
94 buf_length = zip->length;
96 if (fseek(zip->fp, zip->length - buf_length, SEEK_SET) != 0)
101 /* allocate buffer */
102 buf = (char *)malloc(buf_length);
108 if (fread(buf, 1, buf_length, zip->fp) != buf_length)
114 if (ecd_find_sig(buf, buf_length, &offset)) {
115 zip->ecd_length = buf_length - offset;
117 zip->ecd = (char*)malloc( zip->ecd_length );
123 memcpy(zip->ecd, buf + offset, zip->ecd_length);
131 if (buf_length < zip->length) {
133 buf_length = 2*buf_length;
135 WriteLog("Retry reading of zip ecd for %d bytes\n",buf_length);
143 /* offsets in end of central directory structure */
148 #define ZIPECENN 0x0a
150 #define ZIPEOFST 0x10
151 #define ZIPECOML 0x14
154 /* offsets in central directory entry structure */
155 #define ZIPCENSIG 0x0
176 /* offsets in local file header structure */
177 #define ZIPLOCSIG 0x00
179 #define ZIPGENFLG 0x06
185 #define ZIPUNCMP 0x16
187 #define ZIPXTRALN 0x1c
191 // Opens a zip stream for reading
193 // !=0 success, zip stream
196 ZIP * openzip(int pathtype, int pathindex, const char * zipfile)
199 ZIP * zip = (ZIP *)malloc(sizeof(ZIP));
206 zip->fp = fopen(zipfile, "rb");
209 errormsg("Opening for reading", ERROR_FILESYSTEM, zipfile);
215 if (fseek(zip->fp, 0L, SEEK_END) != 0)
217 errormsg ("Seeking to end", ERROR_FILESYSTEM, zipfile);
224 zip->length = ftell(zip->fp);
227 errormsg("Get file size", ERROR_FILESYSTEM, zipfile);
232 if (zip->length == 0)
234 errormsg ("Empty file", ERROR_CORRUPT, zipfile);
241 if (ecd_read(zip) != 0)
243 errormsg("Reading ECD (end of central directory)", ERROR_CORRUPT, zipfile);
249 /* compile ecd info */
250 zip->end_of_cent_dir_sig = read_dword (zip->ecd+ZIPESIG);
251 zip->number_of_this_disk = read_word (zip->ecd+ZIPEDSK);
252 zip->number_of_disk_start_cent_dir = read_word (zip->ecd+ZIPECEN);
253 zip->total_entries_cent_dir_this_disk = read_word (zip->ecd+ZIPENUM);
254 zip->total_entries_cent_dir = read_word (zip->ecd+ZIPECENN);
255 zip->size_of_cent_dir = read_dword (zip->ecd+ZIPECSZ);
256 zip->offset_to_start_of_cent_dir = read_dword (zip->ecd+ZIPEOFST);
257 zip->zipfile_comment_length = read_word (zip->ecd+ZIPECOML);
258 zip->zipfile_comment = zip->ecd+ZIPECOM;
260 /* verify that we can work with this zipfile (no disk spanning allowed) */
261 if ((zip->number_of_this_disk != zip->number_of_disk_start_cent_dir) ||
262 (zip->total_entries_cent_dir_this_disk != zip->total_entries_cent_dir) ||
263 (zip->total_entries_cent_dir < 1))
265 errormsg("Cannot span disks", ERROR_UNSUPPORTED, zipfile);
272 if (fseek(zip->fp, zip->offset_to_start_of_cent_dir, SEEK_SET) != 0)
274 errormsg("Seeking to central directory", ERROR_CORRUPT, zipfile);
281 /* read from start of central directory */
282 zip->cd = (char *)malloc(zip->size_of_cent_dir);
291 if (fread(zip->cd, 1, zip->size_of_cent_dir, zip->fp) != zip->size_of_cent_dir)
293 errormsg("Reading central directory", ERROR_CORRUPT, zipfile);
308 zip->zip = (char*)malloc(strlen(zipfile)+1);
317 strcpy(zip->zip, zipfile);
318 zip->pathtype = pathtype;
319 zip->pathindex = pathindex;
324 /* Reads the current entry from a zip stream
331 struct zipent* readzip(ZIP* zip) {
333 /* end of directory */
334 if (zip->cd_pos >= zip->size_of_cent_dir)
337 /* compile zipent info */
338 zip->ent.cent_file_header_sig = read_dword (zip->cd+zip->cd_pos+ZIPCENSIG);
339 zip->ent.version_made_by = *(zip->cd+zip->cd_pos+ZIPCVER);
340 zip->ent.host_os = *(zip->cd+zip->cd_pos+ZIPCOS);
341 zip->ent.version_needed_to_extract = *(zip->cd+zip->cd_pos+ZIPCVXT);
342 zip->ent.os_needed_to_extract = *(zip->cd+zip->cd_pos+ZIPCEXOS);
343 zip->ent.general_purpose_bit_flag = read_word (zip->cd+zip->cd_pos+ZIPCFLG);
344 zip->ent.compression_method = read_word (zip->cd+zip->cd_pos+ZIPCMTHD);
345 zip->ent.last_mod_file_time = read_word (zip->cd+zip->cd_pos+ZIPCTIM);
346 zip->ent.last_mod_file_date = read_word (zip->cd+zip->cd_pos+ZIPCDAT);
347 zip->ent.crc32 = read_dword (zip->cd+zip->cd_pos+ZIPCCRC);
348 zip->ent.compressed_size = read_dword (zip->cd+zip->cd_pos+ZIPCSIZ);
349 zip->ent.uncompressed_size = read_dword (zip->cd+zip->cd_pos+ZIPCUNC);
350 zip->ent.filename_length = read_word (zip->cd+zip->cd_pos+ZIPCFNL);
351 zip->ent.extra_field_length = read_word (zip->cd+zip->cd_pos+ZIPCXTL);
352 zip->ent.file_comment_length = read_word (zip->cd+zip->cd_pos+ZIPCCML);
353 zip->ent.disk_number_start = read_word (zip->cd+zip->cd_pos+ZIPDSK);
354 zip->ent.internal_file_attrib = read_word (zip->cd+zip->cd_pos+ZIPINT);
355 zip->ent.external_file_attrib = read_dword (zip->cd+zip->cd_pos+ZIPEXT);
356 zip->ent.offset_lcl_hdr_frm_frst_disk = read_dword (zip->cd+zip->cd_pos+ZIPOFST);
358 /* check to see if filename length is illegally long (past the size of this directory
360 if (zip->cd_pos + ZIPCFN + zip->ent.filename_length > zip->size_of_cent_dir)
362 errormsg("Invalid filename length in directory", ERROR_CORRUPT,zip->zip);
368 zip->ent.name = (char*)malloc(zip->ent.filename_length + 1);
369 memcpy(zip->ent.name, zip->cd+zip->cd_pos+ZIPCFN, zip->ent.filename_length);
370 zip->ent.name[zip->ent.filename_length] = 0;
372 /* skip to next entry in central dir */
373 zip->cd_pos += ZIPCFN + zip->ent.filename_length + zip->ent.extra_field_length + zip->ent.file_comment_length;
378 /* Closes a zip stream */
379 void closezip(ZIP * zip)
385 /* only if not suspended */
392 /* Suspend access to a zip file (release file handler)
396 A suspended zip is automatically reopened at first call of
397 readuncompressd() or readcompressed() functions
399 void suspendzip(ZIP * zip)
408 /* Revive a suspended zip file (reopen file handler)
413 ==0 error (zip must be closed with closezip)
415 static ZIP * revivezip(ZIP * zip)
419 zip->fp = fopen(zip->zip, "rb");
427 /* Reset a zip stream to the first entry
431 ZIP file must be opened and not suspended
433 void rewindzip(ZIP * zip)
439 // Seek zip->fp to compressed data
444 int seekcompresszip(ZIP * zip, struct zipent * ent)
455 if (fseek(zip->fp, ent->offset_lcl_hdr_frm_frst_disk, SEEK_SET) != 0)
457 errormsg("Seeking to header", ERROR_CORRUPT, zip->zip);
461 if (fread(buf, 1, ZIPNAME, zip->fp) != ZIPNAME)
463 errormsg("Reading header", ERROR_CORRUPT, zip->zip);
468 UINT16 filename_length = read_word(buf+ZIPFNLN);
469 UINT16 extra_field_length = read_word(buf+ZIPXTRALN);
471 // calculate offset to data and fseek() there
472 offset = ent->offset_lcl_hdr_frm_frst_disk + ZIPNAME + filename_length + extra_field_length;
474 if (fseek(zip->fp, offset, SEEK_SET) != 0)
476 errormsg("Seeking to compressed data", ERROR_CORRUPT, zip->zip);
488 // in_file stream to inflate
489 // in_size size of the compressed data to read
491 // out_size size of decompressed data
492 // out_data buffer for decompressed data
496 // 990525 rewritten for use with zlib MLR
498 static int inflate_file(FILE * in_file, unsigned in_size, unsigned char * out_data, unsigned out_size)
501 unsigned char * in_buffer;
502 z_stream d_stream; // decompression stream
508 d_stream.next_in = 0;
509 d_stream.avail_in = 0;
510 d_stream.next_out = out_data;
511 d_stream.avail_out = out_size;
513 err = inflateInit2(&d_stream, -MAX_WBITS);
514 /* windowBits is passed < 0 to tell that there is no zlib header.
515 * Note that in this case inflate *requires* an extra "dummy" byte
516 * after the compressed stream in order to complete decompression and
517 * return Z_STREAM_END.
521 WriteLog("inflateInit error: %d\n", err);
525 in_buffer = (unsigned char*)malloc(INFLATE_INPUT_BUFFER_MAX+1);
533 WriteLog("inflate error: compressed size too small\n");
537 d_stream.next_in = in_buffer;
538 d_stream.avail_in = fread(in_buffer, 1, MIN(in_size, INFLATE_INPUT_BUFFER_MAX), in_file);
539 in_size -= d_stream.avail_in;
541 d_stream.avail_in++; /* add dummy byte at end of compressed data */
543 err = inflate(&d_stream, Z_NO_FLUSH);
544 if (err == Z_STREAM_END)
548 WriteLog("inflate error: %d\n", err);
554 err = inflateEnd(&d_stream);
557 WriteLog("inflateEnd error: %d\n", err);
564 if ((d_stream.avail_out > 0) || (in_size > 0))
566 WriteLog("zip size mismatch. %i\n", in_size);
574 // Read compressed data
576 // data compressed data read
581 int readcompresszip(ZIP * zip, struct zipent * ent, char * data)
583 int err = seekcompresszip(zip, ent);
587 if (fread(data, 1, ent->compressed_size, zip->fp) != ent->compressed_size)
589 errormsg("Reading compressed data", ERROR_CORRUPT, zip->zip);
597 // Read UNcompressed data
599 // data UNcompressed data
604 int readuncompresszip(ZIP * zip, struct zipent * ent, char * data)
606 if (ent->compression_method == 0x0000)
608 /* file is not compressed, simply stored */
610 /* check if size are equal */
611 if (ent->compressed_size != ent->uncompressed_size)
613 errormsg("Wrong uncompressed size in store compression", ERROR_CORRUPT,zip->zip);
617 return readcompresszip(zip, ent, data);
619 else if (ent->compression_method == 0x0008)
621 /* file is compressed using "Deflate" method */
622 if (ent->version_needed_to_extract > 0x14)
624 errormsg("Version too new", ERROR_UNSUPPORTED, zip->zip);
628 if (ent->os_needed_to_extract != 0x00)
630 errormsg("OS not supported", ERROR_UNSUPPORTED, zip->zip);
634 if (ent->disk_number_start != zip->number_of_this_disk)
636 errormsg("Cannot span disks", ERROR_UNSUPPORTED, zip->zip);
640 /* read compressed data */
641 if (seekcompresszip(zip, ent) != 0)
646 /* configure inflate */
647 if (inflate_file(zip->fp, ent->compressed_size, (unsigned char *)data, ent->uncompressed_size))
649 errormsg("Inflating compressed data", ERROR_CORRUPT, zip->zip);
657 errormsg("Compression method unsupported", ERROR_UNSUPPORTED, zip->zip);
662 /* -------------------------------------------------------------------------
664 ------------------------------------------------------------------------- */
666 /* Use the zip cache */
672 /* ZIP cache entries */
673 #define ZIP_CACHE_MAX 5
675 /* ZIP cache buffer LRU ( Last Recently Used )
676 zip_cache_map[0] is the newer
677 zip_cache_map[ZIP_CACHE_MAX-1] is the older
679 static ZIP* zip_cache_map[ZIP_CACHE_MAX];
681 static ZIP* cache_openzip(int pathtype, int pathindex, const char* zipfile) {
685 /* search in the cache buffer */
686 for(i=0;i<ZIP_CACHE_MAX;++i) {
687 if (zip_cache_map[i] && zip_cache_map[i]->pathtype == pathtype && zip_cache_map[i]->pathindex == pathindex && strcmp(zip_cache_map[i]->zip,zipfile)==0) {
692 WriteLog("Zip cache HIT for %s\n", zipfile);
695 /* reset the zip directory */
696 rewindzip( zip_cache_map[i] );
699 zip = zip_cache_map[i];
703 zip_cache_map[j] = zip_cache_map[j-1];
705 /* set the first entry */
706 zip_cache_map[0] = zip;
708 return zip_cache_map[0];
714 WriteLog("Zip cache FAIL for %s\n", zipfile);
718 zip = openzip( pathtype, pathindex, zipfile );
722 /* close the oldest entry */
723 if (zip_cache_map[ZIP_CACHE_MAX-1]) {
725 closezip(zip_cache_map[ZIP_CACHE_MAX-1]);
726 /* reset the entry */
727 zip_cache_map[ZIP_CACHE_MAX-1] = 0;
731 for(i=ZIP_CACHE_MAX-1;i>0;--i)
732 zip_cache_map[i] = zip_cache_map[i-1];
734 /* set the first entry */
735 zip_cache_map[0] = zip;
737 return zip_cache_map[0];
740 static void cache_closezip(ZIP* zip) {
743 /* search in the cache buffer */
744 for(i=0;i<ZIP_CACHE_MAX;++i) {
745 if (zip_cache_map[i]==zip) {
749 /* reset cache entry */
750 zip_cache_map[i] = 0;
761 /* CK980415 added to allow osd code to clear zip cache for auditing--each time
762 the user opens up an audit for a game we should reread the zip */
763 void unzip_cache_clear()
767 /* search in the cache buffer for any zip info and clear it */
768 for(i=0;i<ZIP_CACHE_MAX;++i) {
769 if (zip_cache_map[i] != NULL) {
771 closezip(zip_cache_map[i]);
773 /* reset cache entry */
774 zip_cache_map[i] = 0;
781 #define cache_suspendzip(a) suspendzip(a)
785 #define cache_openzip(a,b,c) openzip(a,b,c)
786 #define cache_closezip(a) closezip(a)
787 #define cache_suspendzip(a) closezip(a)
789 #define unzip_cache_clear()
793 /* -------------------------------------------------------------------------
794 Backward MAME compatibility
795 ------------------------------------------------------------------------- */
798 // Compare two filenames
799 // NOTE: Don't check directory in zip and ignore case
801 static int equal_filename(const char * zipfile, const char * file)
803 // const char * s1 = file;
804 // start comparison after last / also...!
805 const char * s1 = strrchr(file, '/');
810 // start comparison after last /
811 const char * s2 = strrchr(zipfile, '/');
816 //WriteLog("--> Comparing filenames: [%s] <-> [%s]\n", s1, s2);
818 // This assumes that s1 is longer than s2... Might not be! !!! FIX !!!
819 while (*s1 && toupper(*s1) == toupper(*s2))
829 // Pass the path to the zipfile and the name of the file within the zipfile.
830 // buf will be set to point to the uncompressed image of that zipped file.
831 // length will be set to the length of the uncompressed data.
833 int load_zipped_file(int pathtype, int pathindex, const char * zipfile, const char * filename, unsigned char ** buf, uint32 * length)
838 zip = cache_openzip(pathtype, pathindex, zipfile);
844 /* NS981003: support for "load by CRC" */
848 sprintf(crc, "%08x", (unsigned int)ent->crc32);
850 if (filename == NULL || equal_filename(ent->name, filename)
851 || (ent->crc32 && !strcmp(crc, filename)))
853 *length = ent->uncompressed_size;
855 if (readuncompresszip(zip, ent, (char *)*buf) != 0)
861 cache_suspendzip(zip);
866 cache_suspendzip(zip);