]> icculus.org git repositories - taylor/freespace2.git/blob - src/cfile/cfile.cpp
support persistent file storage for Emscripten
[taylor/freespace2.git] / src / cfile / cfile.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
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
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/CFile/cfile.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Utilities for operating on files
16  *
17  * $Log$
18  * Revision 1.14  2006/04/26 19:36:57  taylor
19  * address an error handling bug in cfwrite()
20  *
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
27  *
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
30  *
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
33  *
34  * Revision 1.10  2004/06/11 00:28:39  tigital
35  * byte-swapping changes for bigendian systems
36  *
37  * Revision 1.9  2003/05/25 02:30:42  taylor
38  * Freespace 1 support
39  *
40  * Revision 1.8  2003/02/20 17:41:07  theoddone33
41  * Userdir patch from Taylor Richards
42  *
43  * Revision 1.7  2002/12/30 03:23:29  relnev
44  * disable root dir check
45  *
46  * Revision 1.6  2002/06/17 06:33:08  relnev
47  * ryan's struct patch for gcc 2.95
48  *
49  * Revision 1.5  2002/06/09 04:41:15  relnev
50  * added copyright header
51  *
52  * Revision 1.4  2002/06/05 08:05:28  relnev
53  * stub/warning removal.
54  *
55  * reworked the sound code.
56  *
57  * Revision 1.3  2002/05/28 08:52:03  relnev
58  * implemented two assembly stubs.
59  *
60  * cleaned up a few warnings.
61  *
62  * added a little demo hackery to make it progress a little farther.
63  *
64  * Revision 1.2  2002/05/28 06:28:20  theoddone33
65  * Filesystem mods, actually reads some data files now
66  *
67  * Revision 1.1.1.1  2002/05/03 03:28:08  root
68  * Initial import.
69  *
70  * 
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.
74  * 
75  * 19    9/08/99 12:03a Dave
76  * Make squad logos render properly in D3D all the time. Added intel anim
77  * directory.
78  * 
79  * 18    9/06/99 2:35p Dave
80  * Rename briefing and debriefing voice direcrory paths properly.
81  * 
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
86  * main hall.
87  * 
88  * 16    8/31/99 9:46a Dave
89  * Support for new cfile cbanims directory.
90  * 
91  * 15    8/06/99 11:20a Johns
92  * Don't call game_cd_changed() in a demo or multiplayer beta build.
93  * 
94  * 14    6/08/99 2:33p Dave
95  * Fixed release build warning. Put in hud config stuff.
96  * 
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.
100  * 
101  * 12    4/30/99 12:18p Dave
102  * Several minor bug fixes.
103  * 
104  * 11    4/07/99 5:54p Dave
105  * Fixes for encryption in updatelauncher.
106  * 
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 :)
110  * 
111  * 9     2/22/99 10:31p Andsager
112  * Get rid of unneeded includes.
113  * 
114  * 8     1/12/99 3:15a Dave
115  * Barracks screen support for selecting squad logos. We need real artwork
116  * :)
117  * 
118  * 7     11/30/98 1:07p Dave
119  * 16 bit conversion, first run.
120  * 
121  * 6     10/29/98 10:41a Dave
122  * Change the way cfile initializes exe directory.
123  * 
124  * 5     10/13/98 9:19a Andsager
125  * Add localization support to cfile.  Optional parameter with cfopen that
126  * looks for localized files.
127  * 
128  * 4     10/12/98 9:54a Dave
129  * Fixed a few file organization things.
130  * 
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
134  * directory.
135  * 
136  * 2     10/07/98 10:52a Dave
137  * Initial checkin.
138  * 
139  * 1     10/07/98 10:48a Dave
140  * 
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
146  * .fsm file).
147  * 
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.
151  * 
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.
155  * 
156  * 107   9/04/98 3:51p Dave
157  * Put in validated mission updating and application during stats
158  * updating.
159  * 
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.
163  * 
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.
167  * 
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.
171  * 
172  * 103   6/17/98 9:30a Allender
173  * fixed red alert replay stats clearing problem
174  * 
175  * 102   6/05/98 9:46a Lawrance
176  * check for CD change on cfopen()
177  * 
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
181  * missions folder)
182  * 
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.
187  * 
188  * 99    5/11/98 10:59a John
189  * Moved the low-level file reading code into cfilearchive.cpp.
190  * 
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
195  * problems.
196  * 
197  * 97    5/03/98 11:53a John
198  * Fixed filename case mangling.
199  * 
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.  
203  * 
204  * 95    5/02/98 11:05p Allender
205  * fix cfilelength for pack files
206  * 
207  *
208  * $NoKeywords: $
209  */
210 #define _CFILE_INTERNAL 
211
212 #include <stdlib.h>
213 #include <string.h>
214 #include <stdio.h>
215 #include <errno.h>
216 #ifndef PLAT_UNIX
217 #include <io.h>
218 #include <direct.h>
219 #else
220 #include <unistd.h>
221 #include <dirent.h>
222 #include <fnmatch.h>
223 #endif
224 #include <sys/stat.h>
225 #include <sys/types.h>
226
227 #ifdef __EMSCRIPTEN__
228 #include <emscripten.h>
229 #endif
230
231 #include "pstypes.h"
232 #include "cfile.h"
233 #include "encrypt.h"
234 //#include "outwnd.h"
235 //#include "vecmat.h"
236 //#include "timer.h"
237 #include "cfilesystem.h"
238 #include "cfilearchive.h"
239 #include "osapi.h"
240 #include "osregistry.h"
241
242 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
243 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
244
245 // During cfile_init, verify that Pathtypes[n].index == n for each item
246 // Each path must have a valid parent that can be tracable all the way back to the root 
247 // so that we can create directories when we need to.
248 //
249 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES]  = {
250         // What type this is          Path                             Extensions              Parent type
251         { CF_TYPE_INVALID,                              NULL,                                                                           NULL,                                                   CF_TYPE_INVALID },
252         // Root must be index 1!!       
253         { CF_TYPE_ROOT,                                 "",                                                                             ".mve",                                                 CF_TYPE_ROOT    },
254         { CF_TYPE_DATA,                                 "Data",                                                                 ".cfg .log .txt",                       CF_TYPE_ROOT    },
255         { CF_TYPE_MAPS,                                 "Data" DIR_SEPARATOR_STR "Maps",                                                        ".pcx .ani .tga",                       CF_TYPE_DATA    },
256         { CF_TYPE_TEXT,                                 "Data" DIR_SEPARATOR_STR "Text",                                                        ".txt .net",                            CF_TYPE_DATA    },
257 #ifdef MAKE_FS1
258         { CF_TYPE_MISSIONS,                             "Data" DIR_SEPARATOR_STR "Missions",                                            ".fsm .fsc .ntl .ssv",  CF_TYPE_DATA    },
259 #else
260         { CF_TYPE_MISSIONS,                             "Data" DIR_SEPARATOR_STR "Missions",                                            ".fs2 .fc2 .ntl .ssv",  CF_TYPE_DATA    },
261 #endif
262         { CF_TYPE_MODELS,                                       "Data" DIR_SEPARATOR_STR "Models",                                              ".pof",                                         CF_TYPE_DATA    },
263         { CF_TYPE_TABLES,                                       "Data" DIR_SEPARATOR_STR "Tables",                                              ".tbl",                                         CF_TYPE_DATA    },
264         { CF_TYPE_SOUNDS,                                       "Data" DIR_SEPARATOR_STR "Sounds",                                              ".wav",                                         CF_TYPE_DATA    },
265         { CF_TYPE_SOUNDS_8B22K,                 "Data" DIR_SEPARATOR_STR "Sounds" DIR_SEPARATOR_STR "8b22k",                            ".wav",                                         CF_TYPE_SOUNDS  },
266         { CF_TYPE_SOUNDS_16B11K,                "Data" DIR_SEPARATOR_STR "Sounds" DIR_SEPARATOR_STR "16b11k",                           ".wav",                                         CF_TYPE_SOUNDS  },
267         { CF_TYPE_VOICE,                                        "Data" DIR_SEPARATOR_STR "Voice",                                                       "",                                                     CF_TYPE_DATA    },
268 #ifdef MAKE_FS1
269         { CF_TYPE_VOICE_BRIEFINGS,              "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Briefings",                 ".wav",                                         CF_TYPE_VOICE   },
270 #else
271         { CF_TYPE_VOICE_BRIEFINGS,              "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Briefing",                  ".wav",                                         CF_TYPE_VOICE   },
272 #endif
273         { CF_TYPE_VOICE_CMD_BRIEF,              "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Command_briefings",".wav",                                          CF_TYPE_VOICE   },
274 #ifdef MAKE_FS1
275         { CF_TYPE_VOICE_DEBRIEFINGS,    "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Debriefings",                       ".wav",                                         CF_TYPE_VOICE   },
276 #else
277         { CF_TYPE_VOICE_DEBRIEFINGS,    "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Debriefing",                        ".wav",                                         CF_TYPE_VOICE   },
278 #endif
279         { CF_TYPE_VOICE_PERSONAS,               "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Personas",                  ".wav",                                         CF_TYPE_VOICE   },
280         { CF_TYPE_VOICE_SPECIAL,                "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Special",                           ".wav",                                         CF_TYPE_VOICE   },
281         { CF_TYPE_VOICE_TRAINING,               "Data" DIR_SEPARATOR_STR "Voice" DIR_SEPARATOR_STR "Training",                  ".wav",                                         CF_TYPE_VOICE   },
282         { CF_TYPE_MUSIC,                                        "Data" DIR_SEPARATOR_STR "Music",                                                       ".wav",                                         CF_TYPE_VOICE   },
283         { CF_TYPE_MOVIES,                                       "Data" DIR_SEPARATOR_STR "Movies",                                              ".mve .msb",                            CF_TYPE_DATA    },
284         { CF_TYPE_INTERFACE,                            "Data" DIR_SEPARATOR_STR "Interface",                                   ".pcx .ani .tga",                       CF_TYPE_DATA    },
285         { CF_TYPE_FONT,                                 "Data" DIR_SEPARATOR_STR "Fonts",                                                       ".vf",                                          CF_TYPE_DATA    },
286         { CF_TYPE_EFFECTS,                              "Data" DIR_SEPARATOR_STR "Effects",                                             ".ani .pcx .neb .tga",  CF_TYPE_DATA    },
287         { CF_TYPE_HUD,                                          "Data" DIR_SEPARATOR_STR "Hud",                                                 ".ani .pcx .tga",                       CF_TYPE_DATA    },
288         { CF_TYPE_PLAYER_MAIN,                  "Data" DIR_SEPARATOR_STR "Players",                                             "",                                                     CF_TYPE_DATA    },
289         { CF_TYPE_PLAYER_IMAGES_MAIN,   "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Images",                  ".pcx",                                         CF_TYPE_PLAYER_MAIN     },
290 #ifdef MAKE_FS1
291         { CF_TYPE_CACHE,                                        "Cache",                                                        ".clr .tmp",                            CF_TYPE_DATA    },      //clr=cached color
292         { CF_TYPE_PLAYERS,                              "Players",                                              ".hcf",                                         CF_TYPE_ROOT    },
293         { CF_TYPE_SINGLE_PLAYERS,               "Players" DIR_SEPARATOR_STR "Single",                   ".plr .csg .css",                       CF_TYPE_PLAYERS },
294         { CF_TYPE_MULTI_PLAYERS,                "Players" DIR_SEPARATOR_STR "Multi",                            ".plr",                                         CF_TYPE_PLAYERS },
295 #else
296         { CF_TYPE_CACHE,                                        "Data" DIR_SEPARATOR_STR "Cache",                                                       ".clr .tmp",                            CF_TYPE_DATA    },      //clr=cached color
297         { CF_TYPE_PLAYERS,                              "Data" DIR_SEPARATOR_STR "Players",                                             ".hcf",                                         CF_TYPE_DATA    },
298         { CF_TYPE_SINGLE_PLAYERS,               "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Single",                  ".plr .csg .css",                       CF_TYPE_PLAYERS },
299         { CF_TYPE_MULTI_PLAYERS,                "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Multi",                           ".plr",                                         CF_TYPE_DATA    },
300 #endif
301         { CF_TYPE_MULTI_CACHE,                  "Data" DIR_SEPARATOR_STR "MultiData",                                   ".pcx .fs2",                            CF_TYPE_DATA    },
302         { CF_TYPE_CONFIG,                                       "Data" DIR_SEPARATOR_STR "Config",                                              ".cfg",                                         CF_TYPE_DATA    },
303         { CF_TYPE_SQUAD_IMAGES_MAIN,    "Data" DIR_SEPARATOR_STR "Players" DIR_SEPARATOR_STR "Squads",                  ".pcx",                                         CF_TYPE_DATA    },
304         { CF_TYPE_DEMOS,                                        "Data" DIR_SEPARATOR_STR "Demos",                                                       ".fsd",                                         CF_TYPE_DATA    },
305         { CF_TYPE_CBANIMS,                              "Data" DIR_SEPARATOR_STR "CBAnims",                                             ".ani",                                         CF_TYPE_DATA    },
306         { CF_TYPE_INTEL_ANIMS,                  "Data" DIR_SEPARATOR_STR "IntelAnims",                                  ".ani",                                         CF_TYPE_DATA    },
307 };
308
309
310 #define CFILE_STACK_MAX 8
311
312 int cfile_inited = 0;
313
314 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
315 CFILE Cfile_list[MAX_CFILE_BLOCKS];
316
317 //
318 // Function prototypes for internally-called functions
319 //
320 int cfget_cfile_block();
321 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
322 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
323 void cf_chksum_long_init();
324
325 void cfile_close()
326 {
327         cf_free_secondary_filelist();
328 }
329
330 // determine if the given path is in a root directory (c:\  or  c:\freespace2.exe  or  c:\fred2.exe   etc)
331 int cfile_in_root_dir(char *exe_path)
332 {
333         int token_count = 0;
334         char path_copy[2048] = "";
335         char *tok;
336
337         // bogus
338         if(exe_path == NULL){
339                 return 1;
340         }
341
342         // copy the path
343         memset(path_copy, 0, 2048);
344         SDL_strlcpy(path_copy, exe_path, SDL_arraysize(path_copy));
345
346         // count how many slashes there are in the path
347         tok = strtok(path_copy, DIR_SEPARATOR_STR);
348         if(tok == NULL){
349                 return 1;
350         }       
351         do {
352                 token_count++;
353                 tok = strtok(NULL, DIR_SEPARATOR_STR);
354         } while(tok != NULL);
355                 
356         // root directory if we have <= 1 slash
357         if(token_count <= 2){
358                 return 1;
359         }
360
361         // not-root directory
362         return 0;
363 }
364
365 // cfile_init() initializes the cfile system.  Called once at application start.
366 //
367 //      returns:  success ==> 0
368 //           error   ==> non-zero
369 //
370 int cfile_init()
371 {
372         int i;
373
374         // initialize encryption
375         encrypt_init(); 
376
377         if ( !cfile_inited ) {
378                 // initialize root and user paths (may have been done already)
379                 if ( cfile_init_paths() ) {
380                         return 1;
381                 }
382
383                 cfile_inited = 1;
384
385                 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
386                         Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
387                 }
388
389                 const char *extras_dir = os_config_read_string(NULL, "ExtrasPath", NULL);
390
391                 if ( extras_dir && (strlen(extras_dir) >= MAX_PATH_LEN) ) {
392                         extras_dir = NULL;
393                 }
394
395                 cf_build_secondary_filelist(extras_dir);
396
397                 // 32 bit CRC table init
398                 cf_chksum_long_init();
399
400
401
402                 atexit( cfile_close );
403         }
404
405         return 0;
406 }
407
408
409 // flush (delete all files in) the passed directory (by type), return the # of files deleted
410 // NOTE : WILL NOT DELETE READ-ONLY FILES
411 int cfile_flush_dir(int dir_type)
412 {
413         char filespec[MAX_PATH_LEN];
414         int del_count;
415
416         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
417
418         cf_create_default_path_string(filespec, dir_type);
419
420         // proceed to delete the files
421         del_count = 0;
422
423 #ifdef PLAT_UNIX
424         DIR *dirp;
425         struct dirent *dir;
426
427         dirp = opendir(filespec);
428         if (dirp) {
429                 while ( (dir = readdir(dirp)) != NULL ) {
430                         if ( !fnmatch("*", dir->d_name, 0) ) {
431                                 char fn[MAX_PATH_LEN];
432                                 SDL_snprintf(fn, MAX_PATH_LEN, "%s/%s", filespec, dir->d_name);
433
434                                 struct stat buf;
435                                 if (stat(fn, &buf) == -1) {
436                                         continue;
437                                 }
438
439                                 if (!S_ISREG(buf.st_mode)) {
440                                         continue;
441                                 }
442
443                                 // delete the file
444                                 cf_delete(dir->d_name, dir_type);
445
446                                 // increment the deleted count
447                                 del_count++;
448                         }
449                 }
450
451                 closedir(dirp);
452         }
453 #else
454         int find_handle;
455         _finddata_t find;
456
457         SDL_strlcat( filespec, "*", SDL_arraysize(filespec) );
458
459         find_handle = _findfirst( filespec, &find );
460
461         if (find_handle != -1) {
462                 do {
463                         if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
464                                 // delete the file
465                                 cf_delete(find.name, dir_type);
466
467                                 // increment the deleted count
468                                 del_count++;
469                         }
470                 } while (!_findnext(find_handle, &find));
471
472                 _findclose( find_handle );
473         }
474 #endif
475
476         // return the # of files deleted
477         return del_count;
478 }
479
480
481 // add the given extention to a filename (or filepath) if it doesn't already have this
482 // extension.
483 //    filename = name of filename or filepath to process
484 //    ext = extension to add.  Must start with the period
485 //    Returns: new filename or filepath with extension.
486 char *cf_add_ext(const char *filename, const char *ext)
487 {
488         int flen, elen;
489         static char path[MAX_PATH_LEN];
490
491         flen = strlen(filename);
492         elen = strlen(ext);
493         SDL_assert(flen < MAX_PATH_LEN);
494         SDL_strlcpy(path, filename, SDL_arraysize(path));
495         if ((flen < 4) || SDL_strcasecmp(path + flen - elen, ext)) {
496                 SDL_assert(flen + elen < MAX_PATH_LEN);
497                 SDL_strlcat(path, ext, SDL_arraysize(path));
498         }
499
500         return path;
501 }
502
503 // Deletes a file.
504 void cf_delete( const char *filename, int dir_type )
505 {
506         char longname[MAX_PATH_LEN];
507
508         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
509
510         cf_create_default_path_string( longname, dir_type, filename );
511
512         FILE *fp = fopen(longname, "rb");
513         if (fp) {
514                 // delete the file
515                 fclose(fp);
516                 unlink(longname);
517         }
518
519 }
520
521
522 // Same as _access function to read a file's access bits
523 int cf_access( const char *filename, int dir_type, int mode )
524 {
525         char longname[MAX_PATH_LEN];
526
527         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
528
529         cf_create_default_path_string( longname, dir_type, filename );
530
531         return access(longname,mode);
532 }
533
534
535 // Returns 1 if file exists, 0 if not.
536 int cf_exist( const char *filename, int dir_type )
537 {
538         char longname[MAX_PATH_LEN];
539
540         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
541
542         cf_create_default_path_string( longname, dir_type, filename );
543
544         FILE *fp = fopen(longname, "rb");
545         if (fp) {
546                 fclose(fp);
547                 return 1;
548         }
549
550         return 0;
551 }
552
553 int cf_rename(const char *old_name, const char *name, int dir_type)
554 {
555         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
556
557         int ret_code;
558         char old_longname[MAX_PATH_LEN];
559         char new_longname[MAX_PATH_LEN];
560         
561         cf_create_default_path_string( old_longname, dir_type, old_name );
562         cf_create_default_path_string( new_longname, dir_type, name );
563
564         ret_code = rename(old_longname, new_longname );         
565         if(ret_code != 0){
566                 switch(errno){
567                 case EACCES :
568                         return CF_RENAME_FAIL_ACCESS;
569                 case ENOENT :
570                 default:
571                         return CF_RENAME_FAIL_EXIST;
572                 }
573         }
574
575         return CF_RENAME_SUCCESS;
576         
577
578 }
579
580 // Creates the directory path if it doesn't exist. Even creates all its
581 // parent paths.
582 void cf_create_directory( int dir_type )
583 {
584         int num_dirs = 0;
585         int dir_tree[CF_MAX_PATH_TYPES];
586         char longname[MAX_PATH_LEN];
587
588         SDL_assert( CF_TYPE_SPECIFIED(dir_type) );
589
590         int current_dir = dir_type;
591
592         do {
593                 SDL_assert( num_dirs < CF_MAX_PATH_TYPES );             // Invalid Pathtypes data?
594
595                 dir_tree[num_dirs++] = current_dir;
596                 current_dir = Pathtypes[current_dir].parent_index;
597
598         } while( current_dir != CF_TYPE_ROOT );
599
600         
601         int i;
602
603         for (i=num_dirs-1; i>=0; i-- )  {
604                 cf_create_default_path_string( longname, dir_tree[i], NULL );
605
606                 if ( mkdir(longname, 0700) == 0 )       {
607                         mprintf(( "CFILE: Created new directory '%s'\n", longname ));
608                 }
609         }
610
611
612 }
613
614
615 // cfopen()
616 //
617 // parameters:  *filepath ==> name of file to open (may be path+name)
618 //              *mode     ==> specifies how file should be opened (eg "rb" for read binary)
619 //                            passing NULL to mode deletes the file if it exists and returns NULL
620 //               type     ==> CFILE_NORMAL
621 //                                        dir_type      =>      override extension check, value is one of CF_TYPE* #defines
622 //
623 //               NOTE: type parameter is an optional parameter.  The default value is CFILE_NORMAL
624 //
625 //
626 // returns:             success ==> address of CFILE structure
627 //                                      error   ==> NULL
628 //
629
630 CFILE *cfopen(const char *file_path, const char *mode, int type, int dir_type, bool localize)
631 {
632         char longname[MAX_PATH_LEN];
633
634 //      nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
635 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
636
637         //================================================
638         // Check that all the parameters make sense
639         SDL_assert(file_path && strlen(file_path));
640         SDL_assert( mode != NULL );
641
642         //===========================================================
643         // If in write mode, just try to open the file straight off
644         // the harddisk.  No fancy packfile stuff here!
645         
646         if ( SDL_strchr(mode,'w') )     {
647 #ifdef PLAT_UNIX
648                 const char *toks = "/";
649 #else
650                 const char *toks = "/\\:";
651 #endif
652
653                 // For write-only files, require a full path or a path type
654                 if ( strpbrk(file_path, toks) ) {
655                         // Full path given?
656                         SDL_strlcpy(longname, file_path, SDL_arraysize(longname));
657                 } else {
658                         // Path type given?
659                         SDL_assert( dir_type != CF_TYPE_ANY );
660
661                         // Create the directory if necessary
662                         cf_create_directory( dir_type );
663
664                         cf_create_default_path_string( longname, dir_type, file_path );
665                 }
666
667                 // JOHN: TODO, you should create the path if it doesn't exist.
668                                 
669                 FILE *fp = fopen(longname, mode);
670                 if (fp) {
671                         return cf_open_fill_cfblock(fp, dir_type);
672                 }
673                 return NULL;
674         } 
675
676
677         //================================================
678         // Search for file on disk, on cdrom, or in a packfile
679
680         int offset, size;
681         char copy_file_path[MAX_PATH_LEN];  // FIX change in memory from cf_find_file_location
682         SDL_strlcpy(copy_file_path, file_path, SDL_arraysize(copy_file_path));
683
684
685         if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) )    {
686                 // Fount it, now create a cfile out of it
687                 FILE *fp = fopen( longname, "rb" );
688
689                 if ( fp )       {
690                         if ( offset )   {
691                                 // Found it in a pack file
692                                 return cf_open_packed_cfblock(fp, dir_type, offset, size );
693                         } else {
694                                 // Found it in a normal file
695                                 return cf_open_fill_cfblock(fp, dir_type);
696                         }
697                 }
698         }
699
700         return NULL;
701 }
702
703
704 // ------------------------------------------------------------------------
705 // ctmpfile() 
706 //
707 // Open up a temporary file.  A unique name is automatically generated.  The
708 // file will be automatically deleted when file is closed.
709 //
710 // return:              NULL                                    =>              tmp file could not be opened
711 //                                      pointer to CFILE        =>              tmp file successfully opened
712 //
713 CFILE *ctmpfile()
714 {
715         FILE    *fp;
716         fp = tmpfile();
717         if ( fp )
718                 return cf_open_fill_cfblock(fp, 0);
719         else
720                 return NULL;
721 }
722
723
724
725 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
726 //      Cfile_block_list[] array and return the index.
727 //
728 // returns:   success ==> index in Cfile_block_list[] array
729 //            failure ==> -1
730 //
731 int cfget_cfile_block()
732 {       
733         int i;
734         Cfile_block *cb;
735
736         for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
737                 cb = &Cfile_block_list[i];
738                 if ( cb->type == CFILE_BLOCK_UNUSED ) {
739                         cb->fp = NULL;
740                         cb->type = CFILE_BLOCK_USED;
741                         return i;
742                 }
743         }
744
745         // If we've reached this point, a free Cfile_block could not be found
746         nprintf(("Warning","A free Cfile_block could not be found.\n"));
747         SDL_assert(0);  // out of free cfile blocks
748         return -1;                      
749 }
750
751
752 // cfclose() closes the file
753 //
754 // returns:   success ==> 0
755 //                                failure ==> EOF
756 //
757 int cfclose( CFILE * cfile )
758 {
759         int result;
760
761         SDL_assert(cfile != NULL);
762         Cfile_block *cb;
763         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
764         cb = &Cfile_block_list[cfile->id];      
765
766         result = 0;
767
768         if (cb->fp != NULL) {
769                 SDL_assert(cb->fp != NULL);
770                 result = fclose(cb->fp);
771         } else {
772                 // VP  do nothing
773         }
774
775         cb->type = CFILE_BLOCK_UNUSED;
776         return result;
777 }
778
779
780
781
782 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
783 // for the case of a file being opened by cf_open();
784 //
785 // returns:   success ==> ptr to CFILE structure.  
786 //            error   ==> NULL
787 //
788 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
789 {
790         int cfile_block_index;
791
792         cfile_block_index = cfget_cfile_block();
793         if ( cfile_block_index == -1 ) {
794                 return NULL;
795         } else {
796                 CFILE *cfp;
797                 Cfile_block *cfbp;
798                 cfbp = &Cfile_block_list[cfile_block_index];
799                 cfp = &Cfile_list[cfile_block_index];;
800                 cfp->id = cfile_block_index;
801                 cfp->version = 0;
802                 cfbp->fp = fp;
803                 cfbp->dir_type = type;
804                 
805                 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
806
807                 return cfp;
808         }
809 }
810
811
812 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
813 // for the case of a file being opened by cf_open();
814 //
815 // returns:   success ==> ptr to CFILE structure.  
816 //            error   ==> NULL
817 //
818 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
819 {
820         // Found it in a pack file
821         int cfile_block_index;
822         
823         cfile_block_index = cfget_cfile_block();
824         if ( cfile_block_index == -1 ) {
825                 return NULL;
826         } else {
827                 CFILE *cfp;
828                 Cfile_block *cfbp;
829                 cfbp = &Cfile_block_list[cfile_block_index];
830         
831                 cfp = &Cfile_list[cfile_block_index];
832                 cfp->id = cfile_block_index;
833                 cfp->version = 0;
834                 cfbp->fp = fp;
835                 cfbp->dir_type = type;
836
837                 cf_init_lowlevel_read_code(cfp,offset, size );
838
839                 return cfp;
840         }
841
842 }
843
844
845 int cf_get_dir_type(CFILE *cfile)
846 {
847         return Cfile_block_list[cfile->id].dir_type;
848 }
849
850
851 // version number of opened file.  Will be 0 unless you put something else here after you
852 // open a file.  Once set, you can use minimum version numbers with the read functions.
853 void cf_set_version( CFILE * cfile, int version )
854 {
855         SDL_assert(cfile != NULL);
856
857         cfile->version = version;
858 }
859
860 // routines to read basic data types from CFILE's.  Put here to
861 // simplify mac/pc reading from cfiles.
862
863 float cfread_float(CFILE *file, int ver, float deflt)
864 {
865         float f;
866
867         if (file->version < ver)
868                 return deflt;
869
870         if (cfread( &f, sizeof(f), 1, file) != 1)
871                 return deflt;
872
873     f = INTEL_FLOAT(f);
874         return f;
875 }
876
877 int cfread_int(CFILE *file, int ver, int deflt)
878 {
879         int i;
880
881         if (file->version < ver)
882                 return deflt;
883
884         if (cfread( &i, sizeof(i), 1, file) != 1)
885                 return deflt;
886
887         i = INTEL_INT(i);
888         return i;
889 }
890
891 uint cfread_uint(CFILE *file, int ver, uint deflt)
892 {
893         uint i;
894
895         if (file->version < ver)
896                 return deflt;
897
898         if (cfread( &i, sizeof(i), 1, file) != 1)
899                 return deflt;
900
901         i = INTEL_INT(i);
902         return i;
903 }
904
905 short cfread_short(CFILE *file, int ver, short deflt)
906 {
907         short s;
908
909         if (file->version < ver)
910                 return deflt;
911
912         if (cfread( &s, sizeof(s), 1, file) != 1)
913                 return deflt;
914
915         s = INTEL_SHORT(s);
916         return s;
917 }
918
919 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
920 {
921         ushort s;
922
923         if (file->version < ver)
924                 return deflt;
925
926         if (cfread( &s, sizeof(s), 1, file) != 1)
927                 return deflt;
928
929         s = INTEL_SHORT(s);
930         return s;
931 }
932
933 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
934 {
935         ubyte b;
936
937         if (file->version < ver)
938                 return deflt;
939
940         if (cfread( &b, sizeof(b), 1, file) != 1)
941                 return deflt;
942
943         return b;
944 }
945
946 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
947 {
948         if (file->version < ver) {
949                 if (deflt)
950                         *vec = *deflt;
951                 else
952                         vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
953
954                 return;
955         }
956
957         vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
958         vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
959         vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
960 }
961         
962 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
963 {
964         if (file->version < ver) {
965                 if (deflt)
966                         *ang = *deflt;
967                 else
968                         ang->p = ang->b = ang->h = 0.0f;
969
970                 return;
971         }
972
973         ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
974         ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
975         ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
976 }
977
978 char cfread_char(CFILE *file, int ver, char deflt)
979 {
980         char b;
981
982         if (file->version < ver)
983                 return deflt;
984
985         if (cfread( &b, sizeof(b), 1, file) != 1)
986                 return deflt;
987
988         return b;
989 }
990
991 void cfread_string(char *buf, int n, CFILE *file)
992 {
993         char c;
994
995         do {
996                 c = cfread_char(file);
997                 if ( n > 0 )    {
998                         *buf++ = c;
999                         n--;
1000                 }
1001         } while (c != 0 );
1002 }
1003
1004 void cfread_string_len(char *buf,int n, CFILE *file)
1005 {
1006         int len;
1007         len = cfread_int(file);
1008         SDL_assert( len < n );
1009         if (len)
1010                 cfread(buf, len, 1, file);
1011
1012         buf[len] = 0;
1013 }
1014
1015 // equivalent write functions of above read functions follow
1016
1017 int cfwrite_float(float f, CFILE *file)
1018 {
1019     f = INTEL_FLOAT(f);
1020         return cfwrite(&f, sizeof(f), 1, file);
1021 }
1022
1023 int cfwrite_int(int i, CFILE *file)
1024 {
1025         i = INTEL_INT(i);
1026         return cfwrite(&i, sizeof(i), 1, file);
1027 }
1028
1029 int cfwrite_uint(uint i, CFILE *file)
1030 {
1031         i = INTEL_INT(i);
1032         return cfwrite(&i, sizeof(i), 1, file);
1033 }
1034
1035 int cfwrite_short(short s, CFILE *file)
1036 {
1037         s = INTEL_SHORT(s);
1038         return cfwrite(&s, sizeof(s), 1, file);
1039 }
1040
1041 int cfwrite_ushort(ushort s, CFILE *file)
1042 {
1043         s = INTEL_SHORT(s);
1044         return cfwrite(&s, sizeof(s), 1, file);
1045 }
1046
1047 int cfwrite_ubyte(ubyte b, CFILE *file)
1048 {
1049         return cfwrite(&b, sizeof(b), 1, file);
1050 }
1051
1052 int cfwrite_vector(vector *vec, CFILE *file)
1053 {
1054         if(!cfwrite_float(vec->xyz.x, file)){
1055                 return 0;
1056         }
1057         if(!cfwrite_float(vec->xyz.y, file)){
1058                 return 0;
1059         }
1060         return cfwrite_float(vec->xyz.z, file);
1061 }
1062
1063 int cfwrite_angles(angles *ang, CFILE *file)
1064 {
1065         if(!cfwrite_float(ang->p, file)){
1066                 return 0;
1067         }
1068         if(!cfwrite_float(ang->b, file)){
1069                 return 0;
1070         }
1071         return cfwrite_float(ang->h, file);
1072 }
1073
1074 int cfwrite_char(char b, CFILE *file)
1075 {
1076         return cfwrite( &b, sizeof(b), 1, file);
1077 }
1078
1079 int cfwrite_string(const char *buf, CFILE *file)
1080 {
1081         if ( (!buf) || (buf && !buf[0]) ) {
1082                 return cfwrite_char(0, file);
1083         } 
1084         int len = strlen(buf);
1085         if(!cfwrite(buf, len, 1, file)){
1086                 return 0;
1087         }
1088         return cfwrite_char(0, file);                   // write out NULL termination                   
1089 }
1090
1091 int cfwrite_string_len(const char *buf, CFILE *file)
1092 {
1093         int len = strlen(buf);
1094
1095         if(!cfwrite_int(len, file)){
1096                 return 0;
1097         }
1098         if (len){
1099                 return cfwrite(buf,len,1,file);
1100         } 
1101
1102         return 1;
1103 }
1104
1105 // Get the filelength
1106 int cfilelength( CFILE * cfile )
1107 {
1108         SDL_assert(cfile != NULL);
1109         Cfile_block *cb;
1110         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1111         cb = &Cfile_block_list[cfile->id];      
1112
1113         SDL_assert(cb->fp != NULL);
1114
1115         // cb->size gets set at cfopen
1116         return cb->size;
1117 }
1118
1119 // cfwrite() writes to the file
1120 //
1121 // returns:   number of full elements actually written
1122 //            
1123 //
1124 int cfwrite(const void *buf, int elsize, int nelem, CFILE *cfile)
1125 {
1126         SDL_assert(cfile != NULL);
1127         SDL_assert(buf != NULL);
1128         SDL_assert(elsize > 0);
1129         SDL_assert(nelem > 0);
1130
1131         Cfile_block *cb;
1132         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1133         cb = &Cfile_block_list[cfile->id];      
1134
1135         int size = elsize * nelem;
1136
1137         SDL_assert(cb->fp != NULL);
1138         SDL_assert(cb->lib_offset == 0 );
1139         int bytes_written = fwrite( buf, 1, size, cb->fp );
1140
1141         if (bytes_written > 0) {
1142                 cb->raw_position += bytes_written;
1143         }
1144
1145         #if defined(CHECK_POSITION) && !defined(NDEBUG)
1146                 int tmp_offset = ftell(cb->fp) - cb->lib_offset;
1147                 SDL_assert(tmp_offset == cb->raw_position);
1148         #endif
1149
1150         return bytes_written / elsize;
1151 }
1152
1153
1154 // cfputc() writes a character to a file
1155 //
1156 // returns:   success ==> returns character written
1157 //                                error   ==> EOF
1158 //
1159 int cfputc(int c, CFILE *cfile)
1160 {
1161         int result = 0;
1162
1163         SDL_assert(cfile != NULL);
1164         Cfile_block *cb;
1165         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1166         cb = &Cfile_block_list[cfile->id];      
1167
1168         SDL_assert(cb->fp != NULL);
1169         result = fputc(c, cb->fp);
1170
1171         return result;  
1172 }
1173
1174
1175 // cfgetc() reads a character from a file
1176 //
1177 // returns:   success ==> returns character read
1178 //                                error   ==> EOF
1179 //
1180 int cfgetc(CFILE *cfile)
1181 {
1182         SDL_assert(cfile != NULL);
1183         
1184         char tmp;
1185
1186         int result = cfread(&tmp, 1, 1, cfile );
1187         if ( result == 1 )      {
1188                 result = char(tmp);
1189         } else {
1190                 result = CF_EOF;
1191         }
1192
1193         return result;  
1194 }
1195
1196
1197
1198
1199
1200 // cfgets() reads a string from a file
1201 //
1202 // returns:   success ==> returns pointer to string
1203 //                                error   ==> NULL
1204 //
1205 char *cfgets(char *buf, int n, CFILE *cfile)
1206 {
1207         SDL_assert(cfile != NULL);
1208         SDL_assert(buf != NULL);
1209         SDL_assert(n > 0 );
1210
1211         char * t = buf;
1212         int i, c;
1213
1214         for (i=0; i<n-1; i++ )  {
1215                 do {
1216                         char tmp_c;
1217
1218                         int ret = cfread( &tmp_c, 1, 1, cfile );
1219                         if ( ret != 1 ) {
1220                                 *buf = 0;
1221                                 if ( buf > t )  {               
1222                                         return t;
1223                                 } else {
1224                                         return NULL;
1225                                 }
1226                         }
1227                         c = int(tmp_c);
1228                 } while ( c == 13 );
1229                 *buf++ = char(c);
1230                 if ( c=='\n' ) break;
1231         }
1232         *buf++ = 0;
1233
1234         return  t;
1235 }
1236
1237 // cfputs() writes a string to a file
1238 //
1239 // returns:   success ==> non-negative value
1240 //                                error   ==> EOF
1241 //
1242 int cfputs(const char *str, CFILE *cfile)
1243 {
1244         SDL_assert(cfile != NULL);
1245         SDL_assert(str != NULL);
1246
1247         Cfile_block *cb;
1248         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1249         cb = &Cfile_block_list[cfile->id];      
1250
1251         int result = 0;
1252
1253         // cfputs() not supported for memory-mapped files
1254         SDL_assert(cb->fp != NULL);
1255         result = fputs(str, cb->fp);
1256
1257         return result;  
1258 }
1259
1260
1261 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1262
1263 // CRC code for mission validation.  given to us by Kevin Bentley on 7/20/98.   Some sort of
1264 // checksumming code that he wrote a while ago.  
1265 #define CRC32_POLYNOMIAL                                        0xEDB88320L
1266 uint CRCTable[256];
1267
1268 #define CF_CHKSUM_SAMPLE_SIZE                           512
1269
1270 // update cur_chksum with the chksum of the new_data of size new_data_size
1271 ushort cf_add_chksum_short(ushort seed, const char *buffer, int size)
1272 {
1273         const ubyte * ptr = (const ubyte *)buffer;
1274         uint sum1,sum2;
1275
1276         sum1 = sum2 = (uint)(seed);
1277
1278         while(size--)   {
1279                 sum1 += *ptr++;
1280                 if (sum1 >= 255 ) sum1 -= 255;
1281                 sum2 += sum1;
1282         }
1283         sum2 %= 255;
1284         
1285         return (ushort)((sum1<<8)+ sum2);
1286 }
1287
1288 // update cur_chksum with the chksum of the new_data of size new_data_size
1289 uint cf_add_chksum_long(uint seed, const char *buffer, int size)
1290 {
1291         uint crc;
1292         unsigned const char *p;
1293         uint temp1;
1294         uint temp2;
1295
1296         p = (unsigned const char*)buffer;
1297         crc = seed;     
1298
1299         while (size--!=0){
1300           temp1 = (crc>>8)&0x00FFFFFFL;
1301           temp2 = CRCTable[((int)crc^*p++)&0xff];
1302           crc = temp1^temp2;
1303         }       
1304         
1305         return crc;
1306 }
1307
1308 void cf_chksum_long_init()
1309 {
1310         int i,j;
1311         uint crc;
1312
1313         for( i=0;i<=255;i++) {
1314                 crc=i;
1315                 for(j=8;j>0;j--) {
1316                         if(crc&1)
1317                                  crc=(crc>>1)^CRC32_POLYNOMIAL;
1318                         else
1319                                  crc>>=1;
1320                 }
1321                 CRCTable[i]=crc;
1322         }       
1323 }
1324
1325 // single function convenient to use for both short and long checksums
1326 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1327 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1328 {
1329         char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1330         int is_long;
1331         int cf_len = 0;
1332         int cf_total;
1333         int read_size;
1334
1335         // determine whether we're doing a short or long checksum
1336         is_long = 0;
1337         if(chk_short){
1338                 SDL_assert(!chk_long);          
1339                 *chk_short = 0;
1340         } else {
1341                 SDL_assert(chk_long);
1342                 is_long = 1;
1343                 *chk_long = 0;
1344         }
1345
1346         // if max_size is -1, set it to be the size of the file
1347         if(max_size < 0){
1348                 cfseek(cfile, 0, SEEK_SET);
1349                 max_size = cfilelength(cfile);
1350         }
1351         
1352         cf_total = 0;
1353         do {
1354                 // determine how much we want to read
1355                 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1356                         read_size = CF_CHKSUM_SAMPLE_SIZE;
1357                 } else {
1358                         read_size = max_size - cf_total;
1359                 }
1360
1361                 // read in some buffer
1362                 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1363
1364                 // total we've read so far
1365                 cf_total += cf_len;
1366
1367                 // add the checksum
1368                 if(cf_len > 0){
1369                         // do the proper short or long checksum
1370                         if(is_long){
1371                                 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1372                         } else {
1373                                 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1374                         }
1375                 }
1376         } while((cf_len > 0) && (cf_total < max_size));
1377
1378         return 1;
1379 }
1380
1381 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1382 int cf_chksum_short(const char *filename, ushort *chksum, int max_size, int cf_type)
1383 {
1384         int ret_val;
1385         CFILE *cfile = NULL;            
1386         
1387         // zero the checksum
1388         *chksum = 0;
1389
1390         // attempt to open the file
1391         cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1392         if(cfile == NULL){              
1393                 return 0;
1394         }
1395         
1396         // call the overloaded cf_chksum function()
1397         ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1398
1399         // close the file down
1400         cfclose(cfile);
1401         cfile = NULL;
1402
1403         // return the result
1404         return ret_val;
1405 }
1406
1407 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1408 // NOTE : preserves current file position
1409 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1410 {
1411         int ret_code;
1412         int start_pos;
1413         
1414         // Returns current position of file.
1415         start_pos = cftell(file);
1416         if(start_pos == -1){
1417                 return 0;
1418         }
1419         
1420         // move to the beginning of the file
1421         if(cfseek(file, 0, CF_SEEK_SET)){
1422                 return 0;
1423         }
1424         ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1425         // move back to the start position
1426         cfseek(file, start_pos, CF_SEEK_SET);
1427
1428         return ret_code;
1429 }
1430
1431 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1432 int cf_chksum_long(const char *filename, uint *chksum, int max_size, int cf_type)
1433 {
1434         int ret_val;
1435         CFILE *cfile = NULL;            
1436         
1437         // zero the checksum
1438         *chksum = 0;
1439
1440         // attempt to open the file
1441         cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1442         if(cfile == NULL){              
1443                 return 0;
1444         }
1445         
1446         // call the overloaded cf_chksum function()
1447         ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1448
1449         // close the file down
1450         cfclose(cfile);
1451         cfile = NULL;
1452
1453         // return the result
1454         return ret_val; 
1455 }
1456
1457 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1458 // NOTE : preserves current file position
1459 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1460 {
1461         int ret_code;
1462         int start_pos;
1463         
1464         // Returns current position of file.
1465         start_pos = cftell(file);
1466         if(start_pos == -1){
1467                 return 0;
1468         }
1469         
1470         // move to the beginning of the file
1471         if(cfseek(file, 0, CF_SEEK_SET)){
1472                 return 0;
1473         }
1474         ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1475         // move back to the start position
1476         cfseek(file, start_pos, CF_SEEK_SET);
1477
1478         return ret_code;
1479 }
1480
1481
1482 // Flush the open file buffer
1483 //
1484 // exit: 0 - success
1485 //                      1 - failure
1486 int cflush(CFILE *cfile)
1487 {
1488         SDL_assert(cfile != NULL);
1489         Cfile_block *cb;
1490         SDL_assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1491         cb = &Cfile_block_list[cfile->id];      
1492
1493         SDL_assert(cb->fp != NULL);
1494         return fflush(cb->fp);
1495 }
1496
1497 // fill in Cfile_root_dir[] and Cfile_user_dir[]
1498 // this can be called at any time, even before cfile_init()
1499 //  returns: non-zero on error
1500 int cfile_init_paths()
1501 {
1502         if ( strlen(Cfile_root_dir) && strlen(Cfile_user_dir) ) {
1503                 return 0;
1504         }
1505
1506         char *t_path = SDL_GetBasePath();
1507
1508         // make sure we have something
1509         if (t_path == NULL) {
1510                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Error trying to determine executable directory!", NULL);
1511                 return 1;
1512         }
1513
1514         // size check
1515         if ( strlen(t_path) >= CFILE_ROOT_DIRECTORY_LEN ) {
1516                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Executable path is too long!", NULL);
1517                 return 1;
1518         }
1519
1520         // set root directory
1521         SDL_strlcpy(Cfile_root_dir, t_path, SDL_arraysize(Cfile_root_dir));
1522         // free SDL copy
1523         SDL_free(t_path);
1524         t_path = NULL;
1525
1526 #ifndef __EMSCRIPTEN__
1527         // are we in a root directory?
1528         if ( cfile_in_root_dir(Cfile_root_dir) ) {
1529                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Freespace2/Fred2 cannot be run from a drive root directory!", NULL);
1530                 return 1;
1531         }
1532
1533         // now for the user/pref directory, the writable location
1534         char *u_path = SDL_GetPrefPath(Osreg_company_name, Osreg_app_name);
1535
1536         // make sure we have something
1537         if (u_path == NULL) {
1538                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Error trying to determine preferences directory!", NULL);
1539                 return 1;
1540         }
1541
1542         // size check
1543         if ( strlen(u_path) >= CFILE_ROOT_DIRECTORY_LEN ) {
1544                 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", "Preferences path is too long!", NULL);
1545                 return 1;
1546         }
1547
1548         // set user/pref directory
1549         SDL_strlcpy(Cfile_user_dir, u_path, SDL_arraysize(Cfile_user_dir));
1550         // free SDL copy
1551         SDL_free(u_path);
1552         u_path = NULL;
1553 #else
1554         SDL_snprintf(Cfile_user_dir, SDL_arraysize(Cfile_user_dir), "/%s/%s/", Osreg_company_name, Osreg_app_name);
1555
1556         EM_ASM({
1557                 const base_path = UTF8ToString($0);
1558                 FS.mkdir(base_path);
1559                 FS.mount(IDBFS, {}, base_path);
1560
1561                 Module.syncdone = 0;
1562
1563                 FS.syncfs(true, function(err) {
1564                         if (err && err.code !== 'EEXIST') {
1565                                 console.log('FS.syncfs() load error: ' + err);
1566                                 assert(err);
1567                         }
1568
1569                         Module.syncdone = 1;
1570                 });
1571         }, Osreg_company_name);
1572 #endif
1573
1574         // see if CF_TYPE_DATA exists for user and if not populate user path
1575         // with full directory tree
1576         char pathname[MAX_PATH_LEN];
1577         struct stat info;
1578
1579         SDL_strlcpy(pathname, Cfile_user_dir, MAX_PATH_LEN);
1580         SDL_strlcat(pathname, Pathtypes[CF_TYPE_DATA].path, MAX_PATH_LEN);
1581
1582         if ( stat(pathname, &info) != 0 ) {
1583                 cf_create_directory(CF_TYPE_MAPS);
1584                 cf_create_directory(CF_TYPE_TEXT);
1585                 cf_create_directory(CF_TYPE_MISSIONS);
1586                 cf_create_directory(CF_TYPE_MODELS);
1587                 cf_create_directory(CF_TYPE_TABLES);
1588                 cf_create_directory(CF_TYPE_SOUNDS_8B22K);
1589                 cf_create_directory(CF_TYPE_SOUNDS_16B11K);
1590                 cf_create_directory(CF_TYPE_VOICE_BRIEFINGS);
1591                 cf_create_directory(CF_TYPE_VOICE_CMD_BRIEF);
1592                 cf_create_directory(CF_TYPE_VOICE_DEBRIEFINGS);
1593                 cf_create_directory(CF_TYPE_VOICE_PERSONAS);
1594                 cf_create_directory(CF_TYPE_VOICE_SPECIAL);
1595                 cf_create_directory(CF_TYPE_VOICE_TRAINING);
1596                 cf_create_directory(CF_TYPE_MUSIC);
1597                 cf_create_directory(CF_TYPE_MOVIES);
1598                 cf_create_directory(CF_TYPE_INTERFACE);
1599                 cf_create_directory(CF_TYPE_FONT);
1600                 cf_create_directory(CF_TYPE_EFFECTS);
1601                 cf_create_directory(CF_TYPE_HUD);
1602                 cf_create_directory(CF_TYPE_PLAYER_IMAGES_MAIN);
1603                 cf_create_directory(CF_TYPE_CACHE);
1604                 cf_create_directory(CF_TYPE_SINGLE_PLAYERS);
1605                 cf_create_directory(CF_TYPE_MULTI_PLAYERS);
1606                 cf_create_directory(CF_TYPE_MULTI_CACHE);
1607                 cf_create_directory(CF_TYPE_CONFIG);
1608                 cf_create_directory(CF_TYPE_SQUAD_IMAGES_MAIN);
1609                 cf_create_directory(CF_TYPE_DEMOS);
1610                 cf_create_directory(CF_TYPE_CBANIMS);
1611                 cf_create_directory(CF_TYPE_INTEL_ANIMS);
1612         }
1613
1614         return 0;
1615 }