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