Debian Codegraph @

code/qcommon/files.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22 /*****************************************************************************
23 * name: files.c
24 *
25 * desc: handle based filesystem for Quake III Arena
26 *
27 * $Archive: /MissionPack/code/qcommon/files.c $
28 *
29 *****************************************************************************/
30
31
32 #include "q_shared.h"
33 #include "qcommon.h"
34 #include "unzip.h"
35
36 /*
37 =============================================================================
38
39 QUAKE3 FILESYSTEM
40
41 All of Quake's data access is through a hierarchical file system, but the contents of
42 the file system can be transparently merged from several sources.
43
44 A "qpath" is a reference to game file data. MAX_ZPATH is 256 characters, which must include
45 a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
46 references outside the quake directory system.
47
48 The "base path" is the path to the directory holding all the game directories and usually
49 the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
50 command line to allow code debugging in a different directory. Basepath cannot
51 be modified at all after startup. Any files that are created (demos, screenshots,
52 etc) will be created relative to the base path, so base path should usually be writable.
53
54 The "home path" is the path used for all write access. On win32 systems we have "base path"
55 == "home path", but on *nix systems the base installation is usually readonly, and
56 "home path" points to ~/.q3a or similar
57
58 The user can also install custom mods and content in "home path", so it should be searched
59 along with "home path" and "cd path" for game content.
60
61
62 The "base game" is the directory under the paths where data comes from by default, and
63 can be either "baseq3" or "demoq3".
64
65 The "current game" may be the same as the base game, or it may be the name of another
66 directory under the paths that should be searched for files before looking in the base game.
67 This is the basis for addons.
68
69 Clients automatically set the game directory after receiving a gamestate from a server,
70 so only servers need to worry about +set fs_game.
71
72 No other directories outside of the base game and current game will ever be referenced by
73 filesystem functions.
74
75 To save disk space and speed loading, directory trees can be collapsed into zip files.
76 The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
77 otherwise the are simply normal uncompressed zip files. A game directory can have multiple
78 zip files of the form "pak0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
79 from the highest number to the lowest, and will always take precedence over the filesystem.
80 This allows a pk3 distributed as a patch to override all existing data.
81
82 Because we will have updated executables freely available online, there is no point to
83 trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
84 should be exactly the same executables as release versions, but with different data that
85 automatically restricts where game media can come from to prevent add-ons from working.
86
87 File search order: when FS_FOpenFileRead gets called it will go through the fs_searchpaths
88 structure and stop on the first successful hit. fs_searchpaths is built with successive
89 calls to FS_AddGameDirectory
90
91 Additionally, we search in several subdirectories:
92 current game is the current mode
93 base game is a variable to allow mods based on other mods
94 (such as baseq3 + missionpack content combination in a mod for instance)
95 BASEGAME is the hardcoded base game ("baseq3")
96
97 e.g. the qpath "sound/newstuff/test.wav" would be searched for in the following places:
98
99 home path + current game's zip files
100 home path + current game's directory
101 base path + current game's zip files
102 base path + current game's directory
103 cd path + current game's zip files
104 cd path + current game's directory
105
106 home path + base game's zip file
107 home path + base game's directory
108 base path + base game's zip file
109 base path + base game's directory
110 cd path + base game's zip file
111 cd path + base game's directory
112
113 home path + BASEGAME's zip file
114 home path + BASEGAME's directory
115 base path + BASEGAME's zip file
116 base path + BASEGAME's directory
117 cd path + BASEGAME's zip file
118 cd path + BASEGAME's directory
119
120 server download, to be written to home path + current game's directory
121
122
123 The filesystem can be safely shutdown and reinitialized with different
124 basedir / cddir / game combinations, but all other subsystems that rely on it
125 (sound, video) must also be forced to restart.
126
127 Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
128 subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
129 load the file with a request to cache. Only one file will be kept cached at a time,
130 so any models that are going to be referenced by both subsystems should alternate
131 between the CM_ load function and the ref load function.
132
133 TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
134 game is currently active. This allows character models, skins, and sounds to be downloaded
135 to a common directory no matter which game is active.
136
137 How to prevent downloading zip files?
138 Pass pk3 file names in systeminfo, and download before FS_Restart()?
139
140 Aborting a download disconnects the client from the server.
141
142 How to mark files as downloadable? Commercial add-ons won't be downloadable.
143
144 Non-commercial downloads will want to download the entire zip file.
145 the game would have to be reset to actually read the zip in
146
147 Auto-update information
148
149 Path separators
150
151 Casing
152
153 separate server gamedir and client gamedir, so if the user starts
154 a local game after having connected to a network game, it won't stick
155 with the network game.
156
157 allow menu options for game selection?
158
159 Read / write config to floppy option.
160
161 Different version coexistance?
162
163 When building a pak file, make sure a q3config.cfg isn't present in it,
164 or configs will never get loaded from disk!
165
166 todo:
167
168 downloading (outside fs?)
169 game directory passing and restarting
170
171 =============================================================================
172
173 */
174
175 // every time a new demo pk3 file is built, this checksum must be updated.
176 // the easiest way to get it is to just run the game and see what it spits out
177 #ifndef STANDALONE
178 #define DEMO_PAK0_CHECKSUM 2985612116u
179 static const unsigned int pak_checksums[] = {
180 1566731103u,
181 298122907u,
182 412165236u,
183 2991495316u,
184 1197932710u,
185 4087071573u,
186 3709064859u,
187 908855077u,
188 977125798u
189 };
190
191 static const unsigned int missionpak_checksums[] =
192 {
193 2430342401u,
194 511014160u,
195 2662638993u,
196 1438664554u
197 };
198 #endif
199
200 // if this is defined, the executable positively won't work with any paks other
201 // than the demo pak, even if productid is present. This is only used for our
202 // last demo release to prevent the mac and linux users from using the demo
203 // executable with the production windows pak before the mac/linux products
204 // hit the shelves a little later
205 // NOW defined in build files
206 //#define PRE_RELEASE_TADEMO
207
208 #define MAX_ZPATH 256
209 #define MAX_SEARCH_PATHS 4096
210 #define MAX_FILEHASH_SIZE 1024
211
212 typedef struct fileInPack_s {
213 char *name; // name of the file
214 unsigned long pos; // file info position in zip
215 unsigned long len; // uncompress file size
216 struct fileInPack_s* next; // next file in the hash
217 } fileInPack_t;
218
219 typedef struct {
220 char pakPathname[MAX_OSPATH]; // c:\quake3\baseq3
221 char pakFilename[MAX_OSPATH]; // c:\quake3\baseq3\pak0.pk3
222 char pakBasename[MAX_OSPATH]; // pak0
223 char pakGamename[MAX_OSPATH]; // baseq3
224 unzFile handle; // handle to zip file
225 unsigned int checksum; // regular checksum
226 int pure_checksum; // checksum for pure
227 int numfiles; // number of files in pk3
228 int referenced; // referenced file flags
229 int hashSize; // hash table size (power of 2)
230 fileInPack_t* *hashTable; // hash table
231 fileInPack_t* buildBuffer; // buffer with the filenames etc.
232 } pack_t;
233
234 typedef struct {
235 char path[MAX_OSPATH]; // c:\quake3
236 char fullpath[MAX_OSPATH]; // c:\quake3\baseq3
237 char gamedir[MAX_OSPATH]; // baseq3
238 } directory_t;
239
240 typedef struct searchpath_s {
241 struct searchpath_s *next;
242
243 pack_t *pack; // only one of pack / dir will be non NULL
244 directory_t *dir;
245 } searchpath_t;
246
247 static char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
248 static cvar_t *fs_debug;
249 static cvar_t *fs_homeconfigpath;
250 static cvar_t *fs_homedatapath;
251 static cvar_t *fs_homestatepath;
252
253 static cvar_t *fs_apppath;
254 static cvar_t *fs_steampath;
255 static cvar_t *fs_gogpath;
256 static cvar_t *fs_microsoftstorepath;
257
258 static cvar_t *fs_basepath;
259 static cvar_t *fs_basegame;
260 static cvar_t *fs_gamedirvar;
261 static searchpath_t *fs_searchpaths;
262 static int fs_readCount; // total bytes read
263 static int fs_loadCount; // total files read
264 static int fs_loadStack; // total files in memory
265 static int fs_packFiles = 0; // total number of files in packs
266
267 static cvar_t *fs_pathVars[16];
268
269 static int fs_checksumFeed;
270
271 typedef union qfile_gus {
272 FILE* o;
273 unzFile z;
274 } qfile_gut;
275
276 typedef struct qfile_us {
277 qfile_gut file;
278 qboolean unique;
279 } qfile_ut;
280
281 typedef struct {
282 qfile_ut handleFiles;
283 qboolean handleSync;
284 int fileSize;
285 int zipFilePos;
286 int zipFileLen;
287 qboolean zipFile;
288 char name[MAX_ZPATH];
289 } fileHandleData_t;
290
291 static fileHandleData_t fsh[MAX_FILE_HANDLES];
292
293 // TTimo - https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
294 // wether we did a reorder on the current search path when joining the server
295 static qboolean fs_reordered;
296
297 // never load anything from pk3 files that are not present at the server when pure
298 static int fs_numServerPaks = 0;
299 static unsigned int fs_serverPaks[MAX_SEARCH_PATHS]; // checksums
300 static char *fs_serverPakNames[MAX_SEARCH_PATHS]; // pk3 names
301
302 // only used for autodownload, to make sure the client has at least
303 // all the pk3 files that are referenced at the server side
304 static int fs_numServerReferencedPaks;
305 static unsigned int fs_serverReferencedPaks[MAX_SEARCH_PATHS]; // checksums
306 static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS]; // pk3 names
307
308 // last valid game folder used
309 char lastValidBase[MAX_OSPATH];
310 char lastValidComBaseGame[MAX_OSPATH];
311 char lastValidFsBaseGame[MAX_OSPATH];
312 char lastValidGame[MAX_OSPATH];
313
314 #ifdef FS_MISSING
315 FILE* missingFiles = NULL;
316 #endif
317
318 /* C99 defines __func__ */
319 #if __STDC_VERSION__ < 199901L
320 # if __GNUC__ >= 2 || _MSC_VER >= 1300
321 # define __func__ __FUNCTION__
322 # else
323 # define __func__ "(unknown)"
324 # endif
325 #endif
326
327 /*
328 ==============
329 FS_Initialized
330 ==============
331 */
332
333 qboolean FS_Initialized( void ) {
334 return (fs_searchpaths != NULL);
335 }
336
337 /*
338 =================
339 FS_PakIsPure
340 =================
341 */
342 qboolean FS_PakIsPure( pack_t *pack ) {
343 int i;
344
345 if ( fs_numServerPaks ) {
346 for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
347 // FIXME: also use hashed file names
348 // NOTE TTimo: a pk3 with same checksum but different name would be validated too
349 // I don't see this as allowing for any exploit, it would only happen if the client does manips of its file names 'not a bug'
350 if ( pack->checksum == fs_serverPaks[i] ) {
351 return qtrue; // on the aproved list
352 }
353 }
354 return qfalse; // not on the pure server pak list
355 }
356 return qtrue;
357 }
358
359
360 /*
361 =================
362 FS_LoadStack
363 return load stack
364 =================
365 */
366 int FS_LoadStack( void )
367 {
368 return fs_loadStack;
369 }
370
371 /*
372 ================
373 return a hash value for the filename
374 ================
375 */
376 static long FS_HashFileName( const char *fname, int hashSize ) {
377 int i;
378 long hash;
379 char letter;
380
381 hash = 0;
382 i = 0;
383 while (fname[i] != '\0') {
384 letter = tolower(fname[i]);
385 if (letter =='.') break; // don't include extension
386 if (letter =='\\') letter = '/'; // damn path names
387 if (letter == PATH_SEP) letter = '/'; // damn path names
388 hash+=(long)(letter)*(i+119);
389 i++;
390 }
391 hash = (hash ^ (hash >> 10) ^ (hash >> 20));
392 hash &= (hashSize-1);
393 return hash;
394 }
395
396 static fileHandle_t FS_HandleForFile(void) {
397 int i;
398
399 for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
400 if ( fsh[i].handleFiles.file.o == NULL ) {
401 return i;
402 }
403 }
404 Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
405 return 0;
406 }
407
408 static FILE *FS_FileForHandle( fileHandle_t f ) {
409 if ( f < 1 || f >= MAX_FILE_HANDLES ) {
410 Com_Error( ERR_DROP, "FS_FileForHandle: out of range" );
411 }
412 if (fsh[f].zipFile == qtrue) {
413 Com_Error( ERR_DROP, "FS_FileForHandle: can't get FILE on zip file" );
414 }
415 if ( ! fsh[f].handleFiles.file.o ) {
416 Com_Error( ERR_DROP, "FS_FileForHandle: NULL" );
417 }
418
419 return fsh[f].handleFiles.file.o;
420 }
421
422 void FS_ForceFlush( fileHandle_t f ) {
423 FILE *file;
424
425 file = FS_FileForHandle(f);
426 setvbuf( file, NULL, _IONBF, 0 );
427 }
428
429 /*
430 ================
431 FS_fplength
432 ================
433 */
434
435 long FS_fplength(FILE *h)
436 {
437 long pos;
438 long end;
439
440 pos = ftell(h);
441 fseek(h, 0, SEEK_END);
442 end = ftell(h);
443 fseek(h, pos, SEEK_SET);
444
445 return end;
446 }
447
448 /*
449 ================
450 FS_filelength
451
452 If this is called on a non-unique FILE (from a pak file),
453 it will return the size of the pak file, not the expected
454 size of the file.
455 ================
456 */
457 long FS_filelength(fileHandle_t f)
458 {
459 FILE *h;
460
461 h = FS_FileForHandle(f);
462
463 if(h == NULL)
464 return -1;
465 else
466 return FS_fplength(h);
467 }
468
469 /*
470 ====================
471 FS_ReplaceSeparators
472
473 Fix things up differently for win/unix/mac
474 ====================
475 */
476 static void FS_ReplaceSeparators( char *path ) {
477 char *s;
478 qboolean lastCharWasSep = qfalse;
479
480 for ( s = path ; *s ; s++ ) {
481 if ( *s == '/' || *s == '\\' ) {
482 if ( !lastCharWasSep ) {
483 *s = PATH_SEP;
484 lastCharWasSep = qtrue;
485 } else {
486 memmove (s, s + 1, strlen (s));
487 }
488 } else {
489 lastCharWasSep = qfalse;
490 }
491 }
492 }
493
494 /*
495 ===================
496 FS_BuildOSPath
497
498 Qpath may have either forward or backwards slashes
499 ===================
500 */
501 char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
502 char temp[MAX_OSPATH];
503 static char ospath[2][MAX_OSPATH];
504 static int toggle;
505
506 toggle ^= 1; // flip-flop to allow two returns without clash
507
508 if( !game || !game[0] ) {
509 game = fs_gamedir;
510 }
511
512 Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath );
513 FS_ReplaceSeparators( temp );
514 Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
515
516 return ospath[toggle];
517 }
518
519 /*
520 ===================
521 FS_BaseDir_BuildOSPath
522
523 Qpath may have either forward or backwards slashes
524 ===================
525 */
526 char *FS_BaseDir_BuildOSPath( const char *base, const char *qpath ) {
527 char *ospath = FS_BuildOSPath(base, qpath, "");
528 ospath[strlen(ospath) - 1] = '\0';
529
530 return ospath;
531 }
532
533
534 /*
535 ============
536 FS_CreatePath
537
538 Creates any directories needed to store the given filename
539 ============
540 */
541 qboolean FS_CreatePath (const char *OSPath) {
542 char *ofs;
543 char path[MAX_OSPATH];
544
545 if (!OSPath || !*OSPath) {
546 return qfalse;
547 }
548
549 // make absolutely sure that it can't back up the path
550 // FIXME: is c: allowed???
551 if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
552 Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
553 return qtrue;
554 }
555
556 Q_strncpyz( path, OSPath, sizeof( path ) );
557 FS_ReplaceSeparators( path );
558
559 // Skip creation of the root directory as it will always be there
560 ofs = strchr( path, PATH_SEP );
561 if ( ofs != NULL ) {
562 ofs++;
563 }
564
565 for (; ofs != NULL && *ofs ; ofs++) {
566 if (*ofs == PATH_SEP) {
567 // create the directory
568 *ofs = 0;
569 if (!Sys_Mkdir (path)) {
570 Com_Error( ERR_FATAL, "FS_CreatePath: failed to create path \"%s\"",
571 path );
572 }
573 *ofs = PATH_SEP;
574 }
575 }
576
577 return qfalse;
578 }
579
580 /*
581 =================
582 FS_CheckFilenameIsMutable
583
584 ERR_FATAL if trying to maniuplate a file with the platform library, QVM, or pk3 extension
585 =================
586 */
587 static void FS_CheckFilenameIsMutable( const char *filename,
588 const char *function )
589 {
590 // Check if the filename ends with the library, QVM, or pk3 extension
591 if( Sys_DllExtension( filename )
592 || COM_CompareExtension( filename, ".qvm" )
593 || COM_CompareExtension( filename, ".pk3" ) )
594 {
595 Com_Error( ERR_FATAL, "%s: Not allowed to manipulate '%s' due "
596 "to %s extension", function, filename, COM_GetExtension( filename ) );
597 }
598 }
599
600 /*
601 ===========
602 FS_Remove
603
604 ===========
605 */
606 void FS_Remove( const char *osPath ) {
607 FS_CheckFilenameIsMutable( osPath, __func__ );
608
609 remove( osPath );
610 }
611
612 /*
613 ===========
614 FS_Remove_HomeData
615
616 ===========
617 */
618 void FS_Remove_HomeData( const char *homePath ) {
619 FS_CheckFilenameIsMutable( homePath, __func__ );
620
621 remove( FS_BuildOSPath( fs_homedatapath->string,
622 fs_gamedir, homePath ) );
623 }
624
625 /*
626 ================
627 FS_FileInPathExists
628
629 Tests if path and file exists
630 ================
631 */
632 qboolean FS_FileInPathExists(const char *testpath)
633 {
634 FILE *filep;
635
636 filep = Sys_FOpen(testpath, "rb");
637
638 if(filep)
639 {
640 fclose(filep);
641 return qtrue;
642 }
643
644 return qfalse;
645 }
646
647 /*
648 ================
649 FS_FileExists_HomeData
650
651 Tests if the file exists in the current gamedir, this DOES NOT
652 search the paths. This is to determine if opening a file to write
653 (which always goes into the current gamedir) will cause any overwrites.
654 NOTE TTimo: this goes with FS_FOpenFileWrite for opening the file afterwards
655 ================
656 */
657 qboolean FS_FileExists_HomeData(const char *file)
658 {
659 return FS_FileInPathExists(FS_BuildOSPath(fs_homedatapath->string, fs_gamedir, file));
660 }
661
662 /*
663 ================
664 FS_BaseDir_FileExists_HomeData
665
666 Tests if the file exists
667 ================
668 */
669 static qboolean FS_BaseDir_FileExists_HomeData( const char *file )
670 {
671 return FS_FileInPathExists(FS_BaseDir_BuildOSPath(fs_homedatapath->string, file));
672 }
673
674
675 /*
676 ===========
677 FS_OSPath_FOpenFileWrite
678 ===========
679 */
680 static fileHandle_t FS_OSPath_FOpenFileWrite( const char *ospath, const char *filename ) {
681 fileHandle_t f;
682
683 if ( !fs_searchpaths ) {
684 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
685 }
686
687 f = FS_HandleForFile();
688 fsh[f].zipFile = qfalse;
689
690 if ( fs_debug->integer ) {
691 Com_Printf( "FS_OSPath_FOpenFileWrite: %s\n", ospath );
692 }
693
694 FS_CheckFilenameIsMutable( ospath, __func__ );
695
696 if( FS_CreatePath( ospath ) ) {
697 return 0;
698 }
699
700 fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "wb" );
701
702 Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
703
704 fsh[f].handleSync = qfalse;
705 if (!fsh[f].handleFiles.file.o) {
706 f = 0;
707 }
708 return f;
709 }
710
711 /*
712 ===========
713 FS_BaseDir_FOpenFileWrite_HomeConfig
714 ===========
715 */
716 fileHandle_t FS_BaseDir_FOpenFileWrite_HomeConfig( const char *filename ) {
717 return FS_OSPath_FOpenFileWrite(
718 FS_BaseDir_BuildOSPath(fs_homeconfigpath->string, filename), filename);
719 }
720
721 /*
722 ===========
723 FS_BaseDir_FOpenFileWrite_HomeData
724 ===========
725 */
726 fileHandle_t FS_BaseDir_FOpenFileWrite_HomeData( const char *filename ) {
727 return FS_OSPath_FOpenFileWrite(
728 FS_BaseDir_BuildOSPath(fs_homedatapath->string, filename), filename);
729 }
730
731 /*
732 ===========
733 FS_BaseDir_FOpenFileWrite_HomeState
734 ===========
735 */
736 fileHandle_t FS_BaseDir_FOpenFileWrite_HomeState( const char *filename ) {
737 return FS_OSPath_FOpenFileWrite(
738 FS_BaseDir_BuildOSPath(fs_homestatepath->string, filename), filename);
739 }
740
741 /*
742 ===========
743 FS_BaseDir_FOpenFileRead
744
745 Search for a file somewhere below the home path then base path
746 in that order
747 ===========
748 */
749 long FS_BaseDir_FOpenFileRead(const char *filename, fileHandle_t *fp)
750 {
751 char *ospath;
752 fileHandle_t f = 0;
753
754 if ( !fs_searchpaths ) {
755 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
756 }
757
758 f = FS_HandleForFile();
759 fsh[f].zipFile = qfalse;
760
761 Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
762
763 // don't let sound stutter
764 S_ClearSoundBuffer();
765
766 for(int i = 0; i < ARRAY_LEN( fs_pathVars ) && !fsh[f].handleFiles.file.o; i++) {
767 const cvar_t *pathVar = fs_pathVars[i];
768
769 if (!pathVar || !pathVar->string[0]) {
770 continue;
771 }
772
773 ospath = FS_BaseDir_BuildOSPath( pathVar->string, filename );
774
775 if ( fs_debug->integer )
776 {
777 Com_Printf( "FS_BaseDir_FOpenFileRead (%s): %s\n", pathVar->name, ospath );
778 }
779
780 fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "rb" );
781 fsh[f].handleSync = qfalse;
782 }
783
784 if (!fsh[f].handleFiles.file.o)
785 {
786 f = 0;
787 }
788
789 *fp = f;
790 if (f) {
791 return FS_filelength(f);
792 }
793
794 return -1;
795 }
796
797
798 /*
799 ===========
800 FS_BaseDir_Rename_HomeData
801
802 ===========
803 */
804 void FS_BaseDir_Rename_HomeData( const char *from, const char *to, qboolean safe ) {
805 char *from_ospath, *to_ospath;
806
807 if ( !fs_searchpaths ) {
808 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
809 }
810
811 // don't let sound stutter
812 S_ClearSoundBuffer();
813
814 from_ospath = FS_BaseDir_BuildOSPath( fs_homedatapath->string, from );
815 to_ospath = FS_BaseDir_BuildOSPath( fs_homedatapath->string, to );
816
817 if ( fs_debug->integer ) {
818 Com_Printf( "FS_BaseDir_Rename_HomeData: %s --> %s\n", from_ospath, to_ospath );
819 }
820
821 if ( safe ) {
822 FS_CheckFilenameIsMutable( to_ospath, __func__ );
823 }
824
825 rename(from_ospath, to_ospath);
826 }
827
828 /*
829 ==============
830 FS_FCloseFile
831
832 If the FILE pointer is an open pak file, leave it open.
833
834 For some reason, other dll's can't just cal fclose()
835 on files returned by FS_FOpenFile...
836 ==============
837 */
838 void FS_FCloseFile( fileHandle_t f ) {
839 if ( !fs_searchpaths ) {
840 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
841 }
842
843 if (fsh[f].zipFile == qtrue) {
844 unzCloseCurrentFile( fsh[f].handleFiles.file.z );
845 if ( fsh[f].handleFiles.unique ) {
846 unzClose( fsh[f].handleFiles.file.z );
847 }
848 Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
849 return;
850 }
851
852 // we didn't find it as a pak, so close it as a unique file
853 if (fsh[f].handleFiles.file.o) {
854 fclose (fsh[f].handleFiles.file.o);
855 }
856 Com_Memset( &fsh[f], 0, sizeof( fsh[f] ) );
857 }
858
859 /*
860 ===========
861 FS_FOpenFileWrite_HomeConfig
862 ===========
863 */
864 fileHandle_t FS_FOpenFileWrite_HomeConfig( const char *filename ) {
865 return FS_OSPath_FOpenFileWrite(
866 FS_BuildOSPath(fs_homeconfigpath->string, fs_gamedir, filename), filename);
867 }
868
869 /*
870 ===========
871 FS_FOpenFileWrite_HomeData
872 ===========
873 */
874 fileHandle_t FS_FOpenFileWrite_HomeData( const char *filename ) {
875 return FS_OSPath_FOpenFileWrite(
876 FS_BuildOSPath(fs_homedatapath->string, fs_gamedir, filename), filename);
877 }
878
879 /*
880 ===========
881 FS_FOpenFileWrite_HomeState
882 ===========
883 */
884 fileHandle_t FS_FOpenFileWrite_HomeState( const char *filename ) {
885 return FS_OSPath_FOpenFileWrite(
886 FS_BuildOSPath(fs_homestatepath->string, fs_gamedir, filename), filename);
887 }
888
889 /*
890 ===========
891 FS_FOpenFileAppend_HomeData
892
893 ===========
894 */
895 fileHandle_t FS_FOpenFileAppend_HomeData( const char *filename ) {
896 char *ospath;
897 fileHandle_t f;
898
899 if ( !fs_searchpaths ) {
900 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
901 }
902
903 f = FS_HandleForFile();
904 fsh[f].zipFile = qfalse;
905
906 Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
907
908 // don't let sound stutter
909 S_ClearSoundBuffer();
910
911 ospath = FS_BuildOSPath( fs_homedatapath->string, fs_gamedir, filename );
912
913 if ( fs_debug->integer ) {
914 Com_Printf( "FS_FOpenFileAppend_HomeData: %s\n", ospath );
915 }
916
917 FS_CheckFilenameIsMutable( ospath, __func__ );
918
919 if( FS_CreatePath( ospath ) ) {
920 return 0;
921 }
922
923 fsh[f].handleFiles.file.o = Sys_FOpen( ospath, "ab" );
924 fsh[f].handleSync = qfalse;
925 if (!fsh[f].handleFiles.file.o) {
926 f = 0;
927 }
928 return f;
929 }
930
931 /*
932 ===========
933 FS_FCreateOpenPipeFile
934
935 ===========
936 */
937 fileHandle_t FS_FCreateOpenPipeFile( const char *filename ) {
938 char *ospath;
939 FILE *fifo;
940 fileHandle_t f;
941
942 if ( !fs_searchpaths ) {
943 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
944 }
945
946 f = FS_HandleForFile();
947 fsh[f].zipFile = qfalse;
948
949 Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
950
951 // don't let sound stutter
952 S_ClearSoundBuffer();
953
954 ospath = FS_BuildOSPath( fs_homedatapath->string, fs_gamedir, filename );
955
956 if ( fs_debug->integer ) {
957 Com_Printf( "FS_FCreateOpenPipeFile: %s\n", ospath );
958 }
959
960 FS_CheckFilenameIsMutable( ospath, __func__ );
961
962 fifo = Sys_Mkfifo( ospath );
963 if( fifo ) {
964 fsh[f].handleFiles.file.o = fifo;
965 fsh[f].handleSync = qfalse;
966 }
967 else
968 {
969 Com_Printf( S_COLOR_YELLOW "WARNING: Could not create new com_pipefile at %s. "
970 "com_pipefile will not be used.\n", ospath );
971 f = 0;
972 }
973
974 return f;
975 }
976
977 /*
978 ===========
979 FS_FilenameCompare
980
981 Ignore case and seprator char distinctions
982 ===========
983 */
984 qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
985 int c1, c2;
986
987 do {
988 c1 = *s1++;
989 c2 = *s2++;
990
991 if (c1 >= 'a' && c1 <= 'z') {
992 c1 -= ('a' - 'A');
993 }
994 if (c2 >= 'a' && c2 <= 'z') {
995 c2 -= ('a' - 'A');
996 }
997
998 if ( c1 == '\\' || c1 == ':' ) {
999 c1 = '/';
1000 }
1001 if ( c2 == '\\' || c2 == ':' ) {
1002 c2 = '/';
1003 }
1004
1005 if (c1 != c2) {
1006 return qtrue; // strings not equal
1007 }
1008 } while (c1);
1009
1010 return qfalse; // strings are equal
1011 }
1012
1013 /*
1014 ===========
1015 FS_IsExt
1016
1017 Return qtrue if ext matches file extension filename
1018 ===========
1019 */
1020
1021 qboolean FS_IsExt(const char *filename, const char *ext, int namelen)
1022 {
1023 int extlen;
1024
1025 extlen = strlen(ext);
1026
1027 if(extlen > namelen)
1028 return qfalse;
1029
1030 filename += namelen - extlen;
1031
1032 return !Q_stricmp(filename, ext);
1033 }
1034
1035 /*
1036 ===========
1037 FS_IsDemoExt
1038
1039 Return qtrue if filename has a demo extension
1040 ===========
1041 */
1042
1043 qboolean FS_IsDemoExt(const char *filename, int namelen)
1044 {
1045 char *ext_test;
1046 int index, protocol;
1047
1048 ext_test = strrchr(filename, '.');
1049 if(ext_test && !Q_stricmpn(ext_test + 1, DEMOEXT, ARRAY_LEN(DEMOEXT) - 1))
1050 {
1051 protocol = atoi(ext_test + ARRAY_LEN(DEMOEXT));
1052
1053 if(protocol == com_protocol->integer)
1054 return qtrue;
1055
1056 #ifdef LEGACY_PROTOCOL
1057 if(protocol == com_legacyprotocol->integer)
1058 return qtrue;
1059 #endif
1060
1061 for(index = 0; demo_protocols[index]; index++)
1062 {
1063 if(demo_protocols[index] == protocol)
1064 return qtrue;
1065 }
1066 }
1067
1068 return qfalse;
1069 }
1070
1071 /*
1072 ===========
1073 FS_FOpenFileReadDir
1074
1075 Tries opening file "filename" in searchpath "search"
1076 Returns filesize and an open FILE pointer.
1077 ===========
1078 */
1079 extern qboolean com_fullyInitialized;
1080
1081 long FS_FOpenFileReadDir(const char *filename, searchpath_t *search, fileHandle_t *file, qboolean uniqueFILE, qboolean unpure)
1082 {
1083 long hash;
1084 pack_t *pak;
1085 fileInPack_t *pakFile;
1086 directory_t *dir;
1087 char *netpath;
1088 FILE *filep;
1089 int len;
1090
1091 if(filename == NULL)
1092 Com_Error(ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed");
1093
1094 // qpaths are not supposed to have a leading slash
1095 if(filename[0] == '/' || filename[0] == '\\')
1096 filename++;
1097
1098 // make absolutely sure that it can't back up the path.
1099 // The searchpaths do guarantee that something will always
1100 // be prepended, so we don't need to worry about "c:" or "//limbo"
1101 if(strstr(filename, ".." ) || strstr(filename, "::"))
1102 {
1103 if(file == NULL)
1104 return qfalse;
1105
1106 *file = 0;
1107 return -1;
1108 }
1109
1110 // make sure the q3key file is only readable by the quake3.exe at initialization
1111 // any other time the key should only be accessed in memory using the provided functions
1112 if(com_fullyInitialized && strstr(filename, "q3key"))
1113 {
1114 if(file == NULL)
1115 return qfalse;
1116
1117 *file = 0;
1118 return -1;
1119 }
1120
1121 if(file == NULL)
1122 {
1123 // just wants to see if file is there
1124
1125 // is the element a pak file?
1126 if(search->pack)
1127 {
1128 hash = FS_HashFileName(filename, search->pack->hashSize);
1129
1130 if(search->pack->hashTable[hash])
1131 {
1132 // look through all the pak file elements
1133 pak = search->pack;
1134 pakFile = pak->hashTable[hash];
1135
1136 do
1137 {
1138 // case and separator insensitive comparisons
1139 if(!FS_FilenameCompare(pakFile->name, filename))
1140 {
1141 // found it!
1142 if(pakFile->len)
1143 return pakFile->len;
1144 else
1145 {
1146 // It's not nice, but legacy code depends
1147 // on positive value if file exists no matter
1148 // what size
1149 return 1;
1150 }
1151 }
1152
1153 pakFile = pakFile->next;
1154 } while(pakFile != NULL);
1155 }
1156 }
1157 else if(search->dir)
1158 {
1159 dir = search->dir;
1160
1161 netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
1162 filep = Sys_FOpen(netpath, "rb");
1163
1164 if(filep)
1165 {
1166 len = FS_fplength(filep);
1167 fclose(filep);
1168
1169 if(len)
1170 return len;
1171 else
1172 return 1;
1173 }
1174 }
1175
1176 return 0;
1177 }
1178
1179 *file = FS_HandleForFile();
1180 fsh[*file].handleFiles.unique = uniqueFILE;
1181
1182 // is the element a pak file?
1183 if(search->pack)
1184 {
1185 hash = FS_HashFileName(filename, search->pack->hashSize);
1186
1187 if(search->pack->hashTable[hash])
1188 {
1189 // disregard if it doesn't match one of the allowed pure pak files
1190 if(!unpure && !FS_PakIsPure(search->pack))
1191 {
1192 *file = 0;
1193 return -1;
1194 }
1195
1196 // look through all the pak file elements
1197 pak = search->pack;
1198 pakFile = pak->hashTable[hash];
1199
1200 do
1201 {
1202 // case and separator insensitive comparisons
1203 if(!FS_FilenameCompare(pakFile->name, filename))
1204 {
1205 // found it!
1206
1207 // mark the pak as having been referenced and mark specifics on cgame and ui
1208 // shaders, txt, arena files by themselves do not count as a reference as
1209 // these are loaded from all pk3s
1210 // from every pk3 file..
1211 len = strlen(filename);
1212
1213 if (!(pak->referenced & FS_GENERAL_REF))
1214 {
1215 if(!FS_IsExt(filename, ".shader", len) &&
1216 !FS_IsExt(filename, ".txt", len) &&
1217 !FS_IsExt(filename, ".cfg", len) &&
1218 !FS_IsExt(filename, ".config", len) &&
1219 !FS_IsExt(filename, ".bot", len) &&
1220 !FS_IsExt(filename, ".arena", len) &&
1221 !FS_IsExt(filename, ".menu", len) &&
1222 Q_stricmp(filename, "vm/qagame.qvm") != 0 &&
1223 !strstr(filename, "levelshots"))
1224 {
1225 pak->referenced |= FS_GENERAL_REF;
1226 }
1227 }
1228
1229 if(strstr(filename, "cgame.qvm"))
1230 pak->referenced |= FS_CGAME_REF;
1231 if(strstr(filename, "ui.qvm"))
1232 pak->referenced |= FS_UI_REF;
1233
1234 if(uniqueFILE)
1235 {
1236 // open a new file on the pakfile
1237 fsh[*file].handleFiles.file.z = unzOpen(pak->pakFilename);
1238
1239 if(fsh[*file].handleFiles.file.z == NULL)
1240 Com_Error(ERR_FATAL, "Couldn't open %s", pak->pakFilename);
1241 }
1242 else
1243 fsh[*file].handleFiles.file.z = pak->handle;
1244
1245 Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
1246 fsh[*file].zipFile = qtrue;
1247
1248 // set the file position in the zip file (also sets the current file info)
1249 unzSetOffset(fsh[*file].handleFiles.file.z, pakFile->pos);
1250
1251 // open the file in the zip
1252 unzOpenCurrentFile(fsh[*file].handleFiles.file.z);
1253 fsh[*file].zipFilePos = pakFile->pos;
1254 fsh[*file].zipFileLen = pakFile->len;
1255
1256 if(fs_debug->integer)
1257 {
1258 Com_Printf("FS_FOpenFileRead: %s (found in '%s')\n",
1259 filename, pak->pakFilename);
1260 }
1261
1262 return pakFile->len;
1263 }
1264
1265 pakFile = pakFile->next;
1266 } while(pakFile != NULL);
1267 }
1268 }
1269 else if(search->dir)
1270 {
1271 // check a file in the directory tree
1272
1273 // if we are running restricted, the only files we
1274 // will allow to come from the directory are .cfg files
1275 len = strlen(filename);
1276 // FIXME TTimo I'm not sure about the fs_numServerPaks test
1277 // if you are using FS_ReadFile to find out if a file exists,
1278 // this test can make the search fail although the file is in the directory
1279 // I had the problem on https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8
1280 // turned out I used FS_FileExists_HomeData instead
1281 if(!unpure && fs_numServerPaks)
1282 {
1283 if(!FS_IsExt(filename, ".cfg", len) && // for config files
1284 !FS_IsExt(filename, ".menu", len) && // menu files
1285 !FS_IsExt(filename, ".game", len) && // menu files
1286 !FS_IsExt(filename, ".dat", len) && // for journal files
1287 !FS_IsDemoExt(filename, len)) // demos
1288 {
1289 *file = 0;
1290 return -1;
1291 }
1292 }
1293
1294 dir = search->dir;
1295
1296 netpath = FS_BuildOSPath(dir->path, dir->gamedir, filename);
1297 filep = Sys_FOpen(netpath, "rb");
1298
1299 if (filep == NULL)
1300 {
1301 *file = 0;
1302 return -1;
1303 }
1304
1305 Q_strncpyz(fsh[*file].name, filename, sizeof(fsh[*file].name));
1306 fsh[*file].zipFile = qfalse;
1307
1308 if(fs_debug->integer)
1309 {
1310 Com_Printf("FS_FOpenFileRead: %s (found in '%s%c%s')\n", filename,
1311 dir->path, PATH_SEP, dir->gamedir);
1312 }
1313
1314 fsh[*file].handleFiles.file.o = filep;
1315 return FS_fplength(filep);
1316 }
1317
1318 *file = 0;
1319 return -1;
1320 }
1321
1322 /*
1323 ===========
1324 FS_FOpenFileRead
1325
1326 Finds the file in the search path.
1327 Returns filesize and an open FILE pointer.
1328 Used for streaming data out of either a
1329 separate file or a ZIP file.
1330 ===========
1331 */
1332 long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
1333 {
1334 searchpath_t *search;
1335 long len;
1336 qboolean isLocalConfig;
1337
1338 if(!fs_searchpaths)
1339 Com_Error(ERR_FATAL, "Filesystem call made without initialization");
1340
1341 isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG);
1342 for(search = fs_searchpaths; search; search = search->next)
1343 {
1344 // autoexec.cfg and q3config.cfg can only be loaded outside of pk3 files.
1345 if (isLocalConfig && search->pack)
1346 continue;
1347
1348 len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
1349
1350 if(file == NULL)
1351 {
1352 if(len > 0)
1353 return len;
1354 }
1355 else
1356 {
1357 if(len >= 0 && *file)
1358 return len;
1359 }
1360
1361 }
1362
1363 #ifdef FS_MISSING
1364 if(missingFiles)
1365 fprintf(missingFiles, "%s\n", filename);
1366 #endif
1367
1368 if(file)
1369 {
1370 *file = 0;
1371 return -1;
1372 }
1373 else
1374 {
1375 // When file is NULL, we're querying the existence of the file
1376 // If we've got here, it doesn't exist
1377 return 0;
1378 }
1379 }
1380
1381 /*
1382 =================
1383 FS_FindVM
1384
1385 Find a suitable VM file in search path order.
1386
1387 In each searchpath try:
1388 - open DLL file if DLL loading enabled
1389 - open QVM file
1390
1391 Enable search for DLL by setting enableDll to FSVM_ENABLEDLL
1392
1393 write found DLL or QVM to "found" and return VMI_NATIVE if DLL, VMI_COMPILED if QVM
1394 Return the searchpath in "startSearch".
1395 =================
1396 */
1397
•1398 int FS_FindVM(void **startSearch, char *found, int foundlen, const char *name, int enableDll, int forceDll)
1399 {
1400 searchpath_t *search, *lastSearch;
1401 directory_t *dir;
1402 pack_t *pack;
1403 char qvmName[MAX_OSPATH];
1404 char *netpath;
1405
1406 if(!fs_searchpaths)
1407 Com_Error(ERR_FATAL, "Filesystem call made without initialization");
1408
1409 Com_sprintf(qvmName, sizeof(qvmName), "vm/%s.qvm", name);
1410
1411 lastSearch = *startSearch;
1412 if(*startSearch == NULL)
1413 search = fs_searchpaths;
1414 else
1415 search = lastSearch->next;
1416
1417 while(search)
1418 {
•1419 if(search->dir && (forceDll || !fs_numServerPaks))
1420 {
1421 dir = search->dir;
1422
1423 if(enableDll)
1424 {
1425 // The original Q3 put the architecture in the library name; in case
1426 // we're loading an old binary only mod, fallback on this format if
1427 // the architecture-less library doesn't exist
1428 const char *dllNameFormats[] =
1429 {
1430 "%s" DLL_EXT,
1431 "%s" ARCH_STRING DLL_EXT
1432 };
1433
1434 for(int i = 0; i < ARRAY_LEN(dllNameFormats); i++)
1435 {
1436 char dllName[MAX_OSPATH];
1437 Com_sprintf(dllName, sizeof(dllName), dllNameFormats[i], name);
1438 netpath = FS_BuildOSPath(dir->path, dir->gamedir, dllName);
1439
1440 if(FS_FileInPathExists(netpath))
1441 {
1442 Q_strncpyz(found, netpath, foundlen);
1443 *startSearch = search;
1444
1445 return VMI_NATIVE;
1446 }
1447 }
1448 }
1449
1450 if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0)
1451 {
1452 *startSearch = search;
1453 return VMI_COMPILED;
1454 }
1455 }
•1456 else if(search->pack && !forceDll)
1457 {
1458 pack = search->pack;
1459
1460 if(lastSearch && lastSearch->pack)
1461 {
1462 // make sure we only try loading one VM file per game dir
1463 // i.e. if VM from pak7.pk3 fails we won't try one from pak6.pk3
1464
1465 if(!FS_FilenameCompare(lastSearch->pack->pakPathname, pack->pakPathname))
1466 {
1467 search = search->next;
1468 continue;
1469 }
1470 }
1471
1472 if(FS_FOpenFileReadDir(qvmName, search, NULL, qfalse, qfalse) > 0)
1473 {
1474 *startSearch = search;
1475
1476 return VMI_COMPILED;
1477 }
1478 }
1479
1480 search = search->next;
1481 }
1482
1483 return -1;
1484 }
1485
1486 /*
1487 =================
1488 FS_Read
1489
1490 Properly handles partial reads
1491 =================
1492 */
1493 int FS_Read( void *buffer, int len, fileHandle_t f ) {
1494 int block, remaining;
1495 int read;
1496 byte *buf;
1497 int tries;
1498
1499 if ( !fs_searchpaths ) {
1500 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
1501 }
1502
1503 if ( !f ) {
1504 return 0;
1505 }
1506
1507 buf = (byte *)buffer;
1508 fs_readCount += len;
1509
1510 if (fsh[f].zipFile == qfalse) {
1511 remaining = len;
1512 tries = 0;
1513 while (remaining) {
1514 block = remaining;
1515 read = fread (buf, 1, block, fsh[f].handleFiles.file.o);
1516 if (read == 0) {
1517 // we might have been trying to read from a CD, which
1518 // sometimes returns a 0 read on windows
1519 if (!tries) {
1520 tries = 1;
1521 } else {
1522 return len-remaining; //Com_Error (ERR_FATAL, "FS_Read: 0 bytes read");
1523 }
1524 }
1525
1526 if (read == -1) {
1527 Com_Error (ERR_FATAL, "FS_Read: -1 bytes read");
1528 }
1529
1530 remaining -= read;
1531 buf += read;
1532 }
1533 return len;
1534 } else {
1535 return unzReadCurrentFile(fsh[f].handleFiles.file.z, buffer, len);
1536 }
1537 }
1538
1539 /*
1540 =================
1541 FS_Write
1542
1543 Properly handles partial writes
1544 =================
1545 */
1546 int FS_Write( const void *buffer, int len, fileHandle_t h ) {
1547 int block, remaining;
1548 int written;
1549 byte *buf;
1550 int tries;
1551 FILE *f;
1552
1553 if ( !fs_searchpaths ) {
1554 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
1555 }
1556
1557 if ( !h ) {
1558 return 0;
1559 }
1560
1561 f = FS_FileForHandle(h);
1562 buf = (byte *)buffer;
1563
1564 remaining = len;
1565 tries = 0;
1566 while (remaining) {
1567 block = remaining;
1568 written = fwrite (buf, 1, block, f);
1569 if (written == 0) {
1570 if (!tries) {
1571 tries = 1;
1572 } else {
1573 Com_Printf( "FS_Write: 0 bytes written\n" );
1574 return 0;
1575 }
1576 }
1577
1578 if (written == -1) {
1579 Com_Printf( "FS_Write: -1 bytes written\n" );
1580 return 0;
1581 }
1582
1583 remaining -= written;
1584 buf += written;
1585 }
1586 if ( fsh[h].handleSync ) {
1587 fflush( f );
1588 }
1589 return len;
1590 }
1591
1592 void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
1593 va_list argptr;
1594 char msg[MAXPRINTMSG];
1595
1596 va_start (argptr,fmt);
1597 Q_vsnprintf (msg, sizeof(msg), fmt, argptr);
1598 va_end (argptr);
1599
1600 FS_Write(msg, strlen(msg), h);
1601 }
1602
1603 #define PK3_SEEK_BUFFER_SIZE 65536
1604
1605 /*
1606 =================
1607 FS_Seek
1608
1609 =================
1610 */
1611 int FS_Seek( fileHandle_t f, long offset, int origin ) {
1612 if ( !fs_searchpaths ) {
1613 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
1614 return -1;
1615 }
1616
1617 if (fsh[f].zipFile == qtrue) {
1618 //FIXME: this is really, really crappy
1619 //(but better than what was here before)
1620 byte buffer[PK3_SEEK_BUFFER_SIZE];
1621 int remainder;
1622 int currentPosition = FS_FTell( f );
1623
1624 // change negative offsets into FS_SEEK_SET
1625 if ( offset < 0 ) {
1626 switch( origin ) {
1627 case FS_SEEK_END:
1628 remainder = fsh[f].zipFileLen + offset;
1629 break;
1630
1631 case FS_SEEK_CUR:
1632 remainder = currentPosition + offset;
1633 break;
1634
1635 case FS_SEEK_SET:
1636 default:
1637 remainder = 0;
1638 break;
1639 }
1640
1641 if ( remainder < 0 ) {
1642 remainder = 0;
1643 }
1644
1645 origin = FS_SEEK_SET;
1646 } else {
1647 if ( origin == FS_SEEK_END ) {
1648 remainder = fsh[f].zipFileLen - currentPosition + offset;
1649 } else {
1650 remainder = offset;
1651 }
1652 }
1653
1654 switch( origin ) {
1655 case FS_SEEK_SET:
1656 if ( remainder == currentPosition ) {
1657 return offset;
1658 }
1659 unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
1660 unzOpenCurrentFile(fsh[f].handleFiles.file.z);
1661 //fallthrough
1662
1663 case FS_SEEK_END:
1664 case FS_SEEK_CUR:
1665 while( remainder > PK3_SEEK_BUFFER_SIZE ) {
1666 FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
1667 remainder -= PK3_SEEK_BUFFER_SIZE;
1668 }
1669 FS_Read( buffer, remainder, f );
1670 return offset;
1671
1672 default:
1673 Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
1674 return -1;
1675 }
1676 } else {
1677 FILE *file;
1678 file = FS_FileForHandle(f);
1679 int _origin = SEEK_SET;
1680 switch( origin ) {
1681 case FS_SEEK_CUR:
1682 _origin = SEEK_CUR;
1683 break;
1684 case FS_SEEK_END:
1685 _origin = SEEK_END;
1686 break;
1687 case FS_SEEK_SET:
1688 _origin = SEEK_SET;
1689 break;
1690 default:
1691 Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
1692 break;
1693 }
1694
1695 return fseek( file, offset, _origin );
1696 }
1697 }
1698
1699
1700 /*
1701 ======================================================================================
1702
1703 CONVENIENCE FUNCTIONS FOR ENTIRE FILES
1704
1705 ======================================================================================
1706 */
1707
1708 int FS_FileIsInPAK(const char *filename, int *pChecksum ) {
1709 searchpath_t *search;
1710 pack_t *pak;
1711 fileInPack_t *pakFile;
1712 long hash = 0;
1713
1714 if ( !fs_searchpaths ) {
1715 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
1716 }
1717
1718 if ( !filename ) {
1719 Com_Error( ERR_FATAL, "FS_FOpenFileRead: NULL 'filename' parameter passed" );
1720 }
1721
1722 // qpaths are not supposed to have a leading slash
1723 if ( filename[0] == '/' || filename[0] == '\\' ) {
1724 filename++;
1725 }
1726
1727 // make absolutely sure that it can't back up the path.
1728 // The searchpaths do guarantee that something will always
1729 // be prepended, so we don't need to worry about "c:" or "//limbo"
1730 if ( strstr( filename, ".." ) || strstr( filename, "::" ) ) {
1731 return -1;
1732 }
1733
1734 //
1735 // search through the path, one element at a time
1736 //
1737
1738 for ( search = fs_searchpaths ; search ; search = search->next ) {
1739 //
1740 if (search->pack) {
1741 hash = FS_HashFileName(filename, search->pack->hashSize);
1742 }
1743 // is the element a pak file?
1744 if ( search->pack && search->pack->hashTable[hash] ) {
1745 // disregard if it doesn't match one of the allowed pure pak files
1746 if ( !FS_PakIsPure(search->pack) ) {
1747 continue;
1748 }
1749
1750 // look through all the pak file elements
1751 pak = search->pack;
1752 pakFile = pak->hashTable[hash];
1753 do {
1754 // case and separator insensitive comparisons
1755 if ( !FS_FilenameCompare( pakFile->name, filename ) ) {
1756 if (pChecksum) {
1757 *pChecksum = pak->pure_checksum;
1758 }
1759 return 1;
1760 }
1761 pakFile = pakFile->next;
1762 } while(pakFile != NULL);
1763 }
1764 }
1765 return -1;
1766 }
1767
1768 /*
1769 ============
1770 FS_ReadFileDir
1771
1772 Filename are relative to the quake search path
1773 a null buffer will just return the file length without loading
1774 If searchPath is non-NULL search only in that specific search path
1775 ============
1776 */
1777 long FS_ReadFileDir(const char *qpath, void *searchPath, qboolean unpure, void **buffer)
1778 {
1779 fileHandle_t h;
1780 searchpath_t *search;
1781 byte* buf;
1782 qboolean isConfig;
1783 long len;
1784
1785 if ( !fs_searchpaths ) {
1786 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
1787 }
1788
1789 if ( !qpath || !qpath[0] ) {
1790 Com_Error( ERR_FATAL, "FS_ReadFile with empty name" );
1791 }
1792
1793 buf = NULL; // quiet compiler warning
1794
1795 // if this is a .cfg file and we are playing back a journal, read
1796 // it from the journal file
1797 if ( strstr( qpath, ".cfg" ) ) {
1798 isConfig = qtrue;
1799 if ( com_journal && com_journal->integer == 2 ) {
1800 int r;
1801
1802 Com_DPrintf( "Loading %s from journal file.\n", qpath );
1803 r = FS_Read( &len, sizeof( len ), com_journalDataFile );
1804 if ( r != sizeof( len ) ) {
1805 if (buffer != NULL) *buffer = NULL;
1806 return -1;
1807 }
1808 // if the file didn't exist when the journal was created
1809 if (!len) {
1810 if (buffer == NULL) {
1811 return 1; // hack for old journal files
1812 }
1813 *buffer = NULL;
1814 return -1;
1815 }
1816 if (buffer == NULL) {
1817 return len;
1818 }
1819
1820 buf = Hunk_AllocateTempMemory(len+1);
1821 *buffer = buf;
1822
1823 r = FS_Read( buf, len, com_journalDataFile );
1824 if ( r != len ) {
1825 Com_Error( ERR_FATAL, "Read from journalDataFile failed" );
1826 }
1827
1828 fs_loadCount++;
1829 fs_loadStack++;
1830
1831 // guarantee that it will have a trailing 0 for string operations
1832 buf[len] = 0;
1833
1834 return len;
1835 }
1836 } else {
1837 isConfig = qfalse;
1838 }
1839
1840 search = searchPath;
1841
1842 if(search == NULL)
1843 {
1844 // look for it in the filesystem or pack files
1845 len = FS_FOpenFileRead(qpath, &h, qfalse);
1846 }
1847 else
1848 {
1849 // look for it in a specific search path only
1850 len = FS_FOpenFileReadDir(qpath, search, &h, qfalse, unpure);
1851 }
1852
1853 if ( h == 0 ) {
1854 if ( buffer ) {
1855 *buffer = NULL;
1856 }
1857 // if we are journalling and it is a config file, write a zero to the journal file
1858 if ( isConfig && com_journal && com_journal->integer == 1 ) {
1859 Com_DPrintf( "Writing zero for %s to journal file.\n", qpath );
1860 len = 0;
1861 FS_Write( &len, sizeof( len ), com_journalDataFile );
1862 FS_Flush( com_journalDataFile );
1863 }
1864 return -1;
1865 }
1866
1867 if ( !buffer ) {
1868 if ( isConfig && com_journal && com_journal->integer == 1 ) {
1869 Com_DPrintf( "Writing len for %s to journal file.\n", qpath );
1870 FS_Write( &len, sizeof( len ), com_journalDataFile );
1871 FS_Flush( com_journalDataFile );
1872 }
1873 FS_FCloseFile( h);
1874 return len;
1875 }
1876
1877 fs_loadCount++;
1878 fs_loadStack++;
1879
1880 buf = Hunk_AllocateTempMemory(len+1);
1881 *buffer = buf;
1882
1883 FS_Read (buf, len, h);
1884
1885 // guarantee that it will have a trailing 0 for string operations
1886 buf[len] = 0;
1887 FS_FCloseFile( h );
1888
1889 // if we are journalling and it is a config file, write it to the journal file
1890 if ( isConfig && com_journal && com_journal->integer == 1 ) {
1891 Com_DPrintf( "Writing %s to journal file.\n", qpath );
1892 FS_Write( &len, sizeof( len ), com_journalDataFile );
1893 FS_Write( buf, len, com_journalDataFile );
1894 FS_Flush( com_journalDataFile );
1895 }
1896 return len;
1897 }
1898
1899 /*
1900 ============
1901 FS_ReadFile
1902
1903 Filename are relative to the quake search path
1904 a null buffer will just return the file length without loading
1905 ============
1906 */
1907 long FS_ReadFile(const char *qpath, void **buffer)
1908 {
1909 return FS_ReadFileDir(qpath, NULL, qfalse, buffer);
1910 }
1911
1912 /*
1913 =============
1914 FS_FreeFile
1915 =============
1916 */
1917 void FS_FreeFile( void *buffer ) {
1918 if ( !fs_searchpaths ) {
1919 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
1920 }
1921 if ( !buffer ) {
1922 Com_Error( ERR_FATAL, "FS_FreeFile( NULL )" );
1923 }
1924 fs_loadStack--;
1925
1926 Hunk_FreeTempMemory( buffer );
1927
1928 // if all of our temp files are free, clear all of our space
1929 if ( fs_loadStack == 0 ) {
1930 Hunk_ClearTempMemory();
1931 }
1932 }
1933
1934 /*
1935 ============
1936 FS_WriteFile
1937
1938 Filename are relative to the quake search path
1939 ============
1940 */
1941 void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
1942 fileHandle_t f;
1943
1944 if ( !fs_searchpaths ) {
1945 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
1946 }
1947
1948 if ( !qpath || !buffer ) {
1949 Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
1950 }
1951
1952 f = FS_FOpenFileWrite_HomeData( qpath );
1953 if ( !f ) {
1954 Com_Printf( "Failed to open %s\n", qpath );
1955 return;
1956 }
1957
1958 FS_Write( buffer, size, f );
1959
1960 FS_FCloseFile( f );
1961 }
1962
1963
1964
1965 /*
1966 ==========================================================================
1967
1968 ZIP FILE LOADING
1969
1970 ==========================================================================
1971 */
1972
1973 /*
1974 =================
1975 FS_LoadZipFile
1976
1977 Creates a new pak_t in the search chain for the contents
1978 of a zip file.
1979 =================
1980 */
1981 static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename)
1982 {
1983 fileInPack_t *buildBuffer;
1984 pack_t *pack;
1985 unzFile uf;
1986 int err;
1987 unz_global_info gi;
1988 char filename_inzip[MAX_ZPATH];
1989 unz_file_info file_info;
1990 int i, len;
1991 long hash;
1992 int fs_numHeaderLongs;
1993 int *fs_headerLongs;
1994 char *namePtr;
1995
1996 fs_numHeaderLongs = 0;
1997
1998 uf = unzOpen(zipfile);
1999 err = unzGetGlobalInfo (uf,&gi);
2000
2001 if (err != UNZ_OK)
2002 return NULL;
2003
2004 len = 0;
2005 unzGoToFirstFile(uf);
2006 for (i = 0; i < gi.number_entry; i++)
2007 {
2008 err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
2009 if (err != UNZ_OK) {
2010 break;
2011 }
2012 len += strlen(filename_inzip) + 1;
2013 unzGoToNextFile(uf);
2014 }
2015
2016 buildBuffer = Z_Malloc( (gi.number_entry * sizeof( fileInPack_t )) + len );
2017 namePtr = ((char *) buildBuffer) + gi.number_entry * sizeof( fileInPack_t );
2018 fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) );
2019 fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed );
2020
2021 // get the hash table size from the number of files in the zip
2022 // because lots of custom pk3 files have less than 32 or 64 files
2023 for (i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1) {
2024 if (i > gi.number_entry) {
2025 break;
2026 }
2027 }
2028
2029 pack = Z_Malloc( sizeof( pack_t ) + i * sizeof(fileInPack_t *) );
2030 pack->hashSize = i;
2031 pack->hashTable = (fileInPack_t **) (((char *) pack) + sizeof( pack_t ));
2032 for(i = 0; i < pack->hashSize; i++) {
2033 pack->hashTable[i] = NULL;
2034 }
2035
2036 Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) );
2037 Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) );
2038
2039 // strip .pk3 if needed
2040 if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, ".pk3" ) ) {
2041 pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0;
2042 }
2043
2044 pack->handle = uf;
2045 pack->numfiles = gi.number_entry;
2046 unzGoToFirstFile(uf);
2047
2048 for (i = 0; i < gi.number_entry; i++)
2049 {
2050 err = unzGetCurrentFileInfo(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
2051 if (err != UNZ_OK) {
2052 break;
2053 }
2054 if (file_info.uncompressed_size > 0) {
2055 fs_headerLongs[fs_numHeaderLongs++] = LittleLong(file_info.crc);
2056 }
2057 Q_strlwr( filename_inzip );
2058 hash = FS_HashFileName(filename_inzip, pack->hashSize);
2059 buildBuffer[i].name = namePtr;
2060 strcpy( buildBuffer[i].name, filename_inzip );
2061 namePtr += strlen(filename_inzip) + 1;
2062 // store the file position in the zip
2063 buildBuffer[i].pos = unzGetOffset(uf);
2064 buildBuffer[i].len = file_info.uncompressed_size;
2065 buildBuffer[i].next = pack->hashTable[hash];
2066 pack->hashTable[hash] = &buildBuffer[i];
2067 unzGoToNextFile(uf);
2068 }
2069
2070 pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) );
2071 pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs );
2072 pack->checksum = LittleLong( pack->checksum );
2073 pack->pure_checksum = LittleLong( pack->pure_checksum );
2074
2075 Z_Free(fs_headerLongs);
2076
2077 pack->buildBuffer = buildBuffer;
2078 return pack;
2079 }
2080
2081 /*
2082 =================
2083 FS_FreePak
2084
2085 Frees a pak structure and releases all associated resources
2086 =================
2087 */
2088
2089 static void FS_FreePak(pack_t *thepak)
2090 {
2091 unzClose(thepak->handle);
2092 Z_Free(thepak->buildBuffer);
2093 Z_Free(thepak);
2094 }
2095
2096 /*
2097 =================
2098 FS_GetZipChecksum
2099
2100 Compares whether the given pak file matches a referenced checksum
2101 =================
2102 */
2103 qboolean FS_CompareZipChecksum(const char *zipfile)
2104 {
2105 pack_t *thepak;
2106 int index;
2107 unsigned int checksum;
2108
2109 thepak = FS_LoadZipFile(zipfile, "");
2110
2111 if(!thepak)
2112 return qfalse;
2113
2114 checksum = thepak->checksum;
2115 FS_FreePak(thepak);
2116
2117 for(index = 0; index < fs_numServerReferencedPaks; index++)
2118 {
2119 if(checksum == fs_serverReferencedPaks[index])
2120 return qtrue;
2121 }
2122
2123 return qfalse;
2124 }
2125
2126 /*
2127 =================================================================================
2128
2129 DIRECTORY SCANNING FUNCTIONS
2130
2131 =================================================================================
2132 */
2133
2134 #define MAX_FOUND_FILES 0x1000
2135
2136 static int FS_ReturnPath( const char *zname, char *zpath, int *depth ) {
2137 int len, at, newdep;
2138
2139 newdep = 0;
2140 zpath[0] = 0;
2141 len = 0;
2142 at = 0;
2143
2144 while(zname[at] != 0)
2145 {
2146 if (zname[at]=='/' || zname[at]=='\\') {
2147 len = at;
2148 newdep++;
2149 }
2150 at++;
2151 }
2152 strcpy(zpath, zname);
2153 zpath[len] = 0;
2154 *depth = newdep;
2155
2156 return len;
2157 }
2158
2159 /*
2160 ==================
2161 FS_AddFileToList
2162 ==================
2163 */
2164 static int FS_AddFileToList( char *name, char *list[MAX_FOUND_FILES], int nfiles ) {
2165 int i;
2166
2167 if ( nfiles == MAX_FOUND_FILES - 1 ) {
2168 return nfiles;
2169 }
2170 for ( i = 0 ; i < nfiles ; i++ ) {
2171 if ( !Q_stricmp( name, list[i] ) ) {
2172 return nfiles; // already in list
2173 }
2174 }
2175 list[nfiles] = CopyString( name );
2176 nfiles++;
2177
2178 return nfiles;
2179 }
2180
2181 /*
2182 ===============
2183 FS_ListFilteredFiles
2184
2185 Returns a uniqued list of files that match the given criteria
2186 from all search paths
2187 ===============
2188 */
2189 char **FS_ListFilteredFiles( const char *path, const char *extension,
2190 char *filter, int *numfiles, qboolean stripPath,
2191 qboolean allowNonPureFilesOnDisk ) {
2192 int nfiles;
2193 char **listCopy;
2194 char *list[MAX_FOUND_FILES];
2195 searchpath_t *search;
2196 int i;
2197 int pathLength;
2198 int extensionLength;
2199 int length, pathDepth, pathSkip;
2200 pack_t *pak;
2201 fileInPack_t *buildBuffer;
2202 char zpath[MAX_ZPATH];
2203
2204 if ( !fs_searchpaths ) {
2205 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
2206 }
2207
2208 if ( !path ) {
2209 *numfiles = 0;
2210 return NULL;
2211 }
2212 if ( !extension ) {
2213 extension = "";
2214 }
2215
2216 pathLength = strlen( path );
2217 if ( path[pathLength-1] == '\\' || path[pathLength-1] == '/' ) {
2218 pathLength--;
2219 }
2220 extensionLength = strlen( extension );
2221 nfiles = 0;
2222 FS_ReturnPath(path, zpath, &pathDepth);
2223
2224 //
2225 // search through the path, one element at a time, adding to list
2226 //
2227 for (search = fs_searchpaths ; search ; search = search->next) {
2228 // is the element a pak file?
2229 if (search->pack) {
2230
2231 //ZOID: If we are pure, don't search for files on paks that
2232 // aren't on the pure list
2233 if ( !FS_PakIsPure(search->pack) ) {
2234 continue;
2235 }
2236
2237 // look through all the pak file elements
2238 pak = search->pack;
2239 buildBuffer = pak->buildBuffer;
2240 for (i = 0; i < pak->numfiles; i++) {
2241 char *name;
2242 int zpathLen, depth;
2243
2244 // check for directory match
2245 name = buildBuffer[i].name;
2246
2247 if (stripPath) {
2248 pathSkip = pathLength;
2249 if (pathLength) {
2250 pathSkip++; // include the '/'
2251 }
2252 } else {
2253 pathSkip = 0;
2254 }
2255
2256 if (filter) {
2257 // case insensitive
2258 if (!Com_FilterPath( filter, name, qfalse ))
2259 continue;
2260
2261 // unique the match
2262 nfiles = FS_AddFileToList( name + pathSkip, list, nfiles );
2263 }
2264 else {
2265
2266 zpathLen = FS_ReturnPath(name, zpath, &depth);
2267
2268 if ( (depth-pathDepth)>2 || pathLength > zpathLen || Q_stricmpn( name, path, pathLength ) ) {
2269 continue;
2270 }
2271
2272 // check for extension match
2273 length = strlen( name );
2274 if ( length < extensionLength ) {
2275 continue;
2276 }
2277
2278 if ( Q_stricmp( name + length - extensionLength, extension ) ) {
2279 continue;
2280 }
2281
2282 // unique the match
2283 nfiles = FS_AddFileToList( name + pathSkip, list, nfiles );
2284 }
2285 }
2286 } else if (search->dir) { // scan for files in the filesystem
2287 char *netpath;
2288 int numSysFiles;
2289 char **sysFiles;
2290 char *name;
2291
2292 // don't scan directories for files if we are pure or restricted
2293 if ( fs_numServerPaks && !allowNonPureFilesOnDisk ) {
2294 continue;
2295 } else {
2296 netpath = FS_BuildOSPath( search->dir->path, search->dir->gamedir, path );
2297 sysFiles = Sys_ListFiles( netpath, extension, filter, &numSysFiles, qfalse );
2298 for ( i = 0 ; i < numSysFiles ; i++ ) {
2299 // unique the match
2300 name = sysFiles[i];
2301 nfiles = FS_AddFileToList( name, list, nfiles );
2302 }
2303 Sys_FreeFileList( sysFiles );
2304 }
2305 }
2306 }
2307
2308 // return a copy of the list
2309 *numfiles = nfiles;
2310
2311 if ( !nfiles ) {
2312 return NULL;
2313 }
2314
2315 listCopy = Z_Malloc( ( nfiles + 1 ) * sizeof( *listCopy ) );
2316 for ( i = 0 ; i < nfiles ; i++ ) {
2317 listCopy[i] = list[i];
2318 }
2319 listCopy[i] = NULL;
2320
2321 return listCopy;
2322 }
2323
2324 /*
2325 =================
2326 FS_ListFiles
2327 =================
2328 */
2329 char **FS_ListFiles( const char *path, const char *extension, int *numfiles ) {
2330 return FS_ListFilteredFiles( path, extension, NULL, numfiles, qtrue, qfalse );
2331 }
2332
2333 /*
2334 =================
2335 FS_FreeFileList
2336 =================
2337 */
2338 void FS_FreeFileList( char **list ) {
2339 int i;
2340
2341 if ( !fs_searchpaths ) {
2342 Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
2343 }
2344
2345 if ( !list ) {
2346 return;
2347 }
2348
2349 for ( i = 0 ; list[i] ; i++ ) {
2350 Z_Free( list[i] );
2351 }
2352
2353 Z_Free( list );
2354 }
2355
2356
2357 /*
2358 ================
2359 FS_GetFileList
2360 ================
2361 */
2362 int FS_GetFileList( const char *path, const char *extension, char *listbuf, int bufsize ) {
2363 int nFiles, i, nTotal, nLen;
2364 char **pFiles = NULL;
2365
2366 *listbuf = 0;
2367 nFiles = 0;
2368 nTotal = 0;
2369
2370 if (Q_stricmp(path, "$modlist") == 0) {
2371 return FS_GetModList(listbuf, bufsize);
2372 }
2373
2374 pFiles = FS_ListFiles(path, extension, &nFiles);
2375
2376 for (i =0; i < nFiles; i++) {
2377 nLen = strlen(pFiles[i]) + 1;
2378 if (nTotal + nLen + 1 < bufsize) {
2379 strcpy(listbuf, pFiles[i]);
2380 listbuf += nLen;
2381 nTotal += nLen;
2382 }
2383 else {
2384 nFiles = i;
2385 break;
2386 }
2387 }
2388
2389 FS_FreeFileList(pFiles);
2390
2391 return nFiles;
2392 }
2393
2394 /*
2395 =======================
2396 Sys_ConcatenateFileLists
2397
2398 mkv: Naive implementation. Concatenates three lists into a
2399 new list, and frees the old lists from the heap.
2400 bk001129 - from cvs1.17 (mkv)
2401
2402 FIXME TTimo those two should move to common.c next to Sys_ListFiles
2403 =======================
2404 */
2405 static unsigned int Sys_CountFileList(char **list)
2406 {
2407 int i = 0;
2408
2409 if (list)
2410 {
2411 while (*list)
2412 {
2413 list++;
2414 i++;
2415 }
2416 }
2417 return i;
2418 }
2419
2420 static char** Sys_ConcatenateFileLists( char **list0, char **list1 )
2421 {
2422 int totalLength = 0;
2423 char** cat = NULL, **dst, **src;
2424
2425 totalLength += Sys_CountFileList(list0);
2426 totalLength += Sys_CountFileList(list1);
2427
2428 /* Create new list. */
2429 dst = cat = Z_Malloc( ( totalLength + 1 ) * sizeof( char* ) );
2430
2431 /* Copy over lists. */
2432 if (list0)
2433 {
2434 for (src = list0; *src; src++, dst++)
2435 *dst = *src;
2436 }
2437 if (list1)
2438 {
2439 for (src = list1; *src; src++, dst++)
2440 *dst = *src;
2441 }
2442
2443 // Terminate the list
2444 *dst = NULL;
2445
2446 // Free our old lists.
2447 // NOTE: not freeing their content, it's been merged in dst and still being used
2448 if (list0) Z_Free( list0 );
2449 if (list1) Z_Free( list1 );
2450
2451 return cat;
2452 }
2453
2454 /*
2455 ================
2456 FS_GetModDescription
2457 ================
2458 */
2459 void FS_GetModDescription( const char *modDir, char *description, int descriptionLen ) {
2460 fileHandle_t descHandle;
2461 char descPath[MAX_QPATH];
2462 int nDescLen;
2463 FILE *file;
2464
2465 Com_sprintf( descPath, sizeof ( descPath ), "%s%cdescription.txt", modDir, PATH_SEP );
2466 nDescLen = FS_BaseDir_FOpenFileRead( descPath, &descHandle );
2467
2468 if ( nDescLen > 0 ) {
2469 file = FS_FileForHandle(descHandle);
2470 Com_Memset( description, 0, descriptionLen );
2471 nDescLen = fread(description, 1, descriptionLen, file);
2472 if (nDescLen >= 0) {
2473 description[nDescLen] = '\0';
2474 }
2475 } else {
2476 Q_strncpyz( description, modDir, descriptionLen );
2477 }
2478
2479 if ( descHandle ) {
2480 FS_FCloseFile( descHandle );
2481 }
2482 }
2483
2484 /*
2485 ================
2486 FS_GetModList
2487
2488 Returns a list of mod directory names
2489 A mod directory is a peer to baseq3 with a pk3 or pk3dir in it
2490 ================
2491 */
2492 int FS_GetModList( char *listbuf, int bufsize ) {
2493 int nMods, i, j, k, nTotal, nLen, nPaks = 0, nDirs = 0, nPakDirs = 0, nPotential, nDescLen;
2494 char **pFiles = NULL;
2495 char **pPaks = NULL;
2496 char **pDirs = NULL;
2497 char *name, *path;
2498 char description[MAX_OSPATH];
2499
2500 int dummy;
2501 char **pFiles0 = NULL;
2502 qboolean bDrop = qfalse;
2503
2504 *listbuf = 0;
2505 nMods = nTotal = 0;
2506
2507 // iterate through paths and get list of potential mods
2508 for (i = 0; i < ARRAY_LEN(fs_pathVars); i++) {
2509 const cvar_t *pathVar = fs_pathVars[i];
2510
2511 if (!pathVar || !pathVar->string[0]) {
2512 continue;
2513 }
2514
2515 pFiles0 = Sys_ListFiles(pathVar->string, NULL, NULL, &dummy, qtrue);
2516 // Sys_ConcatenateFileLists frees the lists so Sys_FreeFileList isn't required
2517 pFiles = Sys_ConcatenateFileLists(pFiles, pFiles0);
2518 }
2519
2520 nPotential = Sys_CountFileList(pFiles);
2521
2522 for (i = 0; i < nPotential; i++) {
2523 name = pFiles[i];
2524 // NOTE: cleaner would involve more changes
2525 // ignore duplicate mod directories
2526 if (i != 0) {
2527 bDrop = qfalse;
2528 for (j = 0; j < i; j++) {
2529 if (Q_stricmp(pFiles[j], name) == 0) {
2530 // this one can be dropped
2531 bDrop = qtrue;
2532 break;
2533 }
2534 }
2535 }
2536 // we also drop "baseq3" "." and ".."
2537 if (bDrop || Q_stricmp(name, com_basegame->string) == 0 || Q_stricmpn(name, ".", 1) == 0) {
2538 continue;
2539 }
2540
2541 // in order to be a valid mod the directory must contain at least one .pk3 or .pk3dir
2542 // we didn't keep the information when we merged the directory names, as to what OS Path it was found under
2543 // so we will try each of them here
2544 for (j = 0; j < ARRAY_LEN(fs_pathVars); j++) {
2545 const cvar_t *pathVar = fs_pathVars[j];
2546
2547 if (!pathVar || !pathVar->string[0]) {
2548 continue;
2549 }
2550
2551 path = FS_BaseDir_BuildOSPath(pathVar->string, name);
2552 nPaks = nDirs = nPakDirs = 0;
2553 pPaks = Sys_ListFiles(path, ".pk3", NULL, &nPaks, qfalse);
2554 pDirs = Sys_ListFiles(path, "/", NULL, &nDirs, qfalse);
2555 for (k = 0; k < nDirs; k++) {
2556 // we only want to count directories ending with ".pk3dir"
2557 if (FS_IsExt(pDirs[k], ".pk3dir", strlen(pDirs[k]))) {
2558 nPakDirs++;
2559 }
2560 }
2561 // we only use Sys_ListFiles to check whether files are present
2562 Sys_FreeFileList(pPaks);
2563 Sys_FreeFileList(pDirs);
2564
2565 if (nPaks > 0 || nPakDirs > 0) {
2566 break;
2567 }
2568 }
2569
2570 if (nPaks > 0 || nPakDirs > 0) {
2571 nLen = strlen(name) + 1;
2572 // nLen is the length of the mod path
2573 // we need to see if there is a description available
2574 FS_GetModDescription(name, description, sizeof(description));
2575 nDescLen = strlen(description) + 1;
2576
2577 if (nTotal + nLen + 1 + nDescLen + 1 < bufsize) {
2578 strcpy(listbuf, name);
2579 listbuf += nLen;
2580 strcpy(listbuf, description);
2581 listbuf += nDescLen;
2582 nTotal += nLen + nDescLen;
2583 nMods++;
2584 } else {
2585 break;
2586 }
2587 }
2588 }
2589 Sys_FreeFileList( pFiles );
2590
2591 return nMods;
2592 }
2593
2594
2595
2596
2597 //============================================================================
2598
2599 /*
2600 ================
2601 FS_Dir_f
2602 ================
2603 */
2604 void FS_Dir_f( void ) {
2605 char *path;
2606 char *extension;
2607 char **dirnames;
2608 int ndirs;
2609 int i;
2610
2611 if ( Cmd_Argc() < 2 || Cmd_Argc() > 3 ) {
2612 Com_Printf( "usage: dir <directory> [extension]\n" );
2613 return;
2614 }
2615
2616 if ( Cmd_Argc() == 2 ) {
2617 path = Cmd_Argv( 1 );
2618 extension = "";
2619 } else {
2620 path = Cmd_Argv( 1 );
2621 extension = Cmd_Argv( 2 );
2622 }
2623
2624 Com_Printf( "Directory of %s %s\n", path, extension );
2625 Com_Printf( "---------------\n" );
2626
2627 dirnames = FS_ListFiles( path, extension, &ndirs );
2628
2629 for ( i = 0; i < ndirs; i++ ) {
2630 Com_Printf( "%s\n", dirnames[i] );
2631 }
2632 FS_FreeFileList( dirnames );
2633 }
2634
2635 /*
2636 ===========
2637 FS_ConvertPath
2638 ===========
2639 */
2640 void FS_ConvertPath( char *s ) {
2641 while (*s) {
2642 if ( *s == '\\' || *s == ':' ) {
2643 *s = '/';
2644 }
2645 s++;
2646 }
2647 }
2648
2649 /*
2650 ===========
2651 FS_PathCmp
2652
2653 Ignore case and seprator char distinctions
2654 ===========
2655 */
2656 int FS_PathCmp( const char *s1, const char *s2 ) {
2657 int c1, c2;
2658
2659 do {
2660 c1 = *s1++;
2661 c2 = *s2++;
2662
2663 if (c1 >= 'a' && c1 <= 'z') {
2664 c1 -= ('a' - 'A');
2665 }
2666 if (c2 >= 'a' && c2 <= 'z') {
2667 c2 -= ('a' - 'A');
2668 }
2669
2670 if ( c1 == '\\' || c1 == ':' ) {
2671 c1 = '/';
2672 }
2673 if ( c2 == '\\' || c2 == ':' ) {
2674 c2 = '/';
2675 }
2676
2677 if (c1 < c2) {
2678 return -1; // strings not equal
2679 }
2680 if (c1 > c2) {
2681 return 1;
2682 }
2683 } while (c1);
2684
2685 return 0; // strings are equal
2686 }
2687
2688 /*
2689 ================
2690 FS_SortFileList
2691 ================
2692 */
2693 void FS_SortFileList(char **filelist, int numfiles) {
2694 int i, j, k, numsortedfiles;
2695 char **sortedlist;
2696
2697 sortedlist = Z_Malloc( ( numfiles + 1 ) * sizeof( *sortedlist ) );
2698 sortedlist[0] = NULL;
2699 numsortedfiles = 0;
2700 for (i = 0; i < numfiles; i++) {
2701 for (j = 0; j < numsortedfiles; j++) {
2702 if (FS_PathCmp(filelist[i], sortedlist[j]) < 0) {
2703 break;
2704 }
2705 }
2706 for (k = numsortedfiles; k > j; k--) {
2707 sortedlist[k] = sortedlist[k-1];
2708 }
2709 sortedlist[j] = filelist[i];
2710 numsortedfiles++;
2711 }
2712 Com_Memcpy(filelist, sortedlist, numfiles * sizeof( *filelist ) );
2713 Z_Free(sortedlist);
2714 }
2715
2716 /*
2717 ================
2718 FS_NewDir_f
2719 ================
2720 */
2721 void FS_NewDir_f( void ) {
2722 char *filter;
2723 char **dirnames;
2724 int ndirs;
2725 int i;
2726
2727 if ( Cmd_Argc() < 2 ) {
2728 Com_Printf( "usage: fdir <filter>\n" );
2729 Com_Printf( "example: fdir *q3dm*.bsp\n");
2730 return;
2731 }
2732
2733 filter = Cmd_Argv( 1 );
2734
2735 Com_Printf( "---------------\n" );
2736
2737 dirnames = FS_ListFilteredFiles( "", "", filter, &ndirs, qfalse, qfalse );
2738
2739 FS_SortFileList(dirnames, ndirs);
2740
2741 for ( i = 0; i < ndirs; i++ ) {
2742 FS_ConvertPath(dirnames[i]);
2743 Com_Printf( "%s\n", dirnames[i] );
2744 }
2745 Com_Printf( "%d files listed\n", ndirs );
2746 FS_FreeFileList( dirnames );
2747 }
2748
2749 /*
2750 ============
2751 FS_Path_f
2752
2753 ============
2754 */
2755 void FS_Path_f( void ) {
2756 searchpath_t *s;
2757 int i;
2758
2759 Com_Printf ("We are looking in the current search path:\n");
2760 for (s = fs_searchpaths; s; s = s->next) {
2761 if (s->pack) {
2762 Com_Printf ("%s (%i files)\n", s->pack->pakFilename, s->pack->numfiles);
2763 if ( fs_numServerPaks ) {
2764 if ( !FS_PakIsPure(s->pack) ) {
2765 Com_Printf( " not on the pure list\n" );
2766 } else {
2767 Com_Printf( " on the pure list\n" );
2768 }
2769 }
2770 } else {
2771 Com_Printf ("%s%c%s\n", s->dir->path, PATH_SEP, s->dir->gamedir );
2772 }
2773 }
2774
2775
2776 Com_Printf( "\n" );
2777 for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
2778 if ( fsh[i].handleFiles.file.o ) {
2779 Com_Printf( "handle %i: %s\n", i, fsh[i].name );
2780 }
2781 }
2782 }
2783
2784 /*
2785 ============
2786 FS_TouchFile_f
2787 ============
2788 */
2789 void FS_TouchFile_f( void ) {
2790 fileHandle_t f;
2791
2792 if ( Cmd_Argc() != 2 ) {
2793 Com_Printf( "Usage: touchFile <file>\n" );
2794 return;
2795 }
2796
2797 FS_FOpenFileRead( Cmd_Argv( 1 ), &f, qfalse );
2798 if ( f ) {
2799 FS_FCloseFile( f );
2800 }
2801 }
2802
2803 /*
2804 ============
2805 FS_Which
2806 ============
2807 */
2808
2809 qboolean FS_Which(const char *filename, void *searchPath)
2810 {
2811 searchpath_t *search = searchPath;
2812
2813 if(FS_FOpenFileReadDir(filename, search, NULL, qfalse, qfalse) > 0)
2814 {
2815 if(search->pack)
2816 {
2817 Com_Printf("File \"%s\" found in \"%s\"\n", filename, search->pack->pakFilename);
2818 return qtrue;
2819 }
2820 else if(search->dir)
2821 {
2822 Com_Printf( "File \"%s\" found at \"%s\"\n", filename, search->dir->fullpath);
2823 return qtrue;
2824 }
2825 }
2826
2827 return qfalse;
2828 }
2829
2830 /*
2831 ============
2832 FS_Which_f
2833 ============
2834 */
2835 void FS_Which_f( void ) {
2836 searchpath_t *search;
2837 char *filename;
2838
2839 filename = Cmd_Argv(1);
2840
2841 if ( !filename[0] ) {
2842 Com_Printf( "Usage: which <file>\n" );
2843 return;
2844 }
2845
2846 // qpaths are not supposed to have a leading slash
2847 if ( filename[0] == '/' || filename[0] == '\\' ) {
2848 filename++;
2849 }
2850
2851 // just wants to see if file is there
2852 for(search = fs_searchpaths; search; search = search->next)
2853 {
2854 if(FS_Which(filename, search))
2855 return;
2856 }
2857
2858 Com_Printf("File not found: \"%s\"\n", filename);
2859 }
2860
2861
2862 //===========================================================================
2863
2864
2865 static int QDECL paksort( const void *a, const void *b ) {
2866 char *aa, *bb;
2867
2868 aa = *(char **)a;
2869 bb = *(char **)b;
2870
2871 return FS_PathCmp( aa, bb );
2872 }
2873
2874 /*
2875 ================
2876 FS_AddGameDirectory
2877
2878 Sets fs_gamedir, adds the directory to the head of the path,
2879 then loads the zip headers
2880 ================
2881 */
2882 static void FS_AddGameDirectory( const char *path, const char *dir ) {
2883 searchpath_t *sp;
2884 searchpath_t *search;
2885 pack_t *pak;
2886 char curpath[MAX_OSPATH + 1], *pakfile;
2887 int numfiles;
2888 char **pakfiles;
2889 int pakfilesi;
2890 char **pakfilestmp;
2891 int numdirs;
2892 char **pakdirs;
2893 int pakdirsi;
2894 char **pakdirstmp;
2895
2896 int pakwhich;
2897 int len;
2898
2899 // Unique
2900 for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
2901 if ( sp->dir && !Q_stricmp(sp->dir->path, path) && !Q_stricmp(sp->dir->gamedir, dir)) {
2902 return; // we've already got this one
2903 }
2904 }
2905
2906 Q_strncpyz( fs_gamedir, dir, sizeof( fs_gamedir ) );
2907
2908 // find all pak files in this directory
2909 Q_strncpyz(curpath, FS_BaseDir_BuildOSPath(path, dir), sizeof(curpath));
2910
2911 // Get .pk3 files
2912 pakfiles = Sys_ListFiles(curpath, ".pk3", NULL, &numfiles, qfalse);
2913
2914 if ( pakfiles ) {
2915 qsort( pakfiles, numfiles, sizeof(char*), paksort );
2916 }
2917
2918 if ( fs_numServerPaks ) {
2919 numdirs = 0;
2920 pakdirs = NULL;
2921 } else {
2922 // Get top level directories (we'll filter them later since the Sys_ListFiles filtering is terrible)
2923 pakdirs = Sys_ListFiles(curpath, "/", NULL, &numdirs, qfalse);
2924
2925 qsort( pakdirs, numdirs, sizeof(char *), paksort );
2926 }
2927
2928 pakfilesi = 0;
2929 pakdirsi = 0;
2930
2931 while((pakfilesi < numfiles) || (pakdirsi < numdirs))
2932 {
2933 // Check if a pakfile or pakdir comes next
2934 if (pakfilesi >= numfiles) {
2935 // We've used all the pakfiles, it must be a pakdir.
2936 pakwhich = 0;
2937 }
2938 else if (pakdirsi >= numdirs) {
2939 // We've used all the pakdirs, it must be a pakfile.
2940 pakwhich = 1;
2941 }
2942 else {
2943 // Could be either, compare to see which name comes first
2944 // Need tmp variables for appropriate indirection for paksort()
2945 pakfilestmp = &pakfiles[pakfilesi];
2946 pakdirstmp = &pakdirs[pakdirsi];
2947 pakwhich = (paksort(pakfilestmp, pakdirstmp) < 0);
2948 }
2949
2950 if (pakwhich) {
2951 // The next .pk3 file is before the next .pk3dir
2952 pakfile = FS_BuildOSPath(path, dir, pakfiles[pakfilesi]);
2953 if ((pak = FS_LoadZipFile(pakfile, pakfiles[pakfilesi])) == 0) {
2954 // This isn't a .pk3! Next!
2955 pakfilesi++;
2956 continue;
2957 }
2958
2959 Q_strncpyz(pak->pakPathname, curpath, sizeof(pak->pakPathname));
2960 // store the game name for downloading
2961 Q_strncpyz(pak->pakGamename, dir, sizeof(pak->pakGamename));
2962
2963 fs_packFiles += pak->numfiles;
2964
2965 search = Z_Malloc(sizeof(searchpath_t));
2966 search->pack = pak;
2967 search->next = fs_searchpaths;
2968 fs_searchpaths = search;
2969
2970 pakfilesi++;
2971 }
2972 else {
2973 // The next .pk3dir is before the next .pk3 file
2974 // But wait, this could be any directory, we're filtering to only ending with ".pk3dir" here.
2975 len = strlen(pakdirs[pakdirsi]);
2976 if (!FS_IsExt(pakdirs[pakdirsi], ".pk3dir", len)) {
2977 // This isn't a .pk3dir! Next!
2978 pakdirsi++;
2979 continue;
2980 }
2981
2982 pakfile = FS_BuildOSPath(path, dir, pakdirs[pakdirsi]);
2983
2984 // add the directory to the search path
2985 search = Z_Malloc(sizeof(searchpath_t));
2986 search->dir = Z_Malloc(sizeof(*search->dir));
2987
2988 Q_strncpyz(search->dir->path, curpath, sizeof(search->dir->path)); // c:\quake3\baseq3
2989 Q_strncpyz(search->dir->fullpath, pakfile, sizeof(search->dir->fullpath)); // c:\quake3\baseq3\mypak.pk3dir
2990 Q_strncpyz(search->dir->gamedir, pakdirs[pakdirsi], sizeof(search->dir->gamedir)); // mypak.pk3dir
2991
2992 search->next = fs_searchpaths;
2993 fs_searchpaths = search;
2994
2995 pakdirsi++;
2996 }
2997 }
2998
2999 // done
3000 Sys_FreeFileList( pakfiles );
3001 Sys_FreeFileList( pakdirs );
3002
3003 //
3004 // add the directory to the search path
3005 //
3006 search = Z_Malloc (sizeof(searchpath_t));
3007 search->dir = Z_Malloc( sizeof( *search->dir ) );
3008
3009 Q_strncpyz(search->dir->path, path, sizeof(search->dir->path));
3010 Q_strncpyz(search->dir->fullpath, curpath, sizeof(search->dir->fullpath));
3011 Q_strncpyz(search->dir->gamedir, dir, sizeof(search->dir->gamedir));
3012
3013 search->next = fs_searchpaths;
3014 fs_searchpaths = search;
3015 }
3016
3017 /*
3018 ================
3019 FS_AddGameDirectories
3020 ================
3021 */
3022 static void FS_AddGameDirectories(const char *dir)
3023 {
3024 // add search path elements in reverse priority order
3025 for(int i = ARRAY_LEN(fs_pathVars) - 1; i >= 0; i--) {
3026 const cvar_t *pathVar = fs_pathVars[i];
3027
3028 if (!pathVar || !pathVar->string[0]) {
3029 continue;
3030 }
3031
3032 FS_AddGameDirectory(pathVar->string, dir);
3033 }
3034 }
3035
3036 /*
3037 ================
3038 FS_idPak
3039 ================
3040 */
3041 qboolean FS_idPak(char *pak, char *base, int numPaks)
3042 {
3043 int i;
3044
3045 for (i = 0; i < NUM_ID_PAKS; i++) {
3046 if ( !FS_FilenameCompare(pak, va("%s/pak%d", base, i)) ) {
3047 break;
3048 }
3049 }
3050 if (i < numPaks) {
3051 return qtrue;
3052 }
3053 return qfalse;
3054 }
3055
3056 /*
3057 ================
3058 FS_CheckDirTraversal
3059
3060 Check whether the string contains stuff like "../" to prevent directory traversal bugs
3061 and return qtrue if it does.
3062 ================
3063 */
3064
3065 qboolean FS_CheckDirTraversal(const char *checkdir)
3066 {
3067 if(strstr(checkdir, "../") || strstr(checkdir, "..\\"))
3068 return qtrue;
3069
3070 return qfalse;
3071 }
3072
3073 /*
3074 ================
3075 FS_InvalidGameDir
3076
3077 return true if path is a reference to current directory or directory traversal
3078 or a sub-directory
3079 ================
3080 */
3081 qboolean FS_InvalidGameDir( const char *gamedir ) {
3082 if ( !strcmp( gamedir, "." ) || !strcmp( gamedir, ".." )
3083 || strchr( gamedir, '/' ) || strchr( gamedir, '\\' ) ) {
3084 return qtrue;
3085 }
3086
3087 return qfalse;
3088 }
3089
3090 /*
3091 ================
3092 FS_ComparePaks
3093
3094 ----------------
3095 dlstring == qtrue
3096
3097 Returns a list of pak files that we should download from the server. They all get stored
3098 in the current gamedir and an FS_Restart will be fired up after we download them all.
3099
3100 The string is the format:
3101
3102 @remotename@localname [repeat]
3103
3104 static int fs_numServerReferencedPaks;
3105 static int fs_serverReferencedPaks[MAX_SEARCH_PATHS];
3106 static char *fs_serverReferencedPakNames[MAX_SEARCH_PATHS];
3107
3108 ----------------
3109 dlstring == qfalse
3110
3111 we are not interested in a download string format, we want something human-readable
3112 (this is used for diagnostics while connecting to a pure server)
3113
3114 ================
3115 */
3116 qboolean FS_ComparePaks( char *neededpaks, int len, qboolean dlstring ) {
3117 searchpath_t *sp;
3118 qboolean havepak;
3119 char *origpos = neededpaks;
3120 int i;
3121
3122 if (!fs_numServerReferencedPaks)
3123 return qfalse; // Server didn't send any pack information along
3124
3125 *neededpaks = 0;
3126
3127 for ( i = 0 ; i < fs_numServerReferencedPaks ; i++ )
3128 {
3129 // Ok, see if we have this pak file
3130 havepak = qfalse;
3131
3132 // never autodownload any of the id paks
3133 if(FS_idPak(fs_serverReferencedPakNames[i], BASEGAME, NUM_ID_PAKS)
3134 #ifndef STANDALONE
3135 || FS_idPak(fs_serverReferencedPakNames[i], BASETA, NUM_TA_PAKS)
3136 #endif
3137 )
3138 {
3139 continue;
3140 }
3141
3142 // Make sure the server cannot make us write to non-quake3 directories.
3143 if(FS_CheckDirTraversal(fs_serverReferencedPakNames[i]))
3144 {
3145 Com_Printf("WARNING: Invalid download name %s\n", fs_serverReferencedPakNames[i]);
3146 continue;
3147 }
3148
3149 for ( sp = fs_searchpaths ; sp ; sp = sp->next ) {
3150 if ( sp->pack && sp->pack->checksum == fs_serverReferencedPaks[i] ) {
3151 havepak = qtrue; // This is it!
3152 break;
3153 }
3154 }
3155
3156 if ( !havepak && fs_serverReferencedPakNames[i] && *fs_serverReferencedPakNames[i] ) {
3157 // Don't got it
3158
3159 if (dlstring)
3160 {
3161 // We need this to make sure we won't hit the end of the buffer or the server could
3162 // overwrite non-pk3 files on clients by writing so much crap into neededpaks that
3163 // Q_strcat cuts off the .pk3 extension.
3164
3165 origpos += strlen(origpos);
3166
3167 // Remote name
3168 Q_strcat( neededpaks, len, "@");
3169 Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
3170 Q_strcat( neededpaks, len, ".pk3" );
3171
3172 // Local name
3173 Q_strcat( neededpaks, len, "@");
3174 // Do we have one with the same name?
3175 if ( FS_BaseDir_FileExists_HomeData( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
3176 {
3177 char st[MAX_ZPATH];
3178 // We already have one called this, we need to download it to another name
3179 // Make something up with the checksum in it
3180 Com_sprintf( st, sizeof( st ), "%s.%08x.pk3", fs_serverReferencedPakNames[i], fs_serverReferencedPaks[i] );
3181 Q_strcat( neededpaks, len, st );
3182 }
3183 else
3184 {
3185 Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
3186 Q_strcat( neededpaks, len, ".pk3" );
3187 }
3188
3189 // Find out whether it might have overflowed the buffer and don't add this file to the
3190 // list if that is the case.
3191 if(strlen(origpos) + (origpos - neededpaks) >= len - 1)
3192 {
3193 *origpos = '\0';
3194 break;
3195 }
3196 }
3197 else
3198 {
3199 Q_strcat( neededpaks, len, fs_serverReferencedPakNames[i] );
3200 Q_strcat( neededpaks, len, ".pk3" );
3201 // Do we have one with the same name?
3202 if ( FS_BaseDir_FileExists_HomeData( va( "%s.pk3", fs_serverReferencedPakNames[i] ) ) )
3203 {
3204 Q_strcat( neededpaks, len, " (local file exists with wrong checksum)");
3205 }
3206 Q_strcat( neededpaks, len, "\n");
3207 }
3208 }
3209 }
3210
3211 if ( *neededpaks ) {
3212 return qtrue;
3213 }
3214
3215 return qfalse; // We have them all
3216 }
3217
3218 /*
3219 ================
3220 FS_Shutdown
3221
3222 Frees all resources.
3223 ================
3224 */
3225 void FS_Shutdown( qboolean closemfp ) {
3226 searchpath_t *p, *next;
3227 int i;
3228
3229 for(i = 0; i < MAX_FILE_HANDLES; i++) {
3230 if (fsh[i].fileSize) {
3231 FS_FCloseFile(i);
3232 }
3233 }
3234
3235 // free everything
3236 for(p = fs_searchpaths; p; p = next)
3237 {
3238 next = p->next;
3239
3240 if(p->pack)
3241 FS_FreePak(p->pack);
3242 if (p->dir)
3243 Z_Free(p->dir);
3244
3245 Z_Free(p);
3246 }
3247
3248 // any FS_ calls will now be an error until reinitialized
3249 fs_searchpaths = NULL;
3250
3251 Cmd_RemoveCommand( "path" );
3252 Cmd_RemoveCommand( "dir" );
3253 Cmd_RemoveCommand( "fdir" );
3254 Cmd_RemoveCommand( "touchFile" );
3255 Cmd_RemoveCommand( "which" );
3256
3257 #ifdef FS_MISSING
3258 if (closemfp) {
3259 fclose(missingFiles);
3260 }
3261 #endif
3262 }
3263
3264 #ifndef STANDALONE
3265 void Com_AppendCDKey( const char *filename );
3266 void Com_ReadCDKey( const char *filename );
3267 #endif
3268
3269 /*
3270 ================
3271 FS_ReorderPurePaks
3272 NOTE TTimo: the reordering that happens here is not reflected in the cvars (\cvarlist *pak*)
3273 this can lead to misleading situations, see https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
3274 ================
3275 */
3276 static void FS_ReorderPurePaks( void )
3277 {
3278 searchpath_t *s;
3279 int i;
3280 searchpath_t **p_insert_index, // for linked list reordering
3281 **p_previous; // when doing the scan
3282
3283 fs_reordered = qfalse;
3284
3285 // only relevant when connected to pure server
3286 if ( !fs_numServerPaks )
3287 return;
3288
3289 p_insert_index = &fs_searchpaths; // we insert in order at the beginning of the list
3290 for ( i = 0 ; i < fs_numServerPaks ; i++ ) {
3291 p_previous = p_insert_index; // track the pointer-to-current-item
3292 for (s = *p_insert_index; s; s = s->next) {
3293 // the part of the list before p_insert_index has been sorted already
3294 if (s->pack && fs_serverPaks[i] == s->pack->checksum) {
3295 fs_reordered = qtrue;
3296 // move this element to the insert list
3297 *p_previous = s->next;
3298 s->next = *p_insert_index;
3299 *p_insert_index = s;
3300 // increment insert list
3301 p_insert_index = &s->next;
3302 break; // iterate to next server pack
3303 }
3304 p_previous = &s->next;
3305 }
3306 }
3307 }
3308
3309 /*
3310 ================
3311 FS_AddPathVar
3312 ================
3313 */
3314 static void FS_AddPathVar( cvar_t *pathVar ) {
3315 if( !pathVar || !*pathVar->string ) {
3316 return;
3317 }
3318
3319 // Check for duplicates
3320 for( int i = 0; i < ARRAY_LEN( fs_pathVars ); i++ ) {
3321 if ( fs_pathVars[i] && !Q_stricmp( fs_pathVars[i]->string, pathVar->string ) ) {
3322 return;
3323 }
3324 }
3325
3326 // Add to first empty slot
3327 for( int i = 0; i < ARRAY_LEN( fs_pathVars ); i++ ) {
3328 if ( !fs_pathVars[i] ) {
3329 fs_pathVars[i] = pathVar;
3330 return;
3331 }
3332 }
3333
3334 Com_Error( ERR_FATAL, "FS_AddPathVar: exhausted fs_pathVars array" );
3335 }
3336
3337 /*
3338 ================
3339 FS_InitPathVars
3340 ================
3341 */
3342 static void FS_InitPathVars( void ) {
3343 memset( fs_pathVars, 0, sizeof( fs_pathVars ) );
3344
3345 FS_AddPathVar( fs_homeconfigpath );
3346 FS_AddPathVar( fs_homedatapath );
3347 FS_AddPathVar( fs_homestatepath );
3348 FS_AddPathVar( fs_basepath );
3349 FS_AddPathVar( fs_apppath );
3350 FS_AddPathVar( fs_steampath );
3351 FS_AddPathVar( fs_gogpath );
3352 FS_AddPathVar( fs_microsoftstorepath );
3353 }
3354
3355 /*
3356 ================
3357 FS_Startup
3358 ================
3359 */
3360 static void FS_Startup( const char *gameName )
3361 {
3362 cvar_t *fs_homepath = Cvar_Get("fs_homepath", "", CVAR_INIT|CVAR_PROTECTED);
3363 const char *configPath = Sys_DefaultHomeConfigPath();
3364 const char *dataPath = Sys_DefaultHomeDataPath();
3365 const char *statePath = Sys_DefaultHomeStatePath();
3366
3367 if(*(fs_homepath)->string) {
3368 // Setting fs_homepath manually overrides everything else
3369 configPath = dataPath = statePath = fs_homepath->string;
3370 } else if(!*configPath || !*dataPath || !*statePath) {
3371 // #shouldneverhappen; just a sensible fallback
3372 configPath = dataPath = statePath = Sys_DefaultInstallPath();
3373 }
3374
3375 Com_Printf( "----- FS_Startup -----\n" );
3376
3377 fs_packFiles = 0;
3378
3379 fs_debug = Cvar_Get( "fs_debug", "0", 0 );
3380 fs_basepath = Cvar_Get ("fs_basepath", Sys_DefaultInstallPath(), CVAR_INIT|CVAR_PROTECTED );
3381 fs_basegame = Cvar_Get ("fs_basegame", "", CVAR_INIT );
3382 fs_homeconfigpath = Cvar_Get ("fs_homeconfigpath", configPath, CVAR_INIT|CVAR_PROTECTED );
3383 fs_homedatapath = Cvar_Get ("fs_homedatapath", dataPath, CVAR_INIT|CVAR_PROTECTED );
3384 fs_homestatepath = Cvar_Get ("fs_homestatepath", statePath, CVAR_INIT|CVAR_PROTECTED );
3385 fs_gamedirvar = Cvar_Get ("fs_game", "", CVAR_INIT|CVAR_SYSTEMINFO );
3386 fs_steampath = Cvar_Get ("fs_steampath", Sys_SteamPath(), CVAR_INIT|CVAR_PROTECTED );
3387 fs_gogpath = Cvar_Get ("fs_gogpath", Sys_GogPath(), CVAR_INIT|CVAR_PROTECTED );
3388 fs_microsoftstorepath = Cvar_Get ("fs_microsoftstorepath", Sys_MicrosoftStorePath(), CVAR_INIT|CVAR_PROTECTED );
3389
3390 #ifdef __APPLE__
3391 fs_apppath = Cvar_Get ("fs_apppath", Sys_DefaultAppPath(), CVAR_INIT|CVAR_PROTECTED );
3392 #endif
3393
3394 FS_InitPathVars( );
3395
3396 if (!gameName[0]) {
3397 Cvar_ForceReset( "com_basegame" );
3398 }
3399
3400 if (!FS_FilenameCompare(fs_gamedirvar->string, gameName)) {
3401 // This is the standard base game. Servers and clients should
3402 // use "" and not the standard basegame name because this messes
3403 // up pak file negotiation and lots of other stuff
3404 Cvar_ForceReset( "fs_game" );
3405 }
3406
3407 if (FS_InvalidGameDir(gameName)) {
3408 Com_Error( ERR_DROP, "Invalid com_basegame '%s'", gameName );
3409 }
3410 if (FS_InvalidGameDir(fs_basegame->string)) {
3411 Com_Error( ERR_DROP, "Invalid fs_basegame '%s'", fs_basegame->string );
3412 }
3413 if (FS_InvalidGameDir(fs_gamedirvar->string)) {
3414 Com_Error( ERR_DROP, "Invalid fs_game '%s'", fs_gamedirvar->string );
3415 }
3416
3417 FS_CreatePath(fs_homeconfigpath->string);
3418 FS_CreatePath(fs_homedatapath->string);
3419 FS_CreatePath(fs_homestatepath->string);
3420
3421 FS_AddGameDirectories(gameName);
3422
3423 // check for additional base game so mods can be based upon other mods
3424 if ( fs_basegame->string[0] && Q_stricmp( fs_basegame->string, gameName ) ) {
3425 FS_AddGameDirectories(fs_basegame->string);
3426 }
3427
3428 // check for additional game folder for mods
3429 if ( fs_gamedirvar->string[0] && Q_stricmp( fs_gamedirvar->string, gameName ) ) {
3430 FS_AddGameDirectories(fs_gamedirvar->string);
3431 }
3432
3433 #ifndef STANDALONE
3434 if (!com_standalone->integer) {
3435 Com_ReadCDKey(BASEGAME);
3436 if (fs_gamedirvar->string[0]) {
3437 Com_AppendCDKey(fs_gamedirvar->string);
3438 }
3439 }
3440 #endif
3441
3442 // add our commands
3443 Cmd_AddCommand ("path", FS_Path_f);
3444 Cmd_AddCommand ("dir", FS_Dir_f );
3445 Cmd_AddCommand ("fdir", FS_NewDir_f );
3446 Cmd_AddCommand ("touchFile", FS_TouchFile_f );
3447 Cmd_AddCommand ("which", FS_Which_f );
3448
3449 // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=506
3450 // reorder the pure pk3 files according to server order
3451 FS_ReorderPurePaks();
3452
3453 // print the current search paths
3454 FS_Path_f();
3455
3456 fs_gamedirvar->modified = qfalse; // We just loaded, it's not modified
3457
3458 Com_Printf( "----------------------\n" );
3459
3460 #ifdef FS_MISSING
3461 if (missingFiles == NULL) {
3462 missingFiles = Sys_FOpen( "\\missing.txt", "ab" );
3463 }
3464 #endif
3465 Com_Printf( "%d files in pk3 files\n", fs_packFiles );
3466 }
3467
3468 #ifndef STANDALONE
3469 /*
3470 ===================
3471 FS_AppendUserFriendlyPakList
3472 ===================
3473 */
3474 static void FS_AppendUserFriendlyPakList( char *buf, size_t bufsize, int foundPakFiles, int numPakFiles )
3475 {
3476 int missingCount = 0;
3477 int missingIndex = 0;
3478 int missingMin = numPakFiles;
3479 int missingMax = 0;
3480 qboolean missingConsecutive = qtrue;
3481 int i;
3482
3483 for ( i = 0; i < numPakFiles; i++ ) {
3484 if ( foundPakFiles & ( 1 << i ) ) {
3485 continue;
3486 }
3487
3488 missingCount++;
3489
3490 if ( missingMin > i ) {
3491 missingMin = i;
3492 }
3493 if ( missingMax < i ) {
3494 missingMax = i;
3495 }
3496
3497 if ( i > missingMin && ( foundPakFiles & ( 1<< ( i - 1 ) ) ) ) {
3498 missingConsecutive = qfalse;
3499 }
3500 }
3501
3502 if ( missingConsecutive && missingMax >= missingMin + 2 ) {
3503 Q_strcat( buf, bufsize,
3504 va( " \"pak%d.pk3\" through \"pak%d.pk3\"",
3505 missingMin, missingMax ) );
3506 } else {
3507 for ( i = 0; i < numPakFiles; i++ ) {
3508 if ( foundPakFiles & (1<<i) ) {
3509 continue;
3510 }
3511
3512 if ( missingIndex > 0 && missingCount > 2 ) {
3513 Q_strcat( buf, bufsize, "," );
3514 }
3515
3516 if ( missingIndex == missingCount - 1 && missingCount > 1 ) {
3517 Q_strcat( buf, bufsize, " and" );
3518 }
3519
3520 Q_strcat( buf, bufsize, va( " \"pak%d.pk3\"", i ) );
3521
3522 missingIndex++;
3523 }
3524 }
3525 }
3526
3527 /*
3528 ===================
3529 FS_CheckPak0
3530
3531 Check whether any of the original id pak files is present,
3532 and start up in standalone mode, if there are none and a
3533 different com_basegame was set.
3534 Note: If you're building a game that doesn't depend on the
3535 Q3 media pak0.pk3, you'll want to remove this by defining
3536 STANDALONE in q_shared.h
3537 ===================
3538 */
3539 static void FS_CheckPak0( void )
3540 {
3541 searchpath_t *path;
3542 pack_t *curpack;
3543 const char *pakBasename;
3544 qboolean founddemo = qfalse;
3545 unsigned int foundPak = 0, foundTA = 0;
3546 qboolean installHome = qfalse;
3547 char *installPath;
3548
3549 for( path = fs_searchpaths; path; path = path->next )
3550 {
3551 if(!path->pack)
3552 continue;
3553
3554 curpack = path->pack;
3555 pakBasename = curpack->pakBasename;
3556
3557 if(!Q_stricmpn( curpack->pakGamename, "demoq3", MAX_OSPATH )
3558 && !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH ))
3559 {
3560 if(curpack->checksum == DEMO_PAK0_CHECKSUM)
3561 founddemo = qtrue;
3562 }
3563
3564 else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH )
3565 && strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 )
3566 && pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1)
3567 {
3568 if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] )
3569 {
3570 if(pakBasename[3] == '0')
3571 {
3572 Com_Printf("\n\n"
3573 "**************************************************\n"
3574 "WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n"
3575 "is not correct. Please re-copy pak0.pk3 from your\n"
3576 "legitimate Q3 CDROM.\n"
3577 "**************************************************\n\n\n",
3578 curpack->checksum );
3579 }
3580 else
3581 {
3582 Com_Printf("\n\n"
3583 "**************************************************\n"
3584 "WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n"
3585 "is not correct. Please re-install the point release\n"
3586 "**************************************************\n\n\n",
3587 pakBasename[3]-'0', curpack->checksum );
3588 }
3589 }
3590
3591 foundPak |= 1<<(pakBasename[3]-'0');
3592 }
3593 else if(!Q_stricmpn(curpack->pakGamename, BASETA, MAX_OSPATH)
3594 && strlen(pakBasename) == 4 && !Q_stricmpn(pakBasename, "pak", 3)
3595 && pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_TA_PAKS - 1)
3596
3597 {
3598 if(curpack->checksum != missionpak_checksums[pakBasename[3]-'0'])
3599 {
3600 Com_Printf("\n\n"
3601 "**************************************************\n"
3602 "WARNING: " BASETA "/pak%d.pk3 is present but its checksum (%u)\n"
3603 "is not correct. Please re-install Team Arena\n"
3604 "**************************************************\n\n\n",
3605 pakBasename[3]-'0', curpack->checksum );
3606 }
3607
3608 foundTA |= 1 << (pakBasename[3]-'0');
3609 }
3610 else
3611 {
3612 int index;
3613
3614 // Finally check whether this pak's checksum is listed because the user tried
3615 // to trick us by renaming the file, and set foundPak's highest bit to indicate this case.
3616
3617 for(index = 0; index < ARRAY_LEN(pak_checksums); index++)
3618 {
3619 if(curpack->checksum == pak_checksums[index])
3620 {
3621 Com_Printf("\n\n"
3622 "**************************************************\n"
3623 "WARNING: %s is renamed pak file %s%cpak%d.pk3\n"
3624 "Running in standalone mode won't work\n"
3625 "Please rename, or remove this file\n"
3626 "**************************************************\n\n\n",
3627 curpack->pakFilename, BASEGAME, PATH_SEP, index);
3628
3629
3630 foundPak |= 0x80000000;
3631 }
3632 }
3633
3634 for(index = 0; index < ARRAY_LEN(missionpak_checksums); index++)
3635 {
3636 if(curpack->checksum == missionpak_checksums[index])
3637 {
3638 Com_Printf("\n\n"
3639 "**************************************************\n"
3640 "WARNING: %s is renamed pak file %s%cpak%d.pk3\n"
3641 "Running in standalone mode won't work\n"
3642 "Please rename, or remove this file\n"
3643 "**************************************************\n\n\n",
3644 curpack->pakFilename, BASETA, PATH_SEP, index);
3645
3646 foundTA |= 0x80000000;
3647 }
3648 }
3649 }
3650 }
3651
3652 if(!foundPak && !foundTA && Q_stricmp(com_basegame->string, BASEGAME))
3653 {
3654 Cvar_Set("com_standalone", "1");
3655 }
3656 else
3657 Cvar_Set("com_standalone", "0");
3658
3659 if(!com_standalone->integer)
3660 {
3661 if(!(foundPak & 0x01))
3662 {
3663 if(founddemo)
3664 {
3665 Com_Printf( "\n\n"
3666 "**************************************************\n"
3667 "WARNING: It looks like you're using pak0.pk3\n"
3668 "from the demo. This may work fine, but it is not\n"
3669 "guaranteed or supported.\n"
3670 "**************************************************\n\n\n" );
3671
3672 foundPak |= 0x01;
3673 }
3674 }
3675 }
3676
3677 #if defined(__linux__)
3678 {
3679 const char *p;
3680
3681 // Users can't write to the default Flatpak fs_basepath
3682 if( ( p = getenv( "FLATPAK_ID" ) ) != NULL && *p != '\0' )
3683 installHome = qtrue;
3684 }
3685 #elif defined(__APPLE__)
3686 // If we're running from an .app, it makes more sense to recommend
3687 // using fs_homepath as fs_basepath is likely not suitable
3688 if( strstr( fs_apppath->string, "Contents/MacOS" ) )
3689 installHome = qtrue;
3690 #endif
3691
3692 if(installHome)
3693 installPath = fs_homedatapath->string;
3694 else
3695 installPath = fs_basepath->string;
3696
3697 if(!com_standalone->integer && (foundPak & ((1<<NUM_ID_PAKS)-1)) != ((1<<NUM_ID_PAKS)-1))
3698 {
3699 char errorText[MAX_STRING_CHARS] = "";
3700 char gamePath[MAX_OSPATH];
3701
3702 Com_sprintf(gamePath, sizeof(gamePath), "%s%c%s%c",
3703 installPath, PATH_SEP, BASEGAME, PATH_SEP);
3704
3705 Q_strcat(errorText, sizeof(errorText),
3706 "Quake 3 data files are missing. Please copy");
3707
3708 FS_AppendUserFriendlyPakList(errorText, sizeof(errorText), foundPak, NUM_ID_PAKS);
3709
3710 Q_strcat(errorText, sizeof(errorText),
3711 va(" from the \"%s\" directory in your Quake 3 install or CD-ROM to:\n\n"
3712 "%s\n\n", BASEGAME, gamePath));
3713
3714 Q_strcat(errorText, sizeof(errorText),
3715 "Quake 3 must be purchased to legitimately obtain pak0. "
3716 "Quake 3 1.32 point release files (pak1 through pak8) "
3717 "are freely available. For details see:\n\n"
3718 "https://buy.ioquake3.org\n\n");
3719
3720 if(installHome)
3721 {
3722 Q_strcat(errorText, sizeof(errorText),
3723 va("Also check that every file "
3724 "in the \"%s\" directory is present and readable", BASEGAME));
3725 }
3726 else
3727 {
3728 Q_strcat(errorText, sizeof(errorText),
3729 va("Also check that your ioq3 executable is in "
3730 "the correct place and that every file "
3731 "in the \"%s\" directory is present and readable", BASEGAME));
3732 }
3733
3734 Sys_OpenFolderInFileManager(gamePath, qtrue);
3735 Com_Error(ERR_FATAL, "%s", errorText);
3736 }
3737
3738 if(!com_standalone->integer && (foundTA & ((1<<NUM_TA_PAKS)-1)) != ((1<<NUM_TA_PAKS)-1)
3739 && (!Q_stricmp(fs_gamedirvar->string, BASETA) || !Q_stricmp(fs_basegame->string, BASETA)))
3740 {
3741 char errorText[MAX_STRING_CHARS] = "";
3742 char gamePath[MAX_OSPATH];
3743
3744 Com_sprintf(gamePath, sizeof(gamePath), "%s%c%s%c",
3745 installPath, PATH_SEP, BASETA, PATH_SEP);
3746
3747 Q_strcat(errorText, sizeof(errorText),
3748 "Quake 3 Team Arena data files are missing. Please copy");
3749
3750 FS_AppendUserFriendlyPakList(errorText, sizeof(errorText), foundTA, NUM_TA_PAKS);
3751
3752 Q_strcat(errorText, sizeof(errorText),
3753 va(" from the \"%s\" directory in your Quake 3 Team Arena install or CD-ROM to:\n\n"
3754 "%s\n\n", BASETA, gamePath));
3755
3756 Q_strcat(errorText, sizeof(errorText),
3757 "Quake 3 Team Arena must be purchased to legitimately obtain pak0. "
3758 "Quake 3 Team Arena point release files (pak1 through pak3) "
3759 "are freely available. For details see:\n\n"
3760 "https://buy.ioquake3.org\n\n");
3761
3762 if(installHome)
3763 {
3764 Q_strcat(errorText, sizeof(errorText),
3765 va("Also check that every file "
3766 "in the \"%s\" directory is present and readable", BASETA));
3767 }
3768 else
3769 {
3770 Q_strcat(errorText, sizeof(errorText),
3771 va("Also check that your ioq3 executable is in "
3772 "the correct place and that every file "
3773 "in the \"%s\" directory is present and readable", BASETA));
3774 }
3775
3776 Sys_OpenFolderInFileManager(gamePath, qtrue);
3777 Com_Error(ERR_FATAL, "%s", errorText);
3778 }
3779 }
3780 #endif
3781
3782 /*
3783 =====================
3784 FS_LoadedPakChecksums
3785
3786 Returns a space separated string containing the checksums of all loaded pk3 files.
3787 Servers with sv_pure set will get this string and pass it to clients.
3788 =====================
3789 */
3790 const char *FS_LoadedPakChecksums( void ) {
3791 static char info[BIG_INFO_STRING];
3792 searchpath_t *search;
3793
3794 info[0] = 0;
3795
3796 for ( search = fs_searchpaths ; search ; search = search->next ) {
3797 // is the element a pak file?
3798 if ( !search->pack ) {
3799 continue;
3800 }
3801
3802 Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
3803 }
3804
3805 return info;
3806 }
3807
3808 /*
3809 =====================
3810 FS_LoadedPakNames
3811
3812 Returns a space separated string containing the names of all loaded pk3 files.
3813 Servers with sv_pure set will get this string and pass it to clients.
3814 =====================
3815 */
3816 const char *FS_LoadedPakNames( void ) {
3817 static char info[BIG_INFO_STRING];
3818 searchpath_t *search;
3819
3820 info[0] = 0;
3821
3822 for ( search = fs_searchpaths ; search ; search = search->next ) {
3823 // is the element a pak file?
3824 if ( !search->pack ) {
3825 continue;
3826 }
3827
3828 if (*info) {
3829 Q_strcat(info, sizeof( info ), " " );
3830 }
3831 Q_strcat( info, sizeof( info ), search->pack->pakBasename );
3832 }
3833
3834 return info;
3835 }
3836
3837 /*
3838 =====================
3839 FS_LoadedPakPureChecksums
3840
3841 Returns a space separated string containing the pure checksums of all loaded pk3 files.
3842 Servers with sv_pure use these checksums to compare with the checksums the clients send
3843 back to the server.
3844 =====================
3845 */
3846 const char *FS_LoadedPakPureChecksums( void ) {
3847 static char info[BIG_INFO_STRING];
3848 searchpath_t *search;
3849
3850 info[0] = 0;
3851
3852 for ( search = fs_searchpaths ; search ; search = search->next ) {
3853 // is the element a pak file?
3854 if ( !search->pack ) {
3855 continue;
3856 }
3857
3858 Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
3859 }
3860
3861 return info;
3862 }
3863
3864 /*
3865 =====================
3866 FS_ReferencedPakChecksums
3867
3868 Returns a space separated string containing the checksums of all referenced pk3 files.
3869 The server will send this to the clients so they can check which files should be auto-downloaded.
3870 =====================
3871 */
3872 const char *FS_ReferencedPakChecksums( void ) {
3873 static char info[BIG_INFO_STRING];
3874 searchpath_t *search;
3875
3876 info[0] = 0;
3877
3878
3879 for ( search = fs_searchpaths ; search ; search = search->next ) {
3880 // is the element a pak file?
3881 if ( search->pack ) {
3882 if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
3883 Q_strcat( info, sizeof( info ), va("%i ", search->pack->checksum ) );
3884 }
3885 }
3886 }
3887
3888 return info;
3889 }
3890
3891 /*
3892 =====================
3893 FS_ReferencedPakPureChecksums
3894
3895 Returns a space separated string containing the pure checksums of all referenced pk3 files.
3896 Servers with sv_pure set will get this string back from clients for pure validation
3897
3898 The string has a specific order, "cgame ui @ ref1 ref2 ref3 ..."
3899 =====================
3900 */
3901 const char *FS_ReferencedPakPureChecksums( void ) {
3902 static char info[BIG_INFO_STRING];
3903 searchpath_t *search;
3904 int nFlags, numPaks, checksum;
3905
3906 info[0] = 0;
3907
3908 checksum = fs_checksumFeed;
3909 numPaks = 0;
3910 for (nFlags = FS_CGAME_REF; nFlags; nFlags = nFlags >> 1) {
3911 if (nFlags & FS_GENERAL_REF) {
3912 // add a delimter between must haves and general refs
3913 //Q_strcat(info, sizeof(info), "@ ");
3914 info[strlen(info)+1] = '\0';
3915 info[strlen(info)+2] = '\0';
3916 info[strlen(info)] = '@';
3917 info[strlen(info)] = ' ';
3918 }
3919 for ( search = fs_searchpaths ; search ; search = search->next ) {
3920 // is the element a pak file and has it been referenced based on flag?
3921 if ( search->pack && (search->pack->referenced & nFlags)) {
3922 Q_strcat( info, sizeof( info ), va("%i ", search->pack->pure_checksum ) );
3923 if (nFlags & (FS_CGAME_REF | FS_UI_REF)) {
3924 break;
3925 }
3926 checksum ^= search->pack->pure_checksum;
3927 numPaks++;
3928 }
3929 }
3930 }
3931 // last checksum is the encoded number of referenced pk3s
3932 checksum ^= numPaks;
3933 Q_strcat( info, sizeof( info ), va("%i ", checksum ) );
3934
3935 return info;
3936 }
3937
3938 /*
3939 =====================
3940 FS_ReferencedPakNames
3941
3942 Returns a space separated string containing the names of all referenced pk3 files.
3943 The server will send this to the clients so they can check which files should be auto-downloaded.
3944 =====================
3945 */
3946 const char *FS_ReferencedPakNames( void ) {
3947 static char info[BIG_INFO_STRING];
3948 searchpath_t *search;
3949
3950 info[0] = 0;
3951
3952 // we want to return ALL pk3's from the fs_game path
3953 // and referenced one's from baseq3
3954 for ( search = fs_searchpaths ; search ; search = search->next ) {
3955 // is the element a pak file?
3956 if ( search->pack ) {
3957 if (search->pack->referenced || Q_stricmpn(search->pack->pakGamename, com_basegame->string, strlen(com_basegame->string))) {
3958 if (*info) {
3959 Q_strcat(info, sizeof( info ), " " );
3960 }
3961 Q_strcat( info, sizeof( info ), search->pack->pakGamename );
3962 Q_strcat( info, sizeof( info ), "/" );
3963 Q_strcat( info, sizeof( info ), search->pack->pakBasename );
3964 }
3965 }
3966 }
3967
3968 return info;
3969 }
3970
3971 /*
3972 =====================
3973 FS_ClearPakReferences
3974 =====================
3975 */
3976 void FS_ClearPakReferences( int flags ) {
3977 searchpath_t *search;
3978
3979 if ( !flags ) {
3980 flags = -1;
3981 }
3982 for ( search = fs_searchpaths; search; search = search->next ) {
3983 // is the element a pak file and has it been referenced?
3984 if ( search->pack ) {
3985 search->pack->referenced &= ~flags;
3986 }
3987 }
3988 }
3989
3990
3991 /*
3992 =====================
3993 FS_PureServerSetLoadedPaks
3994
3995 If the string is empty, all data sources will be allowed.
3996 If not empty, only pk3 files that match one of the space
3997 separated checksums will be checked for files, with the
3998 exception of .cfg and .dat files.
3999 =====================
4000 */
4001 void FS_PureServerSetLoadedPaks( const char *pakSums, const char *pakNames ) {
4002 int i, c, d;
4003
4004 Cmd_TokenizeString( pakSums );
4005
4006 c = Cmd_Argc();
4007 if ( c > MAX_SEARCH_PATHS ) {
4008 c = MAX_SEARCH_PATHS;
4009 }
4010
4011 fs_numServerPaks = c;
4012
4013 for ( i = 0 ; i < c ; i++ ) {
4014 fs_serverPaks[i] = atoi( Cmd_Argv( i ) );
4015 }
4016
4017 if (fs_numServerPaks) {
4018 Com_DPrintf( "Connected to a pure server.\n" );
4019 }
4020 else
4021 {
4022 if (fs_reordered)
4023 {
4024 // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540
4025 // force a restart to make sure the search order will be correct
4026 Com_DPrintf( "FS search reorder is required\n" );
4027 FS_Restart(fs_checksumFeed);
4028 return;
4029 }
4030 }
4031
4032 for ( i = 0 ; i < c ; i++ ) {
4033 if (fs_serverPakNames[i]) {
4034 Z_Free(fs_serverPakNames[i]);
4035 }
4036 fs_serverPakNames[i] = NULL;
4037 }
4038 if ( pakNames && *pakNames ) {
4039 Cmd_TokenizeString( pakNames );
4040
4041 d = Cmd_Argc();
4042 if ( d > MAX_SEARCH_PATHS ) {
4043 d = MAX_SEARCH_PATHS;
4044 }
4045
4046 for ( i = 0 ; i < d ; i++ ) {
4047 fs_serverPakNames[i] = CopyString( Cmd_Argv( i ) );
4048 }
4049 }
4050 }
4051
4052 /*
4053 =====================
4054 FS_PureServerSetReferencedPaks
4055
4056 The checksums and names of the pk3 files referenced at the server
4057 are sent to the client and stored here. The client will use these
4058 checksums to see if any pk3 files need to be auto-downloaded.
4059 =====================
4060 */
4061 void FS_PureServerSetReferencedPaks( const char *pakSums, const char *pakNames ) {
4062 int i, c, d = 0;
4063
4064 Cmd_TokenizeString( pakSums );
4065
4066 c = Cmd_Argc();
4067 if ( c > MAX_SEARCH_PATHS ) {
4068 c = MAX_SEARCH_PATHS;
4069 }
4070
4071 for ( i = 0 ; i < c ; i++ ) {
4072 fs_serverReferencedPaks[i] = atoi( Cmd_Argv( i ) );
4073 }
4074
4075 for (i = 0 ; i < ARRAY_LEN(fs_serverReferencedPakNames); i++)
4076 {
4077 if(fs_serverReferencedPakNames[i])
4078 Z_Free(fs_serverReferencedPakNames[i]);
4079
4080 fs_serverReferencedPakNames[i] = NULL;
4081 }
4082
4083 if ( pakNames && *pakNames ) {
4084 Cmd_TokenizeString( pakNames );
4085
4086 d = Cmd_Argc();
4087
4088 if(d > c)
4089 d = c;
4090
4091 for ( i = 0 ; i < d ; i++ ) {
4092 fs_serverReferencedPakNames[i] = CopyString( Cmd_Argv( i ) );
4093 }
4094 }
4095
4096 // ensure that there are as many checksums as there are pak names.
4097 if(d < c)
4098 c = d;
4099
4100 fs_numServerReferencedPaks = c;
4101 }
4102
4103 /*
4104 ================
4105 FS_InitFilesystem
4106
4107 Called only at initial startup, not when the filesystem
4108 is resetting due to a game change
4109 ================
4110 */
4111 void FS_InitFilesystem( void ) {
4112 // allow command line parms to override our defaults
4113 // we have to specially handle this, because normal command
4114 // line variable sets don't happen until after the filesystem
4115 // has already been initialized
4116 Com_StartupVariable("fs_basepath");
4117 Com_StartupVariable("fs_homepath");
4118 Com_StartupVariable("fs_homeconfigpath");
4119 Com_StartupVariable("fs_homedatapath");
4120 Com_StartupVariable("fs_homestatepath");
4121 Com_StartupVariable("fs_game");
4122
4123 if(!FS_FilenameCompare(Cvar_VariableString("fs_game"), com_basegame->string))
4124 Cvar_Set("fs_game", "");
4125
4126 // try to start up normally
4127 FS_Startup(com_basegame->string);
4128
4129 #ifndef STANDALONE
4130 FS_CheckPak0( );
4131 #endif
4132
4133 // if we can't find default.cfg, assume that the paths are
4134 // busted and error out now, rather than getting an unreadable
4135 // graphics screen when the font fails to load
4136 if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
4137 Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
4138 }
4139
4140 Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
4141 Q_strncpyz(lastValidComBaseGame, com_basegame->string, sizeof(lastValidComBaseGame));
4142 Q_strncpyz(lastValidFsBaseGame, fs_basegame->string, sizeof(lastValidFsBaseGame));
4143 Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
4144 }
4145
4146
4147 /*
4148 ================
4149 FS_Restart
4150 ================
4151 */
4152 void FS_Restart( int checksumFeed ) {
4153 const char *lastGameDir;
4154
4155 // free anything we currently have loaded
4156 FS_Shutdown(qfalse);
4157
4158 // set the checksum feed
4159 fs_checksumFeed = checksumFeed;
4160
4161 // clear pak references
4162 FS_ClearPakReferences(0);
4163
4164 // try to start up normally
4165 FS_Startup(com_basegame->string);
4166
4167 #ifndef STANDALONE
4168 FS_CheckPak0( );
4169 #endif
4170
4171 // if we can't find default.cfg, assume that the paths are
4172 // busted and error out now, rather than getting an unreadable
4173 // graphics screen when the font fails to load
4174 if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
4175 // this might happen when connecting to a pure server not using BASEGAME/pak0.pk3
4176 // (for instance a TA demo server)
4177 if (lastValidBase[0]) {
4178 FS_PureServerSetLoadedPaks("", "");
4179 Cvar_Set("fs_basepath", lastValidBase);
4180 Cvar_Set("com_basegame", lastValidComBaseGame);
4181 Cvar_Set("fs_basegame", lastValidFsBaseGame);
4182 Cvar_Set("fs_game", lastValidGame);
4183 lastValidBase[0] = '\0';
4184 lastValidComBaseGame[0] = '\0';
4185 lastValidFsBaseGame[0] = '\0';
4186 lastValidGame[0] = '\0';
4187 FS_Restart(checksumFeed);
4188 Com_Error( ERR_DROP, "Invalid game folder" );
4189 return;
4190 }
4191 Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
4192 }
4193
4194 lastGameDir = ( lastValidGame[0] ) ? lastValidGame : lastValidComBaseGame;
4195
4196 if ( Q_stricmp( FS_GetCurrentGameDir(), lastGameDir ) ) {
4197 Sys_RemovePIDFile( lastGameDir );
4198 Sys_InitPIDFile( FS_GetCurrentGameDir() );
4199
4200 // skip the q3config.cfg if "safe" is on the command line
4201 if ( !Com_SafeMode() ) {
4202 Cbuf_AddText ("exec " Q3CONFIG_CFG "\n");
4203 }
4204 }
4205
4206 Q_strncpyz(lastValidBase, fs_basepath->string, sizeof(lastValidBase));
4207 Q_strncpyz(lastValidComBaseGame, com_basegame->string, sizeof(lastValidComBaseGame));
4208 Q_strncpyz(lastValidFsBaseGame, fs_basegame->string, sizeof(lastValidFsBaseGame));
4209 Q_strncpyz(lastValidGame, fs_gamedirvar->string, sizeof(lastValidGame));
4210
4211 }
4212
4213 /*
4214 =================
4215 FS_ConditionalRestart
4216
4217 Restart if necessary
4218 Return qtrue if restarting due to game directory changed, qfalse otherwise
4219 =================
4220 */
4221 qboolean FS_ConditionalRestart(int checksumFeed, qboolean disconnect)
4222 {
4223 if(fs_gamedirvar->modified)
4224 {
4225 if(FS_FilenameCompare(lastValidGame, fs_gamedirvar->string) &&
4226 (*lastValidGame || FS_FilenameCompare(fs_gamedirvar->string, com_basegame->string)) &&
4227 (*fs_gamedirvar->string || FS_FilenameCompare(lastValidGame, com_basegame->string)))
4228 {
4229 Com_GameRestart(checksumFeed, disconnect);
4230 return qtrue;
4231 }
4232 else
4233 fs_gamedirvar->modified = qfalse;
4234 }
4235
4236 if(checksumFeed != fs_checksumFeed)
4237 FS_Restart(checksumFeed);
4238 else if(fs_numServerPaks && !fs_reordered)
4239 FS_ReorderPurePaks();
4240
4241 return qfalse;
4242 }
4243
4244 /*
4245 ========================================================================================
4246
4247 Handle based file calls for virtual machines
4248
4249 ========================================================================================
4250 */
4251
4252 int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) {
4253 int r;
4254 qboolean sync;
4255
4256 sync = qfalse;
4257
4258 switch( mode ) {
4259 case FS_READ:
4260 r = FS_FOpenFileRead( qpath, f, qtrue );
4261 break;
4262 case FS_WRITE:
4263 *f = FS_FOpenFileWrite_HomeData( qpath );
4264 r = 0;
4265 if (*f == 0) {
4266 r = -1;
4267 }
4268 break;
4269 case FS_APPEND_SYNC:
4270 sync = qtrue;
4271 case FS_APPEND:
4272 *f = FS_FOpenFileAppend_HomeData( qpath );
4273 r = 0;
4274 if (*f == 0) {
4275 r = -1;
4276 }
4277 break;
4278 default:
4279 Com_Error( ERR_FATAL, "FS_FOpenFileByMode: bad mode" );
4280 return -1;
4281 }
4282
4283 if (!f) {
4284 return r;
4285 }
4286
4287 if ( *f ) {
4288 fsh[*f].fileSize = r;
4289 }
4290 fsh[*f].handleSync = sync;
4291
4292 return r;
4293 }
4294
4295 int FS_FTell( fileHandle_t f ) {
4296 int pos;
4297 if (fsh[f].zipFile == qtrue) {
4298 pos = unztell(fsh[f].handleFiles.file.z);
4299 } else {
4300 pos = ftell(fsh[f].handleFiles.file.o);
4301 }
4302 return pos;
4303 }
4304
4305 void FS_Flush( fileHandle_t f ) {
4306 fflush(fsh[f].handleFiles.file.o);
4307 }
4308
4309 void FS_FilenameCompletion( const char *dir, const char *ext, char *filter,
4310 qboolean stripExt, void(*callback)(const char *s), qboolean allowNonPureFilesOnDisk ) {
4311 char **filenames;
4312 int nfiles;
4313 int i;
4314 char filename[ MAX_STRING_CHARS ];
4315
4316 filenames = FS_ListFilteredFiles( dir, ext, filter,
4317 &nfiles, qtrue, allowNonPureFilesOnDisk );
4318
4319 FS_SortFileList( filenames, nfiles );
4320
4321 for( i = 0; i < nfiles; i++ ) {
4322 FS_ConvertPath( filenames[ i ] );
4323 Q_strncpyz( filename, filenames[ i ], MAX_STRING_CHARS );
4324
4325 if( stripExt ) {
4326 COM_StripExtension(filename, filename, sizeof(filename));
4327 }
4328
4329 callback( filename );
4330 }
4331 FS_FreeFileList( filenames );
4332 }
4333
4334 const char *FS_GetCurrentGameDir(void)
4335 {
4336 if(fs_gamedirvar->string[0])
4337 return fs_gamedirvar->string;
4338
4339 return com_basegame->string;
4340 }