-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathcfile.cpp
More file actions
1694 lines (1343 loc) · 40.8 KB
/
cfile.cpp
File metadata and controls
1694 lines (1343 loc) · 40.8 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
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#define _CFILE_INTERNAL
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cerrno>
#include <sys/stat.h>
#ifdef _WIN32
#include <io.h>
#include <direct.h>
#include <windows.h>
#endif
#include "cfile/cfile.h"
#include "cfile/cfilearchive.h"
#include "cfile/cfilesystem.h"
#include "osapi/osapi.h"
#include "parse/encrypt.h"
#include "cfilesystem.h"
#include <limits>
char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
// During cfile_init, verify that Pathtypes[n].index == n for each item
// Each path must have a valid parent that can be tracable all the way back to the root
// so that we can create directories when we need to.
//
// Please make sure extensions are all lower-case, or we'll break unix compatibility
//
// clang-format off
cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
// What type this is Path Extensions Parent type
{ CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
// Root must be index 1!!
{ CF_TYPE_ROOT, "", ".mve .ogg", CF_TYPE_ROOT },
{ CF_TYPE_DATA, "data", ".cfg .txt", CF_TYPE_ROOT },
{ CF_TYPE_MAPS, "data" DIR_SEPARATOR_STR "maps", ".pcx .ani .eff .tga .jpg .png .dds", CF_TYPE_DATA },
{ CF_TYPE_TEXT, "data" DIR_SEPARATOR_STR "text", ".txt .net", CF_TYPE_DATA },
{ CF_TYPE_MODELS, "data" DIR_SEPARATOR_STR "models", ".pof", CF_TYPE_DATA },
{ CF_TYPE_TABLES, "data" DIR_SEPARATOR_STR "tables", ".tbl .tbm .lua", CF_TYPE_DATA },
{ CF_TYPE_SOUNDS, "data" DIR_SEPARATOR_STR "sounds", ".wav .ogg", CF_TYPE_DATA },
{ CF_TYPE_VOICE, "data" DIR_SEPARATOR_STR "voice", "", CF_TYPE_DATA },
{ CF_TYPE_VOICE_BRIEFINGS, "data" DIR_SEPARATOR_STR "voice" DIR_SEPARATOR_STR "briefing", ".wav .ogg", CF_TYPE_VOICE },
{ CF_TYPE_VOICE_CMD_BRIEF, "data" DIR_SEPARATOR_STR "voice" DIR_SEPARATOR_STR "command_briefings", ".wav .ogg", CF_TYPE_VOICE },
{ CF_TYPE_VOICE_DEBRIEFINGS, "data" DIR_SEPARATOR_STR "voice" DIR_SEPARATOR_STR "debriefing", ".wav .ogg", CF_TYPE_VOICE },
{ CF_TYPE_VOICE_PERSONAS, "data" DIR_SEPARATOR_STR "voice" DIR_SEPARATOR_STR "personas", ".wav .ogg", CF_TYPE_VOICE },
{ CF_TYPE_VOICE_SPECIAL, "data" DIR_SEPARATOR_STR "voice" DIR_SEPARATOR_STR "special", ".wav .ogg", CF_TYPE_VOICE },
{ CF_TYPE_VOICE_TRAINING, "data" DIR_SEPARATOR_STR "voice" DIR_SEPARATOR_STR "training", ".wav .ogg", CF_TYPE_VOICE },
{ CF_TYPE_MUSIC, "data" DIR_SEPARATOR_STR "music", ".wav .ogg", CF_TYPE_DATA },
{ CF_TYPE_MOVIES, "data" DIR_SEPARATOR_STR "movies", ".mve .msb .ogg .mp4 .srt .webm .png",CF_TYPE_DATA },
{ CF_TYPE_INTERFACE, "data" DIR_SEPARATOR_STR "interface", ".pcx .ani .dds .tga .eff .png .jpg .rml .rcss", CF_TYPE_DATA },
{ CF_TYPE_FONT, "data" DIR_SEPARATOR_STR "fonts", ".vf .ttf .otf", CF_TYPE_DATA },
{ CF_TYPE_EFFECTS, "data" DIR_SEPARATOR_STR "effects", ".ani .eff .pcx .neb .tga .jpg .png .dds .sdr", CF_TYPE_DATA },
{ CF_TYPE_HUD, "data" DIR_SEPARATOR_STR "hud", ".pcx .ani .eff .tga .jpg .png .dds", CF_TYPE_DATA },
{ CF_TYPE_PLAYERS, "data" DIR_SEPARATOR_STR "players", ".hcf", /* DON'T add pilot files here!! */ CF_TYPE_DATA },
{ CF_TYPE_PLAYER_IMAGES, "data" DIR_SEPARATOR_STR "players" DIR_SEPARATOR_STR "images", ".pcx .png .dds", CF_TYPE_PLAYERS },
{ CF_TYPE_SQUAD_IMAGES, "data" DIR_SEPARATOR_STR "players" DIR_SEPARATOR_STR "squads", ".pcx .png .dds", CF_TYPE_PLAYERS },
{ CF_TYPE_SINGLE_PLAYERS, "data" DIR_SEPARATOR_STR "players" DIR_SEPARATOR_STR "single", ".pl2 .cs2 .plr .csg .css .json", CF_TYPE_PLAYERS },
{ CF_TYPE_MULTI_PLAYERS, "data" DIR_SEPARATOR_STR "players" DIR_SEPARATOR_STR "multi", ".plr .json", CF_TYPE_PLAYERS },
{ CF_TYPE_PLAYER_BINDS, "data" DIR_SEPARATOR_STR "players" DIR_SEPARATOR_STR "presets", ".json", CF_TYPE_PLAYERS },
{ CF_TYPE_CACHE, "data" DIR_SEPARATOR_STR "cache", ".clr .tmp .bx", CF_TYPE_DATA }, //clr=cached color
{ CF_TYPE_MULTI_CACHE, "data" DIR_SEPARATOR_STR "multidata", ".pcx .png .jpg .dds .fs2 .txt", CF_TYPE_DATA },
{ CF_TYPE_MISSIONS, "data" DIR_SEPARATOR_STR "missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
{ CF_TYPE_CONFIG, "data" DIR_SEPARATOR_STR "config", ".cfg .tbl .tbm .xml .csv", CF_TYPE_DATA },
{ CF_TYPE_DEMOS, "data" DIR_SEPARATOR_STR "demos", ".fsd", CF_TYPE_DATA },
{ CF_TYPE_CBANIMS, "data" DIR_SEPARATOR_STR "cbanims", ".pcx .ani .eff .tga .jpg .png .dds", CF_TYPE_DATA },
{ CF_TYPE_INTEL_ANIMS, "data" DIR_SEPARATOR_STR "intelanims", ".pcx .ani .eff .tga .jpg .png .dds", CF_TYPE_DATA },
{ CF_TYPE_SCRIPTS, "data" DIR_SEPARATOR_STR "scripts", ".lua .lc .fnl", CF_TYPE_DATA },
{ CF_TYPE_FICTION, "data" DIR_SEPARATOR_STR "fiction", ".txt", CF_TYPE_DATA },
{ CF_TYPE_FREDDOCS, "data" DIR_SEPARATOR_STR "freddocs", ".html", CF_TYPE_DATA }
};
// clang-format on
int cfile_inited = 0;
static SCP_vector<SCP_string> Cfile_stack;
std::array<CFILE, MAX_CFILE_BLOCKS> Cfile_block_list;
static const char *Cfile_cdrom_dir = NULL;
//
// Function prototypes for internally-called functions
//
static int cfget_cfile_block();
static CFILE *cf_open_fill_cfblock(const char* source, int line, const char* original_filename, FILE * fp, int type);
static CFILE *cf_open_packed_cfblock(const char* source, int line, const char* original_filename, FILE *fp, int type, size_t offset, size_t size);
static CFILE *cf_open_memory_fill_cfblock(const char* source, int line, const char* original_filename, const void* data, size_t size, int dir_type);
static void cf_chksum_long_init();
static void dump_opened_files()
{
for (int i = 0; i < MAX_CFILE_BLOCKS; i++) {
auto cb = &Cfile_block_list[i];
if (cb->type != CFILE_BLOCK_UNUSED) {
mprintf((" %s:%d\n", cb->source_file, cb->line_num));
}
}
}
void cfile_close()
{
mprintf(("Still opened files:\n"));
dump_opened_files();
cf_free_secondary_filelist();
cfile_inited = 0;
}
#ifdef SCP_UNIX
#define MIN_NUM_PATH_COMPONENTS 2 /* Directory + file */
#else
#define MIN_NUM_PATH_COMPONENTS 3 /* Drive + directory + file */
#endif
/**
* @brief Determine if the given path is in the root directory
*
* @param exe_path Path to executable
*
* @return true if root directory, false if not
*/
static bool cfile_in_root_dir(const char *exe_path)
{
int new_token;
int token_count = 0;
const char *p = exe_path;
Assert(exe_path != NULL);
do {
new_token = 0;
while (*p == DIR_SEPARATOR_CHAR) {
p++;
}
while ((*p != '\0') && (*p != DIR_SEPARATOR_CHAR)) {
new_token = 1;
p++;
}
token_count += new_token;
} while (*p != '\0');
return (token_count < MIN_NUM_PATH_COMPONENTS);
}
/**
* @brief Initialize the cfile system. Called once at application start.
*
* @param exe_dir Path to a file (not a directory)
* @param cdrom_dir Path to a CD drive mount point (may be NULL)
*
* @return 0 On success
* @return 1 On error
*/
int cfile_init(const char *exe_dir, const char *cdrom_dir)
{
// initialize encryption
encrypt_init();
if (cfile_inited) {
return 0;
}
char buf[CFILE_ROOT_DIRECTORY_LEN];
strncpy(buf, exe_dir, CFILE_ROOT_DIRECTORY_LEN - 1);
buf[CFILE_ROOT_DIRECTORY_LEN - 1] = '\0';
// are we in a root directory?
if(cfile_in_root_dir(buf)){
os::dialogs::Message(os::dialogs::MESSAGEBOX_ERROR, "FreeSpace2/Fred2 cannot be run from a drive root directory!");
return 1;
}
// This needs to be set here because cf_build_secondary_filelist assumes it to be true
cfile_inited = 1;
/*
* Determine the executable's directory. Note that DIR_SEPARATOR_CHAR
* is guaranteed to be found in the string else cfile_in_root_dir()
* would have failed.
*/
char *p;
p = strrchr(buf, DIR_SEPARATOR_CHAR);
*p = '\0';
cfile_chdir(buf);
// set root directory
strcpy_s(Cfile_root_dir, buf);
strcpy_s(Cfile_user_dir, os_get_config_path().c_str());
// Initialize the block list with proper data
Cfile_block_list.fill({});
// 32 bit CRC table init
cf_chksum_long_init();
Cfile_cdrom_dir = cdrom_dir;
cf_build_secondary_filelist(Cfile_cdrom_dir);
return 0;
}
#ifdef _WIN32
// Changes to a drive if valid.. 1=A, 2=B, etc
// If flag, then changes to it.
// Returns 0 if not-valid, 1 if valid.
int cfile_chdrive( int DriveNum, int flag )
{
int Valid = 0;
int n, org;
org = -1;
if (!flag)
org = _getdrive();
_chdrive( DriveNum );
n = _getdrive();
if (n == DriveNum )
Valid = 1;
if ( (!flag) && (n != org) )
_chdrive( org );
return Valid;
}
#endif // _WIN32
/**
* @brief Common code for changing directory
*
* @param new_dir Directory to which to change
* @param cur_dir Current directory (only used on Windows)
*
* @retval 0 Success
* @retval 1 Failed to change to new directory's drive (Windows only)
* @retval 2 Failed to change to new directory
*/
static int _cfile_chdir(const char *new_dir, const char *cur_dir __UNUSED)
{
int status;
const char *path = NULL;
const char no_dir[] = "\\.";
#ifdef _WIN32
const char *colon = strchr(new_dir, ':');
if (colon) {
if (!cfile_chdrive(SCP_tolower(*(colon - 1)) - 'a' + 1, 1))
return 1;
path = colon + 1;
} else
#endif /* _WIN32 */
{
path = new_dir;
}
if (*path == '\0') {
path = no_dir;
}
/* This chdir might get a critical error! */
status = _chdir(path);
if (status != 0) {
#ifdef _WIN32
cfile_chdrive(SCP_tolower(cur_dir[0]) - 'a' + 1, 1);
#endif /* _WIN32 */
return 2;
}
return 0;
}
/**
* @brief Push current directory onto a 'stack' and change to a new directory
*
* The current directory is pushed onto a 'stack' so that it can be easily
* restored at a later time. The new directory is derived from @a type.
*
* @param type path type (CF_TYPE_xxx)
*
* @retval -1 'Stack' is full
* @retval 0 Success
* @retval 1 Failed to change to new directory's drive (Windows only)
* @retval 2 Failed to change to new directory
*/
int cfile_push_chdir(int type)
{
SCP_string dir;
char OriginalDirectory[CFILE_ROOT_DIRECTORY_LEN];
_getcwd(OriginalDirectory, CFILE_ROOT_DIRECTORY_LEN - 1);
cf_create_default_path_string(dir, type, NULL);
int rc = _cfile_chdir(dir.c_str(), OriginalDirectory);
// if success then push the original directory on to the stack
if (rc == 0) {
Cfile_stack.push_back(OriginalDirectory);
}
return rc;
}
/**
* @brief Change to the specified directory
*
* @param dir Directory
*
* @retval 0 Success
* @retval 1 Failed to change to new directory's drive (Windows only)
* @retval 2 Failed to change to new directory
*/
int cfile_chdir(const char *dir)
{
char OriginalDirectory[CFILE_ROOT_DIRECTORY_LEN];
_getcwd(OriginalDirectory, CFILE_ROOT_DIRECTORY_LEN - 1);
return _cfile_chdir(dir, OriginalDirectory);
}
int cfile_pop_dir()
{
if (Cfile_stack.empty())
return -1;
int rc = cfile_chdir(Cfile_stack.back().c_str());
Assertion(rc == 0, "Failed to chdir() to previous directory (%s)!", Cfile_stack.back().c_str());
Cfile_stack.pop_back();
return rc;
}
// flush (delete all files in) the passed directory (by type), return the # of files deleted
// NOTE : WILL NOT DELETE READ-ONLY FILES
int cfile_flush_dir(int dir_type)
{
int del_count;
SDL_PathInfo pinfo;
SCP_string filespec;
SCP_string fullpath;
Assert( CF_TYPE_SPECIFIED(dir_type) );
cf_create_default_path_string(filespec, dir_type);
// proceed to delete the files
del_count = 0;
auto results = SDL_GlobDirectory(filespec.c_str(), "*", 0, nullptr);
if (results) {
for (int i = 0; results[i]; ++i) {
fullpath = filespec;
fullpath += results[i];
if ( !SDL_GetPathInfo(fullpath.c_str(), &pinfo) ) {
continue;
}
if (pinfo.type != SDL_PATHTYPE_FILE) {
continue;
}
// delete the file
if ( SDL_RemovePath(fullpath.c_str()) ) {
// increment the deleted count
++del_count;
}
}
SDL_free(results);
}
// return the # of files deleted
return del_count;
}
// add the given extention to a filename (or filepath) if it doesn't already have this
// extension.
// filename = name of filename or filepath to process
// ext = extension to add. Must start with the period
// Returns: new filename or filepath with extension.
const char *cf_add_ext(const char *filename, const char *ext)
{
static char path[MAX_PATH_LEN];
size_t flen = strlen(filename);
size_t elen = strlen(ext);
Assert(flen < MAX_PATH_LEN);
strcpy_s(path, filename);
if ((flen < 4) || stricmp(path + flen - elen, ext) != 0) {
Assert(flen + elen < MAX_PATH_LEN);
strcat_s(path, ext);
}
return path;
}
/**
* @brief Delete the specified file
*
* @param filename Name of file to delete
* @param path_type Path type (CF_TYPE_xxx)
* @param location_flags Where to search for the location of the file to delete
*
* @return 0 on failure, 1 on success
*/
int cf_delete(const char *filename, int path_type, uint32_t location_flags)
{
SCP_string longname;
Assert(CF_TYPE_SPECIFIED(path_type));
cf_create_default_path_string(longname, path_type, filename, location_flags);
return SDL_RemovePath(longname.c_str());
}
// Same as _access function to read a file's access bits
int cf_access(const char *filename, int dir_type, int mode)
{
SCP_string longname;
Assert( CF_TYPE_SPECIFIED(dir_type) );
cf_create_default_path_string(longname, dir_type, filename);
return access(longname.c_str(), mode);
}
// Returns 1 if the file exists, 0 if not.
// Checks only the file system.
// cf_find_file_location checks the filesystem before VPs
// If offset is 0, it was found in the filesystem, so offset is boolean false
// If offset equates to boolean true, it was found in a VP and the logic will negate the function return
int cf_exists(const char *filename, int dir_type)
{
if ( (filename == NULL) || !strlen(filename) )
return 0;
auto find_res = cf_find_file_location(filename, dir_type);
return find_res.found && !find_res.offset;
}
// Goober5000
// Returns !0 if the file exists, 0 if not.
// Checks both the file system and the VPs.
int cf_exists_full(const char *filename, int dir_type)
{
if ( (filename == NULL) || !strlen(filename) )
return 0;
return cf_find_file_location(filename, dir_type).found;
}
// same as the above, but with extension check
int cf_exists_full_ext(const char *filename, int dir_type, const int num_ext, const char **ext_list)
{
if ( (filename == NULL) || !strlen(filename) )
return 0;
if ( (num_ext <= 0) || (ext_list == NULL) )
return 0;
return cf_find_file_location_ext(filename, num_ext, ext_list, dir_type).found;
}
#ifdef _WIN32
void cf_attrib(const char *filename, int set, int clear, int dir_type)
{
SCP_string longname;
Assert( CF_TYPE_SPECIFIED(dir_type) );
cf_create_default_path_string(longname, dir_type, filename);
FILE *fp = fopen(longname.c_str(), "rb");
if (fp) {
fclose(fp);
DWORD z = GetFileAttributes(longname.c_str());
SetFileAttributes(longname.c_str(), z | (set & ~clear));
}
}
#endif
int cf_rename(const char *old_name, const char *name, int dir_type)
{
Assert( CF_TYPE_SPECIFIED(dir_type) );
SCP_string old_longname;
SCP_string new_longname;
cf_create_default_path_string(old_longname, dir_type, old_name);
cf_create_default_path_string(new_longname, dir_type, name);
if (SDL_RenamePath(old_longname.c_str(), new_longname.c_str())) {
return CF_RENAME_SUCCESS;
}
return CF_RENAME_FAIL_ACCESS;
}
// Creates the directory path if it doesn't exist. Even creates all its
// parent paths.
void cf_create_directory(int dir_type, uint32_t location_flags)
{
SCP_string longname;
Assertion( CF_TYPE_SPECIFIED(dir_type), "Invalid dir_type passed to cf_create_directory." );
cf_create_default_path_string(longname, dir_type, nullptr, location_flags);
if (SDL_CreateDirectory(longname.c_str())) {
mprintf(("CFILE: Creating new directory '%s'\n", longname.c_str()));
}
}
// cfopen()
//
// parameters: *filepath ==> name of file to open (may be path+name)
// *mode ==> specifies how file should be opened (eg "rb" for read binary)
// passing NULL to mode triggers an assert and returns NULL
// dir_type => override extension check, value is one of CF_TYPE* #defines
//
// returns: success ==> address of CFILE structure
// error ==> NULL
//
CFILE* _cfopen(const char* source, int line, const char* file_path, const char* mode, int dir_type,
bool /* localize */, uint32_t location_flags)
{
/* Bobboau, what is this doing here? 31 is way too short... - Goober5000
if( strlen(file_path) > 31 )
Error(LOCATION, "file name %s too long, \nmust be less than 31 charicters", file_path);*/
if ( !cfile_inited ) {
Int3();
return NULL;
}
//================================================
// Check that all the parameters make sense
Assert(file_path && strlen(file_path));
Assert( mode != NULL );
//===========================================================
// If in write mode, just try to open the file straight off
// the harddisk. No fancy packfile stuff here!
if ( strchr(mode,'w') || strchr(mode,'+') || strchr(mode,'a') ) {
SCP_string longname;
auto last_separator = strrchr(file_path, DIR_SEPARATOR_CHAR);
// For write-only files, require a full path or a path type
if ( last_separator ) {
// Full path given?
longname = file_path;
} else {
// Path type given?
Assert( dir_type != CF_TYPE_ANY );
if (dir_type == CF_TYPE_ANY)
return NULL;
// Create the directory if necessary
cf_create_directory(dir_type, location_flags);
cf_create_default_path_string(longname, dir_type, file_path, location_flags);
}
// JOHN: TODO, you should create the path if it doesn't exist.
//WMC - For some reason, fread does not return the correct number of bytes read
//in text mode, which messes up FS2_Open's raw_position indicator in fgets. As a consequence, you
//_must_ open files that are gonna be read in binary mode.
char happy_mode[8];
if(strcspn(mode, "ra+") != strlen(mode) && (strchr(mode, 't') || !strchr(mode, 'b')))
{
//*****BEGIN PROCESSING OF MODE*****
//Copies all 'mode' characters over, except for t, and adds b if needed.
unsigned int max = sizeof(happy_mode) - 2; //space for null and 'b'
bool need_b = true;
unsigned int i;
for( i = 0; i < strlen(mode); i++)
{
if(i > max)
break;
if(mode[i] != 't')
happy_mode[i] = mode[i];
if(mode[i] == 'b')
need_b = false;
}
happy_mode[i] = '\0';
if(need_b)
strcat_s(happy_mode, "b");
//*****END PROCESSING OF MODE*****
}
else
{
strcpy_s(happy_mode, mode);
}
FILE *fp = fopen(longname.c_str(), happy_mode);
if (fp) {
return cf_open_fill_cfblock(source, line, last_separator ? (last_separator + 1) : file_path, fp, dir_type);
}
return NULL;
}
//================================================
// Search for file on disk, on cdrom, or in a packfile
auto find_res = cf_find_file_location(file_path, dir_type, location_flags);
if ( find_res.found ) {
// Fount it, now create a cfile out of it
nprintf(("CFileDebug", "Requested file %s found at: %s\n", file_path, find_res.full_name.c_str()));
// since cfopen_special already has all the code to handle the opening we can just use that here
return _cfopen_special(source, line, find_res, mode, dir_type);
}
return NULL;
}
// cfopen_ext()
//
// parameters: *filepath ==> name of file to open (may be path+name)
// *mode ==> specifies how file should be opened (eg "rb" for read binary)
// passing NULL to mode triggers an assert and returns NULL
// dir_type => override extension check, value is one of CF_TYPE* #defines
//
// returns: success ==> address of CFILE structure
// error ==> NULL
//
CFILE *_cfopen_special(const char* source, int line, const CFileLocation &res, const char* mode, int dir_type)
{
if ( !cfile_inited) {
Int3();
return NULL;
}
Assert( !res.full_name.empty() );
Assert( mode != NULL );
// cfopen_special() only supports reading files, not creating them
if ( strchr(mode, 'w') ) {
Int3();
return NULL;
}
// In-Memory files are a bit different from normal files so we need to handle them separately
if (res.data_ptr != nullptr) {
return cf_open_memory_fill_cfblock(source, line, res.name_ext.c_str(), res.data_ptr, res.size, dir_type);
}
else {
// "file_path" should already be a fully qualified path, so just try to open it
FILE *fp = fopen(res.full_name.c_str(), "rb");
if (fp) {
if (res.offset) {
// Found it in a pack file
return cf_open_packed_cfblock(source, line, res.name_ext.c_str(), fp, dir_type, res.offset, res.size);
}
else {
// Found it in a normal file
return cf_open_fill_cfblock(source, line, res.name_ext.c_str(), fp, dir_type);
}
}
}
return NULL;
}
// ------------------------------------------------------------------------
// ctmpfile()
//
// Open up a temporary file. A unique name is automatically generated. The
// file will be automatically deleted when file is closed.
//
// return: NULL => tmp file could not be opened
// pointer to CFILE => tmp file successfully opened
//
CFILE *ctmpfile()
{
FILE *fp;
fp = tmpfile();
if ( fp )
return cf_open_fill_cfblock(LOCATION, "<temporary file>", fp, 0);
else
return NULL;
}
// cfget_cfile_block() will try to find an empty Cfile_block structure in the
// Cfile_block_list[] array and return the index.
//
// returns: success ==> index in Cfile_block_list[] array
// failure ==> -1
//
static int cfget_cfile_block()
{
int i;
CFILE* cfile;
for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
cfile = &Cfile_block_list[i];
if (cfile->type == CFILE_BLOCK_UNUSED) {
cfile->data = nullptr;
cfile->fp = nullptr;
cfile->type = CFILE_BLOCK_USED;
cf_clear_compression_info(cfile);
return i;
}
}
// If we've reached this point, a free Cfile_block could not be found
nprintf(("Warning","A free Cfile_block could not be found.\n"));
// Dump a list of all opened files
mprintf(("Out of cfile blocks! Currently opened files:\n"));
dump_opened_files();
UNREACHABLE("There are no more free cfile blocks. This means that there are too many files opened by FSO.\n"
"This is probably caused by a programming or scripting error where a file does not get closed."); // out of free cfile blocks
return -1;
}
// cfclose() closes the file
//
// returns: success ==> 0
// failure ==> EOF
//
int cfclose( CFILE * cfile )
{
int result;
Assert(cfile != NULL);
result = 0;
if ( cfile->fp != nullptr ) {
Assert(cfile->fp != nullptr);
result = fclose(cfile->fp);
} else {
// VP do nothing
}
cf_clear_compression_info(cfile);
cfile->type = CFILE_BLOCK_UNUSED;
return result;
}
int cf_is_valid(CFILE *cfile)
{
//Was a valid pointer passed?
if(cfile == NULL)
return 0;
//Is it used?
if (cfile->type != CFILE_BLOCK_USED && (cfile->fp != nullptr || cfile->data != nullptr))
return 0;
//It's good, as near as we can tell.
return 1;
}
// cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
// for the case of a file being opened by cf_open();
//
// returns: success ==> ptr to CFILE structure.
// error ==> NULL
//
static CFILE *cf_open_fill_cfblock(const char* source, int line, const char* original_filename, FILE *fp, int type)
{
int cfile_block_index;
cfile_block_index = cfget_cfile_block();
if ( cfile_block_index == -1 ) {
fclose(fp);
return NULL;
} else {
CFILE *cfp = &Cfile_block_list[cfile_block_index];
cfp->data = nullptr;
cfp->fp = fp;
cfp->dir_type = type;
cfp->max_read_len = 0;
cfp->original_filename = original_filename;
cfp->source_file = source;
cfp->line_num = line;
auto pos = ftell(fp);
if(pos == -1L)
pos = 0;
cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)), 0 );
cf_check_compression(cfp);
return cfp;
}
}
// cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
// for the case of a file being opened by cf_open();
//
// returns: success ==> ptr to CFILE structure.
// error ==> NULL
//
static CFILE *cf_open_packed_cfblock(const char* source, int line, const char* original_filename, FILE *fp, int type, size_t offset, size_t size)
{
// Found it in a pack file
int cfile_block_index;
cfile_block_index = cfget_cfile_block();
if ( cfile_block_index == -1 ) {
fclose(fp);
return NULL;
} else {
CFILE *cfp = &Cfile_block_list[cfile_block_index];
cfp->data = nullptr;
cfp->fp = fp;
cfp->dir_type = type;
cfp->max_read_len = 0;
cfp->original_filename = original_filename;
cfp->source_file = source;
cfp->line_num = line;
cf_init_lowlevel_read_code(cfp,offset, size, 0 );
cf_check_compression(cfp);
return cfp;
}
}
static CFILE *cf_open_memory_fill_cfblock(const char* source, int line, const char* original_filename, const void* data, size_t size, int dir_type)
{
int cfile_block_index;
cfile_block_index = cfget_cfile_block();
if ( cfile_block_index == -1 ) {
return NULL;
}
else {
CFILE *cfp = &Cfile_block_list[cfile_block_index];
cfp->max_read_len = 0;
cfp->fp = nullptr;
cfp->dir_type = dir_type;
cfp->original_filename = original_filename;
cfp->source_file = source;
cfp->line_num = line;
cf_init_lowlevel_read_code(cfp, 0, size, 0 );
cfp->data = data;
return cfp;
}
}
const char *cf_get_filename(const CFILE *cfile)
{
return cfile->original_filename.c_str();
}
int cf_get_dir_type(const CFILE *cfile)
{
return cfile->dir_type;
}
// cf_returndata() returns the data pointer for a memory-mapped file that is associated
// with the CFILE structure passed as a parameter
//
//
const void *cf_returndata(CFILE *cfile)
{
Assert(cfile != NULL);
Assert(cfile->data != nullptr);
return cfile->data;
}
// cutoff point where cfread() will throw an error when it hits this limit
// if 'len' is 0 then this check will be disabled
void cf_set_max_read_len( CFILE * cfile, size_t len )
{
Assert( cfile != NULL );
if (len) {
cfile->max_read_len = cfile->raw_position + len;
} else {
cfile->max_read_len = 0;
}
}
// routines to read basic data types from CFILE's. Put here to
// simplify mac/pc reading from cfiles.
float cfread_float(CFILE* file, float deflt)
{
float f;
if (cfread( &f, sizeof(f), 1, file) != 1)
return deflt;
f = INTEL_FLOAT(&f);
return f;
}
int cfread_int(CFILE* file, int deflt)
{
int i;
if (cfread( &i, sizeof(i), 1, file) != 1)
return deflt;
i = INTEL_INT(i);
return i;
}
uint cfread_uint(CFILE* file, uint deflt)
{
uint i;
if (cfread( &i, sizeof(i), 1, file) != 1)
return deflt;
i = INTEL_INT(i);
return i;
}
short cfread_short(CFILE* file, short deflt)
{
short s;
if (cfread( &s, sizeof(s), 1, file) != 1)
return deflt;
s = INTEL_SHORT(s);
return s;
}
ushort cfread_ushort(CFILE* file, ushort deflt)
{
ushort s;
if (cfread( &s, sizeof(s), 1, file) != 1)
return deflt;
s = INTEL_SHORT(s);
return s;
}
ubyte cfread_ubyte(CFILE* file, ubyte deflt)