argh, clean out copy
[supertux.git] / src / unison / physfs-1.1.1 / archivers / qpak.c
1 /*
2  * QPAK support routines for PhysicsFS.
3  *
4  *  This archiver handles the archive format utilized by Quake 1 and 2.
5  *  Quake3-based games use the PkZip/Info-Zip format (which our zip.c
6  *  archiver handles).
7  *
8  *  ========================================================================
9  *
10  *  This format info (in more detail) comes from:
11  *     http://debian.fmi.uni-sofia.bg/~sergei/cgsr/docs/pak.txt
12  *
13  *  Quake PAK Format
14  *
15  *  Header
16  *   (4 bytes)  signature = 'PACK'
17  *   (4 bytes)  directory offset
18  *   (4 bytes)  directory length
19  *
20  *  Directory
21  *   (56 bytes) file name
22  *   (4 bytes)  file position
23  *   (4 bytes)  file length
24  *
25  *  ========================================================================
26  *
27  * Please see the file LICENSE.txt in the source's root directory.
28  *
29  *  This file written by Ryan C. Gordon.
30  */
31
32 #if (defined PHYSFS_SUPPORTS_QPAK)
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include "physfs.h"
38
39 #define __PHYSICSFS_INTERNAL__
40 #include "physfs_internal.h"
41
42 #if 1  /* Make this case insensitive? */
43 #define QPAK_strcmp(x, y) __PHYSFS_stricmpASCII(x, y)
44 #define QPAK_strncmp(x, y, z) __PHYSFS_strnicmpASCII(x, y, z)
45 #else
46 #define QPAK_strcmp(x, y) strcmp(x, y)
47 #define QPAK_strncmp(x, y, z) strncmp(x, y, z)
48 #endif
49
50
51 typedef struct
52 {
53     char name[56];
54     PHYSFS_uint32 startPos;
55     PHYSFS_uint32 size;
56 } QPAKentry;
57
58 typedef struct
59 {
60     char *filename;
61     PHYSFS_sint64 last_mod_time;
62     PHYSFS_uint32 entryCount;
63     QPAKentry *entries;
64 } QPAKinfo;
65
66 typedef struct
67 {
68     void *handle;
69     QPAKentry *entry;
70     PHYSFS_uint32 curPos;
71 } QPAKfileinfo;
72
73 /* Magic numbers... */
74 #define QPAK_SIG 0x4b434150   /* "PACK" in ASCII. */
75
76
77 static void QPAK_dirClose(dvoid *opaque)
78 {
79     QPAKinfo *info = ((QPAKinfo *) opaque);
80     allocator.Free(info->filename);
81     allocator.Free(info->entries);
82     allocator.Free(info);
83 } /* QPAK_dirClose */
84
85
86 static PHYSFS_sint64 QPAK_read(fvoid *opaque, void *buffer,
87                               PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
88 {
89     QPAKfileinfo *finfo = (QPAKfileinfo *) opaque;
90     QPAKentry *entry = finfo->entry;
91     PHYSFS_uint32 bytesLeft = entry->size - finfo->curPos;
92     PHYSFS_uint32 objsLeft = (bytesLeft / objSize);
93     PHYSFS_sint64 rc;
94
95     if (objsLeft < objCount)
96         objCount = objsLeft;
97
98     rc = __PHYSFS_platformRead(finfo->handle, buffer, objSize, objCount);
99     if (rc > 0)
100         finfo->curPos += (PHYSFS_uint32) (rc * objSize);
101
102     return(rc);
103 } /* QPAK_read */
104
105
106 static PHYSFS_sint64 QPAK_write(fvoid *opaque, const void *buffer,
107                                PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
108 {
109     BAIL_MACRO(ERR_NOT_SUPPORTED, -1);
110 } /* QPAK_write */
111
112
113 static int QPAK_eof(fvoid *opaque)
114 {
115     QPAKfileinfo *finfo = (QPAKfileinfo *) opaque;
116     QPAKentry *entry = finfo->entry;
117     return(finfo->curPos >= entry->size);
118 } /* QPAK_eof */
119
120
121 static PHYSFS_sint64 QPAK_tell(fvoid *opaque)
122 {
123     return(((QPAKfileinfo *) opaque)->curPos);
124 } /* QPAK_tell */
125
126
127 static int QPAK_seek(fvoid *opaque, PHYSFS_uint64 offset)
128 {
129     QPAKfileinfo *finfo = (QPAKfileinfo *) opaque;
130     QPAKentry *entry = finfo->entry;
131     int rc;
132
133     BAIL_IF_MACRO(offset < 0, ERR_INVALID_ARGUMENT, 0);
134     BAIL_IF_MACRO(offset >= entry->size, ERR_PAST_EOF, 0);
135     rc = __PHYSFS_platformSeek(finfo->handle, entry->startPos + offset);
136     if (rc)
137         finfo->curPos = (PHYSFS_uint32) offset;
138
139     return(rc);
140 } /* QPAK_seek */
141
142
143 static PHYSFS_sint64 QPAK_fileLength(fvoid *opaque)
144 {
145     QPAKfileinfo *finfo = (QPAKfileinfo *) opaque;
146     return((PHYSFS_sint64) finfo->entry->size);
147 } /* QPAK_fileLength */
148
149
150 static int QPAK_fileClose(fvoid *opaque)
151 {
152     QPAKfileinfo *finfo = (QPAKfileinfo *) opaque;
153     BAIL_IF_MACRO(!__PHYSFS_platformClose(finfo->handle), NULL, 0);
154     allocator.Free(finfo);
155     return(1);
156 } /* QPAK_fileClose */
157
158
159 static int qpak_open(const char *filename, int forWriting,
160                     void **fh, PHYSFS_uint32 *count)
161 {
162     PHYSFS_uint32 buf;
163
164     *fh = NULL;
165     BAIL_IF_MACRO(forWriting, ERR_ARC_IS_READ_ONLY, 0);
166
167     *fh = __PHYSFS_platformOpenRead(filename);
168     BAIL_IF_MACRO(*fh == NULL, NULL, 0);
169     
170     if (__PHYSFS_platformRead(*fh, &buf, sizeof (PHYSFS_uint32), 1) != 1)
171         goto openQpak_failed;
172
173     buf = PHYSFS_swapULE32(buf);
174     GOTO_IF_MACRO(buf != QPAK_SIG, ERR_UNSUPPORTED_ARCHIVE, openQpak_failed);
175
176     if (__PHYSFS_platformRead(*fh, &buf, sizeof (PHYSFS_uint32), 1) != 1)
177         goto openQpak_failed;
178
179     buf = PHYSFS_swapULE32(buf);  /* directory table offset. */
180
181     if (__PHYSFS_platformRead(*fh, count, sizeof (PHYSFS_uint32), 1) != 1)
182         goto openQpak_failed;
183
184     *count = PHYSFS_swapULE32(*count);
185
186     /* corrupted archive? */
187     GOTO_IF_MACRO((*count % 64) != 0, ERR_CORRUPTED, openQpak_failed);
188
189     if (!__PHYSFS_platformSeek(*fh, buf))
190         goto openQpak_failed;
191
192     *count /= 64;
193     return(1);
194
195 openQpak_failed:
196     if (*fh != NULL)
197         __PHYSFS_platformClose(*fh);
198
199     *count = -1;
200     *fh = NULL;
201     return(0);
202 } /* qpak_open */
203
204
205 static int QPAK_isArchive(const char *filename, int forWriting)
206 {
207     void *fh;
208     PHYSFS_uint32 fileCount;
209     int retval = qpak_open(filename, forWriting, &fh, &fileCount);
210
211     if (fh != NULL)
212         __PHYSFS_platformClose(fh);
213
214     return(retval);
215 } /* QPAK_isArchive */
216
217
218 static int qpak_entry_cmp(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
219 {
220     QPAKentry *a = (QPAKentry *) _a;
221     return(QPAK_strcmp(a[one].name, a[two].name));
222 } /* qpak_entry_cmp */
223
224
225 static void qpak_entry_swap(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
226 {
227     QPAKentry tmp;
228     QPAKentry *first = &(((QPAKentry *) _a)[one]);
229     QPAKentry *second = &(((QPAKentry *) _a)[two]);
230     memcpy(&tmp, first, sizeof (QPAKentry));
231     memcpy(first, second, sizeof (QPAKentry));
232     memcpy(second, &tmp, sizeof (QPAKentry));
233 } /* qpak_entry_swap */
234
235
236 static int qpak_load_entries(const char *name, int forWriting, QPAKinfo *info)
237 {
238     void *fh = NULL;
239     PHYSFS_uint32 fileCount;
240     QPAKentry *entry;
241
242     BAIL_IF_MACRO(!qpak_open(name, forWriting, &fh, &fileCount), NULL, 0);
243     info->entryCount = fileCount;
244     info->entries = (QPAKentry*) allocator.Malloc(sizeof(QPAKentry)*fileCount);
245     if (info->entries == NULL)
246     {
247         __PHYSFS_platformClose(fh);
248         BAIL_MACRO(ERR_OUT_OF_MEMORY, 0);
249     } /* if */
250
251     for (entry = info->entries; fileCount > 0; fileCount--, entry++)
252     {
253         PHYSFS_uint32 loc;
254
255         if (__PHYSFS_platformRead(fh,&entry->name,sizeof(entry->name),1) != 1)
256         {
257             __PHYSFS_platformClose(fh);
258             return(0);
259         } /* if */
260
261         if (__PHYSFS_platformRead(fh,&loc,sizeof(loc),1) != 1)
262         {
263             __PHYSFS_platformClose(fh);
264             return(0);
265         } /* if */
266
267         if (__PHYSFS_platformRead(fh,&entry->size,sizeof(entry->size),1) != 1)
268         {
269             __PHYSFS_platformClose(fh);
270             return(0);
271         } /* if */
272
273         entry->size = PHYSFS_swapULE32(entry->size);
274         entry->startPos = PHYSFS_swapULE32(loc);
275     } /* for */
276
277     __PHYSFS_platformClose(fh);
278
279     __PHYSFS_sort(info->entries, info->entryCount,
280                   qpak_entry_cmp, qpak_entry_swap);
281     return(1);
282 } /* qpak_load_entries */
283
284
285 static void *QPAK_openArchive(const char *name, int forWriting)
286 {
287     QPAKinfo *info = (QPAKinfo *) allocator.Malloc(sizeof (QPAKinfo));
288     PHYSFS_sint64 modtime = __PHYSFS_platformGetLastModTime(name);
289
290     BAIL_IF_MACRO(info == NULL, ERR_OUT_OF_MEMORY, NULL);
291     memset(info, '\0', sizeof (QPAKinfo));
292
293     info->filename = (char *) allocator.Malloc(strlen(name) + 1);
294     if (info->filename == NULL)
295     {
296         __PHYSFS_setError(ERR_OUT_OF_MEMORY);
297         goto QPAK_openArchive_failed;
298     } /* if */
299
300     if (!qpak_load_entries(name, forWriting, info))
301         goto QPAK_openArchive_failed;
302
303     strcpy(info->filename, name);
304     info->last_mod_time = modtime;
305     return(info);
306
307 QPAK_openArchive_failed:
308     if (info != NULL)
309     {
310         if (info->filename != NULL)
311             allocator.Free(info->filename);
312         if (info->entries != NULL)
313             allocator.Free(info->entries);
314         allocator.Free(info);
315     } /* if */
316
317     return(NULL);
318 } /* QPAK_openArchive */
319
320
321 static PHYSFS_sint32 qpak_find_start_of_dir(QPAKinfo *info, const char *path,
322                                             int stop_on_first_find)
323 {
324     PHYSFS_sint32 lo = 0;
325     PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
326     PHYSFS_sint32 middle;
327     PHYSFS_uint32 dlen = strlen(path);
328     PHYSFS_sint32 retval = -1;
329     const char *name;
330     int rc;
331
332     if (*path == '\0')  /* root dir? */
333         return(0);
334
335     if ((dlen > 0) && (path[dlen - 1] == '/')) /* ignore trailing slash. */
336         dlen--;
337
338     while (lo <= hi)
339     {
340         middle = lo + ((hi - lo) / 2);
341         name = info->entries[middle].name;
342         rc = QPAK_strncmp(path, name, dlen);
343         if (rc == 0)
344         {
345             char ch = name[dlen];
346             if (ch < '/') /* make sure this isn't just a substr match. */
347                 rc = -1;
348             else if (ch > '/')
349                 rc = 1;
350             else 
351             {
352                 if (stop_on_first_find) /* Just checking dir's existance? */
353                     return(middle);
354
355                 if (name[dlen + 1] == '\0') /* Skip initial dir entry. */
356                     return(middle + 1);
357
358                 /* there might be more entries earlier in the list. */
359                 retval = middle;
360                 hi = middle - 1;
361             } /* else */
362         } /* if */
363
364         if (rc > 0)
365             lo = middle + 1;
366         else
367             hi = middle - 1;
368     } /* while */
369
370     return(retval);
371 } /* qpak_find_start_of_dir */
372
373
374 /*
375  * Moved to seperate function so we can use alloca then immediately throw
376  *  away the allocated stack space...
377  */
378 static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
379                            const char *odir, const char *str, PHYSFS_sint32 ln)
380 {
381     char *newstr = __PHYSFS_smallAlloc(ln + 1);
382     if (newstr == NULL)
383         return;
384
385     memcpy(newstr, str, ln);
386     newstr[ln] = '\0';
387     cb(callbackdata, odir, newstr);
388     __PHYSFS_smallFree(newstr);
389 } /* doEnumCallback */
390
391
392 static void QPAK_enumerateFiles(dvoid *opaque, const char *dname,
393                                 int omitSymLinks, PHYSFS_EnumFilesCallback cb,
394                                 const char *origdir, void *callbackdata)
395 {
396     QPAKinfo *info = ((QPAKinfo *) opaque);
397     PHYSFS_sint32 dlen, dlen_inc, max, i;
398
399     i = qpak_find_start_of_dir(info, dname, 0);
400     if (i == -1)  /* no such directory. */
401         return;
402
403     dlen = strlen(dname);
404     if ((dlen > 0) && (dname[dlen - 1] == '/')) /* ignore trailing slash. */
405         dlen--;
406
407     dlen_inc = ((dlen > 0) ? 1 : 0) + dlen;
408     max = (PHYSFS_sint32) info->entryCount;
409     while (i < max)
410     {
411         char *add;
412         char *ptr;
413         PHYSFS_sint32 ln;
414         char *e = info->entries[i].name;
415         if ((dlen) && ((QPAK_strncmp(e, dname, dlen)) || (e[dlen] != '/')))
416             break;  /* past end of this dir; we're done. */
417
418         add = e + dlen_inc;
419         ptr = strchr(add, '/');
420         ln = (PHYSFS_sint32) ((ptr) ? ptr-add : strlen(add));
421         doEnumCallback(cb, callbackdata, origdir, add, ln);
422         ln += dlen_inc;  /* point past entry to children... */
423
424         /* increment counter and skip children of subdirs... */
425         while ((++i < max) && (ptr != NULL))
426         {
427             char *e_new = info->entries[i].name;
428             if ((QPAK_strncmp(e, e_new, ln) != 0) || (e_new[ln] != '/'))
429                 break;
430         } /* while */
431     } /* while */
432 } /* QPAK_enumerateFiles */
433
434
435 /*
436  * This will find the QPAKentry associated with a path in platform-independent
437  *  notation. Directories don't have QPAKentries associated with them, but 
438  *  (*isDir) will be set to non-zero if a dir was hit.
439  */
440 static QPAKentry *qpak_find_entry(QPAKinfo *info, const char *path, int *isDir)
441 {
442     QPAKentry *a = info->entries;
443     PHYSFS_sint32 pathlen = strlen(path);
444     PHYSFS_sint32 lo = 0;
445     PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
446     PHYSFS_sint32 middle;
447     const char *thispath = NULL;
448     int rc;
449
450     while (lo <= hi)
451     {
452         middle = lo + ((hi - lo) / 2);
453         thispath = a[middle].name;
454         rc = QPAK_strncmp(path, thispath, pathlen);
455
456         if (rc > 0)
457             lo = middle + 1;
458
459         else if (rc < 0)
460             hi = middle - 1;
461
462         else /* substring match...might be dir or entry or nothing. */
463         {
464             if (isDir != NULL)
465             {
466                 *isDir = (thispath[pathlen] == '/');
467                 if (*isDir)
468                     return(NULL);
469             } /* if */
470
471             if (thispath[pathlen] == '\0') /* found entry? */
472                 return(&a[middle]);
473             else
474                 hi = middle - 1;  /* adjust search params, try again. */
475         } /* if */
476     } /* while */
477
478     if (isDir != NULL)
479         *isDir = 0;
480
481     BAIL_MACRO(ERR_NO_SUCH_FILE, NULL);
482 } /* qpak_find_entry */
483
484
485 static int QPAK_exists(dvoid *opaque, const char *name)
486 {
487     int isDir;    
488     QPAKinfo *info = (QPAKinfo *) opaque;
489     QPAKentry *entry = qpak_find_entry(info, name, &isDir);
490     return((entry != NULL) || (isDir));
491 } /* QPAK_exists */
492
493
494 static int QPAK_isDirectory(dvoid *opaque, const char *name, int *fileExists)
495 {
496     QPAKinfo *info = (QPAKinfo *) opaque;
497     int isDir;
498     QPAKentry *entry = qpak_find_entry(info, name, &isDir);
499
500     *fileExists = ((isDir) || (entry != NULL));
501     if (isDir)
502         return(1); /* definitely a dir. */
503
504     BAIL_MACRO(ERR_NO_SUCH_FILE, 0);
505 } /* QPAK_isDirectory */
506
507
508 static int QPAK_isSymLink(dvoid *opaque, const char *name, int *fileExists)
509 {
510     *fileExists = QPAK_exists(opaque, name);
511     return(0);  /* never symlinks in a quake pak. */
512 } /* QPAK_isSymLink */
513
514
515 static PHYSFS_sint64 QPAK_getLastModTime(dvoid *opaque,
516                                         const char *name,
517                                         int *fileExists)
518 {
519     int isDir;
520     QPAKinfo *info = ((QPAKinfo *) opaque);
521     PHYSFS_sint64 retval = -1;
522     QPAKentry *entry = qpak_find_entry(info, name, &isDir);
523
524     *fileExists = ((isDir) || (entry != NULL));
525     if (*fileExists)  /* use time of QPAK itself in the physical filesystem. */
526         retval = info->last_mod_time;
527
528     return(retval);
529 } /* QPAK_getLastModTime */
530
531
532 static fvoid *QPAK_openRead(dvoid *opaque, const char *fnm, int *fileExists)
533 {
534     QPAKinfo *info = ((QPAKinfo *) opaque);
535     QPAKfileinfo *finfo;
536     QPAKentry *entry;
537     int isDir;
538
539     entry = qpak_find_entry(info, fnm, &isDir);
540     *fileExists = ((entry != NULL) || (isDir));
541     BAIL_IF_MACRO(isDir, ERR_NOT_A_FILE, NULL);
542     BAIL_IF_MACRO(entry == NULL, ERR_NO_SUCH_FILE, NULL);
543
544     finfo = (QPAKfileinfo *) allocator.Malloc(sizeof (QPAKfileinfo));
545     BAIL_IF_MACRO(finfo == NULL, ERR_OUT_OF_MEMORY, NULL);
546
547     finfo->handle = __PHYSFS_platformOpenRead(info->filename);
548     if ( (finfo->handle == NULL) ||
549          (!__PHYSFS_platformSeek(finfo->handle, entry->startPos)) )
550     {
551         allocator.Free(finfo);
552         return(NULL);
553     } /* if */
554
555     finfo->curPos = 0;
556     finfo->entry = entry;
557     return(finfo);
558 } /* QPAK_openRead */
559
560
561 static fvoid *QPAK_openWrite(dvoid *opaque, const char *name)
562 {
563     BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
564 } /* QPAK_openWrite */
565
566
567 static fvoid *QPAK_openAppend(dvoid *opaque, const char *name)
568 {
569     BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
570 } /* QPAK_openAppend */
571
572
573 static int QPAK_remove(dvoid *opaque, const char *name)
574 {
575     BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
576 } /* QPAK_remove */
577
578
579 static int QPAK_mkdir(dvoid *opaque, const char *name)
580 {
581     BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
582 } /* QPAK_mkdir */
583
584
585 const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_QPAK =
586 {
587     "PAK",
588     QPAK_ARCHIVE_DESCRIPTION,
589     "Ryan C. Gordon <icculus@icculus.org>",
590     "http://icculus.org/physfs/",
591 };
592
593
594 const PHYSFS_Archiver __PHYSFS_Archiver_QPAK =
595 {
596     &__PHYSFS_ArchiveInfo_QPAK,
597     QPAK_isArchive,          /* isArchive() method      */
598     QPAK_openArchive,        /* openArchive() method    */
599     QPAK_enumerateFiles,     /* enumerateFiles() method */
600     QPAK_exists,             /* exists() method         */
601     QPAK_isDirectory,        /* isDirectory() method    */
602     QPAK_isSymLink,          /* isSymLink() method      */
603     QPAK_getLastModTime,     /* getLastModTime() method */
604     QPAK_openRead,           /* openRead() method       */
605     QPAK_openWrite,          /* openWrite() method      */
606     QPAK_openAppend,         /* openAppend() method     */
607     QPAK_remove,             /* remove() method         */
608     QPAK_mkdir,              /* mkdir() method          */
609     QPAK_dirClose,           /* dirClose() method       */
610     QPAK_read,               /* read() method           */
611     QPAK_write,              /* write() method          */
612     QPAK_eof,                /* eof() method            */
613     QPAK_tell,               /* tell() method           */
614     QPAK_seek,               /* seek() method           */
615     QPAK_fileLength,         /* fileLength() method     */
616     QPAK_fileClose           /* fileClose() method      */
617 };
618
619 #endif  /* defined PHYSFS_SUPPORTS_QPAK */
620
621 /* end of qpak.c ... */
622