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