]> granicus.if.org Git - zziplib/blob - zzip/fseeko.c
memdisk-stuff
[zziplib] / zzip / fseeko.c
1 /*
2  * These routines are fully independent from the traditional zzip
3  * implementation. They assume a readonly seekable stdio handle
4  * representing a complete zip file. The functions show how to 
5  * parse the structure, find files and return a decoded bytestream.
6  *
7  * These routines are a bit simple and really here for documenting
8  * the way to access a zip file. The complexity of zip access comes
9  * from staggered reading of bytes and reposition of a filepointer in
10  * a big archive with lots of files and long compressed datastreams.
11  * Plus varaints of drop-in stdio replacements, obfuscation routines,
12  * auto fileextensions, drop-in dirent replacements, and so on...
13  *
14  * btw, we can _not_ use fgetpos/fsetpos since an fpos_t has no asserted
15  * relation to a linear seek value as specified in zip info headers. In
16  * general it is not a problem if your system has no fseeko/ftello pair
17  * since we can fallback to fseek/ftell which limits the zip disk size
18  * to 2MiBs but the zip-storable seek values are 32bit limited anyway.
19  *
20  * Author: 
21  *      Guido Draheim <guidod@gmx.de>
22  *
23  * Copyright (c) 2003,2004 Guido Draheim
24  *          All rights reserved,
25  *          use under the restrictions of the 
26  *          Lesser GNU General Public License
27  *          or alternatively the restrictions 
28  *          of the Mozilla Public License 1.1
29  */
30
31 #define _LARGEFILE_SOURCE 1
32 #define _ZZIP_ENTRY_STRUCT 1
33
34 #include <zzip/types.h>
35
36 #include <assert.h>
37 #include <stdlib.h>
38 #include <sys/stat.h>
39
40 #if   defined ZZIP_HAVE_STRING_H
41 #include <string.h>
42 #elif defined ZZIP_HAVE_STRINGS_H
43 #include <strings.h>
44 #endif
45
46 #include <zlib.h>
47 #include <zzip/format.h>
48 #include <zzip/fseeko.h>
49 #include <zzip/fetch.h>
50 #include <zzip/__mmap.h>
51 #include <zzip/__fnmatch.h>
52
53 #if __STDC_VERSION__+0 > 199900L
54 #define ___
55 #define ____
56 #else
57 #define ___ {
58 #define ____ }
59 #endif
60
61 #ifndef ZZIP_HAVE_FSEEKO
62 #define fseeko fseek
63 #define ftello ftello
64 #endif
65
66 /* note that the struct zzip_entry inherits the zzip_disk_entry values
67  * and usually carries a copy of its values (in disk format!). To make the
68  * following code more readable, we use a shorthand notation for the
69  * upcast needed in C (not needed in C++) as "disk_(entry)".
70  */
71 #ifdef __zzip_entry_extends_zzip_disk_entry
72 #define disk_(_entry_) _entry_
73 #else
74 #define disk_(_entry_) (& (_entry_)->head)
75 #endif
76
77 /* we try to round all seeks to the pagesize - since we do not use
78  * the sys/mmap interface we have to guess a good value here: */
79 #define PAGESIZE 8192
80
81 /* ====================================================================== */
82 /*                      helper functions                                  */
83
84 /** => zzip_entry_data_offset
85  * This functions read the correspoding struct zzip_file_header from 
86  * the zip disk of the given "entry". The returned off_t points to the
87  * end of the file_header where the current fseek pointer has stopped.
88  * This is used to immediatly parse out any filename/extras block following
89  * the file_header. The return value is null on error.
90  */
91 static zzip_off_t
92 zzip_entry_fread_file_header (ZZIP_ENTRY* entry, 
93                              struct zzip_file_header* file_header)
94 {
95     if (! entry || ! file_header) return 0;
96     ___ zzip_off_t offset = zzip_disk_entry_fileoffset (disk_(entry));
97     if (0 > offset || offset >= entry->disksize) return 0;
98
99     fseeko (entry->diskfile, offset, SEEK_SET);
100     return (fread (file_header, sizeof(*file_header), 1, entry->diskfile)
101             ? offset+sizeof(*file_header) : 0 ); ____;
102 }
103
104 /** helper functions for (fseeko) zip access api
105  *
106  * This functions returns the seekval offset of the data portion of the
107  * file referenced by the given zzip_entry. It requires an intermediate
108  * check of the file_header structure (i.e. it reads it from disk). After 
109  * this call, the contained diskfile readposition is already set to the 
110  * data_offset returned here. On error -1 is returned.
111  */
112 zzip_off_t
113 zzip_entry_data_offset(ZZIP_ENTRY* entry)
114 {
115     struct zzip_file_header file_header;
116     if (! entry) return -1;
117     ___ zzip_off_t offset = 
118         zzip_entry_fread_file_header (entry, & file_header);
119     if (! offset) return -1;
120     offset += zzip_file_header_sizeof_tails (& file_header);
121     fseeko (entry->diskfile, offset, SEEK_SET);
122     return offset; ____;
123 }
124
125 /** => zzip_entry_data_offset
126  * This function is a big helper despite its little name: in a zip file the
127  * encoded filenames are usually NOT zero-terminated but for common usage
128  * with libc we need it that way. Secondly, the filename SHOULD be present
129  * in the zip central directory but if not then we fallback to the filename
130  * given in the file_header of each compressed data portion.
131  */
132 char* _zzip_new
133 zzip_entry_strdup_name(ZZIP_ENTRY* entry)
134 {
135     if (! entry) return 0;
136
137     ___ zzip_size_t len;
138     if ((len = zzip_disk_entry_namlen (disk_(entry)))) {
139         char* name = malloc (len+1);
140         if (! name) return 0;
141         memcpy (name, entry->tail, len);
142         name[len] = '\0';
143         return name;
144     }
145     ___ auto struct zzip_file_header header;
146     if (zzip_entry_fread_file_header (entry, &header) 
147         && ( len = zzip_file_header_namlen(&header) )) {
148         char* name = malloc (len+1);
149         if (! name) return 0;
150         fread (name, 1, len, entry->diskfile);
151         name[len] = '\0';
152         return name;
153     }
154     return 0;
155     ____;____;
156 }
157
158 static int
159 prescan_entry(ZZIP_ENTRY* entry) 
160 {
161     assert (entry);
162     ___ zzip_off_t tailsize = zzip_disk_entry_sizeof_tails (disk_(entry));
163     if (tailsize+1 > entry->tailalloc) {
164         char* newtail = realloc (entry->tail, tailsize+1);
165         if (! newtail) return ENOMEM;
166         entry->tail = newtail;
167         entry->tailalloc = tailsize+1;
168     }
169     fread (entry->tail, 1, tailsize, entry->diskfile);
170     /* name + comment + extras */
171     return 0; ____;
172 }
173
174 static void
175 prescan_clear(ZZIP_ENTRY* entry)
176 {
177     assert (entry);
178     if (entry->tail) free (entry->tail);
179     entry->tail = 0; entry->tailalloc = 0;
180 }
181
182 /* ====================================================================== */
183
184 /** => zzip_entry_findfile
185  *
186  * This function is the first call of all the zip access functions here.
187  * It contains the code to find the first entry of the zip central directory. 
188  * Here we require the stdio handle to represent a real zip file where the
189  * disk_trailer is _last_ in the file area, so that its position would be at 
190  * a fixed offset from the end of the file area if not for the comment field 
191  * allowed to be of variable length (which needs us to do a little search
192  * for the disk_tailer). However, in this simple implementation we disregard
193  * any disk_trailer info telling about multidisk archives, so we just return
194  * a pointer to the first entry in the zip central directory of that file.
195  * 
196  * For an actual means, we are going to search backwards from the end 
197  * of the mmaped block looking for the PK-magic signature of a 
198  * disk_trailer. If we see one then we check the rootseek value to
199  * find the first disk_entry of the root central directory. If we find
200  * the correct PK-magic signature of a disk_entry over there then we 
201  * assume we are done and we are going to return a pointer to that label.
202  *
203  * The return value is a pointer to the first zzip_disk_entry being checked
204  * to be within the bounds of the file area specified by the arguments. If
205  * no disk_trailer was found then null is returned, and likewise we only 
206  * accept a disk_trailer with a seekvalue that points to a disk_entry and 
207  * both parts have valid PK-magic parts. Beyond some sanity check we try to
208  * catch a common brokeness with zip archives that still allows us to find
209  * the start of the zip central directory.
210  */
211 ZZIP_ENTRY* _zzip_new
212 zzip_entry_findfirst(FILE* disk)
213 {
214     if (! disk) return 0;
215     fseeko (disk, 0, SEEK_END);
216     ___ zzip_off_t disksize = ftello (disk);
217     if (disksize < (zzip_off_t) sizeof(struct zzip_disk_trailer)) return 0;
218     /* we read out chunks of 8 KiB in the hope to match disk granularity */
219     ___ zzip_off_t pagesize = PAGESIZE; /* getpagesize() */
220     ___ ZZIP_ENTRY* entry = malloc (sizeof(*entry));  if (! entry) return 0;
221     ___ char* buffer = malloc (pagesize);             if (! buffer) goto nomem;
222
223     assert (pagesize/2 > (zzip_off_t) sizeof (struct zzip_disk_trailer));
224     /* at each step, we will fread a pagesize block which overlaps with the
225      * previous read by means of pagesize/2 step at the end of the while(1) */
226     ___ zzip_off_t mapoffs = disksize &~ (pagesize-1);
227     ___ zzip_off_t mapsize = disksize - mapoffs;
228     if (mapoffs && mapsize < pagesize/2) { 
229         mapoffs -= pagesize/2; mapsize += pagesize/2; }
230     while(1) {
231         fseeko (disk, mapoffs, SEEK_SET);
232         fread (buffer, 1, mapsize, disk);
233         ___ char* p = buffer + mapsize - sizeof(struct zzip_disk_trailer);
234         for (; p >= buffer ; p--)
235         {
236             zzip_off_t root;  /* (struct zzip_disk_entry*) */
237             if (zzip_disk_trailer_check_magic(p)) {
238                 root = zzip_disk_trailer_rootseek (
239                     (struct zzip_disk_trailer*)p);
240                 if (root > disksize - (long)sizeof(struct zzip_disk_trailer)) {
241                     /* first disk_entry is after the disk_trailer? can't be! */
242                     zzip_off_t rootsize = zzip_disk_trailer_rootsize (
243                         (struct zzip_disk_trailer*)p);
244                     if (rootsize > mapoffs) continue;
245                     /* a common brokeness that can be fixed: we just assume the
246                      * central directory was written directly before : */
247                     root = mapoffs - rootsize;
248                 }
249             } else if (zzip_disk64_trailer_check_magic(p)) {
250                 if (sizeof(zzip_off_t) < 8) return 0;
251                 root = zzip_disk64_trailer_rootseek (
252                     (struct zzip_disk64_trailer*)p);
253             } else continue;
254
255             assert (0 <= root && root < mapsize);
256             fseeko (disk, root, SEEK_SET);
257             fread (disk_(entry), 1, sizeof(*disk_(entry)), disk);
258             if (zzip_disk_entry_check_magic(entry)) {
259                 free (buffer);
260                 entry->headseek = root;
261                 entry->diskfile = disk;
262                 entry->disksize = disksize;
263                 if (prescan_entry(entry)) goto nomem;
264                 return entry;
265             }
266         } ____;
267         if (! mapoffs) break;             assert (mapsize >= pagesize/2);
268         mapoffs -= pagesize/2;            /* mapsize += pagesize/2; */
269         mapsize = pagesize;               /* if (mapsize > pagesize) ... */
270         if (disksize - mapoffs > 64*1024) break;
271     }
272     free (buffer);
273  nomem:
274     free (entry);                         ____;____;____;____;____;____;
275     return 0;
276 }
277
278 /** => zzip_entry_findfile
279  *
280  * This function takes an existing "entry" in the central root directory
281  * (e.g. from zzip_entry_findfirst) and moves it to point to the next entry.
282  * On error it returns 0, otherwise the old entry. If no further match is
283  * found then null is returned and the entry already free()d. If you want
284  * to stop searching for matches before that case then please call 
285  * => zzip_entry_free on the cursor struct ZZIP_ENTRY.
286  */
287 ZZIP_ENTRY* _zzip_new
288 zzip_entry_findnext(ZZIP_ENTRY* _zzip_restrict entry)
289 {
290     if (! entry) return entry;
291     if (! zzip_disk_entry_check_magic (entry)) goto err;
292     ___ zzip_off_t seek = 
293         entry->headseek + zzip_disk_entry_sizeto_end (disk_(entry));
294     if (seek + (zzip_off_t) sizeof(*disk_(entry)) > entry->disksize) goto err;
295
296     fseeko (entry->diskfile, seek, SEEK_SET);
297     fread (disk_(entry), 1, sizeof(*disk_(entry)), entry->diskfile);
298     entry->headseek = seek;
299     if (! zzip_disk_entry_check_magic (entry)) goto err;
300     if (prescan_entry(entry)) goto err;
301     return entry;
302  err:
303     zzip_entry_free (entry);
304     return 0; ____;
305 }
306
307 /** => zzip_entry_findfile
308  * this function releases the malloc()ed areas needed for zzip_entry, the
309  * pointer is invalid afterwards. This function has #define synonyms of
310  * zzip_entry_findlast(), zzip_entry_findlastfile(), zzip_entry_findlastmatch()
311  */
312 int
313 zzip_entry_free(ZZIP_ENTRY* entry)
314 {
315     if (! entry) return 0;
316     prescan_clear (entry);
317     free (entry);
318     return 1;
319 }
320
321 /** search for files in the (fseeko) zip central directory
322  *
323  * This function is given a filename as an additional argument, to find the 
324  * disk_entry matching a given filename. The compare-function is usually 
325  * strcmp or strcasecmp or perhaps strcoll, if null then strcmp is used. 
326  * - use null as argument for "old"-entry when searching the first 
327  * matching entry, otherwise the last returned value if you look for other
328  * entries with a special "compare" function (if null then a doubled search
329  * is rather useless with this variant of _findfile). If no further entry is
330  * found then null is returned and any "old"-entry gets already free()d.
331  */
332 ZZIP_ENTRY* _zzip_new
333 zzip_entry_findfile(FILE* disk, char* filename, 
334                     ZZIP_ENTRY* _zzip_restrict entry, 
335                     zzip_strcmp_fn_t compare)
336 {
337     if (! filename || ! disk) return 0;
338     entry = ( ! entry ) ? zzip_entry_findfirst (disk) 
339         : zzip_entry_findnext (entry);
340     if (! compare) compare = (zzip_strcmp_fn_t)(strcmp);
341
342     for (; entry ; entry = zzip_entry_findnext (entry))
343     {   /* filenames within zip files are often not null-terminated! */
344         char* realname = zzip_entry_strdup_name (entry);
345         if (! realname) continue;
346         if (! compare (filename, realname)) {
347             free (realname);    return entry;
348         } else {
349             free (realname);    continue;
350         }
351     }
352     return 0;
353 }
354
355 #ifdef ZZIP_HAVE_FNMATCH_H
356 #define _zzip_fnmatch fnmatch
357 # ifdef FNM_CASEFOLD
358 # define _zzip_fnmatch_CASEFOLD FNM_CASEFOLD
359 # else
360 # define _zzip_fnmatch_CASEFOLD 0
361 # endif
362 #else
363 # define _zzip_fnmatch_CASEFOLD 0
364 /* if your system does not have fnmatch, we fall back to strcmp: */
365 static int _zzip_fnmatch(char* pattern, char* string, int flags)
366
367     puts ("<zzip:strcmp>");
368     return strcmp (pattern, string); 
369 }
370 #endif
371
372 /** => zzip_entry_findfile
373  *
374  * This function uses a compare-function with an additional argument
375  * and it is called just like fnmatch(3) from POSIX.2 AD:1993), i.e.
376  * the argument filespec first and the ziplocal filename second with
377  * the integer-flags put in as third to the indirect call. If the
378  * platform has fnmatch available then null-compare will use that one
379  * and otherwise we fall back to mere strcmp, so if you need fnmatch
380  * searching then please provide an implementation somewhere else.
381  * - use null as argument for "after"-entry when searching the first 
382  * matching entry, or the last disk_entry return-value to find the
383  * next entry matching the given filespec. If no further entry is
384  * found then null is returned and any "old"-entry gets already free()d.
385  */
386 ZZIP_ENTRY* _zzip_new
387 zzip_entry_findmatch(FILE* disk, char* filespec, 
388                      ZZIP_ENTRY* _zzip_restrict entry,
389                      zzip_fnmatch_fn_t compare, int flags)
390 {
391     if (! filespec || ! disk) return 0;
392     entry = ( ! entry ) ? zzip_entry_findfirst (disk) 
393         : zzip_entry_findnext (entry);
394     if (! compare) compare = (zzip_fnmatch_fn_t) _zzip_fnmatch; 
395
396     for (; entry ; entry = zzip_entry_findnext (entry))
397     {   /* filenames within zip files are often not null-terminated! */
398         char* realname = zzip_entry_strdup_name (entry);
399         if (! realname) continue;
400         if (! compare (filespec, realname, flags)) {
401             free (realname);    return entry;
402         } else {
403             free (realname);    continue;
404         }
405     }
406     return 0;
407 }
408
409 /* ====================================================================== */
410
411 /**
412  * typedef struct zzip_disk_file ZZIP_ENTRY_FILE;
413  */
414 struct zzip_entry_file /* : zzip_file_header */
415 {
416     struct zzip_file_header header;    /* fopen detected header */
417     ZZIP_ENTRY* entry;                 /* fopen entry */
418     zzip_off_t  data;                  /* for stored blocks */
419     zzip_size_t avail;                 /* memorized for checks on EOF */
420     zzip_size_t compressed;            /* compressed flag and datasize */
421     zzip_size_t dataoff;               /* offset from data start */
422     z_stream zlib;                     /* for inflated blocks */
423     char     buffer[PAGESIZE];         /* work buffer for inflate algorithm */
424 };
425
426 /** open a file within a zip disk for reading
427  *
428  * This function does take an "entry" argument and copies it (or just takes
429  * it over as owner) to a new ZZIP_ENTRY_FILE handle structure. That
430  * structure contains also a zlib buffer for decoding. This function does
431  * seek to the file_header of the given "entry" and validates it for the
432  * data buffer following it. We do also prefetch some data from the data
433  * buffer thereby trying to match the disk pagesize for faster access later.
434  * The => zzip_entry_fread will then read in chunks of pagesizes which is
435  * the size of the internal readahead buffer. If an error occurs then null
436  * is returned.
437  */
438 ZZIP_ENTRY_FILE* _zzip_new
439 zzip_entry_fopen (ZZIP_ENTRY* entry, int takeover)
440 {
441     if (! entry) return 0;
442     if (! takeover) {
443         ZZIP_ENTRY* found = malloc (sizeof(*entry));
444         if (! found) return 0;
445         memcpy (found, entry, sizeof(*entry));   /* prescan_copy */
446         found->tail = malloc (found->tailalloc);
447         if (! found->tail) { free (found); return 0; }
448         memcpy (found->tail, entry->tail, entry->tailalloc);
449         entry = found;
450     }
451     ___ ZZIP_ENTRY_FILE* file = malloc(sizeof(*file));
452     if (! file) goto fail1;
453     file->entry = entry;
454     if (! zzip_entry_fread_file_header (entry, &file->header))
455         goto fail2;
456     file->avail = zzip_file_header_usize (&file->header);
457     file->data = zzip_entry_data_offset (entry);
458     file->dataoff = 0;
459
460     if (! file->avail || zzip_file_header_data_stored (&file->header))
461     { file->compressed = 0; return file; }
462
463     file->compressed = zzip_file_header_csize (&file->header);
464     file->zlib.opaque = 0;
465     file->zlib.zalloc = Z_NULL;
466     file->zlib.zfree = Z_NULL;
467
468     ___ zzip_off_t seek = file->data;
469     seek += sizeof(file->buffer); seek -= seek & (sizeof(file->buffer)-1);
470     assert (file->data < seek); /* pre-read to next PAGESIZE boundary... */
471     fseeko (file->entry->diskfile, file->data + file->dataoff, SEEK_SET);
472     file->zlib.next_in = file->buffer;
473     file->zlib.avail_in = fread (file->buffer, 1, seek - file->data,
474                                  file->entry->diskfile);
475     file->dataoff += file->zlib.avail_in; ____;
476
477     if (! zzip_file_header_data_deflated (&file->header) 
478         || inflateInit2 (& file->zlib, -MAX_WBITS) != Z_OK) goto fail2;
479
480     return file;
481  fail2:
482     free (file);
483  fail1:
484     zzip_entry_free (entry);
485     return 0; ____;
486 }
487
488 /** => zzip_entry_fopen
489  *
490  * This function opens a file found by name, so it does a search into
491  * the zip central directory with => zzip_entry_findfile and whatever
492  * is found first is given to => zzip_entry_fopen
493  */
494 ZZIP_ENTRY_FILE* _zzip_new
495 zzip_entry_ffile (FILE* disk, char* filename)
496 {
497     ZZIP_ENTRY* entry = zzip_entry_findfile (disk, filename, 0, 0);
498     if (! entry) return 0;
499     return zzip_entry_fopen (entry, 1);
500 }
501
502
503 /** => zzip_entry_fopen
504  *
505  * This function reads more bytes into the output buffer specified as
506  * arguments. The return value is null on eof or error, the stdio-like
507  * interface can not distinguish between these so you need to check
508  * with => zzip_entry_feof for the difference.
509  */
510 zzip_size_t
511 zzip_entry_fread (void* ptr, zzip_size_t sized, zzip_size_t nmemb,
512                   ZZIP_ENTRY_FILE* file)
513 {
514     if (! file) return 0;
515     ___ zzip_size_t size = sized*nmemb;
516     if (! file->compressed) {
517         if (size > file->avail) size = file->avail;
518         fread (ptr, 1, size, file->entry->diskfile);
519         file->dataoff += size;
520         file->avail -= size;
521         return size;
522     }
523     
524     file->zlib.avail_out = size;
525     file->zlib.next_out = ptr;
526     ___ zzip_size_t total_old = file->zlib.total_out;
527     while (1) {
528         if (! file->zlib.avail_in) {   
529             size = file->compressed - file->dataoff;
530             if (size > sizeof(file->buffer)) size = sizeof(file->buffer);
531             /* fseek (file->data + file->dataoff, file->entry->diskfile); */
532             file->zlib.avail_in = fread (file->buffer, 1, size,
533                                          file->entry->diskfile);
534             file->zlib.next_in = file->buffer;
535             file->dataoff += file->zlib.avail_in;
536         }
537         if (! file->zlib.avail_in) return 0;
538         
539         ___ int err = inflate (& file->zlib, Z_NO_FLUSH);
540         if (err == Z_STREAM_END)
541             file->avail = 0;
542         else if (err == Z_OK)
543             file->avail -= file->zlib.total_out - total_old;
544         else
545             return 0;
546         ____;
547         if (file->zlib.avail_out && ! file->zlib.avail_in) continue;
548         return file->zlib.total_out - total_old;
549     }____;____;
550 }
551
552 /** => zzip_entry_fopen
553  * This function releases any zlib decoder info needed for decompression
554  * and dumps the ZZIP_ENTRY_FILE struct then.
555  */
556 int
557 zzip_entry_fclose (ZZIP_ENTRY_FILE* file)
558 {
559     if (! file) return 0;
560     if (file->compressed)
561         inflateEnd (& file->zlib);
562     zzip_entry_free (file->entry);
563     free (file);
564     return 0;
565 }
566
567 /** => zzip_entry_fopen
568  *
569  * This function allows to distinguish an error from an eof condition. 
570  * Actually, if we found an error but we did already reach eof then we
571  * just keep on saying that it was an eof, so the app can just continue.
572  */ 
573 int
574 zzip_entry_feof (ZZIP_ENTRY_FILE* file)
575 {
576     return ! file || ! file->avail;
577 }