]> git.xonotic.org Git - xonotic/gmqcc.git/blob - pak.c
fix typo
[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 <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     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         mem_d(pak);
201         return NULL;
202     }
203
204     memset(&(pak->header), 0, sizeof(pak_header_t));
205
206     /*
207      * We're in "insert" mode, we need to do things like header
208      * "patching" and writing the directories at the end of the
209      * file.
210      */
211     pak->insert       = true;
212     pak->header.magic = PAK_FOURCC;
213
214     /* on BE systems we need to swap the byte order of the FOURCC */
215     util_endianswap(&pak->header.magic, 1, sizeof(uint32_t));
216
217     /*
218      * We need to write out the header since files will be wrote out to
219      * this even with directory entries, and that not wrote.  The header
220      * will need to be patched in later with a file_seek, and overwrite,
221      * we could use offsets and other trickery.  This is just easier.
222      */
223     fs_file_write(&(pak->header), sizeof(pak_header_t), 1, pak->handle);
224
225     return pak;
226 }
227
228 static pak_file_t *pak_open(const char *file, const char *mode) {
229     if (!file || !mode)
230         return NULL;
231
232     switch (*mode) {
233         case 'r': return pak_open_read (file);
234         case 'w': return pak_open_write(file);
235     }
236
237     return NULL;
238 }
239
240 static bool pak_exists(pak_file_t *pak, const char *file, pak_directory_t **dir) {
241     size_t itr;
242
243     if (!pak || !file)
244         return false;
245
246     for (itr = 0; itr < vec_size(pak->directories); itr++) {
247         if (!strcmp(pak->directories[itr].name, file)) {
248             /*
249              * Store back a pointer to the directory that matches
250              * the request if requested (NULL is not allowed).
251              */
252             if (dir) {
253                 *dir = &(pak->directories[itr]);
254             }
255             return true;
256         }
257     }
258
259     return false;
260 }
261
262 /*
263  * Extraction abilities.  These work as you expect them to.
264  */
265 static bool pak_extract_one(pak_file_t *pak, const char *file, const char *outdir) {
266     pak_directory_t *dir   = NULL;
267     unsigned char   *dat   = NULL;
268     char            *local = NULL;
269     FILE            *out;
270
271     if (!pak_exists(pak, file, &dir)) {
272         return false;
273     }
274
275     if (!(dat = (unsigned char *)mem_a(dir->len))) {
276         return false;
277     }
278
279     /*
280      * Generate the directory structure / tree that will be required
281      * to store the extracted file.
282      */
283     pak_tree_build(file);
284
285     /* TODO portable path seperators */
286     util_asprintf(&local, "%s/%s", outdir, file);
287
288     /*
289      * Now create the file, if this operation fails.  Then abort
290      * It shouldn't fail though.
291      */
292     if (!(out = fs_file_open(local, "wb"))) {
293         mem_d(dat);
294         return false;
295     }
296
297     /* free memory for directory string */
298     mem_d(local);
299
300     /* read */
301     fs_file_seek (pak->handle, dir->pos, SEEK_SET);
302     fs_file_read (dat, 1, dir->len, pak->handle);
303
304     /* write */
305     fs_file_write(dat, 1, dir->len, out);
306
307     /* close */
308     fs_file_close(out);
309
310     /* free */
311     mem_d(dat);
312
313     return true;
314 }
315
316 static bool pak_extract_all(pak_file_t *pak, const char *dir) {
317     size_t itr;
318
319     if (!fs_dir_make(dir))
320         return false;
321
322     for (itr = 0; itr < vec_size(pak->directories); itr++) {
323         if (!pak_extract_one(pak, pak->directories[itr].name, dir))
324             return false;
325     }
326
327     return true;
328 }
329
330 /*
331  * Insertion functions (the opposite of extraction).  Yes for generating
332  * PAKs.
333  */
334 static bool pak_insert_one(pak_file_t *pak, const char *file) {
335     pak_directory_t dir;
336     unsigned char  *dat;
337     long            len;
338     FILE           *fp;
339
340     /*
341      * We don't allow insertion on files that already exist within the
342      * pak file.  Weird shit can happen if we allow that ;). We also
343      * don't allow insertion if the pak isn't opened in write mode.
344      */
345     if (!pak || !file || !pak->insert || pak_exists(pak, file, NULL))
346         return false;
347
348     if (!(fp = fs_file_open(file, "rb")))
349         return false;
350
351     /*
352      * Calculate the total file length, since it will be wrote to
353      * the directory entry, and the actual contents of the file
354      * to the PAK file itself.
355      */
356     fs_file_seek(fp, 0, SEEK_END);
357     if ((len = fs_file_tell(fp)) < 0) {
358         fs_file_close(fp);
359         return false;
360     }
361     fs_file_seek(fp, 0, SEEK_SET);
362
363     dir.len = len;
364     dir.pos = fs_file_tell(pak->handle);
365
366     /*
367      * We're limited to 56 bytes for a file name string, that INCLUDES
368      * the directory and '/' seperators.
369      */
370     if (strlen(file) >= 56) {
371         fs_file_close(fp);
372         return false;
373     }
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         fs_file_close(fp);
383         return false;
384     }
385
386     fs_file_read (dat, dir.len, 1, fp);
387     fs_file_close(fp);
388     fs_file_write(dat, dir.len, 1, pak->handle);
389
390     /*
391      * Now add the directory to the directories vector, so pak_close
392      * can actually write it.
393      */
394     vec_push(pak->directories, dir);
395
396     return true;
397 }
398
399 /*
400  * Like pak_insert_one, except this collects files in all directories
401  * from a root directory, and inserts them all.
402  */
403 bool pak_insert_all(pak_file_t *pak, const char *dir) {
404     DIR           *dp;
405     struct dirent *dirp;
406
407     if (!(pak->insert))
408         return false;
409
410     if (!(dp = fs_dir_open(dir)))
411         return false;
412
413     while ((dirp = fs_dir_read(dp))) {
414         if (!(pak_insert_one(pak, dirp->d_name))) {
415             fs_dir_close(dp);
416             return false;
417         }
418     }
419
420     fs_dir_close(dp);
421     return true;
422 }
423
424 static bool pak_close(pak_file_t *pak) {
425     size_t itr;
426
427     if (!pak)
428         return false;
429
430     /*
431      * In insert mode we need to patch the header, and write
432      * our directory entries at the end of the file.
433      */
434     if (pak->insert) {
435         int tell = fs_file_tell(pak->handle);
436         if (tell < 0) {
437             vec_free     (pak->directories);
438             fs_file_close(pak->handle);
439             mem_d        (pak);
440
441             return false;
442         }
443         pak->header.dirlen = vec_size(pak->directories) * 64;
444         pak->header.diroff = tell;
445
446         /* patch header */
447         fs_file_seek (pak->handle, 0, SEEK_SET);
448         fs_file_write(&(pak->header), sizeof(pak_header_t), 1, pak->handle);
449
450         /* write directories */
451         fs_file_seek (pak->handle, pak->header.diroff, SEEK_SET);
452
453         for (itr = 0; itr < vec_size(pak->directories); itr++) {
454             fs_file_write(&(pak->directories[itr]), sizeof(pak_directory_t), 1, pak->handle);
455         }
456     }
457
458     vec_free     (pak->directories);
459     fs_file_close(pak->handle);
460     mem_d        (pak);
461
462     return true;
463 }
464
465 /*
466  * Fancy GCC-like LONG parsing allows things like --opt=param with
467  * assignment operator.  This is used for redirecting stdout/stderr
468  * console to specific files of your choice.
469  */
470 static bool parsecmd(const char *optname, int *argc_, char ***argv_, char **out, int ds, bool split) {
471     int  argc   = *argc_;
472     char **argv = *argv_;
473
474     size_t len = strlen(optname);
475
476     if (strncmp(argv[0]+ds, optname, len))
477         return false;
478
479     /* it's --optname, check how the parameter is supplied */
480     if (argv[0][ds+len] == '=') {
481         *out = argv[0]+ds+len+1;
482         return true;
483     }
484
485     if (!split || argc < ds) /* no parameter was provided, or only single-arg form accepted */
486         return false;
487
488     /* using --opt param */
489     *out = argv[1];
490     --*argc_;
491     ++*argv_;
492     return true;
493 }
494
495 int main(int argc, char **argv) {
496     bool          extract   = true;
497     char         *redirout  = (char*)stdout;
498     char         *redirerr  = (char*)stderr;
499     char         *file      = NULL;
500     char        **files     = NULL;
501     pak_file_t   *pak       = NULL;
502     size_t        iter      = 0;
503
504     con_init();
505
506     /*
507      * Command line option parsing commences now We only need to support
508      * a few things in the test suite.
509      */
510     while (argc > 1) {
511         ++argv;
512         --argc;
513
514         if (argv[0][0] == '-') {
515             if (parsecmd("redirout",  &argc, &argv, &redirout,  1, false))
516                 continue;
517             if (parsecmd("redirerr",  &argc, &argv, &redirerr,  1, false))
518                 continue;
519             if (parsecmd("file",      &argc, &argv, &file,      1, false))
520                 continue;
521
522             con_change(redirout, redirerr);
523
524             switch (argv[0][1]) {
525                 case 'e': extract = true;  continue;
526                 case 'c': extract = false; continue;
527             }
528
529             if (!strcmp(argv[0]+1, "debug")) {
530                 OPTS_OPTION_BOOL(OPTION_DEBUG) = true;
531                 continue;
532             }
533             if (!strcmp(argv[0]+1, "memchk")) {
534                 OPTS_OPTION_BOOL(OPTION_MEMCHK) = true;
535                 continue;
536             }
537             if (!strcmp(argv[0]+1, "nocolor")) {
538                 con_color(0);
539                 continue;
540             }
541         }
542
543         vec_push(files, argv[0]);
544     }
545     con_change(redirout, redirerr);
546
547
548     if (!file) {
549         con_err("-file must be specified for output/input PAK file\n");
550         vec_free(files);
551         return EXIT_FAILURE;
552     }
553
554     if (extract) {
555         if (!(pak = pak_open(file, "r"))) {
556             con_err("failed to open PAK file %s\n", file);
557             vec_free(files);
558             return EXIT_FAILURE;
559         }
560
561         if (!pak_extract_all(pak, "./")) {
562             con_err("failed to extract PAK %s (files may be missing)\n", file);
563             pak_close(pak);
564             vec_free(files);
565             return EXIT_FAILURE;
566         }
567
568         /* not possible */
569         pak_close(pak);
570         vec_free(files);
571         stat_info();
572
573         return EXIT_SUCCESS;
574     }
575
576     if (!(pak = pak_open(file, "w"))) {
577         con_err("failed to open PAK %s for writing\n", file);
578         vec_free(files);
579         return EXIT_FAILURE;
580     }
581
582     for (iter = 0; iter < vec_size(files); iter++) {
583         if (!(pak_insert_one(pak, files[iter]))) {
584             con_err("failed inserting %s for PAK %s\n", files[iter], file);
585             pak_close(pak);
586             vec_free(files);
587             return EXIT_FAILURE;
588         }
589     }
590
591     /* not possible */
592     pak_close(pak);
593     vec_free(files);
594
595     stat_info();
596     return EXIT_SUCCESS;
597 }