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:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
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
26 * The PAK format uses a FOURCC concept for storing the magic ident within
27 * the header as a uint32_t.
29 #define PAK_FOURCC ((uint32_t)(('P' | ('A' << 8) | ('C' << 16) | ('K' << 24))))
32 uint32_t magic; /* "PACK" */
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.
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.
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.
62 static char *pak_tree_sep(char **str, const char *sep) {
69 if (*(end = beg + strcspn(beg, sep)))
70 * end++ = '\0'; /* null terminate */
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
84 static void pak_tree_build(const char *entry) {
93 pathsplit = (char *)mem_a(56);
94 directory = (char *)mem_a(56);
96 memset(pathsplit, 0, 56);
98 util_strncpy(directory, entry, 56);
99 for (itr = 0; (token = pak_tree_sep(&directory, "/")) != NULL; itr++) {
100 elements[itr] = token;
103 for (jtr = 0; jtr < itr - 1; jtr++) {
104 util_strcat(pathsplit, elements[jtr]);
105 util_strcat(pathsplit, "/");
107 if (fs_dir_make(pathsplit)) {
111 /* TODO: undo on fail */
122 pak_directory_t *directories;
128 static pak_file_t *pak_open_read(const char *file) {
132 if (!(pak = (pak_file_t*)mem_a(sizeof(pak_file_t))))
135 if (!(pak->handle = fs_file_open(file, "rb"))) {
140 pak->directories = NULL;
141 pak->insert = false; /* read doesn't allow insert */
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));
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.
152 if (pak->header.magic != PAK_FOURCC) {
153 fs_file_close(pak->handle);
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.
162 fs_file_seek(pak->handle, pak->header.diroff, SEEK_SET);
165 * Read in all directories from the PAK file. These are considered
166 * to be the "file entries".
168 for (itr = 0; itr < pak->header.dirlen / 64; itr++) {
170 fs_file_read (&dir, sizeof(pak_directory_t), 1, pak->handle);
171 util_endianswap(&dir, 1, sizeof(pak_directory_t));
173 vec_push(pak->directories, dir);
178 static pak_file_t *pak_open_write(const char *file) {
181 if (!(pak = (pak_file_t*)mem_a(sizeof(pak_file_t))))
185 * Generate the required directory structure / tree for
186 * writing this PAK file too.
188 pak_tree_build(file);
190 if (!(pak->handle = fs_file_open(file, "wb"))) {
192 * The directory tree that was created, needs to be
193 * removed entierly if we failed to open a file.
195 /* TODO backup directory clean */
201 memset(&(pak->header), 0, sizeof(pak_header_t));
204 * We're in "insert" mode, we need to do things like header
205 * "patching" and writing the directories at the end of the
209 pak->header.magic = PAK_FOURCC;
211 /* on BE systems we need to swap the byte order of the FOURCC */
212 util_endianswap(&pak->header.magic, 1, sizeof(uint32_t));
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.
220 fs_file_write(&(pak->header), sizeof(pak_header_t), 1, pak->handle);
225 pak_file_t *pak_open(const char *file, const char *mode) {
230 case 'r': return pak_open_read (file);
231 case 'w': return pak_open_write(file);
237 bool pak_exists(pak_file_t *pak, const char *file, pak_directory_t **dir) {
243 for (itr = 0; itr < vec_size(pak->directories); itr++) {
244 if (!strcmp(pak->directories[itr].name, file)) {
246 * Store back a pointer to the directory that matches
247 * the request if requested (NULL is not allowed).
250 *dir = &(pak->directories[itr]);
260 * Extraction abilities. These work as you expect them to.
262 bool pak_extract_one(pak_file_t *pak, const char *file, const char *outdir) {
263 pak_directory_t *dir = NULL;
264 unsigned char *dat = NULL;
268 if (!pak_exists(pak, file, &dir)) {
272 if (!(dat = (unsigned char *)mem_a(dir->len))) {
277 * Generate the directory structure / tree that will be required
278 * to store the extracted file.
280 pak_tree_build(file);
282 /* TODO portable path seperators */
283 util_asprintf(&local, "%s/%s", outdir, file);
286 * Now create the file, if this operation fails. Then abort
287 * It shouldn't fail though.
289 if (!(out = fs_file_open(local, "wb"))) {
294 /* free memory for directory string */
298 fs_file_seek (pak->handle, dir->pos, SEEK_SET);
299 fs_file_read (dat, 1, dir->len, pak->handle);
302 fs_file_write(dat, 1, dir->len, out);
313 bool pak_extract_all(pak_file_t *pak, const char *dir) {
316 if (!fs_dir_make(dir))
319 for (itr = 0; itr < vec_size(pak->directories); itr++) {
320 if (!pak_extract_one(pak, pak->directories[itr].name, dir))
328 * Insertion functions (the opposite of extraction). Yes for generating
331 bool pak_insert_one(pak_file_t *pak, const char *file) {
337 * We don't allow insertion on files that already exist within the
338 * pak file. Weird shit can happen if we allow that ;). We also
339 * don't allow insertion if the pak isn't opened in write mode.
341 if (!pak || !file || !pak->insert || pak_exists(pak, file, NULL))
344 if (!(fp = fs_file_open(file, "rb")))
348 * Calculate the total file length, since it will be wrote to
349 * the directory entry, and the actual contents of the file
350 * to the PAK file itself.
352 fs_file_seek(fp, 0, SEEK_END);
353 dir.len = fs_file_tell(fp);
354 fs_file_seek(fp, 0, SEEK_SET);
356 dir.pos = fs_file_tell(pak->handle);
359 * We're limited to 56 bytes for a file name string, that INCLUDES
360 * the directory and '/' seperators.
362 if (strlen(file) >= 56) {
367 util_strncpy(dir.name, file, strlen(file));
370 * Allocate some memory for loading in the data that will be
371 * redirected into the PAK file.
373 if (!(dat = (unsigned char *)mem_a(dir.len))) {
378 fs_file_read (dat, dir.len, 1, fp);
380 fs_file_write(dat, dir.len, 1, pak->handle);
383 * Now add the directory to the directories vector, so pak_close
384 * can actually write it.
386 vec_push(pak->directories, dir);
392 * Like pak_insert_one, except this collects files in all directories
393 * from a root directory, and inserts them all.
395 bool pak_insert_all(pak_file_t *pak, const char *dir) {
402 if (!(dp = fs_dir_open(dir)))
405 while ((dirp = fs_dir_read(dp))) {
406 if (!(pak_insert_one(pak, dirp->d_name))) {
416 bool pak_close(pak_file_t *pak) {
423 * In insert mode we need to patch the header, and write
424 * our directory entries at the end of the file.
427 pak->header.dirlen = vec_size(pak->directories) * 64;
428 pak->header.diroff = ftell(pak->handle);
431 fs_file_seek (pak->handle, 0, SEEK_SET);
432 fs_file_write(&(pak->header), sizeof(pak_header_t), 1, pak->handle);
434 /* write directories */
435 fs_file_seek (pak->handle, pak->header.diroff, SEEK_SET);
437 for (itr = 0; itr < vec_size(pak->directories); itr++) {
438 fs_file_write(&(pak->directories[itr]), sizeof(pak_directory_t), 1, pak->handle);
442 vec_free (pak->directories);
443 fs_file_close(pak->handle);
450 * Fancy GCC-like LONG parsing allows things like --opt=param with
451 * assignment operator. This is used for redirecting stdout/stderr
452 * console to specific files of your choice.
454 static bool parsecmd(const char *optname, int *argc_, char ***argv_, char **out, int ds, bool split) {
456 char **argv = *argv_;
458 size_t len = strlen(optname);
460 if (strncmp(argv[0]+ds, optname, len))
463 /* it's --optname, check how the parameter is supplied */
464 if (argv[0][ds+len] == '=') {
465 *out = argv[0]+ds+len+1;
469 if (!split || argc < ds) /* no parameter was provided, or only single-arg form accepted */
472 /* using --opt param */
479 int main(int argc, char **argv) {
481 char *redirout = (char*)stdout;
482 char *redirerr = (char*)stderr;
485 pak_file_t *pak = NULL;
491 * Command line option parsing commences now We only need to support
492 * a few things in the test suite.
498 if (argv[0][0] == '-') {
499 if (parsecmd("redirout", &argc, &argv, &redirout, 1, false))
501 if (parsecmd("redirerr", &argc, &argv, &redirerr, 1, false))
503 if (parsecmd("file", &argc, &argv, &file, 1, false))
506 con_change(redirout, redirerr);
508 switch (argv[0][1]) {
509 case 'e': extract = true; continue;
510 case 'c': extract = false; continue;
513 if (!strcmp(argv[0]+1, "debug")) {
514 OPTS_OPTION_BOOL(OPTION_DEBUG) = true;
517 if (!strcmp(argv[0]+1, "memchk")) {
518 OPTS_OPTION_BOOL(OPTION_MEMCHK) = true;
521 if (!strcmp(argv[0]+1, "nocolor")) {
527 vec_push(files, argv[0]);
529 con_change(redirout, redirerr);
533 con_err("-file must be specified for output/input PAK file\n");
539 if (!(pak = pak_open(file, "r"))) {
540 con_err("failed to open PAK file %s\n", file);
545 if (!pak_extract_all(pak, "./")) {
546 con_err("failed to extract PAK %s (files may be missing)\n", file);
559 if (!(pak = pak_open(file, "w"))) {
560 con_err("failed to open PAK %s for writing\n", file);
565 for (iter = 0; iter < vec_size(files); iter++) {
566 if (!(pak_insert_one(pak, files[iter]))) {
567 con_err("failed inserting %s for PAK %s\n", files[iter], file);