]> git.xonotic.org Git - xonotic/gmqcc.git/blob - pak.c
Some things. Fix testsuite as well. One test will fail (inexact).
[xonotic/gmqcc.git] / pak.c
1 /*
2  * Copyright (C) 2013, 2014
3  *     Dale Weiler
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <string.h>
24 #include <stdlib.h>
25
26 #include "gmqcc.h"
27
28 /*
29  * The PAK format uses a FOURCC concept for storing the magic ident within
30  * the header as a uint32_t.
31  */
32 #define PAK_FOURCC ((uint32_t)(((uint8_t)'P'|((uint8_t)'A'<<8)|((uint8_t)'C'<<16)|((uint8_t)'K'<<24))))
33
34 typedef struct {
35     uint32_t magic;  /* "PACK" */
36
37     /*
38      * Offset to first directory entry in PAK file.  It's often
39      * best to store the directories at the end of the file opposed
40      * to the front, since it allows easy insertion without having
41      * to load the entire file into memory again.
42      */
43     uint32_t diroff;
44     uint32_t dirlen;
45 } pak_header_t;
46
47 /*
48  * A directory, is sort of a "file entry".  The concept of
49  * a directory in Quake world is a "file entry/record". This
50  * describes a file (with directories/nested ones too in it's
51  * file name).  Hence it can be a file, file with directory, or
52  * file with directories.
53  */
54 typedef struct {
55     char     name[56];
56     uint32_t pos;
57     uint32_t len;
58 } pak_directory_t;
59
60 /*
61  * Used to get the next token from a string, where the
62  * strings themselfs are seperated by chracters from
63  * `sep`.  This is essentially strsep.
64  */
65 static char *pak_tree_sep(char **str, const char *sep) {
66     char *beg = *str;
67     char *end;
68
69     if (!beg)
70         return NULL;
71
72     if (*(end = beg + strcspn(beg, sep)))
73         * end++ = '\0'; /* null terminate */
74     else
75           end   = 0;
76
77     *str = end;
78     return beg;
79 }
80
81 /*
82  * When given a string like "a/b/c/d/e/file"
83  * this function will handle the creation of
84  * the directory structure, included nested
85  * directories.
86  */
87 static void pak_tree_build(const char *entry) {
88     char *directory;
89     char *elements[28];
90     char *pathsplit;
91     char *token;
92
93     size_t itr;
94     size_t jtr;
95
96     pathsplit = (char *)mem_a(56);
97     directory = (char *)mem_a(56);
98
99     memset(pathsplit, 0, 56);
100
101     util_strncpy(directory, entry, 56);
102     for (itr = 0; (token = pak_tree_sep(&directory, "/")) != NULL; itr++) {
103         elements[itr] = token;
104     }
105
106     for (jtr = 0; jtr < itr - 1; jtr++) {
107         util_strcat(pathsplit, elements[jtr]);
108         util_strcat(pathsplit, "/");
109
110         if (fs_dir_make(pathsplit)) {
111             mem_d(pathsplit);
112             mem_d(directory);
113
114             /* TODO: undo on fail */
115
116             return;
117         }
118     }
119
120     mem_d(pathsplit);
121     mem_d(directory);
122 }
123
124 typedef struct {
125     pak_directory_t *directories;
126     pak_header_t     header;
127     fs_file_t       *handle;
128     bool             insert;
129 } pak_file_t;
130
131 static pak_file_t *pak_open_read(const char *file) {
132     pak_file_t *pak;
133     size_t      itr;
134
135     if (!(pak = (pak_file_t*)mem_a(sizeof(pak_file_t))))
136         return NULL;
137
138     if (!(pak->handle = fs_file_open(file, "rb"))) {
139         mem_d(pak);
140         return NULL;
141     }
142
143     pak->directories = NULL;
144     pak->insert      = false; /* read doesn't allow insert */
145
146     memset         (&pak->header, 0, sizeof(pak_header_t));
147     fs_file_read   (&pak->header,    sizeof(pak_header_t), 1, pak->handle);
148
149     util_endianswap(&pak->header.magic,  1, sizeof(pak->header.magic));
150     util_endianswap(&pak->header.diroff, 1, sizeof(pak->header.diroff));
151     util_endianswap(&pak->header.dirlen, 1, sizeof(pak->header.dirlen));
152
153     /*
154      * Every PAK file has "PACK" stored as FOURCC data in the
155      * header.  If this data cannot compare (as checked here), it's
156      * probably not a PAK file.
157      */
158     if (pak->header.magic != PAK_FOURCC) {
159         fs_file_close(pak->handle);
160         mem_d        (pak);
161         return NULL;
162     }
163
164     /*
165      * Time to read in the directory handles and prepare the directories
166      * vector.  We're going to be reading some the file inwards soon.
167      */
168     fs_file_seek(pak->handle, pak->header.diroff, FS_FILE_SEEK_SET);
169
170     /*
171      * Read in all directories from the PAK file. These are considered
172      * to be the "file entries".
173      */
174     for (itr = 0; itr < pak->header.dirlen / 64; itr++) {
175         pak_directory_t dir;
176         fs_file_read   (&dir,    sizeof(pak_directory_t), 1, pak->handle);
177
178         /* Don't translate name - it's just an array of bytes. */
179         util_endianswap(&dir.pos, 1, sizeof(dir.pos));
180         util_endianswap(&dir.len, 1, sizeof(dir.len));
181
182         vec_push(pak->directories, dir);
183     }
184     return pak;
185 }
186
187 static pak_file_t *pak_open_write(const char *file) {
188     pak_file_t *pak;
189
190     if (!(pak = (pak_file_t*)mem_a(sizeof(pak_file_t))))
191         return NULL;
192
193     /*
194      * Generate the required directory structure / tree for
195      * writing this PAK file too.
196      */
197     pak_tree_build(file);
198
199     if (!(pak->handle = fs_file_open(file, "wb"))) {
200         /*
201          * The directory tree that was created, needs to be
202          * removed entierly if we failed to open a file.
203          */
204         /* TODO backup directory clean */
205
206         mem_d(pak);
207         return NULL;
208     }
209
210     memset(&(pak->header), 0, sizeof(pak_header_t));
211
212     /*
213      * We're in "insert" mode, we need to do things like header
214      * "patching" and writing the directories at the end of the
215      * file.
216      */
217     pak->insert       = true;
218     pak->header.magic = PAK_FOURCC;
219
220     /* on BE systems we need to swap the byte order of the FOURCC */
221     util_endianswap(&pak->header.magic, 1, sizeof(uint32_t));
222
223     /*
224      * We need to write out the header since files will be wrote out to
225      * this even with directory entries, and that not wrote.  The header
226      * will need to be patched in later with a file_seek, and overwrite,
227      * we could use offsets and other trickery.  This is just easier.
228      */
229     fs_file_write(&(pak->header), sizeof(pak_header_t), 1, pak->handle);
230
231     return pak;
232 }
233
234 static pak_file_t *pak_open(const char *file, const char *mode) {
235     if (!file || !mode)
236         return NULL;
237
238     switch (*mode) {
239         case 'r': return pak_open_read (file);
240         case 'w': return pak_open_write(file);
241     }
242
243     return NULL;
244 }
245
246 static bool pak_exists(pak_file_t *pak, const char *file, pak_directory_t **dir) {
247     size_t itr;
248
249     if (!pak || !file)
250         return false;
251
252     for (itr = 0; itr < vec_size(pak->directories); itr++) {
253         if (!strcmp(pak->directories[itr].name, file)) {
254             /*
255              * Store back a pointer to the directory that matches
256              * the request if requested (NULL is not allowed).
257              */
258             if (dir) {
259                 *dir = &(pak->directories[itr]);
260             }
261             return true;
262         }
263     }
264
265     return false;
266 }
267
268 /*
269  * Extraction abilities.  These work as you expect them to.
270  */
271 static bool pak_extract_one(pak_file_t *pak, const char *file, const char *outdir) {
272     pak_directory_t *dir   = NULL;
273     unsigned char   *dat   = NULL;
274     char            *local = NULL;
275     fs_file_t       *out   = NULL;
276
277     if (!pak_exists(pak, file, &dir)) {
278         return false;
279     }
280
281     if (!(dat = (unsigned char *)mem_a(dir->len)))
282         goto err;
283
284     /*
285      * Generate the directory structure / tree that will be required
286      * to store the extracted file.
287      */
288     pak_tree_build(file);
289
290     /* TODO portable path seperators */
291     util_asprintf(&local, "%s/%s", outdir, file);
292
293     /*
294      * Now create the file, if this operation fails.  Then abort
295      * It shouldn't fail though.
296      */
297     if (!(out = fs_file_open(local, "wb")))
298         goto err;
299
300     /* free memory for directory string */
301     mem_d(local);
302
303     /* read */
304     if (fs_file_seek (pak->handle, dir->pos, FS_FILE_SEEK_SET) != 0)
305         goto err;
306
307     fs_file_read (dat, 1, dir->len, pak->handle);
308     fs_file_write(dat, 1, dir->len, out);
309     fs_file_close(out);
310
311     mem_d(dat);
312     return true;
313
314 err:
315     if (dat) mem_d(dat);
316     if (out) fs_file_close(out);
317     return false;
318 }
319
320 static bool pak_extract_all(pak_file_t *pak, const char *dir) {
321     size_t itr;
322
323     if (!fs_dir_make(dir))
324         return false;
325
326     for (itr = 0; itr < vec_size(pak->directories); itr++) {
327         if (!pak_extract_one(pak, pak->directories[itr].name, dir))
328             return false;
329     }
330
331     return true;
332 }
333
334 /*
335  * Insertion functions (the opposite of extraction).  Yes for generating
336  * PAKs.
337  */
338 static bool pak_insert_one(pak_file_t *pak, const char *file) {
339     pak_directory_t dir;
340     unsigned char  *dat;
341     long            len;
342     fs_file_t      *fp;
343
344     /*
345      * We don't allow insertion on files that already exist within the
346      * pak file.  Weird shit can happen if we allow that ;). We also
347      * don't allow insertion if the pak isn't opened in write mode.
348      */
349     if (!pak || !file || !pak->insert || pak_exists(pak, file, NULL))
350         return false;
351
352     if (!(fp = fs_file_open(file, "rb")))
353         return false;
354
355     /*
356      * Calculate the total file length, since it will be wrote to
357      * the directory entry, and the actual contents of the file
358      * to the PAK file itself.
359      */
360     if (fs_file_seek(fp, 0, FS_FILE_SEEK_END) != 0 || ((len = fs_file_tell(fp)) < 0))
361         goto err;
362     if (fs_file_seek(fp, 0, FS_FILE_SEEK_SET) != 0)
363         goto err;
364
365     dir.len = len;
366     dir.pos = fs_file_tell(pak->handle);
367
368     /*
369      * We're limited to 56 bytes for a file name string, that INCLUDES
370      * the directory and '/' seperators.
371      */
372     if (strlen(file) >= 56)
373         goto err;
374
375     util_strncpy(dir.name, file, strlen(file));
376
377     /*
378      * Allocate some memory for loading in the data that will be
379      * redirected into the PAK file.
380      */
381     if (!(dat = (unsigned char *)mem_a(dir.len)))
382         goto err;
383
384     fs_file_read (dat, dir.len, 1, fp);
385     fs_file_close(fp);
386     fs_file_write(dat, dir.len, 1, pak->handle);
387
388     /*
389      * Now add the directory to the directories vector, so pak_close
390      * can actually write it.
391      */
392     vec_push(pak->directories, dir);
393
394     return true;
395
396 err:
397     fs_file_close(fp);
398     return false;
399 }
400
401 /*
402  * Like pak_insert_one, except this collects files in all directories
403  * from a root directory, and inserts them all.
404  */
405 #if 0
406 static bool pak_insert_all(pak_file_t *pak, const char *dir) {
407     DIR           *dp;
408     struct dirent *dirp;
409
410     if (!(pak->insert))
411         return false;
412
413     if (!(dp = fs_dir_open(dir)))
414         return false;
415
416     while ((dirp = fs_dir_read(dp))) {
417         if (!(pak_insert_one(pak, dirp->d_name))) {
418             fs_dir_close(dp);
419             return false;
420         }
421     }
422
423     fs_dir_close(dp);
424     return true;
425 }
426 #endif /*!if 0 renable when ready to use */
427
428 static bool pak_close(pak_file_t *pak) {
429     size_t itr;
430     long   tell;
431
432     if (!pak)
433         return false;
434
435     /*
436      * In insert mode we need to patch the header, and write
437      * our directory entries at the end of the file.
438      */
439     if (pak->insert) {
440         if ((tell = fs_file_tell(pak->handle)) != 0)
441             goto err;
442
443         pak->header.dirlen = vec_size(pak->directories) * 64;
444         pak->header.diroff = tell;
445
446         /* patch header */
447         if (fs_file_seek (pak->handle, 0, FS_FILE_SEEK_SET) != 0)
448             goto err;
449
450         fs_file_write(&(pak->header), sizeof(pak_header_t), 1, pak->handle);
451
452         /* write directories */
453         if (fs_file_seek (pak->handle, pak->header.diroff, FS_FILE_SEEK_SET) != 0)
454             goto err;
455
456         for (itr = 0; itr < vec_size(pak->directories); itr++)
457             fs_file_write(&(pak->directories[itr]), sizeof(pak_directory_t), 1, pak->handle);
458     }
459
460     vec_free     (pak->directories);
461     fs_file_close(pak->handle);
462     mem_d        (pak);
463
464     return true;
465
466 err:
467     vec_free     (pak->directories);
468     fs_file_close(pak->handle);
469     mem_d        (pak);
470
471     return false;
472 }
473
474 /*
475  * Fancy GCC-like LONG parsing allows things like --opt=param with
476  * assignment operator.  This is used for redirecting stdout/stderr
477  * console to specific files of your choice.
478  */
479 static bool parsecmd(const char *optname, int *argc_, char ***argv_, char **out, int ds, bool split) {
480     int  argc   = *argc_;
481     char **argv = *argv_;
482
483     size_t len = strlen(optname);
484
485     if (strncmp(argv[0]+ds, optname, len))
486         return false;
487
488     /* it's --optname, check how the parameter is supplied */
489     if (argv[0][ds+len] == '=') {
490         *out = argv[0]+ds+len+1;
491         return true;
492     }
493
494     if (!split || argc < ds) /* no parameter was provided, or only single-arg form accepted */
495         return false;
496
497     /* using --opt param */
498     *out = argv[1];
499     --*argc_;
500     ++*argv_;
501     return true;
502 }
503
504 #include <stdio.h>
505 int main(int argc, char **argv) {
506     bool          extract   = true;
507     char         *redirout  = (char*)stdout;
508     char         *redirerr  = (char*)stderr;
509     char         *file      = NULL;
510     char        **files     = NULL;
511     pak_file_t   *pak       = NULL;
512     size_t        iter      = 0;
513
514     con_init();
515
516     /*
517      * Command line option parsing commences now We only need to support
518      * a few things in the test suite.
519      */
520     while (argc > 1) {
521         ++argv;
522         --argc;
523
524         if (argv[0][0] == '-') {
525             if (parsecmd("redirout",  &argc, &argv, &redirout,  1, false))
526                 continue;
527             if (parsecmd("redirerr",  &argc, &argv, &redirerr,  1, false))
528                 continue;
529             if (parsecmd("file",      &argc, &argv, &file,      1, false))
530                 continue;
531
532             con_change(redirout, redirerr);
533
534             switch (argv[0][1]) {
535                 case 'e': extract = true;  continue;
536                 case 'c': extract = false; continue;
537             }
538
539             if (!strcmp(argv[0]+1, "debug")) {
540                 OPTS_OPTION_BOOL(OPTION_DEBUG) = true;
541                 continue;
542             }
543             if (!strcmp(argv[0]+1, "memchk")) {
544                 OPTS_OPTION_BOOL(OPTION_MEMCHK) = true;
545                 continue;
546             }
547             if (!strcmp(argv[0]+1, "nocolor")) {
548                 con_color(0);
549                 continue;
550             }
551         }
552
553         vec_push(files, argv[0]);
554     }
555     con_change(redirout, redirerr);
556
557
558     if (!file) {
559         con_err("-file must be specified for output/input PAK file\n");
560         vec_free(files);
561         return EXIT_FAILURE;
562     }
563
564     if (extract) {
565         if (!(pak = pak_open(file, "r"))) {
566             con_err("failed to open PAK file %s\n", file);
567             vec_free(files);
568             return EXIT_FAILURE;
569         }
570
571         if (!pak_extract_all(pak, "./")) {
572             con_err("failed to extract PAK %s (files may be missing)\n", file);
573             pak_close(pak);
574             vec_free(files);
575             return EXIT_FAILURE;
576         }
577
578         /* not possible */
579         pak_close(pak);
580         vec_free(files);
581         stat_info();
582
583         return EXIT_SUCCESS;
584     }
585
586     if (!(pak = pak_open(file, "w"))) {
587         con_err("failed to open PAK %s for writing\n", file);
588         vec_free(files);
589         return EXIT_FAILURE;
590     }
591
592     for (iter = 0; iter < vec_size(files); iter++) {
593         if (!(pak_insert_one(pak, files[iter]))) {
594             con_err("failed inserting %s for PAK %s\n", files[iter], file);
595             pak_close(pak);
596             vec_free(files);
597             return EXIT_FAILURE;
598         }
599     }
600
601     /* not possible */
602     pak_close(pak);
603     vec_free(files);
604
605     stat_info();
606     return EXIT_SUCCESS;
607 }