]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - pak.c
Work in progress PAK extractor/insterter.
[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 typedef struct {
28     uint32_t magic;  /* "PACK" */
29
30     /*
31      * Offset to first directory entry in PAK file.  It's often
32      * best to store the directories at the end of the file opposed
33      * to the front, since it allows easy insertion without having
34      * to load the entire file into memory again.
35      */     
36     uint32_t diroff;
37     uint32_t dirlen;
38 } pak_header_t;
39
40 /*
41  * A directory, is sort of a "file entry".  The concept of
42  * a directory in Quake world is a "file entry/record". This
43  * describes a file (with directories/nested ones too in it's
44  * file name).  Hence it can be a file, file with directory, or
45  * file with directories.
46  */ 
47 typedef struct {
48     char     name[56];
49     uint32_t pos;
50     uint32_t len;
51 } pak_directory_t;
52
53 /*
54  * Used to get the next token from a string, where the
55  * strings themselfs are seperated by chracters from
56  * `sep`.  This is essentially strsep.
57  */   
58 static char *pak_tree_sep(char **str, const char *sep) {
59     char *beg = *str;
60     char *end;
61
62     if (!beg)
63         return NULL;
64
65     if (*(end = beg + strcspn(beg, sep)))
66         * end++ = '\0'; /* null terminate */
67     else
68           end   = 0;
69
70     *str = end;
71     return beg;
72 }
73
74 /*
75  * Used to spawn a directory when creating the pak directory structure/
76  * tree.  Think of this as mkdir(path, 0700).  We just cargo cult our
77  * own because _mkdir on windows is "illegal" for Windows8 Certification
78  * do to the requirement of SECURITY_ATTRIBUTES on everything.
79  */    
80 static bool pak_tree_spawn(const char *path) {
81 #ifdef _MSC_VER
82     return CreateDirectoryA(path, NULL); /* non-zero on success */
83 #else
84     return !!(mkdir(path, 0700));        /* zero on success     */
85 #endif
86 }
87
88 /*
89  * When given a string like "a/b/c/d/e/file"
90  * this function will handle the creation of
91  * the directory structure, included nested
92  * directories.
93  */    
94 static void pak_tree_build(const char *entry) {
95     char *directory;
96     char *elements[28];
97     char *pathsplit;
98
99     size_t itr;
100     size_t jtr;
101
102     pathsplit = mem_a(56);
103     directory = mem_a(56);
104
105     strncpy(directory, entry, 56);
106     for (itr = 0; (elements[itr] = pak_tree_sep(&directory, "/")); itr++);
107     for (jtr = 0; jtr < itr - 1; jtr++) {
108         strcat(pathsplit, elements[jtr]);
109         strcat(pathsplit, "/");
110
111         pak_tree_spawn(pathsplit);
112     }
113
114     mem_d(pathsplit);
115     mem_d(directory);
116 }
117
118 typedef struct {
119     pak_directory_t *directories;
120     pak_header_t     header;
121     FILE            *handle;
122     bool             insert;
123 } pak_file_t;
124
125 pak_file_t *pak_open_read(const char *file) {
126     pak_file_t *pak;
127     size_t      itr;
128
129     if (!(pak = mem_a(sizeof(pak_file_t))))
130         return NULL;
131
132     if (!(pak->handle = file_open(file, "rb"))) {
133         mem_d(pak);
134         return NULL;
135     }
136
137     pak->directories = NULL;
138     pak->insert      = false; /* read doesn't allow insert */
139
140     memset         (&(pak->header), 0, sizeof(pak_header_t));
141     file_read      (&(pak->header), 1, sizeof(pak_header_t), pak->handle);
142     util_endianswap(&(pak->header), 1, sizeof(pak_header_t));
143
144     /*
145      * Every PAK file has "PACK" stored as little endian data in the
146      * header.  If this data cannot compare (as checked here), it's
147      * probably not a PAK file.
148      */    
149     if (!(memcmp(&(pak->header.magic), (const void*)"PACK", sizeof(uint32_t)))) {
150         file_close(pak->handle);
151         mem_d     (pak);
152         return NULL;
153     }
154
155     /*
156      * Time to read in the directory handles and prepare the directories
157      * vector.  We're going to be reading some the file inwards soon.
158      */      
159     file_seek(pak->handle, pak->header.diroff, SEEK_SET);
160
161     /*
162      * Read in all directories from the PAK file. These are considered
163      * to be the "file entries".
164      */   
165     for (itr = 0; itr < pak->header.dirlen / 64; itr++) {
166         pak_directory_t dir;
167         file_read      (&dir, 1, sizeof(pak_directory_t), pak->handle);
168         util_endianswap(&dir, 1, sizeof(pak_directory_t));
169
170         vec_push(pak->directories, dir);
171     }
172     return pak;
173 }
174
175 pak_file_t *pak_open_write(const char *file) {
176     pak_file_t *pak;
177
178     if (!(pak = mem_a(sizeof(pak_file_t))))
179         return NULL;
180
181     /*
182      * Generate the required directory structure / tree for
183      * writing this PAK file too.
184      */   
185     pak_tree_build(file);
186
187     if (!(pak->handle = file_open(file, "wb"))) {
188         /*
189          * The directory tree that was created, needs to be
190          * removed entierly if we failed to open a file.
191          */   
192         /* TODO backup directory clean */
193
194         return NULL;
195     }
196
197     memset(&(pak->header), 0, sizeof(pak_header_t));
198
199     /*
200      * We're in "insert" mode, we need to do things like header
201      * "patching" and writing the directories at the end of the
202      * file.
203      */
204     pak->insert = true;
205
206     /*
207      * A valid PAK file contains the magic "PACK" in it's header
208      * stored in little endian format.
209      */
210     memcpy(&(pak->header.magic), (const void*)"PACK", sizeof(uint32_t));
211
212     /*
213      * We need to write out the header since files will be wrote out to
214      * this even with directory entries, and that not wrote.  The header
215      * will need to be patched in later with a file_seek, and overwrite,
216      * we could use offsets and other trickery.  This is just easier.
217      */
218     file_write(&(pak->header), sizeof(pak_header_t), 1, pak->handle);
219
220     return pak;
221 }
222
223 bool pak_exists(pak_file_t *pak, const char *file, pak_directory_t **dir) {
224     size_t itr;
225
226     if (!pak || !file)
227         return false;
228
229     /*
230      * We could technically use a hashtable here.  But I don't think
231      * the lookup complexity is a performance concern.  This may be
232      * O(n) lookup.  But meh?
233      */    
234     for (itr = 0; itr < vec_size(pak->directories); itr++) {
235         if (!strcmp(pak->directories[itr].name, file)) {
236             /*
237              * Store back a pointer to the directory that matches
238              * the request if requested (NULL is not allowed).
239              */   
240             if (dir) {
241                 *dir = &(pak->directories[itr]);
242             }
243             return true;
244         }
245     }
246
247     return false;
248 }
249
250 /*
251  * Extraction abilities.  These work as you expect them to.
252  */ 
253 bool pak_extract_one(pak_file_t *pak, const char *file) {
254     pak_directory_t *dir = NULL;
255     unsigned char   *dat = NULL;
256     FILE            *out;
257
258     if (!pak_exists(pak, file, &dir)) {
259         return false;
260     }
261
262     if (!(dat = (unsigned char *)mem_a(dir->len))) {
263         return false;
264     }
265
266     /*
267      * Generate the directory structure / tree that will be required
268      * to store the extracted file.
269      */   
270     pak_tree_build(file);
271
272     /*
273      * Now create the file, if this operation fails.  Then abort
274      * It shouldn't fail though.
275      */   
276     if (!(out = file_open(file, "wb"))) {
277         mem_d(dat);
278         return false;
279     }
280
281
282     /* read */
283     file_seek (pak->handle, dir->pos, SEEK_SET);
284     file_read (dat, 1, dir->len, pak->handle);
285
286     /* write */
287     file_write(dat, 1, dir->len, out);
288
289     /* close */
290     file_close(out);
291
292     /* free */
293     mem_d(dat);
294
295     return true;
296 }
297
298 bool pak_extract_all(pak_file_t *pak) {
299     size_t itr;
300     for (itr = 0; itr < vec_size(pak->directories); itr++) {
301         if (!pak_extract_one(pak, pak->directories[itr].name))
302             return false;
303     }
304
305     return true;
306 }
307
308 /*
309  * Insertion functions (the opposite of extraction).  Yes for generating
310  * PAKs.
311  */
312 bool pak_insert_one(pak_file_t *pak, const char *file) {
313     pak_directory_t dir;
314     unsigned char  *dat;
315     FILE           *fp;
316
317     /*
318      * We don't allow insertion on files that already exist within the
319      * pak file.  Weird shit can happen if we allow that ;). We also
320      * don't allow insertion if the pak isn't opened in write mode.  
321      */ 
322     if (!pak || !file || !pak->insert || pak_exists(pak, file, NULL))
323         return false;
324
325     if (!(fp = fopen(file, "rb")))
326         return false;
327
328     /*
329      * Calculate the total file length, since it will be wrote to
330      * the directory entry, and the actual contents of the file
331      * to the PAK file itself.
332      */
333     file_seek(fp, 0, SEEK_END);
334     dir.len = ftell(fp);
335     file_seek(fp, 0, SEEK_SET);
336
337     dir.pos = ftell(pak->handle);
338
339     /*
340      * Allocate some memory for loading in the data that will be
341      * redirected into the PAK file.
342      */   
343     if (!(dat = (unsigned char *)mem_a(dir.len))) {
344         file_close(fp);
345         return false;
346     }
347
348     file_read (dat, dir.len, 1, fp);
349     file_close(fp);
350     file_write(dat, dir.len, 1, pak->handle);
351
352     return true;
353 }
354
355 /*
356  * Like pak_insert_one, except this collects files in all directories
357  * from a root directory, and inserts them all.
358  */  
359 bool pak_insert_all(pak_file_t *pak, const char *dir) {
360     DIR           *dp;
361     struct dirent *dirp;
362
363     if (!(pak->insert))
364         return false;
365
366     if (!(dp = opendir(dir)))
367         return false;
368
369     while ((dirp = readdir(dp))) {
370         if (!(pak_insert_one(pak, dirp->d_name))) {
371             closedir(dp);
372             return false;
373         }
374     }
375
376     closedir(dp);
377     return true;
378 }
379
380 bool pak_close(pak_file_t *pak) {
381     size_t itr;
382
383     if (!pak)
384         return false;
385
386     /*
387      * In insert mode we need to patch the header, and write
388      * our directory entries at the end of the file.
389      */  
390     if (pak->insert) {
391         pak->header.dirlen = vec_size(pak->directories) * 64;
392         pak->header.diroff = ftell(pak->handle);
393
394         /* patch header */ 
395         file_seek (pak->handle, 0, SEEK_SET);
396         file_write(&(pak->header), sizeof(pak_header_t), 1, pak->handle);
397
398         /* write directories */
399         file_seek (pak->handle, pak->header.diroff, SEEK_SET);
400
401         for (itr = 0; itr < vec_size(pak->directories); itr++) {
402             file_write(&(pak->directories[itr]), sizeof(pak_directory_t), 1, pak->handle);
403         }
404     }
405
406     vec_free  (pak->directories);
407     file_close(pak->handle);
408     mem_d     (pak);
409
410     return true;
411 }