Upload 2.0.2
[physicsfs] / 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     if (one != two)
221     {
222         const QPAKentry *a = (const QPAKentry *) _a;
223         return(QPAK_strcmp(a[one].name, a[two].name));
224     } /* if */
225
226     return 0;
227 } /* qpak_entry_cmp */
228
229
230 static void qpak_entry_swap(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
231 {
232     if (one != two)
233     {
234         QPAKentry tmp;
235         QPAKentry *first = &(((QPAKentry *) _a)[one]);
236         QPAKentry *second = &(((QPAKentry *) _a)[two]);
237         memcpy(&tmp, first, sizeof (QPAKentry));
238         memcpy(first, second, sizeof (QPAKentry));
239         memcpy(second, &tmp, sizeof (QPAKentry));
240     } /* if */
241 } /* qpak_entry_swap */
242
243
244 static int qpak_load_entries(const char *name, int forWriting, QPAKinfo *info)
245 {
246     void *fh = NULL;
247     PHYSFS_uint32 fileCount;
248     QPAKentry *entry;
249
250     BAIL_IF_MACRO(!qpak_open(name, forWriting, &fh, &fileCount), NULL, 0);
251     info->entryCount = fileCount;
252     info->entries = (QPAKentry*) allocator.Malloc(sizeof(QPAKentry)*fileCount);
253     if (info->entries == NULL)
254     {
255         __PHYSFS_platformClose(fh);
256         BAIL_MACRO(ERR_OUT_OF_MEMORY, 0);
257     } /* if */
258
259     for (entry = info->entries; fileCount > 0; fileCount--, entry++)
260     {
261         PHYSFS_uint32 loc;
262
263         if (__PHYSFS_platformRead(fh,&entry->name,sizeof(entry->name),1) != 1)
264         {
265             __PHYSFS_platformClose(fh);
266             return(0);
267         } /* if */
268
269         if (__PHYSFS_platformRead(fh,&loc,sizeof(loc),1) != 1)
270         {
271             __PHYSFS_platformClose(fh);
272             return(0);
273         } /* if */
274
275         if (__PHYSFS_platformRead(fh,&entry->size,sizeof(entry->size),1) != 1)
276         {
277             __PHYSFS_platformClose(fh);
278             return(0);
279         } /* if */
280
281         entry->size = PHYSFS_swapULE32(entry->size);
282         entry->startPos = PHYSFS_swapULE32(loc);
283     } /* for */
284
285     __PHYSFS_platformClose(fh);
286
287     __PHYSFS_sort(info->entries, info->entryCount,
288                   qpak_entry_cmp, qpak_entry_swap);
289     return(1);
290 } /* qpak_load_entries */
291
292
293 static void *QPAK_openArchive(const char *name, int forWriting)
294 {
295     QPAKinfo *info = (QPAKinfo *) allocator.Malloc(sizeof (QPAKinfo));
296     PHYSFS_sint64 modtime = __PHYSFS_platformGetLastModTime(name);
297
298     BAIL_IF_MACRO(info == NULL, ERR_OUT_OF_MEMORY, NULL);
299     memset(info, '\0', sizeof (QPAKinfo));
300
301     info->filename = (char *) allocator.Malloc(strlen(name) + 1);
302     if (info->filename == NULL)
303     {
304         __PHYSFS_setError(ERR_OUT_OF_MEMORY);
305         goto QPAK_openArchive_failed;
306     } /* if */
307
308     if (!qpak_load_entries(name, forWriting, info))
309         goto QPAK_openArchive_failed;
310
311     strcpy(info->filename, name);
312     info->last_mod_time = modtime;
313     return(info);
314
315 QPAK_openArchive_failed:
316     if (info != NULL)
317     {
318         if (info->filename != NULL)
319             allocator.Free(info->filename);
320         if (info->entries != NULL)
321             allocator.Free(info->entries);
322         allocator.Free(info);
323     } /* if */
324
325     return(NULL);
326 } /* QPAK_openArchive */
327
328
329 static PHYSFS_sint32 qpak_find_start_of_dir(QPAKinfo *info, const char *path,
330                                             int stop_on_first_find)
331 {
332     PHYSFS_sint32 lo = 0;
333     PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
334     PHYSFS_sint32 middle;
335     PHYSFS_uint32 dlen = strlen(path);
336     PHYSFS_sint32 retval = -1;
337     const char *name;
338     int rc;
339
340     if (*path == '\0')  /* root dir? */
341         return(0);
342
343     if ((dlen > 0) && (path[dlen - 1] == '/')) /* ignore trailing slash. */
344         dlen--;
345
346     while (lo <= hi)
347     {
348         middle = lo + ((hi - lo) / 2);
349         name = info->entries[middle].name;
350         rc = QPAK_strncmp(path, name, dlen);
351         if (rc == 0)
352         {
353             char ch = name[dlen];
354             if (ch < '/') /* make sure this isn't just a substr match. */
355                 rc = -1;
356             else if (ch > '/')
357                 rc = 1;
358             else 
359             {
360                 if (stop_on_first_find) /* Just checking dir's existance? */
361                     return(middle);
362
363                 if (name[dlen + 1] == '\0') /* Skip initial dir entry. */
364                     return(middle + 1);
365
366                 /* there might be more entries earlier in the list. */
367                 retval = middle;
368                 hi = middle - 1;
369             } /* else */
370         } /* if */
371
372         if (rc > 0)
373             lo = middle + 1;
374         else
375             hi = middle - 1;
376     } /* while */
377
378     return(retval);
379 } /* qpak_find_start_of_dir */
380
381
382 /*
383  * Moved to seperate function so we can use alloca then immediately throw
384  *  away the allocated stack space...
385  */
386 static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
387                            const char *odir, const char *str, PHYSFS_sint32 ln)
388 {
389     char *newstr = __PHYSFS_smallAlloc(ln + 1);
390     if (newstr == NULL)
391         return;
392
393     memcpy(newstr, str, ln);
394     newstr[ln] = '\0';
395     cb(callbackdata, odir, newstr);
396     __PHYSFS_smallFree(newstr);
397 } /* doEnumCallback */
398
399
400 static void QPAK_enumerateFiles(dvoid *opaque, const char *dname,
401                                 int omitSymLinks, PHYSFS_EnumFilesCallback cb,
402                                 const char *origdir, void *callbackdata)
403 {
404     QPAKinfo *info = ((QPAKinfo *) opaque);
405     PHYSFS_sint32 dlen, dlen_inc, max, i;
406
407     i = qpak_find_start_of_dir(info, dname, 0);
408     if (i == -1)  /* no such directory. */
409         return;
410
411     dlen = strlen(dname);
412     if ((dlen > 0) && (dname[dlen - 1] == '/')) /* ignore trailing slash. */
413         dlen--;
414
415     dlen_inc = ((dlen > 0) ? 1 : 0) + dlen;
416     max = (PHYSFS_sint32) info->entryCount;
417     while (i < max)
418     {
419         char *add;
420         char *ptr;
421         PHYSFS_sint32 ln;
422         char *e = info->entries[i].name;
423         if ((dlen) && ((QPAK_strncmp(e, dname, dlen)) || (e[dlen] != '/')))
424             break;  /* past end of this dir; we're done. */
425
426         add = e + dlen_inc;
427         ptr = strchr(add, '/');
428         ln = (PHYSFS_sint32) ((ptr) ? ptr-add : strlen(add));
429         doEnumCallback(cb, callbackdata, origdir, add, ln);
430         ln += dlen_inc;  /* point past entry to children... */
431
432         /* increment counter and skip children of subdirs... */
433         while ((++i < max) && (ptr != NULL))
434         {
435             char *e_new = info->entries[i].name;
436             if ((QPAK_strncmp(e, e_new, ln) != 0) || (e_new[ln] != '/'))
437                 break;
438         } /* while */
439     } /* while */
440 } /* QPAK_enumerateFiles */
441
442
443 /*
444  * This will find the QPAKentry associated with a path in platform-independent
445  *  notation. Directories don't have QPAKentries associated with them, but 
446  *  (*isDir) will be set to non-zero if a dir was hit.
447  */
448 static QPAKentry *qpak_find_entry(QPAKinfo *info, const char *path, int *isDir)
449 {
450     QPAKentry *a = info->entries;
451     PHYSFS_sint32 pathlen = strlen(path);
452     PHYSFS_sint32 lo = 0;
453     PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
454     PHYSFS_sint32 middle;
455     const char *thispath = NULL;
456     int rc;
457
458     while (lo <= hi)
459     {
460         middle = lo + ((hi - lo) / 2);
461         thispath = a[middle].name;
462         rc = QPAK_strncmp(path, thispath, pathlen);
463
464         if (rc > 0)
465             lo = middle + 1;
466
467         else if (rc < 0)
468             hi = middle - 1;
469
470         else /* substring match...might be dir or entry or nothing. */
471         {
472             if (isDir != NULL)
473             {
474                 *isDir = (thispath[pathlen] == '/');
475                 if (*isDir)
476                     return(NULL);
477             } /* if */
478
479             if (thispath[pathlen] == '\0') /* found entry? */
480                 return(&a[middle]);
481             /* adjust search params, try again. */
482             else if (thispath[pathlen] > '/')
483                 hi = middle - 1;
484             else
485                 lo = middle + 1;
486         } /* if */
487     } /* while */
488
489     if (isDir != NULL)
490         *isDir = 0;
491
492     BAIL_MACRO(ERR_NO_SUCH_FILE, NULL);
493 } /* qpak_find_entry */
494
495
496 static int QPAK_exists(dvoid *opaque, const char *name)
497 {
498     int isDir;    
499     QPAKinfo *info = (QPAKinfo *) opaque;
500     QPAKentry *entry = qpak_find_entry(info, name, &isDir);
501     return((entry != NULL) || (isDir));
502 } /* QPAK_exists */
503
504
505 static int QPAK_isDirectory(dvoid *opaque, const char *name, int *fileExists)
506 {
507     QPAKinfo *info = (QPAKinfo *) opaque;
508     int isDir;
509     QPAKentry *entry = qpak_find_entry(info, name, &isDir);
510
511     *fileExists = ((isDir) || (entry != NULL));
512     if (isDir)
513         return(1); /* definitely a dir. */
514
515     BAIL_MACRO(ERR_NO_SUCH_FILE, 0);
516 } /* QPAK_isDirectory */
517
518
519 static int QPAK_isSymLink(dvoid *opaque, const char *name, int *fileExists)
520 {
521     *fileExists = QPAK_exists(opaque, name);
522     return(0);  /* never symlinks in a quake pak. */
523 } /* QPAK_isSymLink */
524
525
526 static PHYSFS_sint64 QPAK_getLastModTime(dvoid *opaque,
527                                         const char *name,
528                                         int *fileExists)
529 {
530     int isDir;
531     QPAKinfo *info = ((QPAKinfo *) opaque);
532     PHYSFS_sint64 retval = -1;
533     QPAKentry *entry = qpak_find_entry(info, name, &isDir);
534
535     *fileExists = ((isDir) || (entry != NULL));
536     if (*fileExists)  /* use time of QPAK itself in the physical filesystem. */
537         retval = info->last_mod_time;
538
539     return(retval);
540 } /* QPAK_getLastModTime */
541
542
543 static fvoid *QPAK_openRead(dvoid *opaque, const char *fnm, int *fileExists)
544 {
545     QPAKinfo *info = ((QPAKinfo *) opaque);
546     QPAKfileinfo *finfo;
547     QPAKentry *entry;
548     int isDir;
549
550     entry = qpak_find_entry(info, fnm, &isDir);
551     *fileExists = ((entry != NULL) || (isDir));
552     BAIL_IF_MACRO(isDir, ERR_NOT_A_FILE, NULL);
553     BAIL_IF_MACRO(entry == NULL, ERR_NO_SUCH_FILE, NULL);
554
555     finfo = (QPAKfileinfo *) allocator.Malloc(sizeof (QPAKfileinfo));
556     BAIL_IF_MACRO(finfo == NULL, ERR_OUT_OF_MEMORY, NULL);
557
558     finfo->handle = __PHYSFS_platformOpenRead(info->filename);
559     if ( (finfo->handle == NULL) ||
560          (!__PHYSFS_platformSeek(finfo->handle, entry->startPos)) )
561     {
562         allocator.Free(finfo);
563         return(NULL);
564     } /* if */
565
566     finfo->curPos = 0;
567     finfo->entry = entry;
568     return(finfo);
569 } /* QPAK_openRead */
570
571
572 static fvoid *QPAK_openWrite(dvoid *opaque, const char *name)
573 {
574     BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
575 } /* QPAK_openWrite */
576
577
578 static fvoid *QPAK_openAppend(dvoid *opaque, const char *name)
579 {
580     BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
581 } /* QPAK_openAppend */
582
583
584 static int QPAK_remove(dvoid *opaque, const char *name)
585 {
586     BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
587 } /* QPAK_remove */
588
589
590 static int QPAK_mkdir(dvoid *opaque, const char *name)
591 {
592     BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
593 } /* QPAK_mkdir */
594
595
596 const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_QPAK =
597 {
598     "PAK",
599     QPAK_ARCHIVE_DESCRIPTION,
600     "Ryan C. Gordon <icculus@icculus.org>",
601     "http://icculus.org/physfs/",
602 };
603
604
605 const PHYSFS_Archiver __PHYSFS_Archiver_QPAK =
606 {
607     &__PHYSFS_ArchiveInfo_QPAK,
608     QPAK_isArchive,          /* isArchive() method      */
609     QPAK_openArchive,        /* openArchive() method    */
610     QPAK_enumerateFiles,     /* enumerateFiles() method */
611     QPAK_exists,             /* exists() method         */
612     QPAK_isDirectory,        /* isDirectory() method    */
613     QPAK_isSymLink,          /* isSymLink() method      */
614     QPAK_getLastModTime,     /* getLastModTime() method */
615     QPAK_openRead,           /* openRead() method       */
616     QPAK_openWrite,          /* openWrite() method      */
617     QPAK_openAppend,         /* openAppend() method     */
618     QPAK_remove,             /* remove() method         */
619     QPAK_mkdir,              /* mkdir() method          */
620     QPAK_dirClose,           /* dirClose() method       */
621     QPAK_read,               /* read() method           */
622     QPAK_write,              /* write() method          */
623     QPAK_eof,                /* eof() method            */
624     QPAK_tell,               /* tell() method           */
625     QPAK_seek,               /* seek() method           */
626     QPAK_fileLength,         /* fileLength() method     */
627     QPAK_fileClose           /* fileClose() method      */
628 };
629
630 #endif  /* defined PHYSFS_SUPPORTS_QPAK */
631
632 /* end of qpak.c ... */
633