-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfs.c
3683 lines (3122 loc) · 89 KB
/
fs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
DarkPlaces file system
Copyright (C) 2003-2006 Mathieu Olivier
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to:
Free Software Foundation, Inc.
59 Temple Place - Suite 330
Boston, MA 02111-1307, USA
*/
#include "quakedef.h"
#include <limits.h>
#include <fcntl.h>
#ifdef WIN32
# include <direct.h>
# include <io.h>
# include <shlobj.h>
#else
# include <pwd.h>
# include <sys/stat.h>
# include <unistd.h>
#endif
#include "fs.h"
#include "wad.h"
// Win32 requires us to add O_BINARY, but the other OSes don't have it
#ifndef O_BINARY
# define O_BINARY 0
#endif
// In case the system doesn't support the O_NONBLOCK flag
#ifndef O_NONBLOCK
# define O_NONBLOCK 0
#endif
// largefile support for Win32
#ifdef WIN32
# define lseek _lseeki64
#endif
#if _MSC_VER >= 1400
// suppress deprecated warnings
# include <sys/stat.h>
# include <share.h>
# define read _read
# define write _write
# define close _close
# define unlink _unlink
# define dup _dup
#endif
/** \page fs File System
All of Quake's data access is through a hierchal file system, but the contents
of the file system can be transparently merged from several sources.
The "base directory" is the path to the directory holding the quake.exe and
all game directories. The sys_* files pass this to host_init in
quakeparms_t->basedir. This can be overridden with the "-basedir" command
line parm to allow code debugging in a different directory. The base
directory is only used during filesystem initialization.
The "game directory" is the first tree on the search path and directory that
all generated files (savegames, screenshots, demos, config files) will be
saved to. This can be overridden with the "-game" command line parameter.
The game directory can never be changed while quake is executing. This is a
precaution against having a malicious server instruct clients to write files
over areas they shouldn't.
*/
/*
=============================================================================
CONSTANTS
=============================================================================
*/
// Magic numbers of a ZIP file (big-endian format)
#define ZIP_DATA_HEADER 0x504B0304 // "PK\3\4"
#define ZIP_CDIR_HEADER 0x504B0102 // "PK\1\2"
#define ZIP_END_HEADER 0x504B0506 // "PK\5\6"
// Other constants for ZIP files
#define ZIP_MAX_COMMENTS_SIZE ((unsigned short)0xFFFF)
#define ZIP_END_CDIR_SIZE 22
#define ZIP_CDIR_CHUNK_BASE_SIZE 46
#define ZIP_LOCAL_CHUNK_BASE_SIZE 30
#ifdef LINK_TO_ZLIB
#include <zlib.h>
#define qz_inflate inflate
#define qz_inflateEnd inflateEnd
#define qz_inflateInit2_ inflateInit2_
#define qz_inflateReset inflateReset
#define qz_deflateInit2_ deflateInit2_
#define qz_deflateEnd deflateEnd
#define qz_deflate deflate
#define Z_MEMLEVEL_DEFAULT 8
#else
// Zlib constants (from zlib.h)
#define Z_SYNC_FLUSH 2
#define MAX_WBITS 15
#define Z_OK 0
#define Z_STREAM_END 1
#define Z_STREAM_ERROR (-2)
#define Z_DATA_ERROR (-3)
#define Z_MEM_ERROR (-4)
#define Z_BUF_ERROR (-5)
#define ZLIB_VERSION "1.2.3"
#define Z_BINARY 0
#define Z_DEFLATED 8
#define Z_MEMLEVEL_DEFAULT 8
#define Z_NULL 0
#define Z_DEFAULT_COMPRESSION (-1)
#define Z_NO_FLUSH 0
#define Z_SYNC_FLUSH 2
#define Z_FULL_FLUSH 3
#define Z_FINISH 4
// Uncomment the following line if the zlib DLL you have still uses
// the 1.1.x series calling convention on Win32 (WINAPI)
//#define ZLIB_USES_WINAPI
/*
=============================================================================
TYPES
=============================================================================
*/
/*! Zlib stream (from zlib.h)
* \warning: some pointers we don't use directly have
* been cast to "void*" for a matter of simplicity
*/
typedef struct
{
unsigned char *next_in; ///< next input byte
unsigned int avail_in; ///< number of bytes available at next_in
unsigned long total_in; ///< total nb of input bytes read so far
unsigned char *next_out; ///< next output byte should be put there
unsigned int avail_out; ///< remaining free space at next_out
unsigned long total_out; ///< total nb of bytes output so far
char *msg; ///< last error message, NULL if no error
void *state; ///< not visible by applications
void *zalloc; ///< used to allocate the internal state
void *zfree; ///< used to free the internal state
void *opaque; ///< private data object passed to zalloc and zfree
int data_type; ///< best guess about the data type: ascii or binary
unsigned long adler; ///< adler32 value of the uncompressed data
unsigned long reserved; ///< reserved for future use
} z_stream;
#endif
/// inside a package (PAK or PK3)
#define QFILE_FLAG_PACKED (1 << 0)
/// file is compressed using the deflate algorithm (PK3 only)
#define QFILE_FLAG_DEFLATED (1 << 1)
/// file is actually already loaded data
#define QFILE_FLAG_DATA (1 << 2)
#define FILE_BUFF_SIZE 2048
typedef struct
{
z_stream zstream;
size_t comp_length; ///< length of the compressed file
size_t in_ind, in_len; ///< input buffer current index and length
size_t in_position; ///< position in the compressed file
unsigned char input [FILE_BUFF_SIZE];
} ztoolkit_t;
struct qfile_s
{
int flags;
int handle; ///< file descriptor
fs_offset_t real_length; ///< uncompressed file size (for files opened in "read" mode)
fs_offset_t position; ///< current position in the file
fs_offset_t offset; ///< offset into the package (0 if external file)
int ungetc; ///< single stored character from ungetc, cleared to EOF when read
// Contents buffer
fs_offset_t buff_ind, buff_len; ///< buffer current index and length
unsigned char buff [FILE_BUFF_SIZE];
ztoolkit_t* ztk; ///< For zipped files.
const unsigned char *data; ///< For data files.
};
// ------ PK3 files on disk ------ //
// You can get the complete ZIP format description from PKWARE website
typedef struct pk3_endOfCentralDir_s
{
unsigned int signature;
unsigned short disknum;
unsigned short cdir_disknum; ///< number of the disk with the start of the central directory
unsigned short localentries; ///< number of entries in the central directory on this disk
unsigned short nbentries; ///< total number of entries in the central directory on this disk
unsigned int cdir_size; ///< size of the central directory
unsigned int cdir_offset; ///< with respect to the starting disk number
unsigned short comment_size;
fs_offset_t prepended_garbage;
} pk3_endOfCentralDir_t;
// ------ PAK files on disk ------ //
typedef struct dpackfile_s
{
char name[56];
int filepos, filelen;
} dpackfile_t;
typedef struct dpackheader_s
{
char id[4];
int dirofs;
int dirlen;
} dpackheader_t;
/*! \name Packages in memory
* @{
*/
/// the offset in packfile_t is the true contents offset
#define PACKFILE_FLAG_TRUEOFFS (1 << 0)
/// file compressed using the deflate algorithm
#define PACKFILE_FLAG_DEFLATED (1 << 1)
/// file is a symbolic link
#define PACKFILE_FLAG_SYMLINK (1 << 2)
typedef struct packfile_s
{
char name [MAX_QPATH];
int flags;
fs_offset_t offset;
fs_offset_t packsize; ///< size in the package
fs_offset_t realsize; ///< real file size (uncompressed)
} packfile_t;
typedef struct pack_s
{
char filename [MAX_OSPATH];
char shortname [MAX_QPATH];
int handle;
int ignorecase; ///< PK3 ignores case
int numfiles;
qboolean vpack;
packfile_t *files;
} pack_t;
//@}
/// Search paths for files (including packages)
typedef struct searchpath_s
{
// only one of filename / pack will be used
char filename[MAX_OSPATH];
pack_t *pack;
struct searchpath_s *next;
} searchpath_t;
/*
=============================================================================
FUNCTION PROTOTYPES
=============================================================================
*/
void FS_Dir_f(void);
void FS_Ls_f(void);
void FS_Which_f(void);
static searchpath_t *FS_FindFile (const char *name, int* index, qboolean quiet);
static packfile_t* FS_AddFileToPack (const char* name, pack_t* pack,
fs_offset_t offset, fs_offset_t packsize,
fs_offset_t realsize, int flags);
/*
=============================================================================
VARIABLES
=============================================================================
*/
mempool_t *fs_mempool;
searchpath_t *fs_searchpaths = NULL;
const char *const fs_checkgamedir_missing = "missing";
#define MAX_FILES_IN_PACK 65536
char fs_userdir[MAX_OSPATH];
char fs_gamedir[MAX_OSPATH];
char fs_basedir[MAX_OSPATH];
static pack_t *fs_selfpack = NULL;
// list of active game directories (empty if not running a mod)
int fs_numgamedirs = 0;
char fs_gamedirs[MAX_GAMEDIRS][MAX_QPATH];
// list of all gamedirs with modinfo.txt
gamedir_t *fs_all_gamedirs = NULL;
int fs_all_gamedirs_count = 0;
cvar_t scr_screenshot_name = {CVAR_NORESETTODEFAULTS, "scr_screenshot_name","dp", "prefix name for saved screenshots (changes based on -game commandline, as well as which game mode is running; the date is encoded using strftime escapes)"};
cvar_t fs_empty_files_in_pack_mark_deletions = {0, "fs_empty_files_in_pack_mark_deletions", "0", "if enabled, empty files in a pak/pk3 count as not existing but cancel the search in further packs, effectively allowing patch pak/pk3 files to 'delete' files"};
cvar_t cvar_fs_gamedir = {CVAR_READONLY | CVAR_NORESETTODEFAULTS, "fs_gamedir", "", "the list of currently selected gamedirs (use the 'gamedir' command to change this)"};
/*
=============================================================================
PRIVATE FUNCTIONS - PK3 HANDLING
=============================================================================
*/
#ifndef LINK_TO_ZLIB
// Functions exported from zlib
#if defined(WIN32) && defined(ZLIB_USES_WINAPI)
# define ZEXPORT WINAPI
#else
# define ZEXPORT
#endif
static int (ZEXPORT *qz_inflate) (z_stream* strm, int flush);
static int (ZEXPORT *qz_inflateEnd) (z_stream* strm);
static int (ZEXPORT *qz_inflateInit2_) (z_stream* strm, int windowBits, const char *version, int stream_size);
static int (ZEXPORT *qz_inflateReset) (z_stream* strm);
static int (ZEXPORT *qz_deflateInit2_) (z_stream* strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size);
static int (ZEXPORT *qz_deflateEnd) (z_stream* strm);
static int (ZEXPORT *qz_deflate) (z_stream* strm, int flush);
#endif
#define qz_inflateInit2(strm, windowBits) \
qz_inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
#define qz_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
qz_deflateInit2_((strm), (level), (method), (windowBits), (memLevel), (strategy), ZLIB_VERSION, sizeof(z_stream))
#ifndef LINK_TO_ZLIB
// qz_deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
static dllfunction_t zlibfuncs[] =
{
{"inflate", (void **) &qz_inflate},
{"inflateEnd", (void **) &qz_inflateEnd},
{"inflateInit2_", (void **) &qz_inflateInit2_},
{"inflateReset", (void **) &qz_inflateReset},
{"deflateInit2_", (void **) &qz_deflateInit2_},
{"deflateEnd", (void **) &qz_deflateEnd},
{"deflate", (void **) &qz_deflate},
{NULL, NULL}
};
/// Handle for Zlib DLL
static dllhandle_t zlib_dll = NULL;
#endif
#ifdef WIN32
static HRESULT (WINAPI *qSHGetFolderPath) (HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath);
static dllfunction_t shfolderfuncs[] =
{
{"SHGetFolderPathA", (void **) &qSHGetFolderPath},
{NULL, NULL}
};
static dllhandle_t shfolder_dll = NULL;
#endif
/*
====================
PK3_CloseLibrary
Unload the Zlib DLL
====================
*/
void PK3_CloseLibrary (void)
{
#ifndef LINK_TO_ZLIB
Sys_UnloadLibrary (&zlib_dll);
#endif
}
/*
====================
PK3_OpenLibrary
Try to load the Zlib DLL
====================
*/
qboolean PK3_OpenLibrary (void)
{
#ifdef LINK_TO_ZLIB
return true;
#else
const char* dllnames [] =
{
#if defined(WIN32)
# ifdef ZLIB_USES_WINAPI
"zlibwapi.dll",
"zlib.dll",
# else
"zlib1.dll",
# endif
#elif defined(MACOSX)
"libz.dylib",
#else
"libz.so.1",
"libz.so",
#endif
NULL
};
// Already loaded?
if (zlib_dll)
return true;
// Load the DLL
return Sys_LoadLibrary (dllnames, &zlib_dll, zlibfuncs);
#endif
}
/*
====================
FS_HasZlib
See if zlib is available
====================
*/
qboolean FS_HasZlib(void)
{
#ifdef LINK_TO_ZLIB
return true;
#else
PK3_OpenLibrary(); // to be safe
return (zlib_dll != 0);
#endif
}
/*
====================
PK3_GetEndOfCentralDir
Extract the end of the central directory from a PK3 package
====================
*/
qboolean PK3_GetEndOfCentralDir (const char *packfile, int packhandle, pk3_endOfCentralDir_t *eocd)
{
fs_offset_t filesize, maxsize;
unsigned char *buffer, *ptr;
int ind;
// Get the package size
filesize = lseek (packhandle, 0, SEEK_END);
if (filesize < ZIP_END_CDIR_SIZE)
return false;
// Load the end of the file in memory
if (filesize < ZIP_MAX_COMMENTS_SIZE + ZIP_END_CDIR_SIZE)
maxsize = filesize;
else
maxsize = ZIP_MAX_COMMENTS_SIZE + ZIP_END_CDIR_SIZE;
buffer = (unsigned char *)Mem_Alloc (tempmempool, maxsize);
lseek (packhandle, filesize - maxsize, SEEK_SET);
if (read (packhandle, buffer, maxsize) != (fs_offset_t) maxsize)
{
Mem_Free (buffer);
return false;
}
// Look for the end of central dir signature around the end of the file
maxsize -= ZIP_END_CDIR_SIZE;
ptr = &buffer[maxsize];
ind = 0;
while (BuffBigLong (ptr) != ZIP_END_HEADER)
{
if (ind == maxsize)
{
Mem_Free (buffer);
return false;
}
ind++;
ptr--;
}
memcpy (eocd, ptr, ZIP_END_CDIR_SIZE);
eocd->signature = LittleLong (eocd->signature);
eocd->disknum = LittleShort (eocd->disknum);
eocd->cdir_disknum = LittleShort (eocd->cdir_disknum);
eocd->localentries = LittleShort (eocd->localentries);
eocd->nbentries = LittleShort (eocd->nbentries);
eocd->cdir_size = LittleLong (eocd->cdir_size);
eocd->cdir_offset = LittleLong (eocd->cdir_offset);
eocd->comment_size = LittleShort (eocd->comment_size);
eocd->prepended_garbage = filesize - (ind + ZIP_END_CDIR_SIZE) - eocd->cdir_offset - eocd->cdir_size; // this detects "SFX" zip files
eocd->cdir_offset += eocd->prepended_garbage;
Mem_Free (buffer);
return true;
}
/*
====================
PK3_BuildFileList
Extract the file list from a PK3 file
====================
*/
int PK3_BuildFileList (pack_t *pack, const pk3_endOfCentralDir_t *eocd)
{
unsigned char *central_dir, *ptr;
unsigned int ind;
fs_offset_t remaining;
// Load the central directory in memory
central_dir = (unsigned char *)Mem_Alloc (tempmempool, eocd->cdir_size);
lseek (pack->handle, eocd->cdir_offset, SEEK_SET);
if(read (pack->handle, central_dir, eocd->cdir_size) != (fs_offset_t) eocd->cdir_size)
{
Mem_Free (central_dir);
return -1;
}
// Extract the files properties
// The parsing is done "by hand" because some fields have variable sizes and
// the constant part isn't 4-bytes aligned, which makes the use of structs difficult
remaining = eocd->cdir_size;
pack->numfiles = 0;
ptr = central_dir;
for (ind = 0; ind < eocd->nbentries; ind++)
{
fs_offset_t namesize, count;
// Checking the remaining size
if (remaining < ZIP_CDIR_CHUNK_BASE_SIZE)
{
Mem_Free (central_dir);
return -1;
}
remaining -= ZIP_CDIR_CHUNK_BASE_SIZE;
// Check header
if (BuffBigLong (ptr) != ZIP_CDIR_HEADER)
{
Mem_Free (central_dir);
return -1;
}
namesize = BuffLittleShort (&ptr[28]); // filename length
// Check encryption, compression, and attributes
// 1st uint8 : general purpose bit flag
// Check bits 0 (encryption), 3 (data descriptor after the file), and 5 (compressed patched data (?))
//
// LordHavoc: bit 3 would be a problem if we were scanning the archive
// but is not a problem in the central directory where the values are
// always real.
//
// bit 3 seems to always be set by the standard Mac OSX zip maker
//
// 2nd uint8 : external file attributes
// Check bits 3 (file is a directory) and 5 (file is a volume (?))
if ((ptr[8] & 0x21) == 0 && (ptr[38] & 0x18) == 0)
{
// Still enough bytes for the name?
if (remaining < namesize || namesize >= (int)sizeof (*pack->files))
{
Mem_Free (central_dir);
return -1;
}
// WinZip doesn't use the "directory" attribute, so we need to check the name directly
if (ptr[ZIP_CDIR_CHUNK_BASE_SIZE + namesize - 1] != '/')
{
char filename [sizeof (pack->files[0].name)];
fs_offset_t offset, packsize, realsize;
int flags;
// Extract the name (strip it if necessary)
namesize = min(namesize, (int)sizeof (filename) - 1);
memcpy (filename, &ptr[ZIP_CDIR_CHUNK_BASE_SIZE], namesize);
filename[namesize] = '\0';
if (BuffLittleShort (&ptr[10]))
flags = PACKFILE_FLAG_DEFLATED;
else
flags = 0;
offset = BuffLittleLong (&ptr[42]) + eocd->prepended_garbage;
packsize = BuffLittleLong (&ptr[20]);
realsize = BuffLittleLong (&ptr[24]);
switch(ptr[5]) // C_VERSION_MADE_BY_1
{
case 3: // UNIX_
case 2: // VMS_
case 16: // BEOS_
if((BuffLittleShort(&ptr[40]) & 0120000) == 0120000)
// can't use S_ISLNK here, as this has to compile on non-UNIX too
flags |= PACKFILE_FLAG_SYMLINK;
break;
}
FS_AddFileToPack (filename, pack, offset, packsize, realsize, flags);
}
}
// Skip the name, additionnal field, and comment
// 1er uint16 : extra field length
// 2eme uint16 : file comment length
count = namesize + BuffLittleShort (&ptr[30]) + BuffLittleShort (&ptr[32]);
ptr += ZIP_CDIR_CHUNK_BASE_SIZE + count;
remaining -= count;
}
// If the package is empty, central_dir is NULL here
if (central_dir != NULL)
Mem_Free (central_dir);
return pack->numfiles;
}
/*
====================
FS_LoadPackPK3
Create a package entry associated with a PK3 file
====================
*/
pack_t *FS_LoadPackPK3FromFD (const char *packfile, int packhandle)
{
pk3_endOfCentralDir_t eocd;
pack_t *pack;
int real_nb_files;
if (! PK3_GetEndOfCentralDir (packfile, packhandle, &eocd))
{
Con_Printf ("%s is not a PK3 file\n", packfile);
close(packhandle);
return NULL;
}
// Multi-volume ZIP archives are NOT allowed
if (eocd.disknum != 0 || eocd.cdir_disknum != 0)
{
Con_Printf ("%s is a multi-volume ZIP archive\n", packfile);
close(packhandle);
return NULL;
}
// We only need to do this test if MAX_FILES_IN_PACK is lesser than 65535
// since eocd.nbentries is an unsigned 16 bits integer
#if MAX_FILES_IN_PACK < 65535
if (eocd.nbentries > MAX_FILES_IN_PACK)
{
Con_Printf ("%s contains too many files (%hu)\n", packfile, eocd.nbentries);
close(packhandle);
return NULL;
}
#endif
// Create a package structure in memory
pack = (pack_t *)Mem_Alloc(fs_mempool, sizeof (pack_t));
pack->ignorecase = true; // PK3 ignores case
strlcpy (pack->filename, packfile, sizeof (pack->filename));
pack->handle = packhandle;
pack->numfiles = eocd.nbentries;
pack->files = (packfile_t *)Mem_Alloc(fs_mempool, eocd.nbentries * sizeof(packfile_t));
real_nb_files = PK3_BuildFileList (pack, &eocd);
if (real_nb_files < 0)
{
Con_Printf ("%s is not a valid PK3 file\n", packfile);
close(pack->handle);
Mem_Free(pack);
return NULL;
}
Con_DPrintf("Added packfile %s (%i files)\n", packfile, real_nb_files);
return pack;
}
pack_t *FS_LoadPackPK3 (const char *packfile)
{
int packhandle;
#if _MSC_VER >= 1400
_sopen_s(&packhandle, packfile, O_RDONLY | O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE);
#else
packhandle = open (packfile, O_RDONLY | O_BINARY);
#endif
if (packhandle < 0)
return NULL;
return FS_LoadPackPK3FromFD(packfile, packhandle);
}
/*
====================
PK3_GetTrueFileOffset
Find where the true file data offset is
====================
*/
qboolean PK3_GetTrueFileOffset (packfile_t *pfile, pack_t *pack)
{
unsigned char buffer [ZIP_LOCAL_CHUNK_BASE_SIZE];
fs_offset_t count;
// Already found?
if (pfile->flags & PACKFILE_FLAG_TRUEOFFS)
return true;
// Load the local file description
lseek (pack->handle, pfile->offset, SEEK_SET);
count = read (pack->handle, buffer, ZIP_LOCAL_CHUNK_BASE_SIZE);
if (count != ZIP_LOCAL_CHUNK_BASE_SIZE || BuffBigLong (buffer) != ZIP_DATA_HEADER)
{
Con_Printf ("Can't retrieve file %s in package %s\n", pfile->name, pack->filename);
return false;
}
// Skip name and extra field
pfile->offset += BuffLittleShort (&buffer[26]) + BuffLittleShort (&buffer[28]) + ZIP_LOCAL_CHUNK_BASE_SIZE;
pfile->flags |= PACKFILE_FLAG_TRUEOFFS;
return true;
}
/*
=============================================================================
OTHER PRIVATE FUNCTIONS
=============================================================================
*/
/*
====================
FS_AddFileToPack
Add a file to the list of files contained into a package
====================
*/
static packfile_t* FS_AddFileToPack (const char* name, pack_t* pack,
fs_offset_t offset, fs_offset_t packsize,
fs_offset_t realsize, int flags)
{
int (*strcmp_funct) (const char* str1, const char* str2);
int left, right, middle;
packfile_t *pfile;
strcmp_funct = pack->ignorecase ? strcasecmp : strcmp;
// Look for the slot we should put that file into (binary search)
left = 0;
right = pack->numfiles - 1;
while (left <= right)
{
int diff;
middle = (left + right) / 2;
diff = strcmp_funct (pack->files[middle].name, name);
// If we found the file, there's a problem
if (!diff)
Con_Printf ("Package %s contains the file %s several times\n", pack->filename, name);
// If we're too far in the list
if (diff > 0)
right = middle - 1;
else
left = middle + 1;
}
// We have to move the right of the list by one slot to free the one we need
pfile = &pack->files[left];
memmove (pfile + 1, pfile, (pack->numfiles - left) * sizeof (*pfile));
pack->numfiles++;
strlcpy (pfile->name, name, sizeof (pfile->name));
pfile->offset = offset;
pfile->packsize = packsize;
pfile->realsize = realsize;
pfile->flags = flags;
return pfile;
}
/*
============
FS_CreatePath
Only used for FS_OpenRealFile.
============
*/
void FS_CreatePath (char *path)
{
char *ofs, save;
for (ofs = path+1 ; *ofs ; ofs++)
{
if (*ofs == '/' || *ofs == '\\')
{
// create the directory
save = *ofs;
*ofs = 0;
FS_mkdir (path);
*ofs = save;
}
}
}
/*
============
FS_Path_f
============
*/
void FS_Path_f (void)
{
searchpath_t *s;
Con_Print("Current search path:\n");
for (s=fs_searchpaths ; s ; s=s->next)
{
if (s->pack)
{
if(s->pack->vpack)
Con_Printf("%sdir (virtual pack)\n", s->pack->filename);
else
Con_Printf("%s (%i files)\n", s->pack->filename, s->pack->numfiles);
}
else
Con_Printf("%s\n", s->filename);
}
}
/*
=================
FS_LoadPackPAK
=================
*/
/*! Takes an explicit (not game tree related) path to a pak file.
*Loads the header and directory, adding the files at the beginning
*of the list so they override previous pack files.
*/
pack_t *FS_LoadPackPAK (const char *packfile)
{
dpackheader_t header;
int i, numpackfiles;
int packhandle;
pack_t *pack;
dpackfile_t *info;
#if _MSC_VER >= 1400
_sopen_s(&packhandle, packfile, O_RDONLY | O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE);
#else
packhandle = open (packfile, O_RDONLY | O_BINARY);
#endif
if (packhandle < 0)
return NULL;
if(read (packhandle, (void *)&header, sizeof(header)) != sizeof(header))
{
Con_Printf ("%s is not a packfile\n", packfile);
close(packhandle);
return NULL;
}
if (memcmp(header.id, "PACK", 4))
{
Con_Printf ("%s is not a packfile\n", packfile);
close(packhandle);
return NULL;
}
header.dirofs = LittleLong (header.dirofs);
header.dirlen = LittleLong (header.dirlen);
if (header.dirlen % sizeof(dpackfile_t))
{
Con_Printf ("%s has an invalid directory size\n", packfile);
close(packhandle);
return NULL;
}
numpackfiles = header.dirlen / sizeof(dpackfile_t);
if (numpackfiles > MAX_FILES_IN_PACK)
{
Con_Printf ("%s has %i files\n", packfile, numpackfiles);
close(packhandle);
return NULL;
}
info = (dpackfile_t *)Mem_Alloc(tempmempool, sizeof(*info) * numpackfiles);
lseek (packhandle, header.dirofs, SEEK_SET);
if(header.dirlen != read (packhandle, (void *)info, header.dirlen))
{
Con_Printf("%s is an incomplete PAK, not loading\n", packfile);
Mem_Free(info);
close(packhandle);
return NULL;
}
pack = (pack_t *)Mem_Alloc(fs_mempool, sizeof (pack_t));
pack->ignorecase = false; // PAK is case sensitive
strlcpy (pack->filename, packfile, sizeof (pack->filename));
pack->handle = packhandle;
pack->numfiles = 0;
pack->files = (packfile_t *)Mem_Alloc(fs_mempool, numpackfiles * sizeof(packfile_t));
// parse the directory
for (i = 0;i < numpackfiles;i++)
{
fs_offset_t offset = LittleLong (info[i].filepos);
fs_offset_t size = LittleLong (info[i].filelen);
FS_AddFileToPack (info[i].name, pack, offset, size, size, PACKFILE_FLAG_TRUEOFFS);
}
Mem_Free(info);
Con_DPrintf("Added packfile %s (%i files)\n", packfile, numpackfiles);
return pack;
}
/*
====================
FS_LoadPackVirtual
Create a package entry associated with a directory file
====================
*/
pack_t *FS_LoadPackVirtual (const char *dirname)
{
pack_t *pack;
pack = (pack_t *)Mem_Alloc(fs_mempool, sizeof (pack_t));
pack->vpack = true;
pack->ignorecase = false;
strlcpy (pack->filename, dirname, sizeof(pack->filename));
pack->handle = -1;
pack->numfiles = -1;
pack->files = NULL;
Con_DPrintf("Added packfile %s (virtual pack)\n", dirname);
return pack;
}
/*
================
FS_AddPack_Fullpath
================
*/
/*! Adds the given pack to the search path.
* The pack type is autodetected by the file extension.
*
* Returns true if the file was successfully added to the
* search path or if it was already included.
*
* If keep_plain_dirs is set, the pack will be added AFTER the first sequence of
* plain directories.