2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on
10 * $Logfile: /Freespace2/code/CFile/cfile.cpp $
15 * Utilities for operating on files
18 * Revision 1.14 2006/04/26 19:36:57 taylor
19 * address an error handling bug in cfwrite()
21 * Revision 1.13 2005/10/01 22:04:58 taylor
22 * fix FS1 (de)briefing voices, the directory names are different in FS1
23 * hard code the table values so that the fs1.vp file isn't needed
24 * hard code a mission fix for sm2-08a since a have no idea how to fix it otherwise
25 * generally cleanup some FS1 code
26 * fix volume sliders in the options screen that never went all the way up
28 * Revision 1.12 2005/08/12 08:50:09 taylor
29 * recursively create directories (hurt more on OSX) and update all _mkdir() calls accordingly
31 * Revision 1.11 2004/07/04 11:27:29 taylor
32 * cleanup CFILE code a little, warning fixes, remove redundant dir checks, amd64 support
34 * Revision 1.10 2004/06/11 00:28:39 tigital
35 * byte-swapping changes for bigendian systems
37 * Revision 1.9 2003/05/25 02:30:42 taylor
40 * Revision 1.8 2003/02/20 17:41:07 theoddone33
41 * Userdir patch from Taylor Richards
43 * Revision 1.7 2002/12/30 03:23:29 relnev
44 * disable root dir check
46 * Revision 1.6 2002/06/17 06:33:08 relnev
47 * ryan's struct patch for gcc 2.95
49 * Revision 1.5 2002/06/09 04:41:15 relnev
50 * added copyright header
52 * Revision 1.4 2002/06/05 08:05:28 relnev
53 * stub/warning removal.
55 * reworked the sound code.
57 * Revision 1.3 2002/05/28 08:52:03 relnev
58 * implemented two assembly stubs.
60 * cleaned up a few warnings.
62 * added a little demo hackery to make it progress a little farther.
64 * Revision 1.2 2002/05/28 06:28:20 theoddone33
65 * Filesystem mods, actually reads some data files now
67 * Revision 1.1.1.1 2002/05/03 03:28:08 root
71 * 20 9/08/99 10:01p Dave
72 * Make sure game won't run in a drive's root directory. Make sure
73 * standalone routes suqad war messages properly to the host.
75 * 19 9/08/99 12:03a Dave
76 * Make squad logos render properly in D3D all the time. Added intel anim
79 * 18 9/06/99 2:35p Dave
80 * Rename briefing and debriefing voice direcrory paths properly.
82 * 17 9/03/99 1:31a Dave
83 * CD checking by act. Added support to play 2 cutscenes in a row
84 * seamlessly. Fixed super low level cfile bug related to files in the
85 * root directory of a CD. Added cheat code to set campaign mission # in
88 * 16 8/31/99 9:46a Dave
89 * Support for new cfile cbanims directory.
91 * 15 8/06/99 11:20a Johns
92 * Don't call game_cd_changed() in a demo or multiplayer beta build.
94 * 14 6/08/99 2:33p Dave
95 * Fixed release build warning. Put in hud config stuff.
97 * 13 5/19/99 4:07p Dave
98 * Moved versioning code into a nice isolated common place. Fixed up
99 * updating code on the pxo screen. Fixed several stub problems.
101 * 12 4/30/99 12:18p Dave
102 * Several minor bug fixes.
104 * 11 4/07/99 5:54p Dave
105 * Fixes for encryption in updatelauncher.
107 * 10 3/28/99 5:58p Dave
108 * Added early demo code. Make objects move. Nice and framerate
109 * independant, but not much else. Don't use yet unless you're me :)
111 * 9 2/22/99 10:31p Andsager
112 * Get rid of unneeded includes.
114 * 8 1/12/99 3:15a Dave
115 * Barracks screen support for selecting squad logos. We need real artwork
118 * 7 11/30/98 1:07p Dave
119 * 16 bit conversion, first run.
121 * 6 10/29/98 10:41a Dave
122 * Change the way cfile initializes exe directory.
124 * 5 10/13/98 9:19a Andsager
125 * Add localization support to cfile. Optional parameter with cfopen that
126 * looks for localized files.
128 * 4 10/12/98 9:54a Dave
129 * Fixed a few file organization things.
131 * 3 10/07/98 6:27p Dave
132 * Globalized mission and campaign file extensions. Removed Silent Threat
133 * special code. Moved \cache \players and \multidata into the \data
136 * 2 10/07/98 10:52a Dave
139 * 1 10/07/98 10:48a Dave
141 * 110 9/17/98 10:31a Hoffoss
142 * Changed code to use location of executable as root rather than relying
143 * on the cwd being set correctly. This is most helpful in the case of
144 * Fred launching due to the user double-clicking on an .fsm file in
145 * explorer or something (where the cwd is probably the location of the
148 * 109 9/11/98 4:14p Dave
149 * Fixed file checksumming of < file_size. Put in more verbose kicking and
150 * PXO stats store reporting.
152 * 108 9/09/98 5:53p Dave
153 * Put in new tracker packets in API. Change cfile to be able to checksum
154 * portions of a file.
156 * 107 9/04/98 3:51p Dave
157 * Put in validated mission updating and application during stats
160 * 106 8/31/98 2:06p Dave
161 * Make cfile sort the ordering or vp files. Added support/checks for
162 * recognizing "mission disk" players.
164 * 105 8/20/98 5:30p Dave
165 * Put in handy multiplayer logfile system. Now need to put in useful
166 * applications of it all over the code.
168 * 104 8/12/98 4:53p Dave
169 * Put in 32 bit checksumming for PXO missions. No validation on the
170 * actual tracker yet, though.
172 * 103 6/17/98 9:30a Allender
173 * fixed red alert replay stats clearing problem
175 * 102 6/05/98 9:46a Lawrance
176 * check for CD change on cfopen()
178 * 101 5/19/98 1:19p Allender
179 * new low level reliable socket reading code. Make all missions/campaign
180 * load/save to data missions folder (i.e. we are rid of the player
183 * 100 5/13/98 10:22p John
184 * Added cfile functions to read/write rle compressed blocks of data.
185 * Made palman use it for .clr files. Made alphacolors calculate on the
186 * fly rather than caching to/from disk.
188 * 99 5/11/98 10:59a John
189 * Moved the low-level file reading code into cfilearchive.cpp.
191 * 98 5/06/98 5:30p John
192 * Removed unused cfilearchiver. Removed/replaced some unused/little used
193 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
194 * DirectX header files and libs that fixed the Direct3D alpha blending
197 * 97 5/03/98 11:53a John
198 * Fixed filename case mangling.
200 * 96 5/03/98 8:33a John
201 * Made sure there weren't any more broken function lurking around like
202 * the one Allender fixed.
204 * 95 5/02/98 11:05p Allender
205 * fix cfilelength for pack files
210 #define _CFILE_INTERNAL
220 #include <winbase.h> /* needed for memory mapping of file functions */
223 #include <sys/stat.h>
224 #include <sys/types.h>
230 //#include "outwnd.h"
231 //#include "vecmat.h"
233 #include "cfilesystem.h"
234 #include "cfilearchive.h"
236 #include "osregistry.h"
238 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
239 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
241 // During cfile_init, verify that Pathtypes[n].index == n for each item
242 // Each path must have a valid parent that can be tracable all the way back to the root
243 // so that we can create directories when we need to.
245 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
246 // What type this is Path Extensions Parent type
247 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
248 // Root must be index 1!!
249 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
250 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
251 { CF_TYPE_MAPS, "Data" DIR_SEPARATOR_STR "Maps", ".pcx .ani .tga", CF_TYPE_DATA },
252 { CF_TYPE_TEXT, "Data" DIR_SEPARATOR_STR "Text", ".txt .net", CF_TYPE_DATA },
254 { CF_TYPE_MISSIONS, "Data" DIR_SEPARATOR_STR "Missions", ".fsm .fsc .ntl .ssv", CF_TYPE_DATA },
256 { CF_TYPE_MISSIONS, "Data" DIR_SEPARATOR_STR "Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
258 { CF_TYPE_MODELS, "Data" DIR_SEPARATOR_STR "Models", ".pof", CF_TYPE_DATA },
259 { CF_TYPE_TABLES, "Data" DIR_SEPARATOR_STR "Tables", ".tbl", CF_TYPE_DATA },
260 { CF_TYPE_SOUNDS, "Data" DIR_SEPARATOR_STR "Sounds", ".wav", CF_TYPE_DATA },
261 { CF_TYPE_SOUNDS_8B22K, "Data" DIR_SEPARATOR_STR "Sounds" DIR_SEPARATOR_STR "8b22k", ".wav", CF_TYPE_SOUNDS },
262 { CF_TYPE_SOUNDS_16B11K, "Data" DIR_SEPARATOR_STR "Sounds" DIR_SEPARATOR_STR "16b11k", ".wav", CF_TYPE_SOUNDS },
263 { CF_TYPE_VOICE, "Data" DIR_SEPARATOR_STR "Voice", "", CF_TYPE_DATA },
265 { CF_TYPE_VOICE_BRIEFINGS, "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Briefings", ".wav", CF_TYPE_VOICE },
267 { CF_TYPE_VOICE_BRIEFINGS, "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Briefing", ".wav", CF_TYPE_VOICE },
269 { CF_TYPE_VOICE_CMD_BRIEF, "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Command_briefings",".wav", CF_TYPE_VOICE },
271 { CF_TYPE_VOICE_DEBRIEFINGS, "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Debriefings", ".wav", CF_TYPE_VOICE },
273 { CF_TYPE_VOICE_DEBRIEFINGS, "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Debriefing", ".wav", CF_TYPE_VOICE },
275 { CF_TYPE_VOICE_PERSONAS, "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Personas", ".wav", CF_TYPE_VOICE },
276 { CF_TYPE_VOICE_SPECIAL, "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Special", ".wav", CF_TYPE_VOICE },
277 { CF_TYPE_VOICE_TRAINING, "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Training", ".wav", CF_TYPE_VOICE },
278 { CF_TYPE_MUSIC, "Data" DIR_SEPARATOR_STR "Music", ".wav", CF_TYPE_VOICE },
279 { CF_TYPE_MOVIES, "Data" DIR_SEPARATOR_STR "Movies", ".mve .msb", CF_TYPE_DATA },
280 { CF_TYPE_INTERFACE, "Data" DIR_SEPARATOR_STR "Interface", ".pcx .ani .tga", CF_TYPE_DATA },
281 { CF_TYPE_FONT, "Data" DIR_SEPARATOR_STR "Fonts", ".vf", CF_TYPE_DATA },
282 { CF_TYPE_EFFECTS, "Data" DIR_SEPARATOR_STR "Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
283 { CF_TYPE_HUD, "Data" DIR_SEPARATOR_STR "Hud", ".ani .pcx .tga", CF_TYPE_DATA },
284 { CF_TYPE_PLAYER_MAIN, "Data" DIR_SEPARATOR_STR "Players", "", CF_TYPE_DATA },
285 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Images", ".pcx", CF_TYPE_PLAYER_MAIN },
286 { CF_TYPE_CACHE, "Data" DIR_SEPARATOR_STR "Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
287 { CF_TYPE_PLAYERS, "Data" DIR_SEPARATOR_STR "Players", ".hcf", CF_TYPE_DATA },
288 { CF_TYPE_SINGLE_PLAYERS, "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Single", ".plr .csg .css", CF_TYPE_PLAYERS },
289 { CF_TYPE_MULTI_PLAYERS, "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Multi", ".plr", CF_TYPE_DATA },
290 { CF_TYPE_MULTI_CACHE, "Data" DIR_SEPARATOR_STR "MultiData", ".pcx .fs2", CF_TYPE_DATA },
291 { CF_TYPE_CONFIG, "Data" DIR_SEPARATOR_STR "Config", ".cfg", CF_TYPE_DATA },
292 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Squads", ".pcx", CF_TYPE_DATA },
293 { CF_TYPE_DEMOS, "Data" DIR_SEPARATOR_STR "Demos", ".fsd", CF_TYPE_DATA },
294 { CF_TYPE_CBANIMS, "Data" DIR_SEPARATOR_STR "CBAnims", ".ani", CF_TYPE_DATA },
295 { CF_TYPE_INTEL_ANIMS, "Data" DIR_SEPARATOR_STR "IntelAnims", ".ani", CF_TYPE_DATA },
299 #define CFILE_STACK_MAX 8
301 int cfile_inited = 0;
302 static int Cfile_stack_pos = 0;
304 static char Cfile_stack[CFILE_STACK_MAX][MAX_PATH_LEN];
306 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
307 CFILE Cfile_list[MAX_CFILE_BLOCKS];
310 // Function prototypes for internally-called functions
312 int cfget_cfile_block();
313 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
314 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
315 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
316 void cf_chksum_long_init();
320 cf_free_secondary_filelist();
323 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
324 int cfile_in_root_dir(char *exe_path)
327 char path_copy[2048] = "";
331 if(exe_path == NULL){
336 memset(path_copy, 0, 2048);
337 SDL_strlcpy(path_copy, exe_path, sizeof(path_copy));
339 // count how many slashes there are in the path
340 tok = strtok(path_copy, DIR_SEPARATOR_STR);
346 tok = strtok(NULL, DIR_SEPARATOR_STR);
347 } while(tok != NULL);
349 // root directory if we have <= 1 slash
350 if(token_count <= 2){
354 // not-root directory
358 // cfile_init() initializes the cfile system. Called once at application start.
360 // returns: success ==> 0
361 // error ==> non-zero
363 int cfile_init(const char *extras_dir)
367 // initialize encryption
370 if ( !cfile_inited ) {
371 // initialize root and user paths (may have been done already)
372 if ( cfile_init_paths() ) {
378 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
379 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
382 const char *extras_dir = os_config_read_string(NULL, "ExtrasPath", NULL);
384 if ( extras_dir && (strlen(extras_dir) >= MAX_PATH_LEN) ) {
388 cf_build_secondary_filelist(extras_dir);
390 // 32 bit CRC table init
391 cf_chksum_long_init();
395 atexit( cfile_close );
402 // Changes to a drive if valid.. 1=A, 2=B, etc
403 // If flag, then changes to it.
404 // Returns 0 if not-valid, 1 if valid.
405 int cfile_chdrive( int DriveNum, int flag )
418 _chdrive( DriveNum );
425 if ( (!flag) && (n != org) )
431 // push current directory on a 'stack' (so we can restore it) and change the directory
432 int cfile_push_chdir(int type)
436 char OriginalDirectory[128];
438 char NoDir[] = "\\.";
440 _getcwd(OriginalDirectory, 127);
441 SDL_assert(Cfile_stack_pos < CFILE_STACK_MAX);
442 SDL_strlcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory, MAX_PATH_LEN);
444 cf_create_default_path_string( dir, type, NULL );
447 char *Drive = SDL_strchr(dir, ':');
450 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
465 // This chdir might get a critical error!
468 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
476 int cfile_chdir(char *dir)
479 char OriginalDirectory[128];
481 char NoDir[] = "\\.";
483 _getcwd(OriginalDirectory, 127);
487 char *Drive = SDL_strchr(dir, ':');
489 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
504 // This chdir might get a critical error!
507 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
516 SDL_assert(Cfile_stack_pos);
518 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
521 // flush (delete all files in) the passed directory (by type), return the # of files deleted
522 // NOTE : WILL NOT DELETE READ-ONLY FILES
523 int cfile_flush_dir(int dir_type)
533 SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
535 // attempt to change the directory to the passed type
536 if(cfile_push_chdir(dir_type)){
540 // proceed to delete the files
541 find_handle = _findfirst( "*", &find );
543 if (find_handle != -1) {
545 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
547 cf_delete(find.name,dir_type);
549 // increment the deleted count
552 } while (!_findnext(find_handle, &find));
553 _findclose( find_handle );
556 // pop the directory back
559 // return the # of files deleted
565 // add the given extention to a filename (or filepath) if it doesn't already have this
567 // filename = name of filename or filepath to process
568 // ext = extension to add. Must start with the period
569 // Returns: new filename or filepath with extension.
570 char *cf_add_ext(const char *filename, const char *ext)
573 static char path[MAX_PATH_LEN];
575 flen = strlen(filename);
577 SDL_assert(flen < MAX_PATH_LEN);
578 SDL_strlcpy(path, filename, sizeof(path));
579 if ((flen < 4) || SDL_strcasecmp(path + flen - elen, ext)) {
580 SDL_assert(flen + elen < MAX_PATH_LEN);
581 SDL_strlcat(path, ext, sizeof(path));
588 void cf_delete( const char *filename, int dir_type )
590 char longname[MAX_PATH_LEN];
592 SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
594 cf_create_default_path_string( longname, dir_type, filename );
596 FILE *fp = fopen(longname, "rb");
606 // Same as _access function to read a file's access bits
607 int cf_access( const char *filename, int dir_type, int mode )
609 char longname[MAX_PATH_LEN];
611 SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
613 cf_create_default_path_string( longname, dir_type, filename );
615 return access(longname,mode);
619 // Returns 1 if file exists, 0 if not.
620 int cf_exist( const char *filename, int dir_type )
622 char longname[MAX_PATH_LEN];
624 SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
626 cf_create_default_path_string( longname, dir_type, filename );
628 FILE *fp = fopen(longname, "rb");
637 int cf_rename(const char *old_name, const char *name, int dir_type)
639 SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
642 char old_longname[_MAX_PATH];
643 char new_longname[_MAX_PATH];
645 cf_create_default_path_string( old_longname, dir_type, old_name );
646 cf_create_default_path_string( new_longname, dir_type, name );
648 ret_code = rename(old_longname, new_longname );
652 return CF_RENAME_FAIL_ACCESS;
655 return CF_RENAME_FAIL_EXIST;
659 return CF_RENAME_SUCCESS;
664 // Creates the directory path if it doesn't exist. Even creates all its
666 void cf_create_directory( int dir_type )
669 int dir_tree[CF_MAX_PATH_TYPES];
670 char longname[MAX_PATH_LEN];
672 SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
674 int current_dir = dir_type;
677 SDL_assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
679 dir_tree[num_dirs++] = current_dir;
680 current_dir = Pathtypes[current_dir].parent_index;
682 } while( current_dir != CF_TYPE_ROOT );
687 for (i=num_dirs-1; i>=0; i-- ) {
688 cf_create_default_path_string( longname, dir_tree[i], NULL );
690 if ( _mkdir(longname)==0 ) {
691 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
701 // parameters: *filepath ==> name of file to open (may be path+name)
702 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
703 // passing NULL to mode deletes the file if it exists and returns NULL
704 // type ==> one of: CFILE_NORMAL
705 // CFILE_MEMORY_MAPPED
706 // dir_type => override extension check, value is one of CF_TYPE* #defines
708 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
711 // returns: success ==> address of CFILE structure
715 CFILE *cfopen(const char *file_path, const char *mode, int type, int dir_type, bool localize)
717 char longname[_MAX_PATH];
719 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
720 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
722 //================================================
723 // Check that all the parameters make sense
724 SDL_assert(file_path && strlen(file_path));
725 SDL_assert( mode != NULL );
727 // Can only open read-only binary files in memory mapped mode.
728 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
733 //===========================================================
734 // If in write mode, just try to open the file straight off
735 // the harddisk. No fancy packfile stuff here!
737 if ( SDL_strchr(mode,'w') ) {
738 // For write-only files, require a full path or a path type
740 if ( strpbrk(file_path, "/") ) {
742 if ( strpbrk(file_path,"/\\:") ) {
745 SDL_strlcpy(longname, file_path, sizeof(longname));
748 SDL_assert( dir_type != CF_TYPE_ANY );
750 // Create the directory if necessary
751 cf_create_directory( dir_type );
753 cf_create_default_path_string( longname, dir_type, file_path );
755 SDL_assert( !(type & CFILE_MEMORY_MAPPED) );
757 // JOHN: TODO, you should create the path if it doesn't exist.
759 FILE *fp = fopen(longname, mode);
761 return cf_open_fill_cfblock(fp, dir_type);
767 //================================================
768 // Search for file on disk, on cdrom, or in a packfile
771 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
772 SDL_strlcpy(copy_file_path, file_path, sizeof(copy_file_path));
775 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
777 // Fount it, now create a cfile out of it
779 if ( type & CFILE_MEMORY_MAPPED ) {
781 // Can't open memory mapped files out of pack files
788 hFile = CreateFile((LPCWSTR)longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
790 if (hFile != INVALID_HANDLE_VALUE) {
791 return cf_open_mapped_fill_cfblock(hFile, dir_type);
798 FILE *fp = fopen( longname, "rb" );
802 // Found it in a pack file
803 return cf_open_packed_cfblock(fp, dir_type, offset, size );
805 // Found it in a normal file
806 return cf_open_fill_cfblock(fp, dir_type);
817 // ------------------------------------------------------------------------
820 // Open up a temporary file. A unique name is automatically generated. The
821 // file will be automatically deleted when file is closed.
823 // return: NULL => tmp file could not be opened
824 // pointer to CFILE => tmp file successfully opened
831 return cf_open_fill_cfblock(fp, 0);
838 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
839 // Cfile_block_list[] array and return the index.
841 // returns: success ==> index in Cfile_block_list[] array
844 int cfget_cfile_block()
849 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
850 cb = &Cfile_block_list[i];
851 if ( cb->type == CFILE_BLOCK_UNUSED ) {
854 cb->type = CFILE_BLOCK_USED;
859 // If we've reached this point, a free Cfile_block could not be found
860 nprintf(("Warning","A free Cfile_block could not be found.\n"));
861 SDL_assert(0); // out of free cfile blocks
866 // cfclose() closes the file
868 // returns: success ==> 0
871 int cfclose( CFILE * cfile )
875 SDL_assert(cfile != NULL);
877 SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
878 cb = &Cfile_block_list[cfile->id];
882 // close memory mapped file
886 result = UnmapViewOfFile((void*)cb->data);
888 result = CloseHandle(cb->hInFile);
889 SDL_assert(result); // Ensure file handle is closed properly
890 result = CloseHandle(cb->hMapFile);
891 SDL_assert(result); // Ensure file handle is closed properly
895 } else if ( cb->fp != NULL ) {
896 SDL_assert(cb->fp != NULL);
897 result = fclose(cb->fp);
902 cb->type = CFILE_BLOCK_UNUSED;
909 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
910 // for the case of a file being opened by cf_open();
912 // returns: success ==> ptr to CFILE structure.
915 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
917 int cfile_block_index;
919 cfile_block_index = cfget_cfile_block();
920 if ( cfile_block_index == -1 ) {
925 cfbp = &Cfile_block_list[cfile_block_index];
926 cfp = &Cfile_list[cfile_block_index];;
927 cfp->id = cfile_block_index;
931 cfbp->dir_type = type;
933 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
940 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
941 // for the case of a file being opened by cf_open();
943 // returns: success ==> ptr to CFILE structure.
946 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
948 // Found it in a pack file
949 int cfile_block_index;
951 cfile_block_index = cfget_cfile_block();
952 if ( cfile_block_index == -1 ) {
957 cfbp = &Cfile_block_list[cfile_block_index];
959 cfp = &Cfile_list[cfile_block_index];
960 cfp->id = cfile_block_index;
964 cfbp->dir_type = type;
966 cf_init_lowlevel_read_code(cfp,offset, size );
975 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
976 // for the case of a file being opened by cf_open_mapped();
978 // returns: ptr CFILE structure.
980 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
982 int cfile_block_index;
984 cfile_block_index = cfget_cfile_block();
985 if ( cfile_block_index == -1 ) {
991 cfbp = &Cfile_block_list[cfile_block_index];
993 cfp = &Cfile_list[cfile_block_index];
994 cfp->id = cfile_block_index;
996 cfbp->hInFile = hFile;
997 cfbp->dir_type = type;
999 cf_init_lowlevel_read_code(cfp,0 , 0 );
1004 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1005 if (cfbp->hMapFile == NULL) {
1006 nprintf(("Error", "Could not create file-mapping object.\n"));
1010 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1011 SDL_assert( cfbp->data != NULL );
1017 int cf_get_dir_type(CFILE *cfile)
1019 return Cfile_block_list[cfile->id].dir_type;
1022 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1023 // with the CFILE structure passed as a parameter
1027 void *cf_returndata(CFILE *cfile)
1029 SDL_assert(cfile != NULL);
1031 SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1032 cb = &Cfile_block_list[cfile->id];
1033 SDL_assert(cb->data != NULL);
1039 // version number of opened file. Will be 0 unless you put something else here after you
1040 // open a file. Once set, you can use minimum version numbers with the read functions.
1041 void cf_set_version( CFILE * cfile, int version )
1043 SDL_assert(cfile != NULL);
1045 cfile->version = version;
1048 // routines to read basic data types from CFILE's. Put here to
1049 // simplify mac/pc reading from cfiles.
1054 float cfread_float(CFILE *file, int ver, float deflt)
1058 if (file->version < ver)
1061 if (cfread( &f, sizeof(f), 1, file) != 1)
1068 int cfread_int(CFILE *file, int ver, int deflt)
1072 if (file->version < ver)
1075 if (cfread( &i, sizeof(i), 1, file) != 1)
1082 uint cfread_uint(CFILE *file, int ver, uint deflt)
1086 if (file->version < ver)
1089 if (cfread( &i, sizeof(i), 1, file) != 1)
1096 short cfread_short(CFILE *file, int ver, short deflt)
1100 if (file->version < ver)
1103 if (cfread( &s, sizeof(s), 1, file) != 1)
1110 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1114 if (file->version < ver)
1117 if (cfread( &s, sizeof(s), 1, file) != 1)
1124 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1128 if (file->version < ver)
1131 if (cfread( &b, sizeof(b), 1, file) != 1)
1137 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1139 if (file->version < ver) {
1143 vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1148 vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1149 vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1150 vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1153 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1155 if (file->version < ver) {
1159 ang->p = ang->b = ang->h = 0.0f;
1164 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1165 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1166 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1169 char cfread_char(CFILE *file, int ver, char deflt)
1173 if (file->version < ver)
1176 if (cfread( &b, sizeof(b), 1, file) != 1)
1182 void cfread_string(char *buf, int n, CFILE *file)
1187 c = cfread_char(file);
1195 void cfread_string_len(char *buf,int n, CFILE *file)
1198 len = cfread_int(file);
1199 SDL_assert( len < n );
1201 cfread(buf, len, 1, file);
1206 // equivalent write functions of above read functions follow
1208 int cfwrite_float(float f, CFILE *file)
1211 return cfwrite(&f, sizeof(f), 1, file);
1214 int cfwrite_int(int i, CFILE *file)
1217 return cfwrite(&i, sizeof(i), 1, file);
1220 int cfwrite_uint(uint i, CFILE *file)
1223 return cfwrite(&i, sizeof(i), 1, file);
1226 int cfwrite_short(short s, CFILE *file)
1229 return cfwrite(&s, sizeof(s), 1, file);
1232 int cfwrite_ushort(ushort s, CFILE *file)
1235 return cfwrite(&s, sizeof(s), 1, file);
1238 int cfwrite_ubyte(ubyte b, CFILE *file)
1240 return cfwrite(&b, sizeof(b), 1, file);
1243 int cfwrite_vector(vector *vec, CFILE *file)
1245 if(!cfwrite_float(vec->xyz.x, file)){
1248 if(!cfwrite_float(vec->xyz.y, file)){
1251 return cfwrite_float(vec->xyz.z, file);
1254 int cfwrite_angles(angles *ang, CFILE *file)
1256 if(!cfwrite_float(ang->p, file)){
1259 if(!cfwrite_float(ang->b, file)){
1262 return cfwrite_float(ang->h, file);
1265 int cfwrite_char(char b, CFILE *file)
1267 return cfwrite( &b, sizeof(b), 1, file);
1270 int cfwrite_string(const char *buf, CFILE *file)
1272 if ( (!buf) || (buf && !buf[0]) ) {
1273 return cfwrite_char(0, file);
1275 int len = strlen(buf);
1276 if(!cfwrite(buf, len, 1, file)){
1279 return cfwrite_char(0, file); // write out NULL termination
1282 int cfwrite_string_len(const char *buf, CFILE *file)
1284 int len = strlen(buf);
1286 if(!cfwrite_int(len, file)){
1290 return cfwrite(buf,len,1,file);
1296 // Get the filelength
1297 int cfilelength( CFILE * cfile )
1299 SDL_assert(cfile != NULL);
1301 SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1302 cb = &Cfile_block_list[cfile->id];
1304 // TODO: return length of memory mapped file
1305 SDL_assert( !cb->data );
1307 SDL_assert(cb->fp != NULL);
1309 // cb->size gets set at cfopen
1313 // cfwrite() writes to the file
1315 // returns: number of full elements actually written
1318 int cfwrite(const void *buf, int elsize, int nelem, CFILE *cfile)
1320 SDL_assert(cfile != NULL);
1321 SDL_assert(buf != NULL);
1322 SDL_assert(elsize > 0);
1323 SDL_assert(nelem > 0);
1326 SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1327 cb = &Cfile_block_list[cfile->id];
1329 int size = elsize * nelem;
1331 // cfwrite() not supported for memory-mapped files
1332 SDL_assert( !cb->data );
1334 SDL_assert(cb->fp != NULL);
1335 SDL_assert(cb->lib_offset == 0 );
1336 int bytes_written = fwrite( buf, 1, size, cb->fp );
1338 if (bytes_written > 0) {
1339 cb->raw_position += bytes_written;
1342 #if defined(CHECK_POSITION) && !defined(NDEBUG)
1343 int tmp_offset = ftell(cb->fp) - cb->lib_offset;
1344 SDL_assert(tmp_offset == cb->raw_position);
1347 return bytes_written / elsize;
1351 // cfputc() writes a character to a file
1353 // returns: success ==> returns character written
1356 int cfputc(int c, CFILE *cfile)
1360 SDL_assert(cfile != NULL);
1362 SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1363 cb = &Cfile_block_list[cfile->id];
1365 // cfputc() not supported for memory-mapped files
1366 SDL_assert( !cb->data );
1368 SDL_assert(cb->fp != NULL);
1369 result = fputc(c, cb->fp);
1375 // cfgetc() reads a character from a file
1377 // returns: success ==> returns character read
1380 int cfgetc(CFILE *cfile)
1382 SDL_assert(cfile != NULL);
1386 int result = cfread(&tmp, 1, 1, cfile );
1387 if ( result == 1 ) {
1400 // cfgets() reads a string from a file
1402 // returns: success ==> returns pointer to string
1405 char *cfgets(char *buf, int n, CFILE *cfile)
1407 SDL_assert(cfile != NULL);
1408 SDL_assert(buf != NULL);
1414 for (i=0; i<n-1; i++ ) {
1418 int ret = cfread( &tmp_c, 1, 1, cfile );
1428 } while ( c == 13 );
1430 if ( c=='\n' ) break;
1437 // cfputs() writes a string to a file
1439 // returns: success ==> non-negative value
1442 int cfputs(const char *str, CFILE *cfile)
1444 SDL_assert(cfile != NULL);
1445 SDL_assert(str != NULL);
1448 SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1449 cb = &Cfile_block_list[cfile->id];
1453 // cfputs() not supported for memory-mapped files
1454 SDL_assert( !cb->data );
1455 SDL_assert(cb->fp != NULL);
1456 result = fputs(str, cb->fp);
1462 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1464 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1465 // checksumming code that he wrote a while ago.
1466 #define CRC32_POLYNOMIAL 0xEDB88320L
1467 unsigned long CRCTable[256];
1469 #define CF_CHKSUM_SAMPLE_SIZE 512
1471 // update cur_chksum with the chksum of the new_data of size new_data_size
1472 ushort cf_add_chksum_short(ushort seed, const char *buffer, int size)
1474 const ubyte * ptr = (const ubyte *)buffer;
1475 unsigned int sum1,sum2;
1477 sum1 = sum2 = (int)(seed);
1481 if (sum1 >= 255 ) sum1 -= 255;
1486 return (unsigned short)((sum1<<8)+ sum2);
1489 // update cur_chksum with the chksum of the new_data of size new_data_size
1490 unsigned long cf_add_chksum_long(unsigned long seed, const char *buffer, int size)
1493 unsigned const char *p;
1494 unsigned long temp1;
1495 unsigned long temp2;
1497 p = (unsigned const char*)buffer;
1501 temp1 = (crc>>8)&0x00FFFFFFL;
1502 temp2 = CRCTable[((int)crc^*p++)&0xff];
1509 void cf_chksum_long_init()
1514 for( i=0;i<=255;i++) {
1518 crc=(crc>>1)^CRC32_POLYNOMIAL;
1526 // single function convenient to use for both short and long checksums
1527 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1528 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1530 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1536 // determine whether we're doing a short or long checksum
1539 SDL_assert(!chk_long);
1542 SDL_assert(chk_long);
1547 // if max_size is -1, set it to be the size of the file
1549 cfseek(cfile, 0, SEEK_SET);
1550 max_size = cfilelength(cfile);
1555 // determine how much we want to read
1556 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1557 read_size = CF_CHKSUM_SAMPLE_SIZE;
1559 read_size = max_size - cf_total;
1562 // read in some buffer
1563 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1565 // total we've read so far
1570 // do the proper short or long checksum
1572 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1574 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1577 } while((cf_len > 0) && (cf_total < max_size));
1582 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1583 int cf_chksum_short(const char *filename, ushort *chksum, int max_size, int cf_type)
1586 CFILE *cfile = NULL;
1588 // zero the checksum
1591 // attempt to open the file
1592 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1597 // call the overloaded cf_chksum function()
1598 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1600 // close the file down
1604 // return the result
1608 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1609 // NOTE : preserves current file position
1610 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1615 // Returns current position of file.
1616 start_pos = cftell(file);
1617 if(start_pos == -1){
1621 // move to the beginning of the file
1622 if(cfseek(file, 0, CF_SEEK_SET)){
1625 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1626 // move back to the start position
1627 cfseek(file, start_pos, CF_SEEK_SET);
1632 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1633 int cf_chksum_long(const char *filename, uint *chksum, int max_size, int cf_type)
1636 CFILE *cfile = NULL;
1638 // zero the checksum
1641 // attempt to open the file
1642 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1647 // call the overloaded cf_chksum function()
1648 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1650 // close the file down
1654 // return the result
1658 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1659 // NOTE : preserves current file position
1660 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1665 // Returns current position of file.
1666 start_pos = cftell(file);
1667 if(start_pos == -1){
1671 // move to the beginning of the file
1672 if(cfseek(file, 0, CF_SEEK_SET)){
1675 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1676 // move back to the start position
1677 cfseek(file, start_pos, CF_SEEK_SET);
1683 // Flush the open file buffer
1685 // exit: 0 - success
1687 int cflush(CFILE *cfile)
1689 SDL_assert(cfile != NULL);
1691 SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1692 cb = &Cfile_block_list[cfile->id];
1694 // not supported for memory mapped files
1695 SDL_assert( !cb->data );
1697 SDL_assert(cb->fp != NULL);
1698 return fflush(cb->fp);
1701 // fill in Cfile_root_dir[] and Cfile_user_dir[]
1702 // this can be called at any time, even before cfile_init()
1703 // returns: non-zero on error
1704 int cfile_init_paths()
1706 if ( strlen(Cfile_root_dir) && strlen(Cfile_user_dir) ) {
1710 char *t_path = SDL_GetBasePath();
1712 // make sure we have something
1713 if (t_path == NULL) {
1714 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Error trying to determine executable directory!", NULL);
1719 if ( strlen(t_path) >= CFILE_ROOT_DIRECTORY_LEN ) {
1720 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Executable path is too long!", NULL);
1724 // set root directory
1725 SDL_strlcpy(Cfile_root_dir, t_path, sizeof(Cfile_root_dir));
1730 // are we in a root directory?
1731 if ( cfile_in_root_dir(Cfile_root_dir) ) {
1732 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Freespace2/Fred2 cannot be run from a drive root directory!", NULL);
1736 // now for the user/pref directory, the writable location
1737 char *u_path = SDL_GetPrefPath(Osreg_company_name, Osreg_title);
1739 // make sure we have something
1740 if (u_path == NULL) {
1741 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Error trying to determine preferences directory!", NULL);
1746 if ( strlen(u_path) >= CFILE_ROOT_DIRECTORY_LEN ) {
1747 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Preferences path is too long!", NULL);
1751 // set user/pref directory
1752 SDL_strlcpy(Cfile_user_dir, u_path, sizeof(Cfile_user_dir));