PageRenderTime 84ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/neo/framework/FileSystem.cpp

https://bitbucket.org/thayamizu/doom-3
C++ | 4217 lines | 3104 code | 354 blank | 759 comment | 661 complexity | 88d6c3609e62929b425374411469ad52 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, Unlicense, CC0-1.0, GPL-2.0
  1. /*
  2. ===========================================================================
  3. Doom 3 GPL Source Code
  4. Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
  5. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
  6. Doom 3 Source Code is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. Doom 3 Source Code is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
  16. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
  17. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
  18. ===========================================================================
  19. */
  20. #include "../idlib/precompiled.h"
  21. #pragma hdrstop
  22. #include "Unzip.h"
  23. #ifdef WIN32
  24. #include <io.h> // for _read
  25. #else
  26. #if !__MACH__ && __MWERKS__
  27. #include <types.h>
  28. #include <stat.h>
  29. #else
  30. #include <sys/types.h>
  31. #include <sys/stat.h>
  32. #endif
  33. #include <unistd.h>
  34. #endif
  35. #if ID_ENABLE_CURL
  36. #include "../curl/include/curl/curl.h"
  37. #endif
  38. /*
  39. =============================================================================
  40. DOOM FILESYSTEM
  41. All of Doom's data access is through a hierarchical file system, but the contents of
  42. the file system can be transparently merged from several sources.
  43. A "relativePath" is a reference to game file data, which must include a terminating zero.
  44. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any references
  45. outside the Doom directory system.
  46. The "base path" is the path to the directory holding all the game directories and
  47. usually the executable. It defaults to the current directory, but can be overridden
  48. with "+set fs_basepath c:\doom" on the command line. The base path cannot be modified
  49. at all after startup.
  50. The "save path" is the path to the directory where game files will be saved. It defaults
  51. to the base path, but can be overridden with a "+set fs_savepath c:\doom" on the
  52. command line. Any files that are created during the game (demos, screenshots, etc.) will
  53. be created reletive to the save path.
  54. The "cd path" is the path to an alternate hierarchy that will be searched if a file
  55. is not located in the base path. A user can do a partial install that copies some
  56. data to a base path created on their hard drive and leave the rest on the cd. It defaults
  57. to the current directory, but it can be overridden with "+set fs_cdpath g:\doom" on the
  58. command line.
  59. The "dev path" is the path to an alternate hierarchy where the editors and tools used
  60. during development (Radiant, AF editor, dmap, runAAS) will write files to. It defaults to
  61. the cd path, but can be overridden with a "+set fs_devpath c:\doom" on the command line.
  62. If a user runs the game directly from a CD, the base path would be on the CD. This
  63. should still function correctly, but all file writes will fail (harmlessly).
  64. The "base game" is the directory under the paths where data comes from by default, and
  65. can be either "base" or "demo".
  66. The "current game" may be the same as the base game, or it may be the name of another
  67. directory under the paths that should be searched for files before looking in the base
  68. game. The game directory is set with "+set fs_game myaddon" on the command line. This is
  69. the basis for addons.
  70. No other directories outside of the base game and current game will ever be referenced by
  71. filesystem functions.
  72. To save disk space and speed up file loading, directory trees can be collapsed into zip
  73. files. The files use a ".pk4" extension to prevent users from unzipping them accidentally,
  74. but otherwise they are simply normal zip files. A game directory can have multiple zip
  75. files of the form "pak0.pk4", "pak1.pk4", etc. Zip files are searched in decending order
  76. from the highest number to the lowest, and will always take precedence over the filesystem.
  77. This allows a pk4 distributed as a patch to override all existing data.
  78. Because we will have updated executables freely available online, there is no point to
  79. trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
  80. should be exactly the same executables as release versions, but with different data that
  81. automatically restricts where game media can come from to prevent add-ons from working.
  82. After the paths are initialized, Doom will look for the product.txt file. If not found
  83. and verified, the game will run in restricted mode. In restricted mode, only files
  84. contained in demo/pak0.pk4 will be available for loading, and only if the zip header is
  85. verified to not have been modified. A single exception is made for DoomConfig.cfg. Files
  86. can still be written out in restricted mode, so screenshots and demos are allowed.
  87. Restricted mode can be tested by setting "+set fs_restrict 1" on the command line, even
  88. if there is a valid product.txt under the basepath or cdpath.
  89. If the "fs_copyfiles" cvar is set to 1, then every time a file is sourced from the cd
  90. path, it will be copied over to the save path. This is a development aid to help build
  91. test releases and to copy working sets of files.
  92. If the "fs_copyfiles" cvar is set to 2, any file found in fs_cdpath that is newer than
  93. it's fs_savepath version will be copied to fs_savepath (in addition to the fs_copyfiles 1
  94. behaviour).
  95. If the "fs_copyfiles" cvar is set to 3, files from both basepath and cdpath will be copied
  96. over to the save path. This is useful when copying working sets of files mainly from base
  97. path with an additional cd path (which can be a slower network drive for instance).
  98. If the "fs_copyfiles" cvar is set to 4, files that exist in the cd path but NOT the base path
  99. will be copied to the save path
  100. NOTE: fs_copyfiles and case sensitivity. On fs_caseSensitiveOS 0 filesystems ( win32 ), the
  101. copied files may change casing when copied over.
  102. The relative path "sound/newstuff/test.wav" would be searched for in the following places:
  103. for save path, dev path, base path, cd path:
  104. for current game, base game:
  105. search directory
  106. search zip files
  107. downloaded files, to be written to save path + current game's directory
  108. The filesystem can be safely shutdown and reinitialized with different
  109. basedir / cddir / game combinations, but all other subsystems that rely on it
  110. (sound, video) must also be forced to restart.
  111. "fs_caseSensitiveOS":
  112. This cvar is set on operating systems that use case sensitive filesystems (Linux and OSX)
  113. It is a common situation to have the media reference filenames, whereas the file on disc
  114. only matches in a case-insensitive way. When "fs_caseSensitiveOS" is set, the filesystem
  115. will always do a case insensitive search.
  116. IMPORTANT: This only applies to files, and not to directories. There is no case-insensitive
  117. matching of directories. All directory names should be lowercase, when "com_developer" is 1,
  118. the filesystem will warn when it catches bad directory situations (regardless of the
  119. "fs_caseSensitiveOS" setting)
  120. When bad casing in directories happen and "fs_caseSensitiveOS" is set, BuildOSPath will
  121. attempt to correct the situation by forcing the path to lowercase. This assumes the media
  122. is stored all lowercase.
  123. "additional mod path search":
  124. fs_game_base can be used to set an additional search path
  125. in search order, fs_game, fs_game_base, BASEGAME
  126. for instance to base a mod of D3 + D3XP assets, fs_game mymod, fs_game_base d3xp
  127. =============================================================================
  128. */
  129. // define to fix special-cases for GetPackStatus so that files that shipped in
  130. // the wrong place for Doom 3 don't break pure servers.
  131. #define DOOM3_PURE_SPECIAL_CASES
  132. typedef bool (*pureExclusionFunc_t)( const struct pureExclusion_s &excl, int l, const idStr &name );
  133. typedef struct pureExclusion_s {
  134. int nameLen;
  135. int extLen;
  136. const char * name;
  137. const char * ext;
  138. pureExclusionFunc_t func;
  139. } pureExclusion_t;
  140. bool excludeExtension( const pureExclusion_t &excl, int l, const idStr &name ) {
  141. if ( l > excl.extLen && !idStr::Icmp( name.c_str() + l - excl.extLen, excl.ext ) ) {
  142. return true;
  143. }
  144. return false;
  145. }
  146. bool excludePathPrefixAndExtension( const pureExclusion_t &excl, int l, const idStr &name ) {
  147. if ( l > excl.nameLen && !idStr::Icmp( name.c_str() + l - excl.extLen, excl.ext ) && !name.IcmpPrefixPath( excl.name ) ) {
  148. return true;
  149. }
  150. return false;
  151. }
  152. bool excludeFullName( const pureExclusion_t &excl, int l, const idStr &name ) {
  153. if ( l == excl.nameLen && !name.Icmp( excl.name ) ) {
  154. return true;
  155. }
  156. return false;
  157. }
  158. static pureExclusion_t pureExclusions[] = {
  159. { 0, 0, NULL, "/", excludeExtension },
  160. { 0, 0, NULL, "\\", excludeExtension },
  161. { 0, 0, NULL, ".pda", excludeExtension },
  162. { 0, 0, NULL, ".gui", excludeExtension },
  163. { 0, 0, NULL, ".pd", excludeExtension },
  164. { 0, 0, NULL, ".lang", excludeExtension },
  165. { 0, 0, "sound/VO", ".ogg", excludePathPrefixAndExtension },
  166. { 0, 0, "sound/VO", ".wav", excludePathPrefixAndExtension },
  167. #if defined DOOM3_PURE_SPECIAL_CASES
  168. // add any special-case files or paths for pure servers here
  169. { 0, 0, "sound/ed/marscity/vo_intro_cutscene.ogg", NULL, excludeFullName },
  170. { 0, 0, "sound/weapons/soulcube/energize_01.ogg", NULL, excludeFullName },
  171. { 0, 0, "sound/xian/creepy/vocal_fx", ".ogg", excludePathPrefixAndExtension },
  172. { 0, 0, "sound/xian/creepy/vocal_fx", ".wav", excludePathPrefixAndExtension },
  173. { 0, 0, "sound/feedback", ".ogg", excludePathPrefixAndExtension },
  174. { 0, 0, "sound/feedback", ".wav", excludePathPrefixAndExtension },
  175. { 0, 0, "guis/assets/mainmenu/chnote.tga", NULL, excludeFullName },
  176. { 0, 0, "sound/levels/alphalabs2/uac_better_place.ogg", NULL, excludeFullName },
  177. { 0, 0, "textures/bigchars.tga", NULL, excludeFullName },
  178. { 0, 0, "dds/textures/bigchars.dds", NULL, excludeFullName },
  179. { 0, 0, "fonts", ".tga", excludePathPrefixAndExtension },
  180. { 0, 0, "dds/fonts", ".dds", excludePathPrefixAndExtension },
  181. { 0, 0, "default.cfg", NULL, excludeFullName },
  182. // russian zpak001.pk4
  183. { 0, 0, "fonts", ".dat", excludePathPrefixAndExtension },
  184. { 0, 0, "guis/temp.guied", NULL, excludeFullName },
  185. #endif
  186. { 0, 0, NULL, NULL, NULL }
  187. };
  188. // ensures that lengths for pure exclusions are correct
  189. class idInitExclusions {
  190. public:
  191. idInitExclusions() {
  192. for ( int i = 0; pureExclusions[i].func != NULL; i++ ) {
  193. if ( pureExclusions[i].name ) {
  194. pureExclusions[i].nameLen = idStr::Length( pureExclusions[i].name );
  195. }
  196. if ( pureExclusions[i].ext ) {
  197. pureExclusions[i].extLen = idStr::Length( pureExclusions[i].ext );
  198. }
  199. }
  200. }
  201. };
  202. static idInitExclusions initExclusions;
  203. #define MAX_ZIPPED_FILE_NAME 2048
  204. #define FILE_HASH_SIZE 1024
  205. typedef struct fileInPack_s {
  206. idStr name; // name of the file
  207. unsigned long pos; // file info position in zip
  208. struct fileInPack_s * next; // next file in the hash
  209. } fileInPack_t;
  210. typedef enum {
  211. BINARY_UNKNOWN = 0,
  212. BINARY_YES,
  213. BINARY_NO
  214. } binaryStatus_t;
  215. typedef enum {
  216. PURE_UNKNOWN = 0, // need to run the pak through GetPackStatus
  217. PURE_NEUTRAL, // neutral regarding pureness. gets in the pure list if referenced
  218. PURE_ALWAYS, // always referenced - for pak* named files, unless NEVER
  219. PURE_NEVER // VO paks. may be referenced, won't be in the pure lists
  220. } pureStatus_t;
  221. typedef struct {
  222. idList<int> depends;
  223. idList<idDict *> mapDecls;
  224. } addonInfo_t;
  225. typedef struct {
  226. idStr pakFilename; // c:\doom\base\pak0.pk4
  227. unzFile handle;
  228. int checksum;
  229. int numfiles;
  230. int length;
  231. bool referenced;
  232. binaryStatus_t binary;
  233. bool addon; // this is an addon pack - addon_search tells if it's 'active'
  234. bool addon_search; // is in the search list
  235. addonInfo_t *addon_info;
  236. pureStatus_t pureStatus;
  237. bool isNew; // for downloaded paks
  238. fileInPack_t *hashTable[FILE_HASH_SIZE];
  239. fileInPack_t *buildBuffer;
  240. } pack_t;
  241. typedef struct {
  242. idStr path; // c:\doom
  243. idStr gamedir; // base
  244. } directory_t;
  245. typedef struct searchpath_s {
  246. pack_t * pack; // only one of pack / dir will be non NULL
  247. directory_t * dir;
  248. struct searchpath_s *next;
  249. } searchpath_t;
  250. // search flags when opening a file
  251. #define FSFLAG_SEARCH_DIRS ( 1 << 0 )
  252. #define FSFLAG_SEARCH_PAKS ( 1 << 1 )
  253. #define FSFLAG_PURE_NOREF ( 1 << 2 )
  254. #define FSFLAG_BINARY_ONLY ( 1 << 3 )
  255. #define FSFLAG_SEARCH_ADDONS ( 1 << 4 )
  256. // 3 search path (fs_savepath fs_basepath fs_cdpath)
  257. // + .jpg and .tga
  258. #define MAX_CACHED_DIRS 6
  259. // how many OSes to handle game paks for ( we don't have to know them precisely )
  260. #define MAX_GAME_OS 6
  261. #define BINARY_CONFIG "binary.conf"
  262. #define ADDON_CONFIG "addon.conf"
  263. class idDEntry : public idStrList {
  264. public:
  265. idDEntry() {}
  266. virtual ~idDEntry() {}
  267. bool Matches( const char *directory, const char *extension ) const;
  268. void Init( const char *directory, const char *extension, const idStrList &list );
  269. void Clear( void );
  270. private:
  271. idStr directory;
  272. idStr extension;
  273. };
  274. class idFileSystemLocal : public idFileSystem {
  275. public:
  276. idFileSystemLocal( void );
  277. virtual void Init( void );
  278. virtual void StartBackgroundDownloadThread( void );
  279. virtual void Restart( void );
  280. virtual void Shutdown( bool reloading );
  281. virtual bool IsInitialized( void ) const;
  282. virtual bool PerformingCopyFiles( void ) const;
  283. virtual idModList * ListMods( void );
  284. virtual void FreeModList( idModList *modList );
  285. virtual idFileList * ListFiles( const char *relativePath, const char *extension, bool sort = false, bool fullRelativePath = false, const char* gamedir = NULL );
  286. virtual idFileList * ListFilesTree( const char *relativePath, const char *extension, bool sort = false, const char* gamedir = NULL );
  287. virtual void FreeFileList( idFileList *fileList );
  288. virtual const char * OSPathToRelativePath( const char *OSPath );
  289. virtual const char * RelativePathToOSPath( const char *relativePath, const char *basePath );
  290. virtual const char * BuildOSPath( const char *base, const char *game, const char *relativePath );
  291. virtual void CreateOSPath( const char *OSPath );
  292. virtual bool FileIsInPAK( const char *relativePath );
  293. virtual void UpdatePureServerChecksums( void );
  294. virtual bool UpdateGamePakChecksums( void );
  295. virtual fsPureReply_t SetPureServerChecksums( const int pureChecksums[ MAX_PURE_PAKS ], int gamePakChecksum, int missingChecksums[ MAX_PURE_PAKS ], int *missingGamePakChecksum );
  296. virtual void GetPureServerChecksums( int checksums[ MAX_PURE_PAKS ], int OS, int *gamePakChecksum );
  297. virtual void SetRestartChecksums( const int pureChecksums[ MAX_PURE_PAKS ], int gamePakChecksum );
  298. virtual void ClearPureChecksums( void );
  299. virtual int GetOSMask( void );
  300. virtual int ReadFile( const char *relativePath, void **buffer, ID_TIME_T *timestamp );
  301. virtual void FreeFile( void *buffer );
  302. virtual int WriteFile( const char *relativePath, const void *buffer, int size, const char *basePath = "fs_savepath" );
  303. virtual void RemoveFile( const char *relativePath );
  304. virtual idFile * OpenFileReadFlags( const char *relativePath, int searchFlags, pack_t **foundInPak = NULL, bool allowCopyFiles = true, const char* gamedir = NULL );
  305. virtual idFile * OpenFileRead( const char *relativePath, bool allowCopyFiles = true, const char* gamedir = NULL );
  306. virtual idFile * OpenFileWrite( const char *relativePath, const char *basePath = "fs_savepath" );
  307. virtual idFile * OpenFileAppend( const char *relativePath, bool sync = false, const char *basePath = "fs_basepath" );
  308. virtual idFile * OpenFileByMode( const char *relativePath, fsMode_t mode );
  309. virtual idFile * OpenExplicitFileRead( const char *OSPath );
  310. virtual idFile * OpenExplicitFileWrite( const char *OSPath );
  311. virtual void CloseFile( idFile *f );
  312. virtual void BackgroundDownload( backgroundDownload_t *bgl );
  313. virtual void ResetReadCount( void ) { readCount = 0; }
  314. virtual void AddToReadCount( int c ) { readCount += c; }
  315. virtual int GetReadCount( void ) { return readCount; }
  316. virtual void FindDLL( const char *basename, char dllPath[ MAX_OSPATH ], bool updateChecksum );
  317. virtual void ClearDirCache( void );
  318. virtual bool HasD3XP( void );
  319. virtual bool RunningD3XP( void );
  320. virtual void CopyFile( const char *fromOSPath, const char *toOSPath );
  321. virtual int ValidateDownloadPakForChecksum( int checksum, char path[ MAX_STRING_CHARS ], bool isBinary );
  322. virtual idFile * MakeTemporaryFile( void );
  323. virtual int AddZipFile( const char *path );
  324. virtual findFile_t FindFile( const char *path, bool scheduleAddons );
  325. virtual int GetNumMaps();
  326. virtual const idDict * GetMapDecl( int i );
  327. virtual void FindMapScreenshot( const char *path, char *buf, int len );
  328. virtual bool FilenameCompare( const char *s1, const char *s2 ) const;
  329. static void Dir_f( const idCmdArgs &args );
  330. static void DirTree_f( const idCmdArgs &args );
  331. static void Path_f( const idCmdArgs &args );
  332. static void TouchFile_f( const idCmdArgs &args );
  333. static void TouchFileList_f( const idCmdArgs &args );
  334. private:
  335. friend dword BackgroundDownloadThread( void *parms );
  336. searchpath_t * searchPaths;
  337. int readCount; // total bytes read
  338. int loadCount; // total files read
  339. int loadStack; // total files in memory
  340. idStr gameFolder; // this will be a single name without separators
  341. searchpath_t *addonPaks; // not loaded up, but we saw them
  342. idDict mapDict; // for GetMapDecl
  343. static idCVar fs_debug;
  344. static idCVar fs_restrict;
  345. static idCVar fs_copyfiles;
  346. static idCVar fs_basepath;
  347. static idCVar fs_savepath;
  348. static idCVar fs_cdpath;
  349. static idCVar fs_devpath;
  350. static idCVar fs_game;
  351. static idCVar fs_game_base;
  352. static idCVar fs_caseSensitiveOS;
  353. static idCVar fs_searchAddons;
  354. backgroundDownload_t * backgroundDownloads;
  355. backgroundDownload_t defaultBackgroundDownload;
  356. xthreadInfo backgroundThread;
  357. idList<pack_t *> serverPaks;
  358. bool loadedFileFromDir; // set to true once a file was loaded from a directory - can't switch to pure anymore
  359. idList<int> restartChecksums; // used during a restart to set things in right order
  360. idList<int> addonChecksums; // list of checksums that should go to the search list directly ( for restarts )
  361. int restartGamePakChecksum;
  362. int gameDLLChecksum; // the checksum of the last loaded game DLL
  363. int gamePakChecksum; // the checksum of the pak holding the loaded game DLL
  364. int gamePakForOS[ MAX_GAME_OS ];
  365. idDEntry dir_cache[ MAX_CACHED_DIRS ]; // fifo
  366. int dir_cache_index;
  367. int dir_cache_count;
  368. int d3xp; // 0: didn't check, -1: not installed, 1: installed
  369. private:
  370. void ReplaceSeparators( idStr &path, char sep = PATHSEPERATOR_CHAR );
  371. long HashFileName( const char *fname ) const;
  372. int ListOSFiles( const char *directory, const char *extension, idStrList &list );
  373. FILE * OpenOSFile( const char *name, const char *mode, idStr *caseSensitiveName = NULL );
  374. FILE * OpenOSFileCorrectName( idStr &path, const char *mode );
  375. int DirectFileLength( FILE *o );
  376. void CopyFile( idFile *src, const char *toOSPath );
  377. int AddUnique( const char *name, idStrList &list, idHashIndex &hashIndex ) const;
  378. void GetExtensionList( const char *extension, idStrList &extensionList ) const;
  379. int GetFileList( const char *relativePath, const idStrList &extensions, idStrList &list, idHashIndex &hashIndex, bool fullRelativePath, const char* gamedir = NULL );
  380. int GetFileListTree( const char *relativePath, const idStrList &extensions, idStrList &list, idHashIndex &hashIndex, const char* gamedir = NULL );
  381. pack_t * LoadZipFile( const char *zipfile );
  382. void AddGameDirectory( const char *path, const char *dir );
  383. void SetupGameDirectories( const char *gameName );
  384. void Startup( void );
  385. void SetRestrictions( void );
  386. // some files can be obtained from directories without compromising si_pure
  387. bool FileAllowedFromDir( const char *path );
  388. // searches all the paks, no pure check
  389. pack_t * GetPackForChecksum( int checksum, bool searchAddons = false );
  390. // searches all the paks, no pure check
  391. pack_t * FindPakForFileChecksum( const char *relativePath, int fileChecksum, bool bReference );
  392. idFile_InZip * ReadFileFromZip( pack_t *pak, fileInPack_t *pakFile, const char *relativePath );
  393. int GetFileChecksum( idFile *file );
  394. pureStatus_t GetPackStatus( pack_t *pak );
  395. addonInfo_t * ParseAddonDef( const char *buf, const int len );
  396. void FollowAddonDependencies( pack_t *pak );
  397. static size_t CurlWriteFunction( void *ptr, size_t size, size_t nmemb, void *stream );
  398. // curl_progress_callback in curl.h
  399. static int CurlProgressFunction( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow );
  400. };
  401. idCVar idFileSystemLocal::fs_restrict( "fs_restrict", "", CVAR_SYSTEM | CVAR_INIT | CVAR_BOOL, "" );
  402. idCVar idFileSystemLocal::fs_debug( "fs_debug", "0", CVAR_SYSTEM | CVAR_INTEGER, "", 0, 2, idCmdSystem::ArgCompletion_Integer<0,2> );
  403. idCVar idFileSystemLocal::fs_copyfiles( "fs_copyfiles", "0", CVAR_SYSTEM | CVAR_INIT | CVAR_INTEGER, "", 0, 4, idCmdSystem::ArgCompletion_Integer<0,3> );
  404. idCVar idFileSystemLocal::fs_basepath( "fs_basepath", "", CVAR_SYSTEM | CVAR_INIT, "" );
  405. idCVar idFileSystemLocal::fs_savepath( "fs_savepath", "", CVAR_SYSTEM | CVAR_INIT, "" );
  406. idCVar idFileSystemLocal::fs_cdpath( "fs_cdpath", "", CVAR_SYSTEM | CVAR_INIT, "" );
  407. idCVar idFileSystemLocal::fs_devpath( "fs_devpath", "", CVAR_SYSTEM | CVAR_INIT, "" );
  408. idCVar idFileSystemLocal::fs_game( "fs_game", "", CVAR_SYSTEM | CVAR_INIT | CVAR_SERVERINFO, "mod path" );
  409. idCVar idFileSystemLocal::fs_game_base( "fs_game_base", "", CVAR_SYSTEM | CVAR_INIT | CVAR_SERVERINFO, "alternate mod path, searched after the main fs_game path, before the basedir" );
  410. #ifdef WIN32
  411. idCVar idFileSystemLocal::fs_caseSensitiveOS( "fs_caseSensitiveOS", "0", CVAR_SYSTEM | CVAR_BOOL, "" );
  412. #else
  413. idCVar idFileSystemLocal::fs_caseSensitiveOS( "fs_caseSensitiveOS", "1", CVAR_SYSTEM | CVAR_BOOL, "" );
  414. #endif
  415. idCVar idFileSystemLocal::fs_searchAddons( "fs_searchAddons", "0", CVAR_SYSTEM | CVAR_BOOL, "search all addon pk4s ( disables addon functionality )" );
  416. idFileSystemLocal fileSystemLocal;
  417. idFileSystem * fileSystem = &fileSystemLocal;
  418. /*
  419. ================
  420. idFileSystemLocal::idFileSystemLocal
  421. ================
  422. */
  423. idFileSystemLocal::idFileSystemLocal( void ) {
  424. searchPaths = NULL;
  425. readCount = 0;
  426. loadCount = 0;
  427. loadStack = 0;
  428. dir_cache_index = 0;
  429. dir_cache_count = 0;
  430. d3xp = 0;
  431. loadedFileFromDir = false;
  432. restartGamePakChecksum = 0;
  433. memset( &backgroundThread, 0, sizeof( backgroundThread ) );
  434. addonPaks = NULL;
  435. }
  436. /*
  437. ================
  438. idFileSystemLocal::HashFileName
  439. return a hash value for the filename
  440. ================
  441. */
  442. long idFileSystemLocal::HashFileName( const char *fname ) const {
  443. int i;
  444. long hash;
  445. char letter;
  446. hash = 0;
  447. i = 0;
  448. while( fname[i] != '\0' ) {
  449. letter = idStr::ToLower( fname[i] );
  450. if ( letter == '.' ) {
  451. break; // don't include extension
  452. }
  453. if ( letter == '\\' ) {
  454. letter = '/'; // damn path names
  455. }
  456. hash += (long)(letter) * (i+119);
  457. i++;
  458. }
  459. hash &= (FILE_HASH_SIZE-1);
  460. return hash;
  461. }
  462. /*
  463. ===========
  464. idFileSystemLocal::FilenameCompare
  465. Ignore case and separator char distinctions
  466. ===========
  467. */
  468. bool idFileSystemLocal::FilenameCompare( const char *s1, const char *s2 ) const {
  469. int c1, c2;
  470. do {
  471. c1 = *s1++;
  472. c2 = *s2++;
  473. if ( c1 >= 'a' && c1 <= 'z' ) {
  474. c1 -= ('a' - 'A');
  475. }
  476. if ( c2 >= 'a' && c2 <= 'z' ) {
  477. c2 -= ('a' - 'A');
  478. }
  479. if ( c1 == '\\' || c1 == ':' ) {
  480. c1 = '/';
  481. }
  482. if ( c2 == '\\' || c2 == ':' ) {
  483. c2 = '/';
  484. }
  485. if ( c1 != c2 ) {
  486. return true; // strings not equal
  487. }
  488. } while( c1 );
  489. return false; // strings are equal
  490. }
  491. /*
  492. ================
  493. idFileSystemLocal::OpenOSFile
  494. optional caseSensitiveName is set to case sensitive file name as found on disc (fs_caseSensitiveOS only)
  495. ================
  496. */
  497. FILE *idFileSystemLocal::OpenOSFile( const char *fileName, const char *mode, idStr *caseSensitiveName ) {
  498. int i;
  499. FILE *fp;
  500. idStr fpath, entry;
  501. idStrList list;
  502. #ifndef __MWERKS__
  503. #ifndef WIN32
  504. // some systems will let you fopen a directory
  505. struct stat buf;
  506. if ( stat( fileName, &buf ) != -1 && !S_ISREG(buf.st_mode) ) {
  507. return NULL;
  508. }
  509. #endif
  510. #endif
  511. fp = fopen( fileName, mode );
  512. if ( !fp && fs_caseSensitiveOS.GetBool() ) {
  513. fpath = fileName;
  514. fpath.StripFilename();
  515. fpath.StripTrailing( PATHSEPERATOR_CHAR );
  516. if ( ListOSFiles( fpath, NULL, list ) == -1 ) {
  517. return NULL;
  518. }
  519. for ( i = 0; i < list.Num(); i++ ) {
  520. entry = fpath + PATHSEPERATOR_CHAR + list[i];
  521. if ( !entry.Icmp( fileName ) ) {
  522. fp = fopen( entry, mode );
  523. if ( fp ) {
  524. if ( caseSensitiveName ) {
  525. *caseSensitiveName = entry;
  526. caseSensitiveName->StripPath();
  527. }
  528. if ( fs_debug.GetInteger() ) {
  529. common->Printf( "idFileSystemLocal::OpenFileRead: changed %s to %s\n", fileName, entry.c_str() );
  530. }
  531. break;
  532. } else {
  533. // not supposed to happen if ListOSFiles is doing it's job correctly
  534. common->Warning( "idFileSystemLocal::OpenFileRead: fs_caseSensitiveOS 1 could not open %s", entry.c_str() );
  535. }
  536. }
  537. }
  538. } else if ( caseSensitiveName ) {
  539. *caseSensitiveName = fileName;
  540. caseSensitiveName->StripPath();
  541. }
  542. return fp;
  543. }
  544. /*
  545. ================
  546. idFileSystemLocal::OpenOSFileCorrectName
  547. ================
  548. */
  549. FILE *idFileSystemLocal::OpenOSFileCorrectName( idStr &path, const char *mode ) {
  550. idStr caseName;
  551. FILE *f = OpenOSFile( path.c_str(), mode, &caseName );
  552. if ( f ) {
  553. path.StripFilename();
  554. path += PATHSEPERATOR_STR;
  555. path += caseName;
  556. }
  557. return f;
  558. }
  559. /*
  560. ================
  561. idFileSystemLocal::DirectFileLength
  562. ================
  563. */
  564. int idFileSystemLocal::DirectFileLength( FILE *o ) {
  565. int pos;
  566. int end;
  567. pos = ftell( o );
  568. fseek( o, 0, SEEK_END );
  569. end = ftell( o );
  570. fseek( o, pos, SEEK_SET );
  571. return end;
  572. }
  573. /*
  574. ============
  575. idFileSystemLocal::CreateOSPath
  576. Creates any directories needed to store the given filename
  577. ============
  578. */
  579. void idFileSystemLocal::CreateOSPath( const char *OSPath ) {
  580. char *ofs;
  581. // make absolutely sure that it can't back up the path
  582. // FIXME: what about c: ?
  583. if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
  584. #ifdef _DEBUG
  585. common->DPrintf( "refusing to create relative path \"%s\"\n", OSPath );
  586. #endif
  587. return;
  588. }
  589. idStr path( OSPath );
  590. for( ofs = &path[ 1 ]; *ofs ; ofs++ ) {
  591. if ( *ofs == PATHSEPERATOR_CHAR ) {
  592. // create the directory
  593. *ofs = 0;
  594. Sys_Mkdir( path );
  595. *ofs = PATHSEPERATOR_CHAR;
  596. }
  597. }
  598. }
  599. /*
  600. =================
  601. idFileSystemLocal::CopyFile
  602. Copy a fully specified file from one place to another
  603. =================
  604. */
  605. void idFileSystemLocal::CopyFile( const char *fromOSPath, const char *toOSPath ) {
  606. FILE *f;
  607. int len;
  608. byte *buf;
  609. common->Printf( "copy %s to %s\n", fromOSPath, toOSPath );
  610. f = OpenOSFile( fromOSPath, "rb" );
  611. if ( !f ) {
  612. return;
  613. }
  614. fseek( f, 0, SEEK_END );
  615. len = ftell( f );
  616. fseek( f, 0, SEEK_SET );
  617. buf = (byte *)Mem_Alloc( len );
  618. if ( fread( buf, 1, len, f ) != (unsigned int)len ) {
  619. common->FatalError( "short read in idFileSystemLocal::CopyFile()\n" );
  620. }
  621. fclose( f );
  622. CreateOSPath( toOSPath );
  623. f = OpenOSFile( toOSPath, "wb" );
  624. if ( !f ) {
  625. common->Printf( "could not create destination file\n" );
  626. Mem_Free( buf );
  627. return;
  628. }
  629. if ( fwrite( buf, 1, len, f ) != (unsigned int)len ) {
  630. common->FatalError( "short write in idFileSystemLocal::CopyFile()\n" );
  631. }
  632. fclose( f );
  633. Mem_Free( buf );
  634. }
  635. /*
  636. =================
  637. idFileSystemLocal::CopyFile
  638. =================
  639. */
  640. void idFileSystemLocal::CopyFile( idFile *src, const char *toOSPath ) {
  641. FILE *f;
  642. int len;
  643. byte *buf;
  644. common->Printf( "copy %s to %s\n", src->GetName(), toOSPath );
  645. src->Seek( 0, FS_SEEK_END );
  646. len = src->Tell();
  647. src->Seek( 0, FS_SEEK_SET );
  648. buf = (byte *)Mem_Alloc( len );
  649. if ( src->Read( buf, len ) != len ) {
  650. common->FatalError( "Short read in idFileSystemLocal::CopyFile()\n" );
  651. }
  652. CreateOSPath( toOSPath );
  653. f = OpenOSFile( toOSPath, "wb" );
  654. if ( !f ) {
  655. common->Printf( "could not create destination file\n" );
  656. Mem_Free( buf );
  657. return;
  658. }
  659. if ( fwrite( buf, 1, len, f ) != (unsigned int)len ) {
  660. common->FatalError( "Short write in idFileSystemLocal::CopyFile()\n" );
  661. }
  662. fclose( f );
  663. Mem_Free( buf );
  664. }
  665. /*
  666. ====================
  667. idFileSystemLocal::ReplaceSeparators
  668. Fix things up differently for win/unix/mac
  669. ====================
  670. */
  671. void idFileSystemLocal::ReplaceSeparators( idStr &path, char sep ) {
  672. char *s;
  673. for( s = &path[ 0 ]; *s ; s++ ) {
  674. if ( *s == '/' || *s == '\\' ) {
  675. *s = sep;
  676. }
  677. }
  678. }
  679. /*
  680. ===================
  681. idFileSystemLocal::BuildOSPath
  682. ===================
  683. */
  684. const char *idFileSystemLocal::BuildOSPath( const char *base, const char *game, const char *relativePath ) {
  685. static char OSPath[MAX_STRING_CHARS];
  686. idStr newPath;
  687. if ( fs_caseSensitiveOS.GetBool() || com_developer.GetBool() ) {
  688. // extract the path, make sure it's all lowercase
  689. idStr testPath, fileName;
  690. sprintf( testPath, "%s/%s", game , relativePath );
  691. testPath.StripFilename();
  692. if ( testPath.HasUpper() ) {
  693. common->Warning( "Non-portable: path contains uppercase characters: %s", testPath.c_str() );
  694. // attempt a fixup on the fly
  695. if ( fs_caseSensitiveOS.GetBool() ) {
  696. testPath.ToLower();
  697. fileName = relativePath;
  698. fileName.StripPath();
  699. sprintf( newPath, "%s/%s/%s", base, testPath.c_str(), fileName.c_str() );
  700. ReplaceSeparators( newPath );
  701. common->DPrintf( "Fixed up to %s\n", newPath.c_str() );
  702. idStr::Copynz( OSPath, newPath, sizeof( OSPath ) );
  703. return OSPath;
  704. }
  705. }
  706. }
  707. idStr strBase = base;
  708. strBase.StripTrailing( '/' );
  709. strBase.StripTrailing( '\\' );
  710. sprintf( newPath, "%s/%s/%s", strBase.c_str(), game, relativePath );
  711. ReplaceSeparators( newPath );
  712. idStr::Copynz( OSPath, newPath, sizeof( OSPath ) );
  713. return OSPath;
  714. }
  715. /*
  716. ================
  717. idFileSystemLocal::OSPathToRelativePath
  718. takes a full OS path, as might be found in data from a media creation
  719. program, and converts it to a relativePath by stripping off directories
  720. Returns false if the osPath tree doesn't match any of the existing
  721. search paths.
  722. ================
  723. */
  724. const char *idFileSystemLocal::OSPathToRelativePath( const char *OSPath ) {
  725. static char relativePath[MAX_STRING_CHARS];
  726. char *s, *base;
  727. // skip a drive letter?
  728. // search for anything with "base" in it
  729. // Ase files from max may have the form of:
  730. // "//Purgatory/purgatory/doom/base/models/mapobjects/bitch/hologirl.tga"
  731. // which won't match any of our drive letter based search paths
  732. bool ignoreWarning = false;
  733. #ifdef ID_DEMO_BUILD
  734. base = strstr( OSPath, BASE_GAMEDIR );
  735. idStr tempStr = OSPath;
  736. tempStr.ToLower();
  737. if ( ( strstr( tempStr, "//" ) || strstr( tempStr, "w:" ) ) && strstr( tempStr, "/doom/base/") ) {
  738. // will cause a warning but will load the file. ase models have
  739. // hard coded doom/base/ in the material names
  740. base = strstr( OSPath, "base" );
  741. ignoreWarning = true;
  742. }
  743. #else
  744. // look for the first complete directory name
  745. base = (char *)strstr( OSPath, BASE_GAMEDIR );
  746. while ( base ) {
  747. char c1 = '\0', c2;
  748. if ( base > OSPath ) {
  749. c1 = *(base - 1);
  750. }
  751. c2 = *( base + strlen( BASE_GAMEDIR ) );
  752. if ( ( c1 == '/' || c1 == '\\' ) && ( c2 == '/' || c2 == '\\' ) ) {
  753. break;
  754. }
  755. base = strstr( base + 1, BASE_GAMEDIR );
  756. }
  757. #endif
  758. // fs_game and fs_game_base support - look for first complete name with a mod path
  759. // ( fs_game searched before fs_game_base )
  760. const char *fsgame = NULL;
  761. int igame = 0;
  762. for ( igame = 0; igame < 2; igame++ ) {
  763. if ( igame == 0 ) {
  764. fsgame = fs_game.GetString();
  765. } else if ( igame == 1 ) {
  766. fsgame = fs_game_base.GetString();
  767. }
  768. if ( base == NULL && fsgame && strlen( fsgame ) ) {
  769. base = (char *)strstr( OSPath, fsgame );
  770. while ( base ) {
  771. char c1 = '\0', c2;
  772. if ( base > OSPath ) {
  773. c1 = *(base - 1);
  774. }
  775. c2 = *( base + strlen( fsgame ) );
  776. if ( ( c1 == '/' || c1 == '\\' ) && ( c2 == '/' || c2 == '\\' ) ) {
  777. break;
  778. }
  779. base = strstr( base + 1, fsgame );
  780. }
  781. }
  782. }
  783. if ( base ) {
  784. s = strstr( base, "/" );
  785. if ( !s ) {
  786. s = strstr( base, "\\" );
  787. }
  788. if ( s ) {
  789. strcpy( relativePath, s + 1 );
  790. if ( fs_debug.GetInteger() > 1 ) {
  791. common->Printf( "idFileSystem::OSPathToRelativePath: %s becomes %s\n", OSPath, relativePath );
  792. }
  793. return relativePath;
  794. }
  795. }
  796. if ( !ignoreWarning ) {
  797. common->Warning( "idFileSystem::OSPathToRelativePath failed on %s", OSPath );
  798. }
  799. strcpy( relativePath, "" );
  800. return relativePath;
  801. }
  802. /*
  803. =====================
  804. idFileSystemLocal::RelativePathToOSPath
  805. Returns a fully qualified path that can be used with stdio libraries
  806. =====================
  807. */
  808. const char *idFileSystemLocal::RelativePathToOSPath( const char *relativePath, const char *basePath ) {
  809. const char *path = cvarSystem->GetCVarString( basePath );
  810. if ( !path[0] ) {
  811. path = fs_savepath.GetString();
  812. }
  813. return BuildOSPath( path, gameFolder, relativePath );
  814. }
  815. /*
  816. =================
  817. idFileSystemLocal::RemoveFile
  818. =================
  819. */
  820. void idFileSystemLocal::RemoveFile( const char *relativePath ) {
  821. idStr OSPath;
  822. if ( fs_devpath.GetString()[0] ) {
  823. OSPath = BuildOSPath( fs_devpath.GetString(), gameFolder, relativePath );
  824. remove( OSPath );
  825. }
  826. OSPath = BuildOSPath( fs_savepath.GetString(), gameFolder, relativePath );
  827. remove( OSPath );
  828. ClearDirCache();
  829. }
  830. /*
  831. ================
  832. idFileSystemLocal::FileIsInPAK
  833. ================
  834. */
  835. bool idFileSystemLocal::FileIsInPAK( const char *relativePath ) {
  836. searchpath_t *search;
  837. pack_t *pak;
  838. fileInPack_t *pakFile;
  839. long hash;
  840. if ( !searchPaths ) {
  841. common->FatalError( "Filesystem call made without initialization\n" );
  842. }
  843. if ( !relativePath ) {
  844. common->FatalError( "idFileSystemLocal::FileIsInPAK: NULL 'relativePath' parameter passed\n" );
  845. }
  846. // qpaths are not supposed to have a leading slash
  847. if ( relativePath[0] == '/' || relativePath[0] == '\\' ) {
  848. relativePath++;
  849. }
  850. // make absolutely sure that it can't back up the path.
  851. // The searchpaths do guarantee that something will always
  852. // be prepended, so we don't need to worry about "c:" or "//limbo"
  853. if ( strstr( relativePath, ".." ) || strstr( relativePath, "::" ) ) {
  854. return false;
  855. }
  856. //
  857. // search through the path, one element at a time
  858. //
  859. hash = HashFileName( relativePath );
  860. for ( search = searchPaths; search; search = search->next ) {
  861. // is the element a pak file?
  862. if ( search->pack && search->pack->hashTable[hash] ) {
  863. // disregard if it doesn't match one of the allowed pure pak files - or is a localization file
  864. if ( serverPaks.Num() ) {
  865. GetPackStatus( search->pack );
  866. if ( search->pack->pureStatus != PURE_NEVER && !serverPaks.Find( search->pack ) ) {
  867. continue; // not on the pure server pak list
  868. }
  869. }
  870. // look through all the pak file elements
  871. pak = search->pack;
  872. pakFile = pak->hashTable[hash];
  873. do {
  874. // case and separator insensitive comparisons
  875. if ( !FilenameCompare( pakFile->name, relativePath ) ) {
  876. return true;
  877. }
  878. pakFile = pakFile->next;
  879. } while( pakFile != NULL );
  880. }
  881. }
  882. return false;
  883. }
  884. /*
  885. ============
  886. idFileSystemLocal::ReadFile
  887. Filename are relative to the search path
  888. a null buffer will just return the file length and time without loading
  889. timestamp can be NULL if not required
  890. ============
  891. */
  892. int idFileSystemLocal::ReadFile( const char *relativePath, void **buffer, ID_TIME_T *timestamp ) {
  893. idFile * f;
  894. byte * buf;
  895. int len;
  896. bool isConfig;
  897. if ( !searchPaths ) {
  898. common->FatalError( "Filesystem call made without initialization\n" );
  899. }
  900. if ( !relativePath || !relativePath[0] ) {
  901. common->FatalError( "idFileSystemLocal::ReadFile with empty name\n" );
  902. }
  903. if ( timestamp ) {
  904. *timestamp = FILE_NOT_FOUND_TIMESTAMP;
  905. }
  906. if ( buffer ) {
  907. *buffer = NULL;
  908. }
  909. buf = NULL; // quiet compiler warning
  910. // if this is a .cfg file and we are playing back a journal, read
  911. // it from the journal file
  912. if ( strstr( relativePath, ".cfg" ) == relativePath + strlen( relativePath ) - 4 ) {
  913. isConfig = true;
  914. if ( eventLoop && eventLoop->JournalLevel() == 2 ) {
  915. int r;
  916. loadCount++;
  917. loadStack++;
  918. common->DPrintf( "Loading %s from journal file.\n", relativePath );
  919. len = 0;
  920. r = eventLoop->com_journalDataFile->Read( &len, sizeof( len ) );
  921. if ( r != sizeof( len ) ) {
  922. *buffer = NULL;
  923. return -1;
  924. }
  925. buf = (byte *)Mem_ClearedAlloc(len+1);
  926. *buffer = buf;
  927. r = eventLoop->com_journalDataFile->Read( buf, len );
  928. if ( r != len ) {
  929. common->FatalError( "Read from journalDataFile failed" );
  930. }
  931. // guarantee that it will have a trailing 0 for string operations
  932. buf[len] = 0;
  933. return len;
  934. }
  935. } else {
  936. isConfig = false;
  937. }
  938. // look for it in the filesystem or pack files
  939. f = OpenFileRead( relativePath, ( buffer != NULL ) );
  940. if ( f == NULL ) {
  941. if ( buffer ) {
  942. *buffer = NULL;
  943. }
  944. return -1;
  945. }
  946. len = f->Length();
  947. if ( timestamp ) {
  948. *timestamp = f->Timestamp();
  949. }
  950. if ( !buffer ) {
  951. CloseFile( f );
  952. return len;
  953. }
  954. loadCount++;
  955. loadStack++;
  956. buf = (byte *)Mem_ClearedAlloc(len+1);
  957. *buffer = buf;
  958. f->Read( buf, len );
  959. // guarantee that it will have a trailing 0 for string operations
  960. buf[len] = 0;
  961. CloseFile( f );
  962. // if we are journalling and it is a config file, write it to the journal file
  963. if ( isConfig && eventLoop && eventLoop->JournalLevel() == 1 ) {
  964. common->DPrintf( "Writing %s to journal file.\n", relativePath );
  965. eventLoop->com_journalDataFile->Write( &len, sizeof( len ) );
  966. eventLoop->com_journalDataFile->Write( buf, len );
  967. eventLoop->com_journalDataFile->Flush();
  968. }
  969. return len;
  970. }
  971. /*
  972. =============
  973. idFileSystemLocal::FreeFile
  974. =============
  975. */
  976. void idFileSystemLocal::FreeFile( void *buffer ) {
  977. if ( !searchPaths ) {
  978. common->FatalError( "Filesystem call made without initialization\n" );
  979. }
  980. if ( !buffer ) {
  981. common->FatalError( "idFileSystemLocal::FreeFile( NULL )" );
  982. }
  983. loadStack--;
  984. Mem_Free( buffer );
  985. }
  986. /*
  987. ============
  988. idFileSystemLocal::WriteFile
  989. Filenames are relative to the search path
  990. ============
  991. */
  992. int idFileSystemLocal::WriteFile( const char *relativePath, const void *buffer, int size, const char *basePath ) {
  993. idFile *f;
  994. if ( !searchPaths ) {
  995. common->FatalError( "Filesystem call made without initialization\n" );
  996. }
  997. if ( !relativePath || !buffer ) {
  998. common->FatalError( "idFileSystemLocal::WriteFile: NULL parameter" );
  999. }
  1000. f = idFileSystemLocal::OpenFileWrite( relativePath, basePath );
  1001. if ( !f ) {
  1002. common->Printf( "Failed to open %s\n", relativePath );
  1003. return -1;
  1004. }
  1005. size = f->Write( buffer, size );
  1006. CloseFile( f );
  1007. return size;
  1008. }
  1009. /*
  1010. =================
  1011. idFileSystemLocal::ParseAddonDef
  1012. =================
  1013. */
  1014. addonInfo_t *idFileSystemLocal::ParseAddonDef( const char *buf, const int len ) {
  1015. idLexer src;
  1016. idToken token, token2;
  1017. addonInfo_t *info;
  1018. src.LoadMemory( buf, len, "<addon.conf>" );
  1019. src.SetFlags( DECL_LEXER_FLAGS );
  1020. if ( !src.SkipUntilString( "addonDef" ) ) {
  1021. src.Warning( "ParseAddonDef: no addonDef" );
  1022. return NULL;
  1023. }
  1024. if ( !src.ReadToken( &token ) ) {
  1025. src.Warning( "Expected {" );
  1026. return NULL;
  1027. }
  1028. info = new addonInfo_t;
  1029. // read addonDef
  1030. while ( 1 ) {
  1031. if ( !src.ReadToken( &token ) ) {
  1032. delete info;
  1033. return NULL;
  1034. }
  1035. if ( !token.Icmp( "}" ) ) {
  1036. break;
  1037. }
  1038. if ( token.type != TT_STRING ) {
  1039. src.Warning( "Expected quoted string, but found '%s'", token.c_str() );
  1040. delete info;
  1041. return NULL;
  1042. }
  1043. int checksum;
  1044. if ( sscanf( token.c_str(), "0x%x", &checksum ) != 1 && sscanf( token.c_str(), "%x", &checksum ) != 1 ) {
  1045. src.Warning( "Could not parse checksum '%s'", token.c_str() );
  1046. delete info;
  1047. return NULL;
  1048. }
  1049. info->depends.Append( checksum );
  1050. }
  1051. // read any number of mapDef entries
  1052. while ( 1 ) {
  1053. if ( !src.SkipUntilString( "mapDef" ) ) {
  1054. return info;
  1055. }
  1056. if ( !src.ReadToken( &token ) ) {
  1057. src.Warning( "Expected map path" );
  1058. info->mapDecls.DeleteContents( true );
  1059. delete info;
  1060. return NULL;
  1061. }
  1062. idDict *dict = new idDict;
  1063. dict->Set( "path", token.c_str() );
  1064. if ( !src.ReadToken( &token ) ) {
  1065. src.Warning( "Expected {" );
  1066. info->mapDecls.DeleteContents( true );
  1067. delete dict;
  1068. delete info;
  1069. return NULL;
  1070. }
  1071. while ( 1 ) {
  1072. if ( !src.ReadToken( &token ) ) {
  1073. break;
  1074. }
  1075. if ( !token.Icmp( "}" ) ) {
  1076. break;
  1077. }
  1078. if ( token.type != TT_STRING ) {
  1079. src.Warning( "Expected quoted string, but found '%s'", token.c_str() );
  1080. info->mapDecls.DeleteContents( true );
  1081. delete dict;
  1082. delete info;
  1083. return NULL;
  1084. }
  1085. if ( !src.ReadToken( &token2 ) ) {
  1086. src.Warning( "Unexpected end of file" );
  1087. info->mapDecls.DeleteContents( true );
  1088. delete dict;
  1089. delete info;
  1090. return NULL;
  1091. }
  1092. if ( dict->FindKey( token ) ) {
  1093. src.Warning( "'%s' already defined", token.c_str() );
  1094. }
  1095. dict->Set( token, token2 );
  1096. }
  1097. info->mapDecls.Append( dict );
  1098. }
  1099. assert( false );
  1100. return NULL;
  1101. }
  1102. /*
  1103. =================
  1104. idFileSystemLocal::LoadZipFile
  1105. =================
  1106. */
  1107. pack_t *idFileSystemLocal::LoadZipFile( const char *zipfile ) {
  1108. fileInPack_t * buildBuffer;
  1109. pack_t * pack;
  1110. unzFile uf;
  1111. int err;
  1112. unz_global_info gi;
  1113. char filename_inzip[MAX_ZIPPED_FILE_NAME];
  1114. unz_file_info file_info;
  1115. int i;
  1116. long hash;
  1117. int fs_numHeaderLongs;
  1118. int * fs_headerLongs;
  1119. FILE *f;
  1120. int len;
  1121. int confHash;
  1122. fileInPack_t *pakFile;
  1123. f = OpenOSFile( zipfile, "rb" );
  1124. if ( !f ) {
  1125. return NULL;
  1126. }
  1127. fseek( f, 0, SEEK_END );
  1128. len = ftell( f );
  1129. fclose( f );
  1130. fs_numHeaderLongs = 0;
  1131. uf = unzOpen( zipfile );
  1132. err = unzGetGlobalInfo( uf, &gi );
  1133. if ( err != UNZ_OK ) {
  1134. return NULL;
  1135. }
  1136. buildBuffer = new fileInPack_t[gi.number_entry];
  1137. pack = new pack_t;
  1138. for( i = 0; i < FILE_HASH_SIZE; i++ ) {
  1139. pack->hashTable[i] = NULL;
  1140. }
  1141. pack->pakFilename = zipfile;
  1142. pack->handle = uf;
  1143. pack->numfiles = gi.number_entry;
  1144. pack->buildBuffer = buildBuffer;
  1145. pack->referenced = false;
  1146. pack->binary = BINARY_UNKNOWN;
  1147. pack->addon = false;
  1148. pack->addon_search = false;
  1149. pack->addon_info = NULL;
  1150. pack->pureStatus = PURE_UNKNOWN;
  1151. pack->isNew = false;
  1152. pack->length = len;
  1153. unzGoToFirstFile(uf);
  1154. fs_headerLongs = (int *)Mem_ClearedAlloc( gi.number_entry * sizeof(int) );
  1155. for ( i = 0; i < (int)gi.number_entry; i++ ) {
  1156. err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0 );
  1157. if ( err != UNZ_OK ) {
  1158. break;
  1159. }
  1160. if ( file_info.uncompressed_size > 0 ) {
  1161. fs_headerLongs[fs_numHeaderLongs++] = LittleLong( file_info.crc );
  1162. }
  1163. hash = HashFileName( filename_inzip );
  1164. buildBuffer[i].name = filename_inzip;
  1165. buildBuffer[i].name.ToLower();
  1166. buildBuffer[i].name.BackSlashesToSlashes();
  1167. // store the file position in the zip
  1168. unzGetCurrentFileInfoPosition( uf, &buildBuffer[i].pos );
  1169. // add the file to the hash
  1170. buildBuffer[i].next = pack->hashTable[hash];
  1171. pack->hashTable[hash] = &buildBuffer[i];
  1172. // go to the next file in the zip
  1173. unzGoToNextFile(uf);
  1174. }
  1175. // check if this is an addon pak
  1176. pack->addon = false;
  1177. confHash = HashFileName( ADDON_CONFIG );
  1178. for ( pakFile = pack->hashTable[confHash]; pakFile; pakFile = pakFile->next ) {
  1179. if ( !FilenameCompare( pakFile->name, ADDON_CONFIG ) ) {
  1180. pack->addon = true;
  1181. idFile_InZip *file = ReadFileFromZip( pack, pakFile, ADDON_CONFIG );
  1182. // may be just an empty file if you don't bother about the mapDef
  1183. if ( file && file->Length() ) {
  1184. char *buf;
  1185. buf = new char[ file->Length() + 1 ];
  1186. file->Read( (void *)buf, file->Length() );
  1187. buf[ file->Length() ] = '\0';
  1188. pack->addon_info = ParseAddonDef( buf, file->Length() );
  1189. delete[] buf;
  1190. }
  1191. if ( file ) {
  1192. CloseFile( file );
  1193. }
  1194. break;
  1195. }
  1196. }
  1197. pack->checksum = MD4_BlockChecksum( fs_headerLongs, 4 * fs_numHeaderLongs );
  1198. pack->checksum = LittleLong( pack->checksum );
  1199. Mem_Free( fs_headerLongs );
  1200. return pack;
  1201. }
  1202. /*
  1203. ===============
  1204. idFileSystemLocal::AddZipFile
  1205. adds a downloaded pak file to the list so we can work out what we have and what we still need
  1206. the isNew flag is set to true, indicating that we cannot add this pak to the search lists without a restart
  1207. ===============
  1208. */
  1209. int idFileSystemLocal::AddZipFile( const char *path ) {
  1210. idStr fullpath = fs_savepath.GetString();
  1211. pack_t *pak;
  1212. searchpath_t *search, *last;
  1213. fullpath.AppendPath( path );
  1214. pak = LoadZipFile( fullpath );
  1215. if ( !pak ) {
  1216. common->Warning( "AddZipFile %s failed\n", path );
  1217. return 0;
  1218. }
  1219. // insert the pak at the end of the search list - temporary until we restart
  1220. pak->isNew = true;
  1221. search = new searchpath_t;
  1222. search->dir = NULL;
  1223. search->pack = pak;
  1224. search->next = NULL;
  1225. last = searchPaths;
  1226. while ( last->next ) {
  1227. last = last->next;
  1228. }
  1229. last->next = search;
  1230. common->Printf( "Appended pk4 %s with checksum 0x%x\n", pak->pakFilename.c_str(), pak->checksum );
  1231. return pak->checksum;
  1232. }
  1233. /*
  1234. ===============
  1235. idFileSystemLocal::AddUnique
  1236. ===============
  1237. */
  1238. int idFileSystemLocal::AddUnique( const char *name, idStrList &list, idHashIndex &hashIndex ) const {
  1239. int i, hashKey;
  1240. hashKey = hashIndex.GenerateKey( name );
  1241. for ( i = hashIndex.First( hashKey ); i >= 0; i = hashIndex.Next( i ) ) {
  1242. if ( list[i].Icmp( name ) == 0 ) {
  1243. return i;
  1244. }
  1245. }
  1246. i = list.Append( name );
  1247. hashIndex.Add( hashKey, i );
  1248. return i;
  1249. }
  1250. /*
  1251. ===============
  1252. idFileSystemLocal::GetExtensionList
  1253. ===============
  1254. */
  1255. void idFileSystemLocal::GetExtensionList( const char *extension, idStrList &extensionList ) const {
  1256. int s, e, l;
  1257. l = idStr::Length( extension );
  1258. s = 0;
  1259. while( 1 ) {
  1260. e = idStr::FindChar( extension, '|', s, l );
  1261. if ( e != -1 ) {
  1262. extensionList.Append( idStr( extension, s, e ) );
  1263. s = e + 1;
  1264. } else {
  1265. extensionList.Append( idStr( extension, s, l ) );
  1266. break;
  1267. }
  1268. }
  1269. }
  1270. /*
  1271. ===============
  1272. idFileSystemLocal::GetFileList
  1273. Does not clear the list first so this can be used to progressively build a file list.
  1274. When 'sort' is true only the new files added to the list are sorted.
  1275. ===============
  1276. */
  1277. int idFileSystemLocal::GetFileList( const char *relativePath, const idStrList &extensions, idStrList &list, idHashIndex &hashIndex, bool fullRelativePath, const char* gamedir ) {
  1278. searchpath_t * search;
  1279. fileInPack_t * buildBuffer;
  1280. int i, j;
  1281. int pathLength;
  1282. int length;
  1283. const char * name;
  1284. pack_t * pak;
  1285. idStr work;
  1286. if ( !searchPaths ) {
  1287. common->FatalError( "Filesystem call made without initialization\n" );
  1288. }
  1289. if ( !extensions.Num() ) {
  1290. return 0;
  1291. }
  1292. if ( !relativePath ) {
  1293. return 0;
  1294. }
  1295. pathLength = strlen( relativePath );
  1296. if ( pathLength ) {
  1297. pathLength++; // for the trailing '/'
  1298. }
  1299. // search through the path, one element at a time, adding to list
  1300. for( search = searchPaths; search != NULL; search = search->next ) {
  1301. if ( search->dir ) {
  1302. if(gamedir && strlen(gamedir)) {
  1303. if(search->dir->gamedir != gamedir) {
  1304. continue;
  1305. }
  1306. }
  1307. idStrList sysFiles;
  1308. idStr netpath;
  1309. netpath = BuildOSPath( search->dir->path, search->dir->gamedir, relativePath );
  1310. for ( i = 0; i < extensions.Num(); i++ ) {
  1311. // scan for files in the filesystem
  1312. ListOSFiles( netpath, extensions[i], sysFiles );
  1313. // if we are searching for directories, remove . and ..
  1314. if ( extensions[i][0] == '/' && extensions[i][1] == 0 ) {
  1315. sysFiles.Remove( "." );
  1316. sysFiles.Remove( ".." );
  1317. }
  1318. for( j = 0; j < sysFiles.Num(); j++ ) {
  1319. // unique the match
  1320. if ( fullRelativePath ) {
  1321. work = relativePath;
  1322. work += "/";
  1323. work += sysFiles[j];
  1324. AddUnique( work, list, hashIndex );
  1325. }
  1326. else {
  1327. AddUnique( sysFiles[j], list, hashIndex );
  1328. }
  1329. }
  1330. }
  1331. } else if ( search->pack ) {
  1332. // look through all the pak file elements
  1333. // exclude any extra packs if we have server paks to search
  1334. if ( serverPaks.Num() ) {
  1335. GetPackStatus( search->pack );
  1336. if ( search->pack->pureStatus != PURE_NEVER && !serverPaks.Find( search->pack ) ) {
  1337. continue; // not on the pure server pak list
  1338. }
  1339. }
  1340. pak = search->pack;
  1341. buildBuffer = pak->buildBuffer;
  1342. for( i = 0; i < pak->numfiles; i++ ) {
  1343. length = buildBuffer[i].name.Length();
  1344. // if the name is not long anough to at least contain the path
  1345. if ( length <= pathLength ) {
  1346. continue;
  1347. }
  1348. name = buildBuffer[i].name;
  1349. // check for a path match without the trailing '/'
  1350. if ( pathLength && idStr::Icmpn( name, relativePath, pathLength - 1 ) != 0 ) {
  1351. continue;
  1352. }
  1353. // ensure we have a path, and not just a filename containing the path
  1354. if ( name[ pathLength ] == '\0' || name[pathLength - 1] != '/' ) {
  1355. continue;
  1356. }
  1357. // make sure the file is not in a subdirectory
  1358. for ( j = pathLength; name[j+1] != '\0'; j++ ) {
  1359. if ( name[j] == '/' ) {
  1360. break;
  1361. }
  1362. }
  1363. if ( name[j+1] ) {
  1364. continue;
  1365. }
  1366. // check for extension match
  1367. for ( j = 0; j < extensions.Num(); j++ ) {
  1368. if ( length >= extensions[j].Length() && extensions[j].Icmp( name + length - extensions[j].Length() ) == 0 ) {
  1369. break;
  1370. }
  1371. }
  1372. if ( j >= extensions.Num() ) {
  1373. continue;
  1374. }
  1375. // unique the match
  1376. if ( fullRelativePath ) {
  1377. work = relativePath;
  1378. work += "/";
  1379. work += name + pathLength;
  1380. work.StripTrailing( '/' );
  1381. AddUnique( work, list, hashIndex );
  1382. } else {
  1383. work = name + pathLength;
  1384. work.StripTrailing( '/' );
  1385. AddUnique( work, list, hashIndex );
  1386. }
  1387. }
  1388. }
  1389. }
  1390. return list.Num();
  1391. }
  1392. /*
  1393. ===============
  1394. idFileSystemLocal::ListFiles
  1395. ===============
  1396. */
  1397. idFileList *idFileSystemLocal::ListFiles( const char *relativePath, const char *extension, bool sort, bool fullRelativePath, const char* gamedir ) {
  1398. idHashIndex hashIndex( 4096, 4096 );
  1399. idStrList extensionList;
  1400. idFileList *fileList = new idFileList;
  1401. fileList->basePath = relativePath;
  1402. GetExtensionList( extension, extensionList );
  1403. GetFileList( relativePath, extensionList, fileList->list, hashIndex, fullRelativePath, gamedir );
  1404. if ( sort ) {
  1405. idStrListSortPaths( fileList->list );
  1406. }
  1407. return fileList;
  1408. }
  1409. /*
  1410. ===============
  1411. idFileSystemLocal::GetFileListTree
  1412. ===============
  1413. */
  1414. int idFileSystemLocal::GetFileListTree( const char *relativePath, const idStrList &extensions, idStrList &list, idHashIndex &hashIndex, const char* gamedir ) {
  1415. int i;
  1416. idStrList slash, folders( 128 );
  1417. idHashIndex folderHashIndex( 1024, 128 );
  1418. // recurse through the subdirectories
  1419. slash.Append( "/" );
  1420. GetFileList( relativePath, slash, folders, folderHashIndex, true, gamedir );
  1421. for ( i = 0; i < folders.Num(); i++ ) {
  1422. if ( folders[i][0] == '.' ) {
  1423. continue;
  1424. }
  1425. if ( folders[i].Icmp( relativePath ) == 0 ){
  1426. continue;
  1427. }
  1428. GetFileListTree( folders[i], extensions, list, hashIndex, gamedir );
  1429. }
  1430. // list files in the current directory
  1431. GetFileList( relativePath, extensions, list, hashIndex, true, gamedir );
  1432. return list.Num();
  1433. }
  1434. /*
  1435. ===============
  1436. idFileSystemLocal::ListFilesTree
  1437. ===============
  1438. */
  1439. idFileList *idFileSystemLocal::ListFilesTree( const char *relativePath, const char *extension, bool sort, const char* gamedir ) {
  1440. idHashIndex hashIndex( 4096, 4096 );
  1441. idStrList extensionList;
  1442. idFileList *fileList = new idFileList();
  1443. fileList->basePath = relativePath;
  1444. fileList->list.SetGranularity( 4096 );
  1445. GetExtensionList( extension, extensionList );
  1446. GetFileListTree( relativePath, extensionList, fileList->list, hashIndex, gamedir );
  1447. if ( sort ) {
  1448. idStrListSortPaths( fileList->list );
  1449. }
  1450. return fileList;
  1451. }
  1452. /*
  1453. ===============
  1454. idFileSystemLocal::FreeFileList
  1455. ===============
  1456. */
  1457. void idFileSystemLocal::FreeFileList( idFileList *fileList ) {
  1458. delete fileList;
  1459. }
  1460. /*
  1461. ===============
  1462. idFileSystemLocal::ListMods
  1463. ===============
  1464. */
  1465. idModList *idFileSystemLocal::ListMods( void ) {
  1466. int i;
  1467. const int MAX_DESCRIPTION = 256;
  1468. char desc[ MAX_DESCRIPTION ];
  1469. idStrList dirs;
  1470. idStrList pk4s;
  1471. idModList *list = new idModList;
  1472. const char *search[ 4 ];
  1473. int isearch;
  1474. search[0] = fs_savepath.GetString();
  1475. search[1] = fs_devpath.GetString();
  1476. search[2] = fs_basepath.GetString();
  1477. search[3] = fs_cdpath.GetString();
  1478. for ( isearch = 0; isearch < 4; isearch++ ) {
  1479. dirs.Clear();
  1480. pk4s.Clear();
  1481. // scan for directories
  1482. ListOSFiles( search[ isearch ], "/", dirs );
  1483. dirs.Remove( "." );
  1484. dirs.Remove( ".." );
  1485. dirs.Remove( "base" );
  1486. dirs.Remove( "pb" );
  1487. // see if there are any pk4 files in each directory
  1488. for( i = 0; i < dirs.Num(); i++ ) {
  1489. idStr gamepath = BuildOSPath( search[ isearch ], dirs[ i ], "" );
  1490. ListOSFiles( gamepath, ".pk4", pk4s );
  1491. if ( pk4s.Num() ) {
  1492. if ( !list->mods.Find( dirs[ i ] ) ) {
  1493. // D3 1.3 #31, only list d3xp if the pak is present
  1494. if ( dirs[ i ].Icmp( "d3xp" ) || HasD3XP() ) {
  1495. list->mods.Append( dirs[ i ] );
  1496. }
  1497. }
  1498. }
  1499. }
  1500. }
  1501. list->mods.Sort();
  1502. // read the descriptions for each mod - search all paths
  1503. for ( i = 0; i < list->mods.Num(); i++ ) {
  1504. for ( isearch = 0; isearch < 4; isearch++ ) {
  1505. idStr descfile = BuildOSPath( search[ isearch ], list->mods[ i ], "description.txt" );
  1506. FILE *f = OpenOSFile( descfile, "r" );
  1507. if ( f ) {
  1508. if ( fgets( desc, MAX_DESCRIPTION, f ) ) {
  1509. list->descriptions.Append( desc );
  1510. fclose( f );
  1511. break;
  1512. } else {
  1513. common->DWarning( "Error reading %s", descfile.c_str() );
  1514. fclose( f );
  1515. continue;
  1516. }
  1517. }
  1518. }
  1519. if ( isearch == 4 ) {
  1520. list->descriptions.Append( list->mods[ i ] );
  1521. }
  1522. }
  1523. list->mods.Insert( "" );
  1524. list->descriptions.Insert( "Doom 3" );
  1525. assert( list->mods.Num() == list->descriptions.Num() );
  1526. return list;
  1527. }
  1528. /*
  1529. ===============
  1530. idFileSystemLocal::FreeModList
  1531. ===============
  1532. */
  1533. void idFileSystemLocal::FreeModList( idModList *modList ) {
  1534. delete modList;
  1535. }
  1536. /*
  1537. ===============
  1538. idDEntry::Matches
  1539. ===============
  1540. */
  1541. bool idDEntry::Matches(const char *directory, const char *extension) const {
  1542. if ( !idDEntry::directory.Icmp( directory ) && !idDEntry::extension.Icmp( extension ) ) {
  1543. return true;
  1544. }
  1545. return false;
  1546. }
  1547. /*
  1548. ===============
  1549. idDEntry::Init
  1550. ===============
  1551. */
  1552. void idDEntry::Init( const char *directory, const char *extension, const idStrList &list ) {
  1553. idDEntry::directory = directory;
  1554. idDEntry::extension = extension;
  1555. idStrList::operator=(list);
  1556. }
  1557. /*
  1558. ===============
  1559. idDEntry::Clear
  1560. ===============
  1561. */
  1562. void idDEntry::Clear( void ) {
  1563. directory.Clear();
  1564. extension.Clear();
  1565. idStrList::Clear();
  1566. }
  1567. /*
  1568. ===============
  1569. idFileSystemLocal::ListOSFiles
  1570. call to the OS for a listing of files in an OS directory
  1571. optionally, perform some caching of the entries
  1572. ===============
  1573. */
  1574. int idFileSystemLocal::ListOSFiles( const char *directory, const char *extension, idStrList &list ) {
  1575. int i, j, ret;
  1576. if ( !extension ) {
  1577. extension = "";
  1578. }
  1579. if ( !fs_caseSensitiveOS.GetBool() ) {
  1580. return Sys_ListFiles( directory, extension, list );
  1581. }
  1582. // try in cache
  1583. i = dir_cache_index - 1;
  1584. while( i >= dir_cache_index - dir_cache_count ) {
  1585. j = (i+MAX_CACHED_DIRS) % MAX_CACHED_DIRS;
  1586. if ( dir_cache[j].Matches( directory, extension ) ) {
  1587. if ( fs_debug.GetInteger() ) {
  1588. //common->Printf( "idFileSystemLocal::ListOSFiles: cache hit: %s\n", directory );
  1589. }
  1590. list = dir_cache[j];
  1591. return list.Num();
  1592. }
  1593. i--;
  1594. }
  1595. if ( fs_debug.GetInteger() ) {
  1596. //common->Printf( "idFileSystemLocal::ListOSFiles: cache miss: %s\n", directory );
  1597. }
  1598. ret = Sys_ListFiles( directory, extension, list );
  1599. if ( ret == -1 ) {
  1600. return -1;
  1601. }
  1602. // push a new entry
  1603. dir_cache[dir_cache_index].Init( directory, extension, list );
  1604. dir_cache_index = (++dir_cache_index) % MAX_CACHED_DIRS;
  1605. if ( dir_cache_count < MAX_CACHED_DIRS ) {
  1606. dir_cache_count++;
  1607. }
  1608. return ret;
  1609. }
  1610. /*
  1611. ================
  1612. idFileSystemLocal::Dir_f
  1613. ================
  1614. */
  1615. void idFileSystemLocal::Dir_f( const idCmdArgs &args ) {
  1616. idStr relativePath;
  1617. idStr extension;
  1618. idFileList *fileList;
  1619. int i;
  1620. if ( args.Argc() < 2 || args.Argc() > 3 ) {
  1621. common->Printf( "usage: dir <directory> [extension]\n" );
  1622. return;
  1623. }
  1624. if ( args.Argc() == 2 ) {
  1625. relativePath = args.Argv( 1 );
  1626. extension = "";
  1627. }
  1628. else {
  1629. relativePath = args.Argv( 1 );
  1630. extension = args.Argv( 2 );
  1631. if ( extension[0] != '.' ) {
  1632. common->Warning( "extension should have a leading dot" );
  1633. }
  1634. }
  1635. relativePath.BackSlashesToSlashes();
  1636. relativePath.StripTrailing( '/' );
  1637. common->Printf( "Listing of %s/*%s\n", relativePath.c_str(), extension.c_str() );
  1638. common->Printf( "---------------\n" );
  1639. fileList = fileSystemLocal.ListFiles( relativePath, extension );
  1640. for ( i = 0; i < fileList->GetNumFiles(); i++ ) {
  1641. common->Printf( "%s\n", fileList->GetFile( i ) );
  1642. }
  1643. common->Printf( "%d files\n", fileList->list.Num() );
  1644. fileSystemLocal.FreeFileList( fileList );
  1645. }
  1646. /*
  1647. ================
  1648. idFileSystemLocal::DirTree_f
  1649. ================
  1650. */
  1651. void idFileSystemLocal::DirTree_f( const idCmdArgs &args ) {
  1652. idStr relativePath;
  1653. idStr extension;
  1654. idFileList *fileList;
  1655. int i;
  1656. if ( args.Argc() < 2 || args.Argc() > 3 ) {
  1657. common->Printf( "usage: dirtree <directory> [extension]\n" );
  1658. return;
  1659. }
  1660. if ( args.Argc() == 2 ) {
  1661. relativePath = args.Argv( 1 );
  1662. extension = "";
  1663. }
  1664. else {
  1665. relativePath = args.Argv( 1 );
  1666. extension = args.Argv( 2 );
  1667. if ( extension[0] != '.' ) {
  1668. common->Warning( "extension should have a leading dot" );
  1669. }
  1670. }
  1671. relativePath.BackSlashesToSlashes();
  1672. relativePath.StripTrailing( '/' );
  1673. common->Printf( "Listing of %s/*%s /s\n", relativePath.c_str(), extension.c_str() );
  1674. common->Printf( "---------------\n" );
  1675. fileList = fileSystemLocal.ListFilesTree( relativePath, extension );
  1676. for ( i = 0; i < fileList->GetNumFiles(); i++ ) {
  1677. common->Printf( "%s\n", fileList->GetFile( i ) );
  1678. }
  1679. common->Printf( "%d files\n", fileList->list.Num() );
  1680. fileSystemLocal.FreeFileList( fileList );
  1681. }
  1682. /*
  1683. ============
  1684. idFileSystemLocal::Path_f
  1685. ============
  1686. */
  1687. void idFileSystemLocal::Path_f( const idCmdArgs &args ) {
  1688. searchpath_t *sp;
  1689. int i;
  1690. idStr status;
  1691. common->Printf( "Current search path:\n" );
  1692. for ( sp = fileSystemLocal.searchPaths; sp; sp = sp->next ) {
  1693. if ( sp->pack ) {
  1694. if ( com_developer.GetBool() ) {
  1695. sprintf( status, "%s (%i files - 0x%x %s", sp->pack->pakFilename.c_str(), sp->pack->numfiles, sp->pack->checksum, sp->pack->referenced ? "referenced" : "not referenced" );
  1696. if ( sp->pack->addon ) {
  1697. status += " - addon)\n";
  1698. } else {
  1699. status += ")\n";
  1700. }
  1701. common->Printf( status.c_str() );
  1702. } else {
  1703. common->Printf( "%s (%i files)\n", sp->pack->pakFilename.c_str(), sp->pack->numfiles );
  1704. }
  1705. if ( fileSystemLocal.serverPaks.Num() ) {
  1706. if ( fileSystemLocal.serverPaks.Find( sp->pack ) ) {
  1707. common->Printf( " on the pure list\n" );
  1708. } else {
  1709. common->Printf( " not on the pure list\n" );
  1710. }
  1711. }
  1712. } else {
  1713. common->Printf( "%s/%s\n", sp->dir->path.c_str(), sp->dir->gamedir.c_str() );
  1714. }
  1715. }
  1716. common->Printf( "game DLL: 0x%x in pak: 0x%x\n", fileSystemLocal.gameDLLChecksum, fileSystemLocal.gamePakChecksum );
  1717. #if ID_FAKE_PURE
  1718. common->Printf( "Note: ID_FAKE_PURE is enabled\n" );
  1719. #endif
  1720. for( i = 0; i < MAX_GAME_OS; i++ ) {
  1721. if ( fileSystemLocal.gamePakForOS[ i ] ) {
  1722. common->Printf( "OS %d - pak 0x%x\n", i, fileSystemLocal.gamePakForOS[ i ] );
  1723. }
  1724. }
  1725. // show addon packs that are *not* in the search lists
  1726. common->Printf( "Addon pk4s:\n" );
  1727. for ( sp = fileSystemLocal.addonPaks; sp; sp = sp->next ) {
  1728. if ( com_developer.GetBool() ) {
  1729. common->Printf( "%s (%i files - 0x%x)\n", sp->pack->pakFilename.c_str(), sp->pack->numfiles, sp->pack->checksum );
  1730. } else {
  1731. common->Printf( "%s (%i files)\n", sp->pack->pakFilename.c_str(), sp->pack->numfiles );
  1732. }
  1733. }
  1734. }
  1735. /*
  1736. ============
  1737. idFileSystemLocal::GetOSMask
  1738. ============
  1739. */
  1740. int idFileSystemLocal::GetOSMask( void ) {
  1741. int i, ret = 0;
  1742. for( i = 0; i < MAX_GAME_OS; i++ ) {
  1743. if ( fileSystemLocal.gamePakForOS[ i ] ) {
  1744. ret |= ( 1 << i );
  1745. }
  1746. }
  1747. if ( !ret ) {
  1748. return -1;
  1749. }
  1750. return ret;
  1751. }
  1752. /*
  1753. ============
  1754. idFileSystemLocal::TouchFile_f
  1755. The only purpose of this function is to allow game script files to copy
  1756. arbitrary files furing an "fs_copyfiles 1" run.
  1757. ============
  1758. */
  1759. void idFileSystemLocal::TouchFile_f( const idCmdArgs &args ) {
  1760. idFile *f;
  1761. if ( args.Argc() != 2 ) {
  1762. common->Printf( "Usage: touchFile <file>\n" );
  1763. return;
  1764. }
  1765. f = fileSystemLocal.OpenFileRead( args.Argv( 1 ) );
  1766. if ( f ) {
  1767. fileSystemLocal.CloseFile( f );
  1768. }
  1769. }
  1770. /*
  1771. ============
  1772. idFileSystemLocal::TouchFileList_f
  1773. Takes a text file and touches every file in it, use one file per line.
  1774. ============
  1775. */
  1776. void idFileSystemLocal::TouchFileList_f( const idCmdArgs &args ) {
  1777. if ( args.Argc() != 2 ) {
  1778. common->Printf( "Usage: touchFileList <filename>\n" );
  1779. return;
  1780. }
  1781. const char *buffer = NULL;
  1782. idParser src( LEXFL_NOFATALERRORS | LEXFL_NOSTRINGCONCAT | LEXFL_ALLOWMULTICHARLITERALS | LEXFL_ALLOWBACKSLASHSTRINGCONCAT );
  1783. if ( fileSystem->ReadFile( args.Argv( 1 ), ( void** )&buffer, NULL ) && buffer ) {
  1784. src.LoadMemory( buffer, strlen( buffer ), args.Argv( 1 ) );
  1785. if ( src.IsLoaded() ) {
  1786. idToken token;
  1787. while( src.ReadToken( &token ) ) {
  1788. common->Printf( "%s\n", token.c_str() );
  1789. session->UpdateScreen();
  1790. idFile *f = fileSystemLocal.OpenFileRead( token );
  1791. if ( f ) {
  1792. fileSystemLocal.CloseFile( f );
  1793. }
  1794. }
  1795. }
  1796. }
  1797. }
  1798. /*
  1799. ================
  1800. idFileSystemLocal::AddGameDirectory
  1801. Sets gameFolder, adds the directory to the head of the search paths, then loads any pk4 files.
  1802. ================
  1803. */
  1804. void idFileSystemLocal::AddGameDirectory( const char *path, const char *dir ) {
  1805. int i;
  1806. searchpath_t * search;
  1807. pack_t * pak;
  1808. idStr pakfile;
  1809. idStrList pakfiles;
  1810. // check if the search path already exists
  1811. for ( search = searchPaths; search; search = search->next ) {
  1812. // if this element is a pak file
  1813. if ( !search->dir ) {
  1814. continue;
  1815. }
  1816. if ( search->dir->path.Cmp( path ) == 0 && search->dir->gamedir.Cmp( dir ) == 0 ) {
  1817. return;
  1818. }
  1819. }
  1820. gameFolder = dir;
  1821. //
  1822. // add the directory to the search path
  1823. //
  1824. search = new searchpath_t;
  1825. search->dir = new directory_t;
  1826. search->pack = NULL;
  1827. search->dir->path = path;
  1828. search->dir->gamedir = dir;
  1829. search->next = searchPaths;
  1830. searchPaths = search;
  1831. // find all pak files in this directory
  1832. pakfile = BuildOSPath( path, dir, "" );
  1833. pakfile[ pakfile.Length() - 1 ] = 0; // strip the trailing slash
  1834. ListOSFiles( pakfile, ".pk4", pakfiles );
  1835. // sort them so that later alphabetic matches override
  1836. // earlier ones. This makes pak1.pk4 override pak0.pk4
  1837. pakfiles.Sort();
  1838. for ( i = 0; i < pakfiles.Num(); i++ ) {
  1839. pakfile = BuildOSPath( path, dir, pakfiles[i] );
  1840. pak = LoadZipFile( pakfile );
  1841. if ( !pak ) {
  1842. continue;
  1843. }
  1844. // insert the pak after the directory it comes from
  1845. search = new searchpath_t;
  1846. search->dir = NULL;
  1847. search->pack = pak;
  1848. search->next = searchPaths->next;
  1849. searchPaths->next = search;
  1850. common->Printf( "Loaded pk4 %s with checksum 0x%x\n", pakfile.c_str(), pak->checksum );
  1851. }
  1852. }
  1853. /*
  1854. ================
  1855. idFileSystemLocal::SetupGameDirectories
  1856. Takes care of the correct search order.
  1857. ================
  1858. */
  1859. void idFileSystemLocal::SetupGameDirectories( const char *gameName ) {
  1860. // setup cdpath
  1861. if ( fs_cdpath.GetString()[0] ) {
  1862. AddGameDirectory( fs_cdpath.GetString(), gameName );
  1863. }
  1864. // setup basepath
  1865. if ( fs_basepath.GetString()[0] ) {
  1866. AddGameDirectory( fs_basepath.GetString(), gameName );
  1867. }
  1868. // setup devpath
  1869. if ( fs_devpath.GetString()[0] ) {
  1870. AddGameDirectory( fs_devpath.GetString(), gameName );
  1871. }
  1872. // setup savepath
  1873. if ( fs_savepath.GetString()[0] ) {
  1874. AddGameDirectory( fs_savepath.GetString(), gameName );
  1875. }
  1876. }
  1877. /*
  1878. ===============
  1879. idFileSystemLocal::FollowDependencies
  1880. ===============
  1881. */
  1882. void idFileSystemLocal::FollowAddonDependencies( pack_t *pak ) {
  1883. assert( pak );
  1884. if ( !pak->addon_info || !pak->addon_info->depends.Num() ) {
  1885. return;
  1886. }
  1887. int i, num = pak->addon_info->depends.Num();
  1888. for ( i = 0; i < num; i++ ) {
  1889. pack_t *deppak = GetPackForChecksum( pak->addon_info->depends[ i ], true );
  1890. if ( deppak ) {
  1891. // make sure it hasn't been marked for search already
  1892. if ( !deppak->addon_search ) {
  1893. // must clean addonChecksums as we go
  1894. int addon_index = addonChecksums.FindIndex( deppak->checksum );
  1895. if ( addon_index >= 0 ) {
  1896. addonChecksums.RemoveIndex( addon_index );
  1897. }
  1898. deppak->addon_search = true;
  1899. common->Printf( "Addon pk4 %s 0x%x depends on pak %s 0x%x, will be searched\n",
  1900. pak->pakFilename.c_str(), pak->checksum,
  1901. deppak->pakFilename.c_str(), deppak->checksum );
  1902. FollowAddonDependencies( deppak );
  1903. }
  1904. } else {
  1905. common->Printf( "Addon pk4 %s 0x%x depends on unknown pak 0x%x\n",
  1906. pak->pakFilename.c_str(), pak->checksum, pak->addon_info->depends[ i ] );
  1907. }
  1908. }
  1909. }
  1910. /*
  1911. ================
  1912. idFileSystemLocal::Startup
  1913. ================
  1914. */
  1915. void idFileSystemLocal::Startup( void ) {
  1916. searchpath_t **search;
  1917. int i;
  1918. pack_t *pak;
  1919. int addon_index;
  1920. common->Printf( "------ Initializing File System ------\n" );
  1921. if ( restartChecksums.Num() ) {
  1922. common->Printf( "restarting in pure mode with %d pak files\n", restartChecksums.Num() );
  1923. }
  1924. if ( addonChecksums.Num() ) {
  1925. common->Printf( "restarting filesystem with %d addon pak file(s) to include\n", addonChecksums.Num() );
  1926. }
  1927. SetupGameDirectories( BASE_GAMEDIR );
  1928. // fs_game_base override
  1929. if ( fs_game_base.GetString()[0] &&
  1930. idStr::Icmp( fs_game_base.GetString(), BASE_GAMEDIR ) ) {
  1931. SetupGameDirectories( fs_game_base.GetString() );
  1932. }
  1933. // fs_game override
  1934. if ( fs_game.GetString()[0] &&
  1935. idStr::Icmp( fs_game.GetString(), BASE_GAMEDIR ) &&
  1936. idStr::Icmp( fs_game.GetString(), fs_game_base.GetString() ) ) {
  1937. SetupGameDirectories( fs_game.GetString() );
  1938. }
  1939. // currently all addons are in the search list - deal with filtering out and dependencies now
  1940. // scan through and deal with dependencies
  1941. search = &searchPaths;
  1942. while ( *search ) {
  1943. if ( !( *search )->pack || !( *search )->pack->addon ) {
  1944. search = &( ( *search )->next );
  1945. continue;
  1946. }
  1947. pak = ( *search )->pack;
  1948. if ( fs_searchAddons.GetBool() ) {
  1949. // when we have fs_searchAddons on we should never have addonChecksums
  1950. assert( !addonChecksums.Num() );
  1951. pak->addon_search = true;
  1952. search = &( ( *search )->next );
  1953. continue;
  1954. }
  1955. addon_index = addonChecksums.FindIndex( pak->checksum );
  1956. if ( addon_index >= 0 ) {
  1957. assert( !pak->addon_search ); // any pak getting flagged as addon_search should also have been removed from addonChecksums already
  1958. pak->addon_search = true;
  1959. addonChecksums.RemoveIndex( addon_index );
  1960. FollowAddonDependencies( pak );
  1961. }
  1962. search = &( ( *search )->next );
  1963. }
  1964. // now scan to filter out addons not marked addon_search
  1965. search = &searchPaths;
  1966. while ( *search ) {
  1967. if ( !( *search )->pack || !( *search )->pack->addon ) {
  1968. search = &( ( *search )->next );
  1969. continue;
  1970. }
  1971. assert( !( *search )->dir );
  1972. pak = ( *search )->pack;
  1973. if ( pak->addon_search ) {
  1974. common->Printf( "Addon pk4 %s with checksum 0x%x is on the search list\n",
  1975. pak->pakFilename.c_str(), pak->checksum );
  1976. search = &( ( *search )->next );
  1977. } else {
  1978. // remove from search list, put in addons list
  1979. searchpath_t *paksearch = *search;
  1980. *search = ( *search )->next;
  1981. paksearch->next = addonPaks;
  1982. addonPaks = paksearch;
  1983. common->Printf( "Addon pk4 %s with checksum 0x%x is on addon list\n",
  1984. pak->pakFilename.c_str(), pak->checksum );
  1985. }
  1986. }
  1987. // all addon paks found and accounted for
  1988. assert( !addonChecksums.Num() );
  1989. addonChecksums.Clear(); // just in case
  1990. if ( restartChecksums.Num() ) {
  1991. search = &searchPaths;
  1992. while ( *search ) {
  1993. if ( !( *search )->pack ) {
  1994. search = &( ( *search )->next );
  1995. continue;
  1996. }
  1997. if ( ( i = restartChecksums.FindIndex( ( *search )->pack->checksum ) ) != -1 ) {
  1998. if ( i == 0 ) {
  1999. // this pak is the next one in the pure search order
  2000. serverPaks.Append( ( *search )->pack );
  2001. restartChecksums.RemoveIndex( 0 );
  2002. if ( !restartChecksums.Num() ) {
  2003. break; // early out, we're done
  2004. }
  2005. search = &( ( *search )->next );
  2006. continue;
  2007. } else {
  2008. // this pak will be on the pure list, but order is not right yet
  2009. searchpath_t *aux;
  2010. aux = ( *search )->next;
  2011. if ( !aux ) {
  2012. // last of the list can't be swapped back
  2013. if ( fs_debug.GetBool() ) {
  2014. common->Printf( "found pure checksum %x at index %d, but the end of search path is reached\n", ( *search )->pack->checksum, i );
  2015. idStr checks;
  2016. checks.Clear();
  2017. for ( i = 0; i < serverPaks.Num(); i++ ) {
  2018. checks += va( "%p ", serverPaks[ i ] );
  2019. }
  2020. common->Printf( "%d pure paks - %s \n", serverPaks.Num(), checks.c_str() );
  2021. checks.Clear();
  2022. for ( i = 0; i < restartChecksums.Num(); i++ ) {
  2023. checks += va( "%x ", restartChecksums[ i ] );
  2024. }
  2025. common->Printf( "%d paks left - %s\n", restartChecksums.Num(), checks.c_str() );
  2026. }
  2027. common->FatalError( "Failed to restart with pure mode restrictions for server connect" );
  2028. }
  2029. // put this search path at the end of the list
  2030. searchpath_t *search_end;
  2031. search_end = ( *search )->next;
  2032. while ( search_end->next ) {
  2033. search_end = search_end->next;
  2034. }
  2035. search_end->next = *search;
  2036. *search = ( *search )->next;
  2037. search_end->next->next = NULL;
  2038. continue;
  2039. }
  2040. }
  2041. // this pak is not on the pure list
  2042. search = &( ( *search )->next );
  2043. }
  2044. // the list must be empty
  2045. if ( restartChecksums.Num() ) {
  2046. if ( fs_debug.GetBool() ) {
  2047. idStr checks;
  2048. checks.Clear();
  2049. for ( i = 0; i < serverPaks.Num(); i++ ) {
  2050. checks += va( "%p ", serverPaks[ i ] );
  2051. }
  2052. common->Printf( "%d pure paks - %s \n", serverPaks.Num(), checks.c_str() );
  2053. checks.Clear();
  2054. for ( i = 0; i < restartChecksums.Num(); i++ ) {
  2055. checks += va( "%x ", restartChecksums[ i ] );
  2056. }
  2057. common->Printf( "%d paks left - %s\n", restartChecksums.Num(), checks.c_str() );
  2058. }
  2059. common->FatalError( "Failed to restart with pure mode restrictions for server connect" );
  2060. }
  2061. // also the game pak checksum
  2062. // we could check if the game pak is actually present, but we would not be restarting if there wasn't one @ first pure check
  2063. gamePakChecksum = restartGamePakChecksum;
  2064. }
  2065. // add our commands
  2066. cmdSystem->AddCommand( "dir", Dir_f, CMD_FL_SYSTEM, "lists a folder", idCmdSystem::ArgCompletion_FileName );
  2067. cmdSystem->AddCommand( "dirtree", DirTree_f, CMD_FL_SYSTEM, "lists a folder with subfolders" );
  2068. cmdSystem->AddCommand( "path", Path_f, CMD_FL_SYSTEM, "lists search paths" );
  2069. cmdSystem->AddCommand( "touchFile", TouchFile_f, CMD_FL_SYSTEM, "touches a file" );
  2070. cmdSystem->AddCommand( "touchFileList", TouchFileList_f, CMD_FL_SYSTEM, "touches a list of files" );
  2071. // print the current search paths
  2072. Path_f( idCmdArgs() );
  2073. common->Printf( "file system initialized.\n" );
  2074. common->Printf( "--------------------------------------\n" );
  2075. }
  2076. /*
  2077. ===================
  2078. idFileSystemLocal::SetRestrictions
  2079. Looks for product keys and restricts media add on ability
  2080. if the full version is not found
  2081. ===================
  2082. */
  2083. void idFileSystemLocal::SetRestrictions( void ) {
  2084. #ifdef ID_DEMO_BUILD
  2085. common->Printf( "\nRunning in restricted demo mode.\n\n" );
  2086. // make sure that the pak file has the header checksum we expect
  2087. searchpath_t *search;
  2088. for ( search = searchPaths; search; search = search->next ) {
  2089. if ( search->pack ) {
  2090. // a tiny attempt to keep the checksum from being scannable from the exe
  2091. if ( ( search->pack->checksum ^ 0x84268436u ) != ( DEMO_PAK_CHECKSUM ^ 0x84268436u ) ) {
  2092. common->FatalError( "Corrupted %s: 0x%x", search->pack->pakFilename.c_str(), search->pack->checksum );
  2093. }
  2094. }
  2095. }
  2096. cvarSystem->SetCVarBool( "fs_restrict", true );
  2097. #endif
  2098. }
  2099. /*
  2100. =====================
  2101. idFileSystemLocal::UpdatePureServerChecksums
  2102. =====================
  2103. */
  2104. void idFileSystemLocal::UpdatePureServerChecksums( void ) {
  2105. searchpath_t *search;
  2106. int i;
  2107. pureStatus_t status;
  2108. serverPaks.Clear();
  2109. for ( search = searchPaths; search; search = search->next ) {
  2110. // is the element a referenced pak file?
  2111. if ( !search->pack ) {
  2112. continue;
  2113. }
  2114. status = GetPackStatus( search->pack );
  2115. if ( status == PURE_NEVER ) {
  2116. continue;
  2117. }
  2118. if ( status == PURE_NEUTRAL && !search->pack->referenced ) {
  2119. continue;
  2120. }
  2121. serverPaks.Append( search->pack );
  2122. if ( serverPaks.Num() >= MAX_PURE_PAKS ) {
  2123. common->FatalError( "MAX_PURE_PAKS ( %d ) exceeded\n", MAX_PURE_PAKS );
  2124. }
  2125. }
  2126. if ( fs_debug.GetBool() ) {
  2127. idStr checks;
  2128. for ( i = 0; i < serverPaks.Num(); i++ ) {
  2129. checks += va( "%x ", serverPaks[ i ]->checksum );
  2130. }
  2131. common->Printf( "set pure list - %d paks ( %s)\n", serverPaks.Num(), checks.c_str() );
  2132. }
  2133. }
  2134. /*
  2135. =====================
  2136. idFileSystemLocal::UpdateGamePakChecksums
  2137. =====================
  2138. */
  2139. bool idFileSystemLocal::UpdateGamePakChecksums( void ) {
  2140. searchpath_t *search;
  2141. fileInPack_t *pakFile;
  2142. int confHash;
  2143. idFile *confFile;
  2144. char *buf;
  2145. idLexer *lexConf;
  2146. idToken token;
  2147. int id;
  2148. confHash = HashFileName( BINARY_CONFIG );
  2149. memset( gamePakForOS, 0, sizeof( gamePakForOS ) );
  2150. for ( search = searchPaths; search; search = search->next ) {
  2151. if ( !search->pack ) {
  2152. continue;
  2153. }
  2154. search->pack->binary = BINARY_NO;
  2155. for ( pakFile = search->pack->hashTable[confHash]; pakFile; pakFile = pakFile->next ) {
  2156. if ( !FilenameCompare( pakFile->name, BINARY_CONFIG ) ) {
  2157. search->pack->binary = BINARY_YES;
  2158. confFile = ReadFileFromZip( search->pack, pakFile, BINARY_CONFIG );
  2159. buf = new char[ confFile->Length() + 1 ];
  2160. confFile->Read( (void *)buf, confFile->Length() );
  2161. buf[ confFile->Length() ] = '\0';
  2162. lexConf = new idLexer( buf, confFile->Length(), confFile->GetFullPath() );
  2163. while ( lexConf->ReadToken( &token ) ) {
  2164. if ( token.IsNumeric() ) {
  2165. id = atoi( token );
  2166. if ( id < MAX_GAME_OS && !gamePakForOS[ id ] ) {
  2167. if ( fs_debug.GetBool() ) {
  2168. common->Printf( "Adding game pak checksum for OS %d: %s 0x%x\n", id, confFile->GetFullPath(), search->pack->checksum );
  2169. }
  2170. gamePakForOS[ id ] = search->pack->checksum;
  2171. }
  2172. }
  2173. }
  2174. CloseFile( confFile );
  2175. delete lexConf;
  2176. delete[] buf;
  2177. }
  2178. }
  2179. }
  2180. // some sanity checks on the game code references
  2181. // make sure that at least the local OS got a pure reference
  2182. if ( !gamePakForOS[ BUILD_OS_ID ] ) {
  2183. common->Warning( "No game code pak reference found for the local OS" );
  2184. return false;
  2185. }
  2186. if ( !cvarSystem->GetCVarBool( "net_serverAllowServerMod" ) &&
  2187. gamePakChecksum != gamePakForOS[ BUILD_OS_ID ] ) {
  2188. common->Warning( "The current game code doesn't match pak files (net_serverAllowServerMod is off)" );
  2189. return false;
  2190. }
  2191. return true;
  2192. }
  2193. /*
  2194. =====================
  2195. idFileSystemLocal::GetPackForChecksum
  2196. =====================
  2197. */
  2198. pack_t* idFileSystemLocal::GetPackForChecksum( int checksum, bool searchAddons ) {
  2199. searchpath_t *search;
  2200. for ( search = searchPaths; search; search = search->next ) {
  2201. if ( !search->pack ) {
  2202. continue;
  2203. }
  2204. if ( search->pack->checksum == checksum ) {
  2205. return search->pack;
  2206. }
  2207. }
  2208. if ( searchAddons ) {
  2209. for ( search = addonPaks; search; search = search->next ) {
  2210. assert( search->pack && search->pack->addon );
  2211. if ( search->pack->checksum == checksum ) {
  2212. return search->pack;
  2213. }
  2214. }
  2215. }
  2216. return NULL;
  2217. }
  2218. /*
  2219. ===============
  2220. idFileSystemLocal::ValidateDownloadPakForChecksum
  2221. ===============
  2222. */
  2223. int idFileSystemLocal::ValidateDownloadPakForChecksum( int checksum, char path[ MAX_STRING_CHARS ], bool isBinary ) {
  2224. int i;
  2225. idStrList testList;
  2226. idStr name;
  2227. idStr relativePath;
  2228. bool pakBinary;
  2229. pack_t *pak = GetPackForChecksum( checksum );
  2230. if ( !pak ) {
  2231. return 0;
  2232. }
  2233. // validate this pak for a potential download
  2234. // ignore pak*.pk4 for download. those are reserved to distribution and cannot be downloaded
  2235. name = pak->pakFilename;
  2236. name.StripPath();
  2237. if ( strstr( name.c_str(), "pak" ) == name.c_str() ) {
  2238. common->DPrintf( "%s is not a donwloadable pak\n", pak->pakFilename.c_str() );
  2239. return 0;
  2240. }
  2241. // check the binary
  2242. // a pure server sets the binary flag when starting the game
  2243. assert( pak->binary != BINARY_UNKNOWN );
  2244. pakBinary = ( pak->binary == BINARY_YES ) ? true : false;
  2245. if ( isBinary != pakBinary ) {
  2246. common->DPrintf( "%s binary flag mismatch\n", pak->pakFilename.c_str() );
  2247. return 0;
  2248. }
  2249. // extract a path that includes the fs_game: != OSPathToRelativePath
  2250. testList.Append( fs_savepath.GetString() );
  2251. testList.Append( fs_devpath.GetString() );
  2252. testList.Append( fs_basepath.GetString() );
  2253. testList.Append( fs_cdpath.GetString() );
  2254. for ( i = 0; i < testList.Num(); i ++ ) {
  2255. if ( testList[ i ].Length() && !testList[ i ].Icmpn( pak->pakFilename, testList[ i ].Length() ) ) {
  2256. relativePath = pak->pakFilename.c_str() + testList[ i ].Length() + 1;
  2257. break;
  2258. }
  2259. }
  2260. if ( i == testList.Num() ) {
  2261. common->Warning( "idFileSystem::ValidateDownloadPak: failed to extract relative path for %s", pak->pakFilename.c_str() );
  2262. return 0;
  2263. }
  2264. idStr::Copynz( path, relativePath, MAX_STRING_CHARS );
  2265. return pak->length;
  2266. }
  2267. /*
  2268. =====================
  2269. idFileSystemLocal::ClearPureChecksums
  2270. =====================
  2271. */
  2272. void idFileSystemLocal::ClearPureChecksums( void ) {
  2273. common->DPrintf( "Cleared pure server lock\n" );
  2274. serverPaks.Clear();
  2275. }
  2276. /*
  2277. =====================
  2278. idFileSystemLocal::SetPureServerChecksums
  2279. set the pure paks according to what the server asks
  2280. if that's not possible, identify why and build an answer
  2281. can be:
  2282. loadedFileFromDir - some files were loaded from directories instead of paks (a restart in pure pak-only is required)
  2283. missing/wrong checksums - some pak files would need to be installed/updated (downloaded for instance)
  2284. some pak files currently referenced are not referenced by the server
  2285. wrong order - if the pak order doesn't match, means some stuff could have been loaded from somewhere else
  2286. server referenced files are prepended to the list if possible ( that doesn't break pureness )
  2287. DLL:
  2288. the checksum of the pak containing the DLL is maintained seperately, the server can send different replies by OS
  2289. =====================
  2290. */
  2291. fsPureReply_t idFileSystemLocal::SetPureServerChecksums( const int pureChecksums[ MAX_PURE_PAKS ], int _gamePakChecksum, int missingChecksums[ MAX_PURE_PAKS ], int *missingGamePakChecksum ) {
  2292. pack_t *pack;
  2293. int i, j, imissing;
  2294. bool success = true;
  2295. bool canPrepend = true;
  2296. char dllName[MAX_OSPATH];
  2297. int dllHash;
  2298. fileInPack_t * pakFile;
  2299. sys->DLL_GetFileName( "game", dllName, MAX_OSPATH );
  2300. dllHash = HashFileName( dllName );
  2301. imissing = 0;
  2302. missingChecksums[ 0 ] = 0;
  2303. assert( missingGamePakChecksum );
  2304. *missingGamePakChecksum = 0;
  2305. if ( pureChecksums[ 0 ] == 0 ) {
  2306. ClearPureChecksums();
  2307. return PURE_OK;
  2308. }
  2309. if ( !serverPaks.Num() ) {
  2310. // there was no pure lockdown yet - lock to what we already have
  2311. UpdatePureServerChecksums();
  2312. }
  2313. i = 0; j = 0;
  2314. while ( pureChecksums[ i ] ) {
  2315. if ( j < serverPaks.Num() && serverPaks[ j ]->checksum == pureChecksums[ i ] ) {
  2316. canPrepend = false; // once you start matching into the list there is no prepending anymore
  2317. i++; j++; // the pak is matched, is in the right order, continue..
  2318. } else {
  2319. pack = GetPackForChecksum( pureChecksums[ i ], true );
  2320. if ( pack && pack->addon && !pack->addon_search ) {
  2321. // this is an addon pack, and it's not on our current search list
  2322. // setting success to false meaning that a restart including this addon is required
  2323. if ( fs_debug.GetBool() ) {
  2324. common->Printf( "pak %s checksumed 0x%x is on addon list. Restart required.\n", pack->pakFilename.c_str(), pack->checksum );
  2325. }
  2326. success = false;
  2327. }
  2328. if ( pack && pack->isNew ) {
  2329. // that's a downloaded pack, we will need to restart
  2330. if ( fs_debug.GetBool() ) {
  2331. common->Printf( "pak %s checksumed 0x%x is a newly downloaded file. Restart required.\n", pack->pakFilename.c_str(), pack->checksum );
  2332. }
  2333. success = false;
  2334. }
  2335. if ( pack ) {
  2336. if ( canPrepend ) {
  2337. // we still have a chance
  2338. if ( fs_debug.GetBool() ) {
  2339. common->Printf( "prepend pak %s checksumed 0x%x at index %d\n", pack->pakFilename.c_str(), pack->checksum, j );
  2340. }
  2341. // NOTE: there is a light possibility this adds at the end of the list if UpdatePureServerChecksums didn't set anything
  2342. serverPaks.Insert( pack, j );
  2343. i++; j++; // continue..
  2344. } else {
  2345. success = false;
  2346. if ( fs_debug.GetBool() ) {
  2347. // verbose the situation
  2348. if ( serverPaks.Find( pack ) ) {
  2349. common->Printf( "pak %s checksumed 0x%x is in the pure list at wrong index. Current index is %d, found at %d\n", pack->pakFilename.c_str(), pack->checksum, j, serverPaks.FindIndex( pack ) );
  2350. } else {
  2351. common->Printf( "pak %s checksumed 0x%x can't be added to pure list because of search order\n", pack->pakFilename.c_str(), pack->checksum );
  2352. }
  2353. }
  2354. i++; // advance server checksums only
  2355. }
  2356. } else {
  2357. // didn't find a matching checksum
  2358. success = false;
  2359. missingChecksums[ imissing++ ] = pureChecksums[ i ];
  2360. missingChecksums[ imissing ] = 0;
  2361. if ( fs_debug.GetBool() ) {
  2362. common->Printf( "checksum not found - 0x%x\n", pureChecksums[ i ] );
  2363. }
  2364. i++; // advance the server checksums only
  2365. }
  2366. }
  2367. }
  2368. while ( j < serverPaks.Num() ) {
  2369. success = false; // just in case some extra pak files are referenced at the end of our local list
  2370. if ( fs_debug.GetBool() ) {
  2371. common->Printf( "pak %s checksumed 0x%x is an extra reference at the end of local pure list\n", serverPaks[ j ]->pakFilename.c_str(), serverPaks[ j ]->checksum );
  2372. }
  2373. j++;
  2374. }
  2375. // DLL checksuming
  2376. if ( !_gamePakChecksum ) {
  2377. // server doesn't have knowledge of code we can use ( OS issue )
  2378. return PURE_NODLL;
  2379. }
  2380. assert( gameDLLChecksum );
  2381. #if ID_FAKE_PURE
  2382. gamePakChecksum = _gamePakChecksum;
  2383. #endif
  2384. if ( _gamePakChecksum != gamePakChecksum ) {
  2385. // current DLL is wrong, search for a pak with the approriate checksum
  2386. // ( search all paks, the pure list is not relevant here )
  2387. pack = GetPackForChecksum( _gamePakChecksum );
  2388. if ( !pack ) {
  2389. if ( fs_debug.GetBool() ) {
  2390. common->Printf( "missing the game code pak ( 0x%x )\n", _gamePakChecksum );
  2391. }
  2392. // if there are other paks missing they have also been marked above
  2393. *missingGamePakChecksum = _gamePakChecksum;
  2394. return PURE_MISSING;
  2395. }
  2396. // if assets paks are missing, don't try any of the DLL restart / NODLL
  2397. if ( imissing ) {
  2398. return PURE_MISSING;
  2399. }
  2400. // we have a matching pak
  2401. if ( fs_debug.GetBool() ) {
  2402. common->Printf( "server's game code pak candidate is '%s' ( 0x%x )\n", pack->pakFilename.c_str(), pack->checksum );
  2403. }
  2404. // make sure there is a valid DLL for us
  2405. if ( pack->hashTable[ dllHash ] ) {
  2406. for ( pakFile = pack->hashTable[ dllHash ]; pakFile; pakFile = pakFile->next ) {
  2407. if ( !FilenameCompare( pakFile->name, dllName ) ) {
  2408. gamePakChecksum = _gamePakChecksum; // this will be used to extract the DLL in pure mode FindDLL
  2409. return PURE_RESTART;
  2410. }
  2411. }
  2412. }
  2413. common->Warning( "media is misconfigured. server claims pak '%s' ( 0x%x ) has media for us, but '%s' is not found\n", pack->pakFilename.c_str(), pack->checksum, dllName );
  2414. return PURE_NODLL;
  2415. }
  2416. // we reply to missing after DLL check so it can be part of the list
  2417. if ( imissing ) {
  2418. return PURE_MISSING;
  2419. }
  2420. // one last check
  2421. if ( loadedFileFromDir ) {
  2422. success = false;
  2423. if ( fs_debug.GetBool() ) {
  2424. common->Printf( "SetPureServerChecksums: there are files loaded from dir\n" );
  2425. }
  2426. }
  2427. return ( success ? PURE_OK : PURE_RESTART );
  2428. }
  2429. /*
  2430. =====================
  2431. idFileSystemLocal::GetPureServerChecksums
  2432. =====================
  2433. */
  2434. void idFileSystemLocal::GetPureServerChecksums( int checksums[ MAX_PURE_PAKS ], int OS, int *_gamePakChecksum ) {
  2435. int i;
  2436. for ( i = 0; i < serverPaks.Num(); i++ ) {
  2437. checksums[ i ] = serverPaks[ i ]->checksum;
  2438. }
  2439. checksums[ i ] = 0;
  2440. if ( _gamePakChecksum ) {
  2441. if ( OS >= 0 ) {
  2442. *_gamePakChecksum = gamePakForOS[ OS ];
  2443. } else {
  2444. *_gamePakChecksum = gamePakChecksum;
  2445. }
  2446. }
  2447. }
  2448. /*
  2449. =====================
  2450. idFileSystemLocal::SetRestartChecksums
  2451. =====================
  2452. */
  2453. void idFileSystemLocal::SetRestartChecksums( const int pureChecksums[ MAX_PURE_PAKS ], int gamePakChecksum ) {
  2454. int i;
  2455. pack_t *pack;
  2456. restartChecksums.Clear();
  2457. i = 0;
  2458. while ( pureChecksums[ i ] ) {
  2459. pack = GetPackForChecksum( pureChecksums[ i ], true );
  2460. if ( !pack ) {
  2461. common->FatalError( "SetRestartChecksums failed: no pak for checksum 0x%x\n", pureChecksums[i] );
  2462. }
  2463. if ( pack->addon && addonChecksums.FindIndex( pack->checksum ) < 0 ) {
  2464. // can't mark it pure if we're not even gonna search it :-)
  2465. addonChecksums.Append( pack->checksum );
  2466. }
  2467. restartChecksums.Append( pureChecksums[ i ] );
  2468. i++;
  2469. }
  2470. restartGamePakChecksum = gamePakChecksum;
  2471. }
  2472. /*
  2473. ================
  2474. idFileSystemLocal::Init
  2475. Called only at inital startup, not when the filesystem
  2476. is resetting due to a game change
  2477. ================
  2478. */
  2479. void idFileSystemLocal::Init( void ) {
  2480. // allow command line parms to override our defaults
  2481. // we have to specially handle this, because normal command
  2482. // line variable sets don't happen until after the filesystem
  2483. // has already been initialized
  2484. common->StartupVariable( "fs_basepath", false );
  2485. common->StartupVariable( "fs_savepath", false );
  2486. common->StartupVariable( "fs_cdpath", false );
  2487. common->StartupVariable( "fs_devpath", false );
  2488. common->StartupVariable( "fs_game", false );
  2489. common->StartupVariable( "fs_game_base", false );
  2490. common->StartupVariable( "fs_copyfiles", false );
  2491. common->StartupVariable( "fs_restrict", false );
  2492. common->StartupVariable( "fs_searchAddons", false );
  2493. #if !ID_ALLOW_D3XP
  2494. if ( fs_game.GetString()[0] && !idStr::Icmp( fs_game.GetString(), "d3xp" ) ) {
  2495. fs_game.SetString( NULL );
  2496. }
  2497. if ( fs_game_base.GetString()[0] && !idStr::Icmp( fs_game_base.GetString(), "d3xp" ) ) {
  2498. fs_game_base.SetString( NULL );
  2499. }
  2500. #endif
  2501. if ( fs_basepath.GetString()[0] == '\0' ) {
  2502. fs_basepath.SetString( Sys_DefaultBasePath() );
  2503. }
  2504. if ( fs_savepath.GetString()[0] == '\0' ) {
  2505. fs_savepath.SetString( Sys_DefaultSavePath() );
  2506. }
  2507. if ( fs_cdpath.GetString()[0] == '\0' ) {
  2508. fs_cdpath.SetString( Sys_DefaultCDPath() );
  2509. }
  2510. if ( fs_devpath.GetString()[0] == '\0' ) {
  2511. #ifdef WIN32
  2512. fs_devpath.SetString( fs_cdpath.GetString()[0] ? fs_cdpath.GetString() : fs_basepath.GetString() );
  2513. #else
  2514. fs_devpath.SetString( fs_savepath.GetString() );
  2515. #endif
  2516. }
  2517. // try to start up normally
  2518. Startup( );
  2519. // see if we are going to allow add-ons
  2520. SetRestrictions();
  2521. // spawn a thread to handle background file reads
  2522. StartBackgroundDownloadThread();
  2523. // if we can't find default.cfg, assume that the paths are
  2524. // busted and error out now, rather than getting an unreadable
  2525. // graphics screen when the font fails to load
  2526. // Dedicated servers can run with no outside files at all
  2527. if ( ReadFile( "default.cfg", NULL, NULL ) <= 0 ) {
  2528. common->FatalError( "Couldn't load default.cfg" );
  2529. }
  2530. }
  2531. /*
  2532. ================
  2533. idFileSystemLocal::Restart
  2534. ================
  2535. */
  2536. void idFileSystemLocal::Restart( void ) {
  2537. // free anything we currently have loaded
  2538. Shutdown( true );
  2539. Startup( );
  2540. // see if we are going to allow add-ons
  2541. SetRestrictions();
  2542. // if we can't find default.cfg, assume that the paths are
  2543. // busted and error out now, rather than getting an unreadable
  2544. // graphics screen when the font fails to load
  2545. if ( ReadFile( "default.cfg", NULL, NULL ) <= 0 ) {
  2546. common->FatalError( "Couldn't load default.cfg" );
  2547. }
  2548. }
  2549. /*
  2550. ================
  2551. idFileSystemLocal::Shutdown
  2552. Frees all resources and closes all files
  2553. ================
  2554. */
  2555. void idFileSystemLocal::Shutdown( bool reloading ) {
  2556. searchpath_t *sp, *next, *loop;
  2557. gameFolder.Clear();
  2558. serverPaks.Clear();
  2559. if ( !reloading ) {
  2560. restartChecksums.Clear();
  2561. addonChecksums.Clear();
  2562. }
  2563. loadedFileFromDir = false;
  2564. gameDLLChecksum = 0;
  2565. gamePakChecksum = 0;
  2566. ClearDirCache();
  2567. // free everything - loop through searchPaths and addonPaks
  2568. for ( loop = searchPaths; loop; loop == searchPaths ? loop = addonPaks : loop = NULL ) {
  2569. for ( sp = loop; sp; sp = next ) {
  2570. next = sp->next;
  2571. if ( sp->pack ) {
  2572. unzClose( sp->pack->handle );
  2573. delete [] sp->pack->buildBuffer;
  2574. if ( sp->pack->addon_info ) {
  2575. sp->pack->addon_info->mapDecls.DeleteContents( true );
  2576. delete sp->pack->addon_info;
  2577. }
  2578. delete sp->pack;
  2579. }
  2580. if ( sp->dir ) {
  2581. delete sp->dir;
  2582. }
  2583. delete sp;
  2584. }
  2585. }
  2586. // any FS_ calls will now be an error until reinitialized
  2587. searchPaths = NULL;
  2588. addonPaks = NULL;
  2589. cmdSystem->RemoveCommand( "path" );
  2590. cmdSystem->RemoveCommand( "dir" );
  2591. cmdSystem->RemoveCommand( "dirtree" );
  2592. cmdSystem->RemoveCommand( "touchFile" );
  2593. mapDict.Clear();
  2594. }
  2595. /*
  2596. ================
  2597. idFileSystemLocal::IsInitialized
  2598. ================
  2599. */
  2600. bool idFileSystemLocal::IsInitialized( void ) const {
  2601. return ( searchPaths != NULL );
  2602. }
  2603. /*
  2604. =================================================================================
  2605. Opening files
  2606. =================================================================================
  2607. */
  2608. /*
  2609. ===========
  2610. idFileSystemLocal::FileAllowedFromDir
  2611. ===========
  2612. */
  2613. bool idFileSystemLocal::FileAllowedFromDir( const char *path ) {
  2614. unsigned int l;
  2615. l = strlen( path );
  2616. if ( !strcmp( path + l - 4, ".cfg" ) // for config files
  2617. || !strcmp( path + l - 4, ".dat" ) // for journal files
  2618. || !strcmp( path + l - 4, ".dll" ) // dynamic modules are handled a different way for pure
  2619. || !strcmp( path + l - 3, ".so" )
  2620. || ( l > 6 && !strcmp( path + l - 6, ".dylib" ) )
  2621. || ( l > 10 && !strcmp( path + l - 10, ".scriptcfg" ) ) // configuration script, such as map cycle
  2622. #if ID_PURE_ALLOWDDS
  2623. || !strcmp( path + l - 4, ".dds" )
  2624. #endif
  2625. ) {
  2626. // note: cd and xp keys, as well as config.spec are opened through an explicit OS path and don't hit this
  2627. return true;
  2628. }
  2629. // savegames
  2630. if ( strstr( path, "savegames" ) == path &&
  2631. ( !strcmp( path + l - 4, ".tga" ) || !strcmp( path + l -4, ".txt" ) || !strcmp( path + l - 5, ".save" ) ) ) {
  2632. return true;
  2633. }
  2634. // screen shots
  2635. if ( strstr( path, "screenshots" ) == path && !strcmp( path + l - 4, ".tga" ) ) {
  2636. return true;
  2637. }
  2638. // objective tgas
  2639. if ( strstr( path, "maps/game" ) == path &&
  2640. !strcmp( path + l - 4, ".tga" ) ) {
  2641. return true;
  2642. }
  2643. // splash screens extracted from addons
  2644. if ( strstr( path, "guis/assets/splash/addon" ) == path &&
  2645. !strcmp( path + l -4, ".tga" ) ) {
  2646. return true;
  2647. }
  2648. return false;
  2649. }
  2650. /*
  2651. ===========
  2652. idFileSystemLocal::GetPackStatus
  2653. ===========
  2654. */
  2655. pureStatus_t idFileSystemLocal::GetPackStatus( pack_t *pak ) {
  2656. int i, l, hashindex;
  2657. fileInPack_t *file;
  2658. bool abrt;
  2659. idStr name;
  2660. if ( pak->pureStatus != PURE_UNKNOWN ) {
  2661. return pak->pureStatus;
  2662. }
  2663. // check content for PURE_NEVER
  2664. i = 0;
  2665. file = pak->buildBuffer;
  2666. for ( hashindex = 0; hashindex < FILE_HASH_SIZE; hashindex++ ) {
  2667. abrt = false;
  2668. file = pak->hashTable[ hashindex ];
  2669. while ( file ) {
  2670. abrt = true;
  2671. l = file->name.Length();
  2672. for ( int j = 0; pureExclusions[j].func != NULL; j++ ) {
  2673. if ( pureExclusions[j].func( pureExclusions[j], l, file->name ) ) {
  2674. abrt = false;
  2675. break;
  2676. }
  2677. }
  2678. if ( abrt ) {
  2679. common->DPrintf( "pak '%s' candidate for pure: '%s'\n", pak->pakFilename.c_str(), file->name.c_str() );
  2680. break;
  2681. }
  2682. file = file->next;
  2683. i++;
  2684. }
  2685. if ( abrt ) {
  2686. break;
  2687. }
  2688. }
  2689. if ( i == pak->numfiles ) {
  2690. pak->pureStatus = PURE_NEVER;
  2691. return PURE_NEVER;
  2692. }
  2693. // check pak name for PURE_ALWAYS
  2694. pak->pakFilename.ExtractFileName( name );
  2695. if ( !name.IcmpPrefixPath( "pak" ) ) {
  2696. pak->pureStatus = PURE_ALWAYS;
  2697. return PURE_ALWAYS;
  2698. }
  2699. pak->pureStatus = PURE_NEUTRAL;
  2700. return PURE_NEUTRAL;
  2701. }
  2702. /*
  2703. ===========
  2704. idFileSystemLocal::ReadFileFromZip
  2705. ===========
  2706. */
  2707. idFile_InZip * idFileSystemLocal::ReadFileFromZip( pack_t *pak, fileInPack_t *pakFile, const char *relativePath ) {
  2708. unz_s * zfi;
  2709. FILE * fp;
  2710. idFile_InZip *file = new idFile_InZip();
  2711. // open a new file on the pakfile
  2712. file->z = unzReOpen( pak->pakFilename, pak->handle );
  2713. if ( file->z == NULL ) {
  2714. common->FatalError( "Couldn't reopen %s", pak->pakFilename.c_str() );
  2715. }
  2716. file->name = relativePath;
  2717. file->fullPath = pak->pakFilename + "/" + relativePath;
  2718. zfi = (unz_s *)file->z;
  2719. // in case the file was new
  2720. fp = zfi->file;
  2721. // set the file position in the zip file (also sets the current file info)
  2722. unzSetCurrentFileInfoPosition( pak->handle, pakFile->pos );
  2723. // copy the file info into the unzip structure
  2724. memcpy( zfi, pak->handle, sizeof(unz_s) );
  2725. // we copy this back into the structure
  2726. zfi->file = fp;
  2727. // open the file in the zip
  2728. unzOpenCurrentFile( file->z );
  2729. file->zipFilePos = pakFile->pos;
  2730. file->fileSize = zfi->cur_file_info.uncompressed_size;
  2731. return file;
  2732. }
  2733. /*
  2734. ===========
  2735. idFileSystemLocal::OpenFileReadFlags
  2736. Finds the file in the search path, following search flag recommendations
  2737. Returns filesize and an open FILE pointer.
  2738. Used for streaming data out of either a
  2739. separate file or a ZIP file.
  2740. ===========
  2741. */
  2742. idFile *idFileSystemLocal::OpenFileReadFlags( const char *relativePath, int searchFlags, pack_t **foundInPak, bool allowCopyFiles, const char* gamedir ) {
  2743. searchpath_t * search;
  2744. idStr netpath;
  2745. pack_t * pak;
  2746. fileInPack_t * pakFile;
  2747. directory_t * dir;
  2748. long hash;
  2749. FILE * fp;
  2750. if ( !searchPaths ) {
  2751. common->FatalError( "Filesystem call made without initialization\n" );
  2752. }
  2753. if ( !relativePath ) {
  2754. common->FatalError( "idFileSystemLocal::OpenFileRead: NULL 'relativePath' parameter passed\n" );
  2755. }
  2756. if ( foundInPak ) {
  2757. *foundInPak = NULL;
  2758. }
  2759. // qpaths are not supposed to have a leading slash
  2760. if ( relativePath[0] == '/' || relativePath[0] == '\\' ) {
  2761. relativePath++;
  2762. }
  2763. // make absolutely sure that it can't back up the path.
  2764. // The searchpaths do guarantee that something will always
  2765. // be prepended, so we don't need to worry about "c:" or "//limbo"
  2766. if ( strstr( relativePath, ".." ) || strstr( relativePath, "::" ) ) {
  2767. return NULL;
  2768. }
  2769. // edge case
  2770. if ( relativePath[0] == '\0' ) {
  2771. return NULL;
  2772. }
  2773. // make sure the doomkey file is only readable by game at initialization
  2774. // any other time the key should only be accessed in memory using the provided functions
  2775. if( common->IsInitialized() && ( idStr::Icmp( relativePath, CDKEY_FILE ) == 0 || idStr::Icmp( relativePath, XPKEY_FILE ) == 0 ) ) {
  2776. return NULL;
  2777. }
  2778. //
  2779. // search through the path, one element at a time
  2780. //
  2781. hash = HashFileName( relativePath );
  2782. for ( search = searchPaths; search; search = search->next ) {
  2783. if ( search->dir && ( searchFlags & FSFLAG_SEARCH_DIRS ) ) {
  2784. // check a file in the directory tree
  2785. // if we are running restricted, the only files we
  2786. // will allow to come from the directory are .cfg files
  2787. if ( fs_restrict.GetBool() || serverPaks.Num() ) {
  2788. if ( !FileAllowedFromDir( relativePath ) ) {
  2789. continue;
  2790. }
  2791. }
  2792. dir = search->dir;
  2793. if(gamedir && strlen(gamedir)) {
  2794. if(dir->gamedir != gamedir) {
  2795. continue;
  2796. }
  2797. }
  2798. netpath = BuildOSPath( dir->path, dir->gamedir, relativePath );
  2799. fp = OpenOSFileCorrectName( netpath, "rb" );
  2800. if ( !fp ) {
  2801. continue;
  2802. }
  2803. idFile_Permanent *file = new idFile_Permanent();
  2804. file->o = fp;
  2805. file->name = relativePath;
  2806. file->fullPath = netpath;
  2807. file->mode = ( 1 << FS_READ );
  2808. file->fileSize = DirectFileLength( file->o );
  2809. if ( fs_debug.GetInteger() ) {
  2810. common->Printf( "idFileSystem::OpenFileRead: %s (found in '%s/%s')\n", relativePath, dir->path.c_str(), dir->gamedir.c_str() );
  2811. }
  2812. if ( !loadedFileFromDir && !FileAllowedFromDir( relativePath ) ) {
  2813. if ( restartChecksums.Num() ) {
  2814. common->FatalError( "'%s' loaded from directory: Failed to restart with pure mode restrictions for server connect", relativePath );
  2815. }
  2816. common->DPrintf( "filesystem: switching to pure mode will require a restart. '%s' loaded from directory.\n", relativePath );
  2817. loadedFileFromDir = true;
  2818. }
  2819. // if fs_copyfiles is set
  2820. if ( allowCopyFiles && fs_copyfiles.GetInteger() ) {
  2821. idStr copypath;
  2822. idStr name;
  2823. copypath = BuildOSPath( fs_savepath.GetString(), dir->gamedir, relativePath );
  2824. netpath.ExtractFileName( name );
  2825. copypath.StripFilename( );
  2826. copypath += PATHSEPERATOR_STR;
  2827. copypath += name;
  2828. bool isFromCDPath = !dir->path.Cmp( fs_cdpath.GetString() );
  2829. bool isFromSavePath = !dir->path.Cmp( fs_savepath.GetString() );
  2830. bool isFromBasePath = !dir->path.Cmp( fs_basepath.GetString() );
  2831. switch ( fs_copyfiles.GetInteger() ) {
  2832. case 1:
  2833. // copy from cd path only
  2834. if ( isFromCDPath ) {
  2835. CopyFile( netpath, copypath );
  2836. }
  2837. break;
  2838. case 2:
  2839. // from cd path + timestamps
  2840. if ( isFromCDPath ) {
  2841. CopyFile( netpath, copypath );
  2842. } else if ( isFromSavePath || isFromBasePath ) {
  2843. idStr sourcepath;
  2844. sourcepath = BuildOSPath( fs_cdpath.GetString(), dir->gamedir, relativePath );
  2845. FILE *f1 = OpenOSFile( sourcepath, "r" );
  2846. if ( f1 ) {
  2847. ID_TIME_T t1 = Sys_FileTimeStamp( f1 );
  2848. fclose( f1 );
  2849. FILE *f2 = OpenOSFile( copypath, "r" );
  2850. if ( f2 ) {
  2851. ID_TIME_T t2 = Sys_FileTimeStamp( f2 );
  2852. fclose( f2 );
  2853. if ( t1 > t2 ) {
  2854. CopyFile( sourcepath, copypath );
  2855. }
  2856. }
  2857. }
  2858. }
  2859. break;
  2860. case 3:
  2861. if ( isFromCDPath || isFromBasePath ) {
  2862. CopyFile( netpath, copypath );
  2863. }
  2864. break;
  2865. case 4:
  2866. if ( isFromCDPath && !isFromBasePath ) {
  2867. CopyFile( netpath, copypath );
  2868. }
  2869. break;
  2870. }
  2871. }
  2872. return file;
  2873. } else if ( search->pack && ( searchFlags & FSFLAG_SEARCH_PAKS ) ) {
  2874. if ( !search->pack->hashTable[hash] ) {
  2875. continue;
  2876. }
  2877. // disregard if it doesn't match one of the allowed pure pak files
  2878. if ( serverPaks.Num() ) {
  2879. GetPackStatus( search->pack );
  2880. if ( search->pack->pureStatus != PURE_NEVER && !serverPaks.Find( search->pack ) ) {
  2881. continue; // not on the pure server pak list
  2882. }
  2883. }
  2884. // look through all the pak file elements
  2885. pak = search->pack;
  2886. if ( searchFlags & FSFLAG_BINARY_ONLY ) {
  2887. // make sure this pak is tagged as a binary file
  2888. if ( pak->binary == BINARY_UNKNOWN ) {
  2889. int confHash;
  2890. fileInPack_t *pakFile;
  2891. confHash = HashFileName( BINARY_CONFIG );
  2892. pak->binary = BINARY_NO;
  2893. for ( pakFile = search->pack->hashTable[confHash]; pakFile; pakFile = pakFile->next ) {
  2894. if ( !FilenameCompare( pakFile->name, BINARY_CONFIG ) ) {
  2895. pak->binary = BINARY_YES;
  2896. break;
  2897. }
  2898. }
  2899. }
  2900. if ( pak->binary == BINARY_NO ) {
  2901. continue; // not a binary pak, skip
  2902. }
  2903. }
  2904. for ( pakFile = pak->hashTable[hash]; pakFile; pakFile = pakFile->next ) {
  2905. // case and separator insensitive comparisons
  2906. if ( !FilenameCompare( pakFile->name, relativePath ) ) {
  2907. idFile_InZip *file = ReadFileFromZip( pak, pakFile, relativePath );
  2908. if ( foundInPak ) {
  2909. *foundInPak = pak;
  2910. }
  2911. if ( !pak->referenced && !( searchFlags & FSFLAG_PURE_NOREF ) ) {
  2912. // mark this pak referenced
  2913. if ( fs_debug.GetInteger( ) ) {
  2914. common->Printf( "idFileSystem::OpenFileRead: %s -> adding %s to referenced paks\n", relativePath, pak->pakFilename.c_str() );
  2915. }
  2916. pak->referenced = true;
  2917. }
  2918. if ( fs_debug.GetInteger( ) ) {
  2919. common->Printf( "idFileSystem::OpenFileRead: %s (found in '%s')\n", relativePath, pak->pakFilename.c_str() );
  2920. }
  2921. return file;
  2922. }
  2923. }
  2924. }
  2925. }
  2926. if ( searchFlags & FSFLAG_SEARCH_ADDONS ) {
  2927. for ( search = addonPaks; search; search = search->next ) {
  2928. assert( search->pack );
  2929. fileInPack_t *pakFile;
  2930. pak = search->pack;
  2931. for ( pakFile = pak->hashTable[hash]; pakFile; pakFile = pakFile->next ) {
  2932. if ( !FilenameCompare( pakFile->name, relativePath ) ) {
  2933. idFile_InZip *file = ReadFileFromZip( pak, pakFile, relativePath );
  2934. if ( foundInPak ) {
  2935. *foundInPak = pak;
  2936. }
  2937. // we don't toggle pure on paks found in addons - they can't be used without a reloadEngine anyway
  2938. if ( fs_debug.GetInteger( ) ) {
  2939. common->Printf( "idFileSystem::OpenFileRead: %s (found in addon pk4 '%s')\n", relativePath, search->pack->pakFilename.c_str() );
  2940. }
  2941. return file;
  2942. }
  2943. }
  2944. }
  2945. }
  2946. if ( fs_debug.GetInteger( ) ) {
  2947. common->Printf( "Can't find %s\n", relativePath );
  2948. }
  2949. return NULL;
  2950. }
  2951. /*
  2952. ===========
  2953. idFileSystemLocal::OpenFileRead
  2954. ===========
  2955. */
  2956. idFile *idFileSystemLocal::OpenFileRead( const char *relativePath, bool allowCopyFiles, const char* gamedir ) {
  2957. return OpenFileReadFlags( relativePath, FSFLAG_SEARCH_DIRS | FSFLAG_SEARCH_PAKS, NULL, allowCopyFiles, gamedir );
  2958. }
  2959. /*
  2960. ===========
  2961. idFileSystemLocal::OpenFileWrite
  2962. ===========
  2963. */
  2964. idFile *idFileSystemLocal::OpenFileWrite( const char *relativePath, const char *basePath ) {
  2965. const char *path;
  2966. idStr OSpath;
  2967. idFile_Permanent *f;
  2968. if ( !searchPaths ) {
  2969. common->FatalError( "Filesystem call made without initialization\n" );
  2970. }
  2971. path = cvarSystem->GetCVarString( basePath );
  2972. if ( !path[0] ) {
  2973. path = fs_savepath.GetString();
  2974. }
  2975. OSpath = BuildOSPath( path, gameFolder, relativePath );
  2976. if ( fs_debug.GetInteger() ) {
  2977. common->Printf( "idFileSystem::OpenFileWrite: %s\n", OSpath.c_str() );
  2978. }
  2979. // if the dir we are writing to is in our current list, it will be outdated
  2980. // so just flush everything
  2981. ClearDirCache();
  2982. common->DPrintf( "writing to: %s\n", OSpath.c_str() );
  2983. CreateOSPath( OSpath );
  2984. f = new idFile_Permanent();
  2985. f->o = OpenOSFile( OSpath, "wb" );
  2986. if ( !f->o ) {
  2987. delete f;
  2988. return NULL;
  2989. }
  2990. f->name = relativePath;
  2991. f->fullPath = OSpath;
  2992. f->mode = ( 1 << FS_WRITE );
  2993. f->handleSync = false;
  2994. f->fileSize = 0;
  2995. return f;
  2996. }
  2997. /*
  2998. ===========
  2999. idFileSystemLocal::OpenExplicitFileRead
  3000. ===========
  3001. */
  3002. idFile *idFileSystemLocal::OpenExplicitFileRead( const char *OSPath ) {
  3003. idFile_Permanent *f;
  3004. if ( !searchPaths ) {
  3005. common->FatalError( "Filesystem call made without initialization\n" );
  3006. }
  3007. if ( fs_debug.GetInteger() ) {
  3008. common->Printf( "idFileSystem::OpenExplicitFileRead: %s\n", OSPath );
  3009. }
  3010. common->DPrintf( "idFileSystem::OpenExplicitFileRead - reading from: %s\n", OSPath );
  3011. f = new idFile_Permanent();
  3012. f->o = OpenOSFile( OSPath, "rb" );
  3013. if ( !f->o ) {
  3014. delete f;
  3015. return NULL;
  3016. }
  3017. f->name = OSPath;
  3018. f->fullPath = OSPath;
  3019. f->mode = ( 1 << FS_READ );
  3020. f->handleSync = false;
  3021. f->fileSize = DirectFileLength( f->o );
  3022. return f;
  3023. }
  3024. /*
  3025. ===========
  3026. idFileSystemLocal::OpenExplicitFileWrite
  3027. ===========
  3028. */
  3029. idFile *idFileSystemLocal::OpenExplicitFileWrite( const char *OSPath ) {
  3030. idFile_Permanent *f;
  3031. if ( !searchPaths ) {
  3032. common->FatalError( "Filesystem call made without initialization\n" );
  3033. }
  3034. if ( fs_debug.GetInteger() ) {
  3035. common->Printf( "idFileSystem::OpenExplicitFileWrite: %s\n", OSPath );
  3036. }
  3037. common->DPrintf( "writing to: %s\n", OSPath );
  3038. CreateOSPath( OSPath );
  3039. f = new idFile_Permanent();
  3040. f->o = OpenOSFile( OSPath, "wb" );
  3041. if ( !f->o ) {
  3042. delete f;
  3043. return NULL;
  3044. }
  3045. f->name = OSPath;
  3046. f->fullPath = OSPath;
  3047. f->mode = ( 1 << FS_WRITE );
  3048. f->handleSync = false;
  3049. f->fileSize = 0;
  3050. return f;
  3051. }
  3052. /*
  3053. ===========
  3054. idFileSystemLocal::OpenFileAppend
  3055. ===========
  3056. */
  3057. idFile *idFileSystemLocal::OpenFileAppend( const char *relativePath, bool sync, const char *basePath ) {
  3058. const char *path;
  3059. idStr OSpath;
  3060. idFile_Permanent *f;
  3061. if ( !searchPaths ) {
  3062. common->FatalError( "Filesystem call made without initialization\n" );
  3063. }
  3064. path = cvarSystem->GetCVarString( basePath );
  3065. if ( !path[0] ) {
  3066. path = fs_savepath.GetString();
  3067. }
  3068. OSpath = BuildOSPath( path, gameFolder, relativePath );
  3069. CreateOSPath( OSpath );
  3070. if ( fs_debug.GetInteger() ) {
  3071. common->Printf( "idFileSystem::OpenFileAppend: %s\n", OSpath.c_str() );
  3072. }
  3073. f = new idFile_Permanent();
  3074. f->o = OpenOSFile( OSpath, "ab" );
  3075. if ( !f->o ) {
  3076. delete f;
  3077. return NULL;
  3078. }
  3079. f->name = relativePath;
  3080. f->fullPath = OSpath;
  3081. f->mode = ( 1 << FS_WRITE ) + ( 1 << FS_APPEND );
  3082. f->handleSync = sync;
  3083. f->fileSize = DirectFileLength( f->o );
  3084. return f;
  3085. }
  3086. /*
  3087. ================
  3088. idFileSystemLocal::OpenFileByMode
  3089. ================
  3090. */
  3091. idFile *idFileSystemLocal::OpenFileByMode( const char *relativePath, fsMode_t mode ) {
  3092. if ( mode == FS_READ ) {
  3093. return OpenFileRead( relativePath );
  3094. }
  3095. if ( mode == FS_WRITE ) {
  3096. return OpenFileWrite( relativePath );
  3097. }
  3098. if ( mode == FS_APPEND ) {
  3099. return OpenFileAppend( relativePath, true );
  3100. }
  3101. common->FatalError( "idFileSystemLocal::OpenFileByMode: bad mode" );
  3102. return NULL;
  3103. }
  3104. /*
  3105. ==============
  3106. idFileSystemLocal::CloseFile
  3107. ==============
  3108. */
  3109. void idFileSystemLocal::CloseFile( idFile *f ) {
  3110. if ( !searchPaths ) {
  3111. common->FatalError( "Filesystem call made without initialization\n" );
  3112. }
  3113. delete f;
  3114. }
  3115. /*
  3116. =================================================================================
  3117. back ground loading
  3118. =================================================================================
  3119. */
  3120. /*
  3121. =================
  3122. idFileSystemLocal::CurlWriteFunction
  3123. =================
  3124. */
  3125. size_t idFileSystemLocal::CurlWriteFunction( void *ptr, size_t size, size_t nmemb, void *stream ) {
  3126. backgroundDownload_t *bgl = (backgroundDownload_t *)stream;
  3127. if ( !bgl->f ) {
  3128. return size * nmemb;
  3129. }
  3130. #ifdef _WIN32
  3131. return _write( static_cast<idFile_Permanent*>(bgl->f)->GetFilePtr()->_file, ptr, size * nmemb );
  3132. #else
  3133. return fwrite( ptr, size, nmemb, static_cast<idFile_Permanent*>(bgl->f)->GetFilePtr() );
  3134. #endif
  3135. }
  3136. /*
  3137. =================
  3138. idFileSystemLocal::CurlProgressFunction
  3139. =================
  3140. */
  3141. int idFileSystemLocal::CurlProgressFunction( void *clientp, double dltotal, double dlnow, double ultotal, double ulnow ) {
  3142. backgroundDownload_t *bgl = (backgroundDownload_t *)clientp;
  3143. if ( bgl->url.status == DL_ABORTING ) {
  3144. return 1;
  3145. }
  3146. bgl->url.dltotal = dltotal;
  3147. bgl->url.dlnow = dlnow;
  3148. return 0;
  3149. }
  3150. /*
  3151. ===================
  3152. BackgroundDownload
  3153. Reads part of a file from a background thread.
  3154. ===================
  3155. */
  3156. dword BackgroundDownloadThread( void *parms ) {
  3157. while( 1 ) {
  3158. Sys_EnterCriticalSection();
  3159. backgroundDownload_t *bgl = fileSystemLocal.backgroundDownloads;
  3160. if ( !bgl ) {
  3161. Sys_LeaveCriticalSection();
  3162. Sys_WaitForEvent();
  3163. continue;
  3164. }
  3165. // remove this from the list
  3166. fileSystemLocal.backgroundDownloads = bgl->next;
  3167. Sys_LeaveCriticalSection();
  3168. bgl->next = NULL;
  3169. if ( bgl->opcode == DLTYPE_FILE ) {
  3170. // use the low level read function, because fread may allocate memory
  3171. #if defined(WIN32)
  3172. _read( static_cast<idFile_Permanent*>(bgl->f)->GetFilePtr()->_file, bgl->file.buffer, bgl->file.length );
  3173. #else
  3174. fread( bgl->file.buffer, bgl->file.length, 1, static_cast<idFile_Permanent*>(bgl->f)->GetFilePtr() );
  3175. #endif
  3176. bgl->completed = true;
  3177. } else {
  3178. #if ID_ENABLE_CURL
  3179. // DLTYPE_URL
  3180. // use a local buffer for curl error since the size define is local
  3181. char error_buf[ CURL_ERROR_SIZE ];
  3182. bgl->url.dlerror[ 0 ] = '\0';
  3183. CURL *session = curl_easy_init();
  3184. CURLcode ret;
  3185. if ( !session ) {
  3186. bgl->url.dlstatus = CURLE_FAILED_INIT;
  3187. bgl->url.status = DL_FAILED;
  3188. bgl->completed = true;
  3189. continue;
  3190. }
  3191. ret = curl_easy_setopt( session, CURLOPT_ERRORBUFFER, error_buf );
  3192. if ( ret ) {
  3193. bgl->url.dlstatus = ret;
  3194. bgl->url.status = DL_FAILED;
  3195. bgl->completed = true;
  3196. continue;
  3197. }
  3198. ret = curl_easy_setopt( session, CURLOPT_URL, bgl->url.url.c_str() );
  3199. if ( ret ) {
  3200. bgl->url.dlstatus = ret;
  3201. bgl->url.status = DL_FAILED;
  3202. bgl->completed = true;
  3203. continue;
  3204. }
  3205. ret = curl_easy_setopt( session, CURLOPT_FAILONERROR, 1 );
  3206. if ( ret ) {
  3207. bgl->url.dlstatus = ret;
  3208. bgl->url.status = DL_FAILED;
  3209. bgl->completed = true;
  3210. continue;
  3211. }
  3212. ret = curl_easy_setopt( session, CURLOPT_WRITEFUNCTION, idFileSystemLocal::CurlWriteFunction );
  3213. if ( ret ) {
  3214. bgl->url.dlstatus = ret;
  3215. bgl->url.status = DL_FAILED;
  3216. bgl->completed = true;
  3217. continue;
  3218. }
  3219. ret = curl_easy_setopt( session, CURLOPT_WRITEDATA, bgl );
  3220. if ( ret ) {
  3221. bgl->url.dlstatus = ret;
  3222. bgl->url.status = DL_FAILED;
  3223. bgl->completed = true;
  3224. continue;
  3225. }
  3226. ret = curl_easy_setopt( session, CURLOPT_NOPROGRESS, 0 );
  3227. if ( ret ) {
  3228. bgl->url.dlstatus = ret;
  3229. bgl->url.status = DL_FAILED;
  3230. bgl->completed = true;
  3231. continue;
  3232. }
  3233. ret = curl_easy_setopt( session, CURLOPT_PROGRESSFUNCTION, idFileSystemLocal::CurlProgressFunction );
  3234. if ( ret ) {
  3235. bgl->url.dlstatus = ret;
  3236. bgl->url.status = DL_FAILED;
  3237. bgl->completed = true;
  3238. continue;
  3239. }
  3240. ret = curl_easy_setopt( session, CURLOPT_PROGRESSDATA, bgl );
  3241. if ( ret ) {
  3242. bgl->url.dlstatus = ret;
  3243. bgl->url.status = DL_FAILED;
  3244. bgl->completed = true;
  3245. continue;
  3246. }
  3247. bgl->url.dlnow = 0;
  3248. bgl->url.dltotal = 0;
  3249. bgl->url.status = DL_INPROGRESS;
  3250. ret = curl_easy_perform( session );
  3251. if ( ret ) {
  3252. Sys_Printf( "curl_easy_perform failed: %s\n", error_buf );
  3253. idStr::Copynz( bgl->url.dlerror, error_buf, MAX_STRING_CHARS );
  3254. bgl->url.dlstatus = ret;
  3255. bgl->url.status = DL_FAILED;
  3256. bgl->completed = true;
  3257. continue;
  3258. }
  3259. bgl->url.status = DL_DONE;
  3260. bgl->completed = true;
  3261. #else
  3262. bgl->url.status = DL_FAILED;
  3263. bgl->completed = true;
  3264. #endif
  3265. }
  3266. }
  3267. return 0;
  3268. }
  3269. /*
  3270. =================
  3271. idFileSystemLocal::StartBackgroundReadThread
  3272. =================
  3273. */
  3274. void idFileSystemLocal::StartBackgroundDownloadThread() {
  3275. if ( !backgroundThread.threadHandle ) {
  3276. Sys_CreateThread( (xthread_t)BackgroundDownloadThread, NULL, THREAD_NORMAL, backgroundThread, "backgroundDownload", g_threads, &g_thread_count );
  3277. if ( !backgroundThread.threadHandle ) {
  3278. common->Warning( "idFileSystemLocal::StartBackgroundDownloadThread: failed" );
  3279. }
  3280. } else {
  3281. common->Printf( "background thread already running\n" );
  3282. }
  3283. }
  3284. /*
  3285. =================
  3286. idFileSystemLocal::BackgroundDownload
  3287. =================
  3288. */
  3289. void idFileSystemLocal::BackgroundDownload( backgroundDownload_t *bgl ) {
  3290. if ( bgl->opcode == DLTYPE_FILE ) {
  3291. if ( dynamic_cast<idFile_Permanent *>(bgl->f) ) {
  3292. // add the bgl to the background download list
  3293. Sys_EnterCriticalSection();
  3294. bgl->next = backgroundDownloads;
  3295. backgroundDownloads = bgl;
  3296. Sys_TriggerEvent();
  3297. Sys_LeaveCriticalSection();
  3298. } else {
  3299. // read zipped file directly
  3300. bgl->f->Seek( bgl->file.position, FS_SEEK_SET );
  3301. bgl->f->Read( bgl->file.buffer, bgl->file.length );
  3302. bgl->completed = true;
  3303. }
  3304. } else {
  3305. Sys_EnterCriticalSection();
  3306. bgl->next = backgroundDownloads;
  3307. backgroundDownloads = bgl;
  3308. Sys_TriggerEvent();
  3309. Sys_LeaveCriticalSection();
  3310. }
  3311. }
  3312. /*
  3313. =================
  3314. idFileSystemLocal::PerformingCopyFiles
  3315. =================
  3316. */
  3317. bool idFileSystemLocal::PerformingCopyFiles( void ) const {
  3318. return fs_copyfiles.GetInteger() > 0;
  3319. }
  3320. /*
  3321. =================
  3322. idFileSystemLocal::FindPakForFileChecksum
  3323. =================
  3324. */
  3325. pack_t *idFileSystemLocal::FindPakForFileChecksum( const char *relativePath, int findChecksum, bool bReference ) {
  3326. searchpath_t *search;
  3327. pack_t *pak;
  3328. fileInPack_t *pakFile;
  3329. int hash;
  3330. assert( !serverPaks.Num() );
  3331. hash = HashFileName( relativePath );
  3332. for ( search = searchPaths; search; search = search->next ) {
  3333. if ( search->pack && search->pack->hashTable[ hash ] ) {
  3334. pak = search->pack;
  3335. for ( pakFile = pak->hashTable[ hash ]; pakFile; pakFile = pakFile->next ) {
  3336. if ( !FilenameCompare( pakFile->name, relativePath ) ) {
  3337. idFile_InZip *file = ReadFileFromZip( pak, pakFile, relativePath );
  3338. if ( findChecksum == GetFileChecksum( file ) ) {
  3339. if ( fs_debug.GetBool() ) {
  3340. common->Printf( "found '%s' with checksum 0x%x in pak '%s'\n", relativePath, findChecksum, pak->pakFilename.c_str() );
  3341. }
  3342. if ( bReference ) {
  3343. pak->referenced = true;
  3344. // FIXME: use dependencies for pak references
  3345. }
  3346. CloseFile( file );
  3347. return pak;
  3348. } else if ( fs_debug.GetBool() ) {
  3349. common->Printf( "'%s' in pak '%s' has != checksum %x\n", relativePath, pak->pakFilename.c_str(), GetFileChecksum( file ) );
  3350. }
  3351. CloseFile( file );
  3352. }
  3353. }
  3354. }
  3355. }
  3356. if ( fs_debug.GetBool() ) {
  3357. common->Printf( "no pak file found for '%s' checksumed %x\n", relativePath, findChecksum );
  3358. }
  3359. return NULL;
  3360. }
  3361. /*
  3362. =================
  3363. idFileSystemLocal::GetFileChecksum
  3364. =================
  3365. */
  3366. int idFileSystemLocal::GetFileChecksum( idFile *file ) {
  3367. int len, ret;
  3368. byte *buf;
  3369. file->Seek( 0, FS_SEEK_END );
  3370. len = file->Tell();
  3371. file->Seek( 0, FS_SEEK_SET );
  3372. buf = (byte *)Mem_Alloc( len );
  3373. if ( file->Read( buf, len ) != len ) {
  3374. common->FatalError( "Short read in idFileSystemLocal::GetFileChecksum()\n" );
  3375. }
  3376. ret = MD4_BlockChecksum( buf, len );
  3377. Mem_Free( buf );
  3378. return ret;
  3379. }
  3380. /*
  3381. =================
  3382. idFileSystemLocal::FindDLL
  3383. =================
  3384. */
  3385. void idFileSystemLocal::FindDLL( const char *name, char _dllPath[ MAX_OSPATH ], bool updateChecksum ) {
  3386. idFile *dllFile = NULL;
  3387. char dllName[MAX_OSPATH];
  3388. idStr dllPath;
  3389. int dllHash;
  3390. pack_t *inPak;
  3391. pack_t *pak;
  3392. fileInPack_t *pakFile;
  3393. sys->DLL_GetFileName( name, dllName, MAX_OSPATH );
  3394. dllHash = HashFileName( dllName );
  3395. #if ID_FAKE_PURE
  3396. if ( 1 ) {
  3397. #else
  3398. if ( !serverPaks.Num() ) {
  3399. #endif
  3400. // from executable directory first - this is handy for developement
  3401. dllPath = Sys_EXEPath( );
  3402. dllPath.StripFilename( );
  3403. dllPath.AppendPath( dllName );
  3404. dllFile = OpenExplicitFileRead( dllPath );
  3405. }
  3406. if ( !dllFile ) {
  3407. if ( !serverPaks.Num() ) {
  3408. // not running in pure mode, try to extract from a pak file first
  3409. dllFile = OpenFileReadFlags( dllName, FSFLAG_SEARCH_PAKS | FSFLAG_PURE_NOREF | FSFLAG_BINARY_ONLY, &inPak );
  3410. if ( dllFile ) {
  3411. common->Printf( "found DLL in pak file: %s\n", dllFile->GetFullPath() );
  3412. dllPath = RelativePathToOSPath( dllName, "fs_savepath" );
  3413. CopyFile( dllFile, dllPath );
  3414. CloseFile( dllFile );
  3415. dllFile = OpenFileReadFlags( dllName, FSFLAG_SEARCH_DIRS );
  3416. if ( !dllFile ) {
  3417. common->Error( "DLL extraction to fs_savepath failed\n" );
  3418. } else if ( updateChecksum ) {
  3419. gameDLLChecksum = GetFileChecksum( dllFile );
  3420. gamePakChecksum = inPak->checksum;
  3421. updateChecksum = false; // don't try again below
  3422. }
  3423. } else {
  3424. // didn't find a source in a pak file, try in the directory
  3425. dllFile = OpenFileReadFlags( dllName, FSFLAG_SEARCH_DIRS );
  3426. if ( dllFile ) {
  3427. if ( updateChecksum ) {
  3428. gameDLLChecksum = GetFileChecksum( dllFile );
  3429. // see if we can mark a pak file
  3430. pak = FindPakForFileChecksum( dllName, gameDLLChecksum, false );
  3431. pak ? gamePakChecksum = pak->checksum : gamePakChecksum = 0;
  3432. updateChecksum = false;
  3433. }
  3434. }
  3435. }
  3436. } else {
  3437. // we are in pure mode. this path to be reached only for game DLL situations
  3438. // with a code pak checksum given by server
  3439. assert( gamePakChecksum );
  3440. assert( updateChecksum );
  3441. pak = GetPackForChecksum( gamePakChecksum );
  3442. if ( !pak ) {
  3443. // not supposed to happen, bug in pure code?
  3444. common->Warning( "FindDLL in pure mode: game pak not found ( 0x%x )\n", gamePakChecksum );
  3445. } else {
  3446. // extract and copy
  3447. for ( pakFile = pak->hashTable[dllHash]; pakFile; pakFile = pakFile->next ) {
  3448. if ( !FilenameCompare( pakFile->name, dllName ) ) {
  3449. dllFile = ReadFileFromZip( pak, pakFile, dllName );
  3450. common->Printf( "found DLL in game pak file: %s\n", pak->pakFilename.c_str() );
  3451. dllPath = RelativePathToOSPath( dllName, "fs_savepath" );
  3452. CopyFile( dllFile, dllPath );
  3453. CloseFile( dllFile );
  3454. dllFile = OpenFileReadFlags( dllName, FSFLAG_SEARCH_DIRS );
  3455. if ( !dllFile ) {
  3456. common->Error( "DLL extraction to fs_savepath failed\n" );
  3457. } else {
  3458. gameDLLChecksum = GetFileChecksum( dllFile );
  3459. updateChecksum = false; // don't try again below
  3460. }
  3461. }
  3462. }
  3463. }
  3464. }
  3465. }
  3466. if ( updateChecksum ) {
  3467. if ( dllFile ) {
  3468. gameDLLChecksum = GetFileChecksum( dllFile );
  3469. } else {
  3470. gameDLLChecksum = 0;
  3471. }
  3472. gamePakChecksum = 0;
  3473. }
  3474. if ( dllFile ) {
  3475. dllPath = dllFile->GetFullPath( );
  3476. CloseFile( dllFile );
  3477. dllFile = NULL;
  3478. } else {
  3479. dllPath = "";
  3480. }
  3481. idStr::snPrintf( _dllPath, MAX_OSPATH, dllPath.c_str() );
  3482. }
  3483. /*
  3484. ================
  3485. idFileSystemLocal::ClearDirCache
  3486. ================
  3487. */
  3488. void idFileSystemLocal::ClearDirCache( void ) {
  3489. int i;
  3490. dir_cache_index = 0;
  3491. dir_cache_count = 0;
  3492. for( i = 0; i < MAX_CACHED_DIRS; i++ ) {
  3493. dir_cache[ i ].Clear();
  3494. }
  3495. }
  3496. /*
  3497. ===============
  3498. idFileSystemLocal::HasD3XP
  3499. ===============
  3500. */
  3501. bool idFileSystemLocal::HasD3XP( void ) {
  3502. int i;
  3503. idStrList dirs, pk4s;
  3504. idStr gamepath;
  3505. if ( d3xp == -1 ) {
  3506. return false;
  3507. } else if ( d3xp == 1 ) {
  3508. return true;
  3509. }
  3510. #if 0
  3511. // check for a d3xp directory with a pk4 file
  3512. // copied over from ListMods - only looks in basepath
  3513. ListOSFiles( fs_basepath.GetString(), "/", dirs );
  3514. for ( i = 0; i < dirs.Num(); i++ ) {
  3515. if ( dirs[i].Icmp( "d3xp" ) == 0 ) {
  3516. gamepath = BuildOSPath( fs_basepath.GetString(), dirs[ i ], "" );
  3517. ListOSFiles( gamepath, ".pk4", pk4s );
  3518. if ( pk4s.Num() ) {
  3519. d3xp = 1;
  3520. return true;
  3521. }
  3522. }
  3523. }
  3524. #elif ID_ALLOW_D3XP
  3525. // check for d3xp's d3xp/pak000.pk4 in any search path
  3526. // checking wether the pak is loaded by checksum wouldn't be enough:
  3527. // we may have a different fs_game right now but still need to reply that it's installed
  3528. const char *search[4];
  3529. idFile *pakfile;
  3530. search[0] = fs_savepath.GetString();
  3531. search[1] = fs_devpath.GetString();
  3532. search[2] = fs_basepath.GetString();
  3533. search[3] = fs_cdpath.GetString();
  3534. for ( i = 0; i < 4; i++ ) {
  3535. pakfile = OpenExplicitFileRead( BuildOSPath( search[ i ], "d3xp", "pak000.pk4" ) );
  3536. if ( pakfile ) {
  3537. CloseFile( pakfile );
  3538. d3xp = 1;
  3539. return true;
  3540. }
  3541. }
  3542. #endif
  3543. #if ID_ALLOW_D3XP
  3544. // if we didn't find a pk4 file then the user might have unpacked so look for default.cfg file
  3545. // that's the old way mostly used during developement. don't think it hurts to leave it there
  3546. ListOSFiles( fs_basepath.GetString(), "/", dirs );
  3547. for ( i = 0; i < dirs.Num(); i++ ) {
  3548. if ( dirs[i].Icmp( "d3xp" ) == 0 ) {
  3549. gamepath = BuildOSPath( fs_savepath.GetString(), dirs[ i ], "default.cfg" );
  3550. idFile* cfg = OpenExplicitFileRead(gamepath);
  3551. if(cfg) {
  3552. CloseFile(cfg);
  3553. d3xp = 1;
  3554. return true;
  3555. }
  3556. }
  3557. }
  3558. #endif
  3559. d3xp = -1;
  3560. return false;
  3561. }
  3562. /*
  3563. ===============
  3564. idFileSystemLocal::RunningD3XP
  3565. ===============
  3566. */
  3567. bool idFileSystemLocal::RunningD3XP( void ) {
  3568. // TODO: mark the checksum of the gold XP and check for it being referenced ( for double mod support )
  3569. // a simple fs_game check should be enough for now..
  3570. if ( !idStr::Icmp( fs_game.GetString(), "d3xp" ) ||
  3571. !idStr::Icmp( fs_game_base.GetString(), "d3xp" ) ) {
  3572. return true;
  3573. }
  3574. return false;
  3575. }
  3576. /*
  3577. ===============
  3578. idFileSystemLocal::MakeTemporaryFile
  3579. ===============
  3580. */
  3581. idFile * idFileSystemLocal::MakeTemporaryFile( void ) {
  3582. FILE *f = tmpfile();
  3583. if ( !f ) {
  3584. common->Warning( "idFileSystem::MakeTemporaryFile failed: %s", strerror( errno ) );
  3585. return NULL;
  3586. }
  3587. idFile_Permanent *file = new idFile_Permanent();
  3588. file->o = f;
  3589. file->name = "<tempfile>";
  3590. file->fullPath = "<tempfile>";
  3591. file->mode = ( 1 << FS_READ ) + ( 1 << FS_WRITE );
  3592. file->fileSize = 0;
  3593. return file;
  3594. }
  3595. /*
  3596. ===============
  3597. idFileSystemLocal::FindFile
  3598. ===============
  3599. */
  3600. findFile_t idFileSystemLocal::FindFile( const char *path, bool scheduleAddons ) {
  3601. pack_t *pak;
  3602. idFile *f = OpenFileReadFlags( path, FSFLAG_SEARCH_DIRS | FSFLAG_SEARCH_PAKS | FSFLAG_SEARCH_ADDONS, &pak );
  3603. if ( !f ) {
  3604. return FIND_NO;
  3605. }
  3606. if ( !pak ) {
  3607. // found in FS, not even in paks
  3608. return FIND_YES;
  3609. }
  3610. // marking addons for inclusion on reload - may need to do that even when already in the search path
  3611. if ( scheduleAddons && pak->addon && addonChecksums.FindIndex( pak->checksum ) < 0 ) {
  3612. addonChecksums.Append( pak->checksum );
  3613. }
  3614. // an addon that's not on search list yet? that will require a restart
  3615. if ( pak->addon && !pak->addon_search ) {
  3616. delete f;
  3617. return FIND_ADDON;
  3618. }
  3619. delete f;
  3620. return FIND_YES;
  3621. }
  3622. /*
  3623. ===============
  3624. idFileSystemLocal::GetNumMaps
  3625. account for actual decls and for addon maps
  3626. ===============
  3627. */
  3628. int idFileSystemLocal::GetNumMaps() {
  3629. int i;
  3630. searchpath_t *search = NULL;
  3631. int ret = declManager->GetNumDecls( DECL_MAPDEF );
  3632. // add to this all addon decls - coming from all addon packs ( searched or not )
  3633. for ( i = 0; i < 2; i++ ) {
  3634. if ( i == 0 ) {
  3635. search = searchPaths;
  3636. } else if ( i == 1 ) {
  3637. search = addonPaks;
  3638. }
  3639. for ( ; search ; search = search->next ) {
  3640. if ( !search->pack || !search->pack->addon || !search->pack->addon_info ) {
  3641. continue;
  3642. }
  3643. ret += search->pack->addon_info->mapDecls.Num();
  3644. }
  3645. }
  3646. return ret;
  3647. }
  3648. /*
  3649. ===============
  3650. idFileSystemLocal::GetMapDecl
  3651. retrieve the decl dictionary, add a 'path' value
  3652. ===============
  3653. */
  3654. const idDict * idFileSystemLocal::GetMapDecl( int idecl ) {
  3655. int i;
  3656. const idDecl *mapDecl;
  3657. const idDeclEntityDef *mapDef;
  3658. int numdecls = declManager->GetNumDecls( DECL_MAPDEF );
  3659. searchpath_t *search = NULL;
  3660. if ( idecl < numdecls ) {
  3661. mapDecl = declManager->DeclByIndex( DECL_MAPDEF, idecl );
  3662. mapDef = static_cast<const idDeclEntityDef *>( mapDecl );
  3663. if ( !mapDef ) {
  3664. common->Error( "idFileSystemLocal::GetMapDecl %d: not found\n", idecl );
  3665. }
  3666. mapDict = mapDef->dict;
  3667. mapDict.Set( "path", mapDef->GetName() );
  3668. return &mapDict;
  3669. }
  3670. idecl -= numdecls;
  3671. for ( i = 0; i < 2; i++ ) {
  3672. if ( i == 0 ) {
  3673. search = searchPaths;
  3674. } else if ( i == 1 ) {
  3675. search = addonPaks;
  3676. }
  3677. for ( ; search ; search = search->next ) {
  3678. if ( !search->pack || !search->pack->addon || !search->pack->addon_info ) {
  3679. continue;
  3680. }
  3681. // each addon may have a bunch of map decls
  3682. if ( idecl < search->pack->addon_info->mapDecls.Num() ) {
  3683. mapDict = *search->pack->addon_info->mapDecls[ idecl ];
  3684. return &mapDict;
  3685. }
  3686. idecl -= search->pack->addon_info->mapDecls.Num();
  3687. assert( idecl >= 0 );
  3688. }
  3689. }
  3690. return NULL;
  3691. }
  3692. /*
  3693. ===============
  3694. idFileSystemLocal::FindMapScreenshot
  3695. ===============
  3696. */
  3697. void idFileSystemLocal::FindMapScreenshot( const char *path, char *buf, int len ) {
  3698. idFile *file;
  3699. idStr mapname = path;
  3700. mapname.StripPath();
  3701. mapname.StripFileExtension();
  3702. idStr::snPrintf( buf, len, "guis/assets/splash/%s.tga", mapname.c_str() );
  3703. if ( ReadFile( buf, NULL, NULL ) == -1 ) {
  3704. // try to extract from an addon
  3705. file = OpenFileReadFlags( buf, FSFLAG_SEARCH_ADDONS );
  3706. if ( file ) {
  3707. // save it out to an addon splash directory
  3708. int dlen = file->Length();
  3709. char *data = new char[ dlen ];
  3710. file->Read( data, dlen );
  3711. CloseFile( file );
  3712. idStr::snPrintf( buf, len, "guis/assets/splash/addon/%s.tga", mapname.c_str() );
  3713. WriteFile( buf, data, dlen );
  3714. delete[] data;
  3715. } else {
  3716. idStr::Copynz( buf, "guis/assets/splash/pdtempa", len );
  3717. }
  3718. }
  3719. }