files_common.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /*****************************************************************************
  2. * name: files.c
  3. *
  4. * desc: handle based filesystem for Quake III Arena
  5. *
  6. *
  7. *****************************************************************************/
  8. #include "../game/q_shared.h"
  9. #include "qcommon.h"
  10. #include "files.h"
  11. /*
  12. =============================================================================
  13. QUAKE3 FILESYSTEM
  14. All of Quake's data access is through a hierarchical file system, but the contents of
  15. the file system can be transparently merged from several sources.
  16. A "qpath" is a reference to game file data. MAX_QPATH is 64 characters, which must include
  17. a terminating zero. "..", "\\", and ":" are explicitly illegal in qpaths to prevent any
  18. references outside the quake directory system.
  19. The "base path" is the path to the directory holding all the game directories and usually
  20. the executable. It defaults to ".", but can be overridden with a "+set fs_basepath c:\quake3"
  21. command line to allow code debugging in a different directory. Basepath cannot
  22. be modified at all after startup. Any files that are created (demos, screenshots,
  23. etc) will be created relative to the base path, so base path should usually be writable.
  24. The "cd path" is the path to an alternate hierarchy that will be searched if a file
  25. is not located in the base path. A user can do a partial install that copies some
  26. data to a base path created on their hard drive and leave the rest on the cd. Files
  27. are never writen to the cd path. It defaults to a value set by the installer, like
  28. "e:\quake3", but it can be overridden with "+set ds_cdpath g:\quake3".
  29. If a user runs the game directly from a CD, the base path would be on the CD. This
  30. should still function correctly, but all file writes will fail (harmlessly).
  31. The "base game" is the directory under the paths where data comes from by default, and
  32. can be either "base" or "demo".
  33. The "current game" may be the same as the base game, or it may be the name of another
  34. directory under the paths that should be searched for files before looking in the base game.
  35. This is the basis for addons.
  36. Clients automatically set the game directory after receiving a gamestate from a server,
  37. so only servers need to worry about +set fs_game.
  38. No other directories outside of the base game and current game will ever be referenced by
  39. filesystem functions.
  40. To save disk space and speed loading, directory trees can be collapsed into zip files.
  41. The files use a ".pk3" extension to prevent users from unzipping them accidentally, but
  42. otherwise the are simply normal uncompressed zip files. A game directory can have multiple
  43. zip files of the form "asset0.pk3", "pak1.pk3", etc. Zip files are searched in decending order
  44. from the highest number to the lowest, and will always take precedence over the filesystem.
  45. This allows a pk3 distributed as a patch to override all existing data.
  46. Because we will have updated executables freely available online, there is no point to
  47. trying to restrict demo / oem versions of the game with code changes. Demo / oem versions
  48. should be exactly the same executables as release versions, but with different data that
  49. automatically restricts where game media can come from to prevent add-ons from working.
  50. After the paths are initialized, quake will look for the product.txt file. If not
  51. found and verified, the game will run in restricted mode. In restricted mode, only
  52. files contained in demo/asset0.pk3 will be available for loading, and only if the zip header is
  53. verified to not have been modified. A single exception is made for jaconfig.cfg. Files
  54. can still be written out in restricted mode, so screenshots and demos are allowed.
  55. Restricted mode can be tested by setting "+set fs_restrict 1" on the command line, even
  56. if there is a valid product.txt under the basepath or cdpath.
  57. If not running in restricted mode, and a file is not found in any local filesystem,
  58. an attempt will be made to download it and save it under the base path.
  59. If the "fs_copyfiles" cvar is set to 1, then every time a file is sourced from the cd
  60. path, it will be copied over to the base path. This is a development aid to help build
  61. test releases and to copy working sets over slow network links.
  62. (If set to 2, copying will only take place if the two filetimes are NOT EQUAL)
  63. The qpath "sound/newstuff/test.wav" would be searched for in the following places:
  64. base path + current game's zip files
  65. base path + current game's directory
  66. cd path + current game's zip files
  67. cd path + current game's directory
  68. base path + base game's zip files
  69. base path + base game's directory
  70. cd path + base game's zip files
  71. cd path + base game's directory
  72. server download, to be written to base path + current game's directory
  73. The filesystem can be safely shutdown and reinitialized with different
  74. basedir / cddir / game combinations, but all other subsystems that rely on it
  75. (sound, video) must also be forced to restart.
  76. Because the same files are loaded by both the clip model (CM_) and renderer (TR_)
  77. subsystems, a simple single-file caching scheme is used. The CM_ subsystems will
  78. load the file with a request to cache. Only one file will be kept cached at a time,
  79. so any models that are going to be referenced by both subsystems should alternate
  80. between the CM_ load function and the ref load function.
  81. TODO: A qpath that starts with a leading slash will always refer to the base game, even if another
  82. game is currently active. This allows character models, skins, and sounds to be downloaded
  83. to a common directory no matter which game is active.
  84. How to prevent downloading zip files?
  85. Pass pk3 file names in systeminfo, and download before FS_Restart()?
  86. Aborting a download disconnects the client from the server.
  87. How to mark files as downloadable? Commercial add-ons won't be downloadable.
  88. Non-commercial downloads will want to download the entire zip file.
  89. the game would have to be reset to actually read the zip in
  90. Auto-update information
  91. Path separators
  92. Casing
  93. separate server gamedir and client gamedir, so if the user starts
  94. a local game after having connected to a network game, it won't stick
  95. with the network game.
  96. allow menu options for game selection?
  97. Read / write config to floppy option.
  98. Different version coexistance?
  99. When building a pak file, make sure a jaconfig.cfg isn't present in it,
  100. or configs will never get loaded from disk!
  101. todo:
  102. downloading (outside fs?)
  103. game directory passing and restarting
  104. =============================================================================
  105. */
  106. // if this is defined, the executable positively won't work with any paks other
  107. // than the demo pak, even if productid is present. This is only used for our
  108. // last demo release to prevent the mac and linux users from using the demo
  109. // executable with the production windows pak before the mac/linux products
  110. // hit the shelves a little later
  111. //#define PRE_RELEASE_DEMO
  112. char fs_gamedir[MAX_OSPATH]; // this will be a single file name with no separators
  113. cvar_t *fs_debug;
  114. cvar_t *fs_basepath;
  115. cvar_t *fs_cdpath;
  116. cvar_t *fs_copyfiles;
  117. cvar_t *fs_gamedirvar;
  118. cvar_t *fs_restrict;
  119. searchpath_t *fs_searchpaths;
  120. int fs_readCount; // total bytes read
  121. int fs_loadCount; // total files read
  122. int fs_packFiles; // total number of files in packs
  123. qboolean initialized = qfalse;
  124. fileHandleData_t fsh[MAX_FILE_HANDLES];
  125. void FS_CheckInit(void)
  126. {
  127. if (!initialized)
  128. {
  129. Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
  130. }
  131. }
  132. /*
  133. ==============
  134. FS_Initialized
  135. ==============
  136. */
  137. qboolean FS_Initialized() {
  138. return (qboolean)(fs_searchpaths != NULL);
  139. }
  140. fileHandle_t FS_HandleForFile(void) {
  141. int i;
  142. for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
  143. #ifdef _XBOX
  144. if ( !fsh[i].used ) {
  145. #else
  146. if ( fsh[i].handleFiles.file.o == NULL ) {
  147. #endif
  148. return i;
  149. }
  150. }
  151. Com_Printf( "FS_HandleForFile: all handles taken:\n" );
  152. for ( i = 1 ; i < MAX_FILE_HANDLES ; i++ ) {
  153. Com_Printf( "%d. %s\n", i, fsh[i].name);
  154. }
  155. Com_Error( ERR_DROP, "FS_HandleForFile: none free" );
  156. return 0;
  157. }
  158. /*
  159. ====================
  160. FS_ReplaceSeparators
  161. Fix things up differently for win/unix/mac
  162. ====================
  163. */
  164. void FS_ReplaceSeparators( char *path ) {
  165. char *s;
  166. for ( s = path ; *s ; s++ ) {
  167. if ( *s == '/' || *s == '\\' ) {
  168. *s = PATH_SEP;
  169. }
  170. }
  171. }
  172. /*
  173. ===================
  174. FS_BuildOSPath
  175. Qpath may have either forward or backwards slashes
  176. ===================
  177. */
  178. char *FS_BuildOSPath( const char *qpath )
  179. {
  180. char temp[MAX_OSPATH];
  181. static char ospath[2][MAX_OSPATH];
  182. static int toggle;
  183. toggle ^= 1; // flip-flop to allow two returns without clash
  184. Com_sprintf( temp, sizeof(temp), "/%s/%s", fs_gamedirvar->string, qpath );
  185. FS_ReplaceSeparators( temp );
  186. Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s",
  187. fs_basepath->string, temp );
  188. return ospath[toggle];
  189. }
  190. char *FS_BuildOSPathUnMapped( const char *qpath )
  191. {
  192. char temp[MAX_OSPATH];
  193. static char ospath[2][MAX_OSPATH];
  194. static int toggle;
  195. toggle ^= 1; // flip-flop to allow two returns without clash
  196. Com_sprintf( temp, sizeof(temp), "/%s/%s", fs_gamedirvar->string, qpath );
  197. FS_ReplaceSeparators( temp );
  198. Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s",
  199. "d:", temp );
  200. return ospath[toggle];
  201. }
  202. #ifndef _XBOX
  203. char *FS_BuildOSPath( const char *base, const char *game, const char *qpath ) {
  204. char temp[MAX_OSPATH];
  205. static char ospath[4][MAX_OSPATH];
  206. static int toggle;
  207. toggle = (++toggle)&3; // allows four returns without clash (increased from 2 during fs_copyfiles 2 enhancement)
  208. Com_sprintf( temp, sizeof(temp), "/%s/%s", game, qpath );
  209. FS_ReplaceSeparators( temp );
  210. Com_sprintf( ospath[toggle], sizeof( ospath[0] ), "%s%s", base, temp );
  211. return ospath[toggle];
  212. }
  213. #endif
  214. /*
  215. ============
  216. FS_CreatePath
  217. Creates any directories needed to store the given filename
  218. ============
  219. */
  220. void FS_CreatePath (char *OSPath) {
  221. char *ofs;
  222. // make absolutely sure that it can't back up the path
  223. // FIXME: is c: allowed???
  224. if ( strstr( OSPath, ".." ) || strstr( OSPath, "::" ) ) {
  225. Com_Printf( "WARNING: refusing to create relative path \"%s\"\n", OSPath );
  226. return;
  227. }
  228. strlwr(OSPath);
  229. for (ofs = OSPath+1 ; *ofs ; ofs++) {
  230. if (*ofs == PATH_SEP) {
  231. // create the directory
  232. *ofs = 0;
  233. Sys_Mkdir (OSPath);
  234. *ofs = PATH_SEP;
  235. }
  236. }
  237. }
  238. /*
  239. ===========
  240. FS_SV_FOpenFileRead
  241. ===========
  242. */
  243. int FS_SV_FOpenFileRead( const char *filename, fileHandle_t *fp ) {
  244. char *ospath;
  245. fileHandle_t f;
  246. if ( !fs_searchpaths ) {
  247. Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
  248. }
  249. f = FS_HandleForFile();
  250. fsh[f].zipFile = qfalse;
  251. Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
  252. // don't let sound stutter
  253. S_ClearSoundBuffer();
  254. #ifdef _XBOX
  255. ospath = FS_BuildOSPath( filename );
  256. #else
  257. ospath = FS_BuildOSPath( fs_basepath->string, filename, "" );
  258. #endif
  259. // remove trailing slash
  260. ospath[strlen(ospath)-1] = '\0';
  261. if ( fs_debug->integer ) {
  262. Com_Printf( "FS_SV_FOpenFileRead: %s\n", ospath );
  263. }
  264. fsh[f].handleFiles.file.o = fopen( ospath, "rb" );
  265. fsh[f].handleSync = qfalse;
  266. if (!fsh[f].handleFiles.file.o) {
  267. f = 0;
  268. }
  269. *fp = f;
  270. if (f) {
  271. return FS_filelength(f);
  272. }
  273. return 0;
  274. }
  275. /*
  276. ===========
  277. FS_FOpenFileAppend
  278. ===========
  279. */
  280. fileHandle_t FS_FOpenFileAppend( const char *filename ) {
  281. char *ospath;
  282. fileHandle_t f;
  283. if ( !fs_searchpaths ) {
  284. Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
  285. }
  286. f = FS_HandleForFile();
  287. fsh[f].zipFile = qfalse;
  288. Q_strncpyz( fsh[f].name, filename, sizeof( fsh[f].name ) );
  289. // don't let sound stutter
  290. S_ClearSoundBuffer();
  291. #ifdef _XBOX
  292. ospath = FS_BuildOSPath( filename );
  293. #else
  294. ospath = FS_BuildOSPath( fs_basepath->string, fs_gamedir, filename );
  295. #endif
  296. if ( fs_debug->integer ) {
  297. Com_Printf( "FS_FOpenFileAppend: %s\n", ospath );
  298. }
  299. FS_CreatePath( ospath );
  300. fsh[f].handleFiles.file.o = fopen( ospath, "ab" );
  301. fsh[f].handleSync = qfalse;
  302. if (!fsh[f].handleFiles.file.o) {
  303. f = 0;
  304. }
  305. return f;
  306. }
  307. /*
  308. ===========
  309. FS_FilenameCompare
  310. Ignore case and seprator char distinctions
  311. ===========
  312. */
  313. qboolean FS_FilenameCompare( const char *s1, const char *s2 ) {
  314. int c1, c2;
  315. do {
  316. c1 = *s1++;
  317. c2 = *s2++;
  318. if ( Q_islower(c1) ) {
  319. c1 -= ('a' - 'A');
  320. }
  321. if ( Q_islower(c2) ) {
  322. c2 -= ('a' - 'A');
  323. }
  324. if ( c1 == '\\' || c1 == ':' ) {
  325. c1 = '/';
  326. }
  327. if ( c2 == '\\' || c2 == ':' ) {
  328. c2 = '/';
  329. }
  330. if (c1 != c2) {
  331. return -1; // strings not equal
  332. }
  333. } while (c1);
  334. return 0; // strings are equal
  335. }
  336. #define MAXPRINTMSG 4096
  337. void QDECL FS_Printf( fileHandle_t h, const char *fmt, ... ) {
  338. va_list argptr;
  339. char msg[MAXPRINTMSG];
  340. va_start (argptr,fmt);
  341. vsprintf (msg,fmt,argptr);
  342. va_end (argptr);
  343. FS_Write(msg, strlen(msg), h);
  344. }
  345. /*
  346. ============
  347. FS_WriteFile
  348. Filename are relative to the quake search path
  349. ============
  350. */
  351. void FS_WriteFile( const char *qpath, const void *buffer, int size ) {
  352. fileHandle_t f;
  353. if ( !fs_searchpaths ) {
  354. Com_Error( ERR_FATAL, "Filesystem call made without initialization\n" );
  355. }
  356. if ( !qpath || !buffer ) {
  357. Com_Error( ERR_FATAL, "FS_WriteFile: NULL parameter" );
  358. }
  359. f = FS_FOpenFileWrite( qpath );
  360. if ( !f ) {
  361. Com_Printf( "Failed to open %s\n", qpath );
  362. return;
  363. }
  364. FS_Write( buffer, size, f );
  365. FS_FCloseFile( f );
  366. }
  367. /*
  368. ================
  369. FS_Shutdown
  370. Frees all resources and closes all files
  371. ================
  372. */
  373. void FS_Shutdown( void ) {
  374. searchpath_t *p, *next;
  375. int i;
  376. for(i = 0; i < MAX_FILE_HANDLES; i++) {
  377. if (fsh[i].fileSize) {
  378. FS_FCloseFile(i);
  379. }
  380. }
  381. // free everything
  382. for ( p = fs_searchpaths ; p ; p = next ) {
  383. next = p->next;
  384. if ( p->pack ) {
  385. #ifndef _XBOX
  386. unzClose(p->pack->handle);
  387. #endif
  388. Z_Free( p->pack->buildBuffer );
  389. Z_Free( p->pack );
  390. }
  391. if ( p->dir ) {
  392. Z_Free( p->dir );
  393. }
  394. Z_Free( p );
  395. }
  396. // any FS_ calls will now be an error until reinitialized
  397. fs_searchpaths = NULL;
  398. Cmd_RemoveCommand( "path" );
  399. Cmd_RemoveCommand( "dir" );
  400. Cmd_RemoveCommand( "touchFile" );
  401. initialized = qfalse;
  402. }
  403. /*
  404. ================
  405. FS_InitFilesystem
  406. Called only at inital startup, not when the filesystem
  407. is resetting due to a game change
  408. ================
  409. */
  410. void FS_InitFilesystem( void ) {
  411. // allow command line parms to override our defaults
  412. // we don't have to specially handle this, because normal command
  413. // line variable sets happen before the filesystem
  414. // has been initialized
  415. //
  416. // UPDATE: BTO (VV)
  417. // we have to specially handle this, because normal command
  418. // line variable sets don't happen until after the filesystem
  419. // has already been initialized
  420. Com_StartupVariable( "fs_cdpath" );
  421. Com_StartupVariable( "fs_basepath" );
  422. Com_StartupVariable( "fs_game" );
  423. Com_StartupVariable( "fs_copyfiles" );
  424. Com_StartupVariable( "fs_restrict" );
  425. // try to start up normally
  426. FS_Startup( BASEGAME );
  427. initialized = qtrue;
  428. // see if we are going to allow add-ons
  429. FS_SetRestrictions();
  430. // if we can't find default.cfg, assume that the paths are
  431. // busted and error out now, rather than getting an unreadable
  432. // graphics screen when the font fails to load
  433. if ( FS_ReadFile( "default.cfg", NULL ) <= 0 ) {
  434. Com_Error( ERR_FATAL, "Couldn't load default.cfg" );
  435. }
  436. }
  437. void FS_Flush( fileHandle_t f ) {
  438. fflush(fsh[f].handleFiles.file.o);
  439. }