-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathFileSystem.cpp
More file actions
7919 lines (6995 loc) · 227 KB
/
Copy pathFileSystem.cpp
File metadata and controls
7919 lines (6995 loc) · 227 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "Unzip.h"
#include "GameDirPolicy.h"
#include "LevelLoadCacheManager.h"
#include "openq4_paks_generated.h"
#include "../sys/URLPolicy.h"
#include <errno.h>
#include <stdint.h>
#include <limits>
#include <mutex>
#include <thread>
#include <vector>
#if defined( USE_SDL3 )
#include <SDL3/SDL_filesystem.h>
#include <SDL3/SDL_error.h>
#endif
#ifdef WIN32
#include <windows.h>
#include <io.h> // for _read
#include <direct.h> // for _getcwd
#else
#if !defined( __MACH__ ) && defined( __MWERKS__ )
#include <types.h>
#include <stat.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#endif
#include <unistd.h>
#endif
#if ID_ENABLE_CURL
#include "../curl/include/curl/curl.h"
#if defined( LIBCURL_VERSION_NUM ) && LIBCURL_VERSION_NUM >= 0x071304 && defined( CURL_VERSION_ASYNCHDNS )
#define OPENQ4_CURL_CAPABLE_BUILD 1
#else
#define OPENQ4_CURL_CAPABLE_BUILD 0
#endif
#endif
int Com_GetNumStartupCommandLines( void );
const idCmdArgs *Com_GetStartupCommandLine( int index );
/*
========================
FS_IsWindowsDeviceQPathSegment
Windows resolves these names to devices even when an extension is present.
Reject both the legacy single-byte and UTF-8 encodings of the superscript
digits that Windows also treats as COM/LPT device numbers.
========================
*/
static bool FS_IsWindowsDeviceQPathSegment( const char *segment, int segmentLength ) {
int stemLength = 0;
while ( stemLength < segmentLength && segment[ stemLength ] != '.' ) {
stemLength++;
}
if ( stemLength == 3 ) {
return idStr::Icmpn( segment, "con", 3 ) == 0 ||
idStr::Icmpn( segment, "prn", 3 ) == 0 ||
idStr::Icmpn( segment, "aux", 3 ) == 0 ||
idStr::Icmpn( segment, "nul", 3 ) == 0;
}
const bool portPrefix = stemLength >= 4 &&
( idStr::Icmpn( segment, "com", 3 ) == 0 || idStr::Icmpn( segment, "lpt", 3 ) == 0 );
if ( !portPrefix ) {
return false;
}
const unsigned char digit = static_cast<unsigned char>( segment[ 3 ] );
if ( stemLength == 4 ) {
return ( digit >= '1' && digit <= '9' ) || digit == 0xB9 || digit == 0xB2 || digit == 0xB3;
}
return stemLength == 5 && digit == 0xC2 &&
( static_cast<unsigned char>( segment[ 4 ] ) == 0xB9 ||
static_cast<unsigned char>( segment[ 4 ] ) == 0xB2 ||
static_cast<unsigned char>( segment[ 4 ] ) == 0xB3 );
}
/*
========================
FS_HasParentOSPathSegment
Explicit OS paths may legitimately contain repeated dots in a filename or
directory name. Reject only a complete parent-directory component so an
absolute save path cannot be used to make CreateOSPath back up the hierarchy.
========================
*/
static bool FS_HasParentOSPathSegment( const char *OSPath ) {
const char *segmentStart = OSPath;
for ( const char *scan = OSPath; ; scan++ ) {
const char c = *scan;
if ( c != '\0' && c != '/' && c != '\\' ) {
continue;
}
if ( scan - segmentStart == 2 && segmentStart[ 0 ] == '.' && segmentStart[ 1 ] == '.' ) {
return true;
}
if ( c == '\0' ) {
return false;
}
segmentStart = scan + 1;
}
}
/*
========================
FS_ValidateRelativeWritePath
Mutation APIs accept portable qpaths, not OS paths. Validate before joining
the caller-controlled value to a writable root so platform normalization can
never reinterpret a segment or escape the game directory.
========================
*/
static bool FS_ValidateRelativeWritePath( const char *relativePath, const char **reason ) {
if ( reason != NULL ) {
*reason = NULL;
}
if ( relativePath == NULL || relativePath[ 0 ] == '\0' ) {
if ( reason != NULL ) {
*reason = "path is empty";
}
return false;
}
if ( relativePath[ 0 ] == '/' || relativePath[ 0 ] == '\\' ) {
if ( reason != NULL ) {
*reason = "path is rooted";
}
return false;
}
const char *segmentStart = relativePath;
for ( const char *scan = relativePath; ; scan++ ) {
const unsigned char c = static_cast<unsigned char>( *scan );
if ( c == '\\' || c == ':' ) {
if ( reason != NULL ) {
*reason = "path contains an OS path separator or volume marker";
}
return false;
}
if ( c != '\0' && ( c < 32 || c == '<' || c == '>' || c == '"' || c == '|' || c == '?' || c == '*' ) ) {
if ( reason != NULL ) {
*reason = "path contains a non-portable filename character";
}
return false;
}
if ( c != '/' && c != '\0' ) {
continue;
}
const int segmentLength = static_cast<int>( scan - segmentStart );
if ( segmentLength == 0 ) {
if ( reason != NULL ) {
*reason = "path contains an empty segment";
}
return false;
}
if ( ( segmentLength == 1 && segmentStart[ 0 ] == '.' ) ||
( segmentLength == 2 && segmentStart[ 0 ] == '.' && segmentStart[ 1 ] == '.' ) ) {
if ( reason != NULL ) {
*reason = "path contains a dot directory segment";
}
return false;
}
if ( segmentStart[ 0 ] == ' ' ||
segmentStart[ segmentLength - 1 ] == '.' ||
segmentStart[ segmentLength - 1 ] == ' ' ) {
if ( reason != NULL ) {
*reason = "path segment starts or ends in a character normalized by Windows";
}
return false;
}
if ( FS_IsWindowsDeviceQPathSegment( segmentStart, segmentLength ) ) {
if ( reason != NULL ) {
*reason = "path contains a Windows device name";
}
return false;
}
if ( c == '\0' ) {
return true;
}
segmentStart = scan + 1;
}
}
/*
=============================================================================
DOOM FILESYSTEM
All of Doom's data access is through a hierarchical file system, but the contents of
the file system can be transparently merged from several sources.
A "relativePath" is a reference to game file data, which must include a terminating zero.
Dot directory segments, empty segments, OS separators and volume markers are
illegal in qpaths used for mutation, preventing references outside the Doom
directory system and platform-specific filename aliases.
The "base path" is the path to the directory holding all the game directories and
usually the executable. It defaults to the current directory, but can be overridden
with "+set fs_basepath c:\doom" on the command line. The base path cannot be modified
at all after startup.
The "home path" is the user-writable root path for openQ4 data. It can be overridden
with "+set fs_homepath c:\users\you\saved games\openq4" on the command line.
The "save path" is the path to the directory where game files will be saved. It defaults
to the home path, but can be overridden with a "+set fs_savepath c:\doom" on the
command line. Any files that are created during the game (demos, screenshots, etc.) will
be created reletive to the save path.
The "cd path" is the path to an alternate hierarchy that will be searched if a file
is not located in the base path. A user can do a partial install that copies some
data to a base path created on their hard drive and leave the rest on the cd. It defaults
to the process current directory and is locked at startup.
If a user runs the game directly from a CD, the base path would be on the CD. This
should still function correctly, but all file writes will fail (harmlessly).
The "base game" is the directory under the paths where data comes from by default, and
can be either "base" or "demo".
The "current game" may be the same as the base game, or it may be the name of another
directory under the paths that should be searched for files before looking in the base
game. The game directory is set with "+set fs_game myaddon" on the command line. This is
the basis for addons.
No other directories outside of the base game and current game will ever be referenced by
filesystem functions.
To save disk space and speed up file loading, directory trees can be collapsed into zip
files. The files use a ".pk4" extension to prevent users from unzipping them accidentally,
but otherwise they are simply normal zip files. A game directory can have multiple zip
files of the form "pak0.pk4", "pak1.pk4", etc. Zip files are searched in decending order
from the highest number to the lowest, and will always take precedence over the filesystem.
This allows a pk4 distributed as a patch to override all existing data.
Because we will have updated executables freely available online, there is no point to
trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
should be exactly the same executables as release versions, but with different data that
automatically restricts where game media can come from to prevent add-ons from working.
After the paths are initialized, Doom will look for the product.txt file. If not found
and verified, the game will run in restricted mode. In restricted mode, only files
contained in demo/pak0.pk4 will be available for loading, and only if the zip header is
verified to not have been modified. A single exception is made for DoomConfig.cfg. Files
can still be written out in restricted mode, so screenshots and demos are allowed.
Restricted mode can be tested by setting "+set fs_restrict 1" on the command line, even
if there is a valid product.txt under the basepath or cdpath.
If the "fs_copyfiles" cvar is set to 1, then every time a file is sourced from the cd
path, it will be copied over to the save path. This is a development aid to help build
test releases and to copy working sets of files.
If the "fs_copyfiles" cvar is set to 2, any file found in fs_cdpath that is newer than
it's fs_savepath version will be copied to fs_savepath (in addition to the fs_copyfiles 1
behaviour).
If the "fs_copyfiles" cvar is set to 3, files from both basepath and cdpath will be copied
over to the save path. This is useful when copying working sets of files mainly from base
path with an additional cd path (which can be a slower network drive for instance).
If the "fs_copyfiles" cvar is set to 4, files that exist in the cd path but NOT the base path
will be copied to the save path
NOTE: fs_copyfiles and case sensitivity. On fs_caseSensitiveOS 0 filesystems ( win32 ), the
copied files may change casing when copied over.
The relative path "sound/newstuff/test.wav" would be searched for in the following places:
for save path, base path, cd path:
for current game, base game:
search directory
search zip files
downloaded files, to be written to save path + current game's directory
The filesystem can be safely shutdown and reinitialized with different
basedir / cddir / game combinations, but all other subsystems that rely on it
(sound, video) must also be forced to restart.
"fs_caseSensitiveOS":
This cvar is set on operating systems that use case sensitive filesystems (Linux and OSX)
It is a common situation to have the media reference filenames, whereas the file on disc
only matches in a case-insensitive way. When "fs_caseSensitiveOS" is set, the filesystem
will always do a case insensitive search.
Directory segments are also resolved case-insensitively when they already exist on disk.
When "com_developer" is 1, the filesystem will warn when it catches bad directory
situations (regardless of the "fs_caseSensitiveOS" setting). Missing directories are
left unchanged so write paths can still create new content and failed reads report the
unresolved segment in debug output instead of relying on lowercase assumptions.
"additional mod path search":
fs_game_base can be used to set an additional search path
in search order, fs_game, fs_game_base, BASEGAME
for instance to base a mod of openQ4 + D3XP assets, fs_game mymod, fs_game_base baseoq4
=============================================================================
*/
// define to fix special-cases for GetPackStatus so that files that shipped in
// the wrong place for openQ4 don't break pure servers.
#define DOOM3_PURE_SPECIAL_CASES
typedef bool (*pureExclusionFunc_t)( const struct pureExclusion_s &excl, int l, const idStr &name );
typedef struct pureExclusion_s {
int nameLen;
int extLen;
const char * name;
const char * ext;
pureExclusionFunc_t func;
} pureExclusion_t;
bool excludeExtension( const pureExclusion_t &excl, int l, const idStr &name ) {
if ( l > excl.extLen && !idStr::Icmp( name.c_str() + l - excl.extLen, excl.ext ) ) {
return true;
}
return false;
}
bool excludePathPrefixAndExtension( const pureExclusion_t &excl, int l, const idStr &name ) {
if ( l > excl.nameLen && !idStr::Icmp( name.c_str() + l - excl.extLen, excl.ext ) && !name.IcmpPrefixPath( excl.name ) ) {
return true;
}
return false;
}
bool excludeFullName( const pureExclusion_t &excl, int l, const idStr &name ) {
if ( l == excl.nameLen && !name.Icmp( excl.name ) ) {
return true;
}
return false;
}
static pureExclusion_t pureExclusions[] = {
{ 0, 0, NULL, "/", excludeExtension },
{ 0, 0, NULL, "\\", excludeExtension },
{ 0, 0, NULL, ".pda", excludeExtension },
{ 0, 0, NULL, ".gui", excludeExtension },
{ 0, 0, NULL, ".pd", excludeExtension },
{ 0, 0, NULL, ".lang", excludeExtension },
{ 0, 0, "sound/VO", ".ogg", excludePathPrefixAndExtension },
{ 0, 0, "sound/VO", ".wav", excludePathPrefixAndExtension },
#if defined DOOM3_PURE_SPECIAL_CASES
// add any special-case files or paths for pure servers here
{ 0, 0, "sound/ed/marscity/vo_intro_cutscene.ogg", NULL, excludeFullName },
{ 0, 0, "sound/weapons/soulcube/energize_01.ogg", NULL, excludeFullName },
{ 0, 0, "sound/xian/creepy/vocal_fx", ".ogg", excludePathPrefixAndExtension },
{ 0, 0, "sound/xian/creepy/vocal_fx", ".wav", excludePathPrefixAndExtension },
{ 0, 0, "sound/feedback", ".ogg", excludePathPrefixAndExtension },
{ 0, 0, "sound/feedback", ".wav", excludePathPrefixAndExtension },
{ 0, 0, "guis/assets/mainmenu/chnote.tga", NULL, excludeFullName },
{ 0, 0, "sound/levels/alphalabs2/uac_better_place.ogg", NULL, excludeFullName },
{ 0, 0, "textures/bigchars.tga", NULL, excludeFullName },
{ 0, 0, "dds/textures/bigchars.dds", NULL, excludeFullName },
{ 0, 0, "fonts", ".tga", excludePathPrefixAndExtension },
{ 0, 0, "dds/fonts", ".dds", excludePathPrefixAndExtension },
{ 0, 0, "default.cfg", NULL, excludeFullName },
// russian zpak001.pk4
{ 0, 0, "fonts", ".dat", excludePathPrefixAndExtension },
{ 0, 0, "guis/temp.guied", NULL, excludeFullName },
#endif
{ 0, 0, NULL, NULL, NULL }
};
// ensures that lengths for pure exclusions are correct
class idInitExclusions {
public:
idInitExclusions() {
for ( int i = 0; pureExclusions[i].func != NULL; i++ ) {
if ( pureExclusions[i].name ) {
pureExclusions[i].nameLen = idStr::Length( pureExclusions[i].name );
}
if ( pureExclusions[i].ext ) {
pureExclusions[i].extLen = idStr::Length( pureExclusions[i].ext );
}
}
}
};
static idInitExclusions initExclusions;
typedef struct {
const char * name;
unsigned int checksum;
bool required;
bool pureBase;
} officialPk4Info_t;
static officialPk4Info_t officialPk4s[] = {
// core retail media baseline for Quake 4
{ "pak001.pk4", 0xf2cbc998, true, true },
{ "pak002.pk4", 0x7f8d80d1, true, true },
{ "pak003.pk4", 0x1b57b207, true, true },
{ "pak004.pk4", 0x385aa578, true, true },
{ "pak005.pk4", 0x60d50a1d, true, true },
{ "pak006.pk4", 0x9099ed11, true, true },
{ "pak007.pk4", 0xaf301fff, true, true },
{ "pak008.pk4", 0x4ac6f6d9, true, true },
{ "pak009.pk4", 0x36030c7d, true, true },
{ "pak010.pk4", 0x4b80fbda, true, true },
{ "pak011.pk4", 0x8acf4cfa, true, true },
{ "pak012.pk4", 0xbe4120b0, true, true },
{ "pak013.pk4", 0x6ad67f40, true, true },
{ "pak014.pk4", 0xee51cd59, true, true },
{ "pak015.pk4", 0xf5bf4e0c, true, true },
{ "pak016.pk4", 0x2196f58c, true, true },
{ "pak017.pk4", 0x91118a35, true, true },
{ "pak018.pk4", 0x98a14f03, true, true },
{ "pak019.pk4", 0xbc82ac79, true, true },
{ "pak020.pk4", 0xce74cda5, true, true },
{ "pak021.pk4", 0x2ba6e70c, true, true },
{ "pak022.pk4", 0x4e390eec, true, true },
// official patch/menu media, but not required by openQ4 startup
{ "pak023.pk4", 0x7c1fd3a5, false, true },
{ "pak024.pk4", 0x5546d551, false, true },
{ "pak025.pk4", 0xcaeec1fd, false, true },
// official but optional
{ "q4cmp_pak001.pk4", 0xd0813943, false, false },
{ "zpak_english.pk4", 0x5868f530, false, false },
{ "zpak_english_01.pk4", 0xd9f04b8b, false, false },
{ "zpak_english_02.pk4", 0x9dbd91fd, false, false },
{ "zpak_english_03.pk4", 0x02eb6ad8, false, false },
{ "zpak_english_04.pk4", 0xd3fefaa1, false, false },
{ "zpak_english_05.pk4", 0x8596af60, false, false },
{ "zpak_spanish.pk4", 0xb706e2b8, false, false },
{ NULL, 0, false, false }
};
static bool FS_IsIgnoredOfficialGameBinaryPk4( const char *pakName ) {
idStr name;
if ( !pakName || !pakName[ 0 ] ) {
return false;
}
name = pakName;
name.StripPath();
if ( !name.Icmp( "game000.pk4" ) ||
!name.Icmp( "game100.pk4" ) ||
!name.Icmp( "game200.pk4" ) ||
!name.Icmp( "game300.pk4" ) ) {
return true;
}
return idStr::Filter( "gamex*.pk4", name.c_str(), false );
}
static const officialPk4Info_t *FindOfficialPk4Info( const char *pakName ) {
for ( int i = 0; officialPk4s[ i ].name != NULL; i++ ) {
if ( !idStr::Icmp( officialPk4s[ i ].name, pakName ) ) {
return &officialPk4s[ i ];
}
}
return NULL;
}
typedef struct {
int number;
int digitCount;
} numberedPakName_t;
static bool FS_ParseNumberedPakName( const char *pakName, numberedPakName_t &numberedPak ) {
const char *baseName;
const char *digits;
const char *p;
int number;
int digitCount;
numberedPak.number = 0;
numberedPak.digitCount = 0;
if ( !pakName || !pakName[ 0 ] ) {
return false;
}
baseName = pakName;
for ( p = pakName; *p != '\0'; p++ ) {
if ( *p == '/' || *p == '\\' ) {
baseName = p + 1;
}
}
pakName = baseName;
if ( idStr::Icmpn( pakName, "pak", 3 ) ) {
return false;
}
digits = pakName + 3;
if ( digits[ 0 ] < '0' || digits[ 0 ] > '9' ) {
return false;
}
number = 0;
digitCount = 0;
for ( p = digits; *p >= '0' && *p <= '9'; p++ ) {
if ( number < 1000000 ) {
number = ( number * 10 ) + ( *p - '0' );
}
digitCount++;
}
if ( idStr::Icmp( p, ".pk4" ) ) {
return false;
}
numberedPak.number = number;
numberedPak.digitCount = digitCount;
return true;
}
static int FS_ComparePk4LoadOrder( const idStrPtr *a, const idStrPtr *b ) {
numberedPakName_t aPak;
numberedPakName_t bPak;
const idStr &aName = **a;
const idStr &bName = **b;
const bool aNumberedPak = FS_ParseNumberedPakName( aName.c_str(), aPak );
const bool bNumberedPak = FS_ParseNumberedPakName( bName.c_str(), bPak );
if ( aNumberedPak && bNumberedPak ) {
// AddGameDirectory inserts each later-loaded archive closer to the head of
// the search path. Process wider numbered forms first so pak1.pk4 wins over
// pak01.pk4/pak001.pk4 when both naming schemes are present.
if ( aPak.digitCount != bPak.digitCount ) {
return bPak.digitCount - aPak.digitCount;
}
if ( aPak.number != bPak.number ) {
return aPak.number - bPak.number;
}
}
if ( aNumberedPak != bNumberedPak ) {
const char *aKey = aNumberedPak ? "pak" : aName.c_str();
const char *bKey = bNumberedPak ? "pak" : bName.c_str();
const int cmp = idStr::Icmp( aKey, bKey );
if ( cmp != 0 ) {
return cmp;
}
return aNumberedPak ? -1 : 1;
}
return aName.Icmp( bName );
}
static void FS_SortPk4FilesForLoadOrder( idStrList &pakfiles ) {
idList<idStr> other;
idList<idStrPtr> pointerList;
if ( pakfiles.Num() <= 1 ) {
return;
}
pointerList.SetNum( pakfiles.Num() );
for ( int i = 0; i < pakfiles.Num(); i++ ) {
pointerList[ i ] = &pakfiles[ i ];
}
pointerList.Sort( FS_ComparePk4LoadOrder );
other.SetNum( pakfiles.Num() );
other.SetGranularity( pakfiles.GetGranularity() );
for ( int i = 0; i < other.Num(); i++ ) {
other[ i ] = *pointerList[ i ];
}
pakfiles.Swap( other );
}
static const char *fsLanguagePackOrder[] = {
"english",
"spanish",
"french",
"italian",
"german",
"russian",
"polish",
"korean",
"japanese",
"chinese",
NULL
};
static bool FS_IsKnownLanguage( const char *language ) {
if ( language == NULL || language[ 0 ] == '\0' ) {
return false;
}
for ( int i = 0; fsLanguagePackOrder[ i ] != NULL; ++i ) {
if ( !idStr::Icmp( language, fsLanguagePackOrder[ i ] ) ) {
return true;
}
}
return false;
}
static bool FS_LanguageListContains( const idStrList &languages, const char *language ) {
if ( language == NULL || language[ 0 ] == '\0' ) {
return false;
}
for ( int i = 0; i < languages.Num(); ++i ) {
if ( !languages[ i ].Icmp( language ) ) {
return true;
}
}
return false;
}
static void FS_AppendUniqueLanguage( idStrList &languages, const char *language ) {
if ( language == NULL || language[ 0 ] == '\0' || FS_LanguageListContains( languages, language ) ) {
return;
}
languages.Append( language );
}
static bool FS_ParseLanguagePackName( const char *pakFilename, idStr &language, bool allowPatchArchives = true ) {
idStr fileName;
int suffix;
if ( pakFilename == NULL || pakFilename[ 0 ] == '\0' ) {
return false;
}
fileName = pakFilename;
fileName.StripPath();
fileName.ToLower();
if ( !fileName.CheckExtension( ".pk4" ) || fileName.Icmpn( "zpak_", 5 ) ) {
return false;
}
fileName.StripFileExtension();
language = fileName.Right( fileName.Length() - 5 );
suffix = language.Find( '_' );
if ( suffix == 0 ) {
return false;
}
if ( suffix > 0 ) {
if ( !allowPatchArchives ) {
return false;
}
language.CapLength( suffix );
}
return FS_IsKnownLanguage( language.c_str() );
}
static bool FS_PakPathIsInGameDir( const char *pakFilename, const char *gameDir ) {
idStr directory;
idStr dirName;
if ( pakFilename == NULL || gameDir == NULL ) {
return false;
}
directory = pakFilename;
directory.StripFilename();
dirName = directory;
dirName.StripPath();
return !dirName.Icmp( gameDir );
}
static void FS_OrderLanguagePackList( idStrList &languages ) {
idStrList ordered;
for ( int i = 0; fsLanguagePackOrder[ i ] != NULL; ++i ) {
if ( FS_LanguageListContains( languages, fsLanguagePackOrder[ i ] ) ) {
ordered.Append( fsLanguagePackOrder[ i ] );
}
}
for ( int i = 0; i < languages.Num(); ++i ) {
FS_AppendUniqueLanguage( ordered, languages[ i ].c_str() );
}
languages.Swap( ordered );
}
static bool FS_FileExists( const char *path ) {
FILE *f;
if ( !path || !path[ 0 ] ) {
return false;
}
f = fopen( path, "rb" );
if ( f ) {
fclose( f );
return true;
}
return false;
}
static void FS_AddUniquePath( idStrList &paths, const char *path ) {
idStr normalized;
idStr existing;
if ( !path || !path[ 0 ] ) {
return;
}
normalized = path;
normalized.Replace( "\\\\", "\\" );
normalized.BackSlashesToSlashes();
normalized.StripTrailing( '/' );
if ( !normalized.Length() ) {
return;
}
for ( int i = 0; i < paths.Num(); i++ ) {
existing = paths[ i ];
existing.Replace( "\\\\", "\\" );
existing.BackSlashesToSlashes();
existing.StripTrailing( '/' );
if ( !idStr::IcmpPath( existing.c_str(), normalized.c_str() ) ) {
return;
}
}
paths.Append( normalized );
}
static bool FS_IsEnvPathListSeparator( char c ) {
#ifdef WIN32
return c == ';';
#else
return c == ':' || c == ';';
#endif
}
static void FS_AppendEnvPathList( idStrList &paths, const char *envName ) {
const char *value = getenv( envName );
if ( !value || !value[ 0 ] ) {
return;
}
idStr valueList = value;
const int length = valueList.Length();
int start = 0;
for ( int i = 0; i <= length; i++ ) {
if ( i == length || FS_IsEnvPathListSeparator( valueList[ i ] ) ) {
if ( i > start ) {
idStr path = valueList.Mid( start, i - start );
path.Strip( ' ' );
path.Strip( '\t' );
path.Strip( '\"' );
FS_AddUniquePath( paths, path.c_str() );
}
start = i + 1;
}
}
}
static void FS_LogPathList( const char *label, const idStrList &paths ) {
if ( common == NULL ) {
return;
}
common->Printf( "%s (%d):\n", label, paths.Num() );
for ( int i = 0; i < paths.Num(); i++ ) {
common->Printf( " %s\n", paths[ i ].c_str() );
}
}
static bool FS_HasGameFilesAtGameDirPath( const char *gameDirPath ) {
idStr pakPath;
if ( !gameDirPath || !gameDirPath[ 0 ] ) {
return false;
}
pakPath = gameDirPath;
pakPath.AppendPath( "pak001.pk4" );
return FS_FileExists( pakPath.c_str() );
}
static bool FS_TryResolveBasePathCandidate( const char *candidatePath, idStr &resolvedBasePath ) {
idStr normalized;
idStr gameDirPath;
idStr parentPath;
if ( !candidatePath || !candidatePath[ 0 ] ) {
return false;
}
normalized = candidatePath;
normalized.Replace( "\\\\", "\\" );
normalized.BackSlashesToSlashes();
normalized.StripTrailing( '/' );
if ( !normalized.Length() ) {
return false;
}
// Candidate is an install root containing BASE_GAMEDIR.
gameDirPath = normalized;
gameDirPath.AppendPath( BASE_GAMEDIR );
if ( FS_HasGameFilesAtGameDirPath( gameDirPath.c_str() ) ) {
resolvedBasePath = normalized;
return true;
}
// Candidate may already point directly at BASE_GAMEDIR.
if ( FS_HasGameFilesAtGameDirPath( normalized.c_str() ) ) {
parentPath = normalized;
parentPath.StripFilename();
parentPath.StripTrailing( '/' );
if ( parentPath.Length() ) {
resolvedBasePath = parentPath;
return true;
}
}
return false;
}
static bool FS_HasGameFilesAtBasePath( const char *basePath ) {
idStr resolvedBasePath;
return FS_TryResolveBasePathCandidate( basePath, resolvedBasePath );
}
static bool FS_GetCurrentWorkingDirectory( idStr &cwd ) {
char buf[ MAX_OSPATH ];
#ifdef WIN32
if ( !_getcwd( buf, sizeof( buf ) - 1 ) ) {
return false;
}
#else
if ( !getcwd( buf, sizeof( buf ) - 1 ) ) {
return false;
}
#endif
buf[ sizeof( buf ) - 1 ] = '\0';
cwd = buf;
return true;
}
static void FS_ExtractQuotedTokens( const char *line, idStrList &tokens ) {
const char *p;
const char *start;
char token[ 2048 ];
int len;
tokens.Clear();
if ( !line ) {
return;
}
p = line;
while ( ( p = strchr( p, '\"' ) ) != NULL ) {
start = ++p;
while ( *p && *p != '\"' ) {
p++;
}
if ( *p != '\"' ) {
break;
}
len = (int)( p - start );
if ( len > 0 ) {
if ( len >= (int)sizeof( token ) ) {
len = sizeof( token ) - 1;
}
memcpy( token, start, len );
token[ len ] = '\0';
tokens.Append( token );
}
p++;
}
}
#ifdef WIN32
static bool FS_ReadRegistryString( HKEY root, const char *subKey, const char *valueName, REGSAM accessFlags, idStr &result ) {
HKEY hKey;
LONG status;
BYTE buffer[ 4096 ];
DWORD type;
DWORD size;
result.Clear();
if ( !subKey || !subKey[ 0 ] || !valueName || !valueName[ 0 ] ) {
return false;
}
status = RegOpenKeyExA( root, subKey, 0, KEY_READ | accessFlags, &hKey );
if ( status != ERROR_SUCCESS ) {
return false;
}
type = 0;
size = sizeof( buffer ) - 1;
status = RegQueryValueExA( hKey, valueName, NULL, &type, buffer, &size );
RegCloseKey( hKey );
if ( status != ERROR_SUCCESS || size == 0 ) {
return false;
}
if ( type != REG_SZ && type != REG_EXPAND_SZ ) {
return false;
}
buffer[ size < sizeof( buffer ) ? size : ( sizeof( buffer ) - 1 ) ] = '\0';
result = (const char *)buffer;
if ( type == REG_EXPAND_SZ ) {
char expanded[ 4096 ];
DWORD expandedLen = ExpandEnvironmentStringsA( result.c_str(), expanded, sizeof( expanded ) );
if ( expandedLen > 0 && expandedLen <= sizeof( expanded ) ) {
expanded[ sizeof( expanded ) - 1 ] = '\0';
result = expanded;
}
}
result.Replace( "\\\\", "\\" );
result.BackSlashesToSlashes();
result.StripTrailing( '/' );
return result.Length() > 0;
}
static void FS_AppendGogPathsFromRegistryGamesBranch( HKEY root, const char *branch, idStrList &candidates, REGSAM accessFlags ) {
HKEY hKey;
LONG status;
DWORD index;
char subKeyName[ 256 ];
DWORD subKeyNameLen;
idStr subKeyPath;
idStr pathValue;
if ( !branch || !branch[ 0 ] ) {
return;
}
status = RegOpenKeyExA( root, branch, 0, KEY_READ | accessFlags, &hKey );
if ( status != ERROR_SUCCESS ) {
return;
}
index = 0;
for ( ;; ) {
subKeyNameLen = sizeof( subKeyName );
status = RegEnumKeyExA( hKey, index, subKeyName, &subKeyNameLen, NULL, NULL, NULL, NULL );
if ( status != ERROR_SUCCESS ) {
break;
}
subKeyPath = branch;
subKeyPath += "\\";
subKeyPath += subKeyName;
if ( FS_ReadRegistryString( root, subKeyPath.c_str(), "path", accessFlags, pathValue ) ) {
FS_AddUniquePath( candidates, pathValue.c_str() );
}
index++;
}
RegCloseKey( hKey );
}
static void FS_AppendGogPathsFromRegistryUninstallBranch( HKEY root, const char *branch, idStrList &candidates, REGSAM accessFlags ) {
HKEY hKey;
LONG status;
DWORD index;
char subKeyName[ 256 ];
DWORD subKeyNameLen;
idStr subKeyPath;
idStr displayName;
idStr publisher;