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