PageRenderTime 53ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/fs.c

https://gitlab.com/xonotic/darkplaces
C | 4160 lines | 2814 code | 521 blank | 825 comment | 611 complexity | 1fd6f523645c86ace0a9b8f1470e40d3 MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. DarkPlaces file system
  3. Copyright (C) 2003-2006 Mathieu Olivier
  4. This program is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU General Public License
  6. as published by the Free Software Foundation; either version 2
  7. of the License, or (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. See the GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to:
  14. Free Software Foundation, Inc.
  15. 59 Temple Place - Suite 330
  16. Boston, MA 02111-1307, USA
  17. */
  18. #include <limits.h>
  19. #include <fcntl.h>
  20. #ifdef WIN32
  21. # include <direct.h>
  22. # include <io.h>
  23. # include <shlobj.h>
  24. # include <sys/stat.h>
  25. # include <share.h>
  26. #else
  27. # include <pwd.h>
  28. # include <sys/stat.h>
  29. # include <unistd.h>
  30. #endif
  31. #include "quakedef.h"
  32. #if TARGET_OS_IPHONE
  33. // include SDL for IPHONEOS code
  34. # include <SDL.h>
  35. #endif
  36. #include "thread.h"
  37. #include "fs.h"
  38. #include "wad.h"
  39. // Win32 requires us to add O_BINARY, but the other OSes don't have it
  40. #ifndef O_BINARY
  41. # define O_BINARY 0
  42. #endif
  43. // In case the system doesn't support the O_NONBLOCK flag
  44. #ifndef O_NONBLOCK
  45. # define O_NONBLOCK 0
  46. #endif
  47. // largefile support for Win32
  48. #ifdef WIN32
  49. #undef lseek
  50. # define lseek _lseeki64
  51. #endif
  52. // suppress deprecated warnings
  53. #if _MSC_VER >= 1400
  54. # define read _read
  55. # define write _write
  56. # define close _close
  57. # define unlink _unlink
  58. # define dup _dup
  59. #endif
  60. #if USE_RWOPS
  61. # include <SDL.h>
  62. typedef SDL_RWops *filedesc_t;
  63. # define FILEDESC_INVALID NULL
  64. # define FILEDESC_ISVALID(fd) ((fd) != NULL)
  65. # define FILEDESC_READ(fd,buf,count) ((fs_offset_t)SDL_RWread(fd, buf, 1, count))
  66. # define FILEDESC_WRITE(fd,buf,count) ((fs_offset_t)SDL_RWwrite(fd, buf, 1, count))
  67. # define FILEDESC_CLOSE SDL_RWclose
  68. # define FILEDESC_SEEK SDL_RWseek
  69. static filedesc_t FILEDESC_DUP(const char *filename, filedesc_t fd) {
  70. filedesc_t new_fd = SDL_RWFromFile(filename, "rb");
  71. if (SDL_RWseek(new_fd, SDL_RWseek(fd, 0, RW_SEEK_CUR), RW_SEEK_SET) < 0) {
  72. SDL_RWclose(new_fd);
  73. return NULL;
  74. }
  75. return new_fd;
  76. }
  77. # define unlink(name) Con_DPrintf("Sorry, no unlink support when trying to unlink %s.\n", (name))
  78. #else
  79. typedef int filedesc_t;
  80. # define FILEDESC_INVALID -1
  81. # define FILEDESC_ISVALID(fd) ((fd) != -1)
  82. # define FILEDESC_READ read
  83. # define FILEDESC_WRITE write
  84. # define FILEDESC_CLOSE close
  85. # define FILEDESC_SEEK lseek
  86. static filedesc_t FILEDESC_DUP(const char *filename, filedesc_t fd) {
  87. return dup(fd);
  88. }
  89. #endif
  90. /** \page fs File System
  91. All of Quake's data access is through a hierchal file system, but the contents
  92. of the file system can be transparently merged from several sources.
  93. The "base directory" is the path to the directory holding the quake.exe and
  94. all game directories. The sys_* files pass this to host_init in
  95. quakeparms_t->basedir. This can be overridden with the "-basedir" command
  96. line parm to allow code debugging in a different directory. The base
  97. directory is only used during filesystem initialization.
  98. The "game directory" is the first tree on the search path and directory that
  99. all generated files (savegames, screenshots, demos, config files) will be
  100. saved to. This can be overridden with the "-game" command line parameter.
  101. The game directory can never be changed while quake is executing. This is a
  102. precaution against having a malicious server instruct clients to write files
  103. over areas they shouldn't.
  104. */
  105. /*
  106. =============================================================================
  107. CONSTANTS
  108. =============================================================================
  109. */
  110. // Magic numbers of a ZIP file (big-endian format)
  111. #define ZIP_DATA_HEADER 0x504B0304 // "PK\3\4"
  112. #define ZIP_CDIR_HEADER 0x504B0102 // "PK\1\2"
  113. #define ZIP_END_HEADER 0x504B0506 // "PK\5\6"
  114. // Other constants for ZIP files
  115. #define ZIP_MAX_COMMENTS_SIZE ((unsigned short)0xFFFF)
  116. #define ZIP_END_CDIR_SIZE 22
  117. #define ZIP_CDIR_CHUNK_BASE_SIZE 46
  118. #define ZIP_LOCAL_CHUNK_BASE_SIZE 30
  119. #ifdef LINK_TO_ZLIB
  120. #include <zlib.h>
  121. #define qz_inflate inflate
  122. #define qz_inflateEnd inflateEnd
  123. #define qz_inflateInit2_ inflateInit2_
  124. #define qz_inflateReset inflateReset
  125. #define qz_deflateInit2_ deflateInit2_
  126. #define qz_deflateEnd deflateEnd
  127. #define qz_deflate deflate
  128. #define Z_MEMLEVEL_DEFAULT 8
  129. #else
  130. // Zlib constants (from zlib.h)
  131. #define Z_SYNC_FLUSH 2
  132. #define MAX_WBITS 15
  133. #define Z_OK 0
  134. #define Z_STREAM_END 1
  135. #define Z_STREAM_ERROR (-2)
  136. #define Z_DATA_ERROR (-3)
  137. #define Z_MEM_ERROR (-4)
  138. #define Z_BUF_ERROR (-5)
  139. #define ZLIB_VERSION "1.2.3"
  140. #define Z_BINARY 0
  141. #define Z_DEFLATED 8
  142. #define Z_MEMLEVEL_DEFAULT 8
  143. #define Z_NULL 0
  144. #define Z_DEFAULT_COMPRESSION (-1)
  145. #define Z_NO_FLUSH 0
  146. #define Z_SYNC_FLUSH 2
  147. #define Z_FULL_FLUSH 3
  148. #define Z_FINISH 4
  149. // Uncomment the following line if the zlib DLL you have still uses
  150. // the 1.1.x series calling convention on Win32 (WINAPI)
  151. //#define ZLIB_USES_WINAPI
  152. /*
  153. =============================================================================
  154. TYPES
  155. =============================================================================
  156. */
  157. /*! Zlib stream (from zlib.h)
  158. * \warning: some pointers we don't use directly have
  159. * been cast to "void*" for a matter of simplicity
  160. */
  161. typedef struct
  162. {
  163. unsigned char *next_in; ///< next input byte
  164. unsigned int avail_in; ///< number of bytes available at next_in
  165. unsigned long total_in; ///< total nb of input bytes read so far
  166. unsigned char *next_out; ///< next output byte should be put there
  167. unsigned int avail_out; ///< remaining free space at next_out
  168. unsigned long total_out; ///< total nb of bytes output so far
  169. char *msg; ///< last error message, NULL if no error
  170. void *state; ///< not visible by applications
  171. void *zalloc; ///< used to allocate the internal state
  172. void *zfree; ///< used to free the internal state
  173. void *opaque; ///< private data object passed to zalloc and zfree
  174. int data_type; ///< best guess about the data type: ascii or binary
  175. unsigned long adler; ///< adler32 value of the uncompressed data
  176. unsigned long reserved; ///< reserved for future use
  177. } z_stream;
  178. #endif
  179. /// inside a package (PAK or PK3)
  180. #define QFILE_FLAG_PACKED (1 << 0)
  181. /// file is compressed using the deflate algorithm (PK3 only)
  182. #define QFILE_FLAG_DEFLATED (1 << 1)
  183. /// file is actually already loaded data
  184. #define QFILE_FLAG_DATA (1 << 2)
  185. /// real file will be removed on close
  186. #define QFILE_FLAG_REMOVE (1 << 3)
  187. #define FILE_BUFF_SIZE 2048
  188. typedef struct
  189. {
  190. z_stream zstream;
  191. size_t comp_length; ///< length of the compressed file
  192. size_t in_ind, in_len; ///< input buffer current index and length
  193. size_t in_position; ///< position in the compressed file
  194. unsigned char input [FILE_BUFF_SIZE];
  195. } ztoolkit_t;
  196. struct qfile_s
  197. {
  198. int flags;
  199. filedesc_t handle; ///< file descriptor
  200. fs_offset_t real_length; ///< uncompressed file size (for files opened in "read" mode)
  201. fs_offset_t position; ///< current position in the file
  202. fs_offset_t offset; ///< offset into the package (0 if external file)
  203. int ungetc; ///< single stored character from ungetc, cleared to EOF when read
  204. // Contents buffer
  205. fs_offset_t buff_ind, buff_len; ///< buffer current index and length
  206. unsigned char buff [FILE_BUFF_SIZE];
  207. ztoolkit_t* ztk; ///< For zipped files.
  208. const unsigned char *data; ///< For data files.
  209. const char *filename; ///< Kept around for QFILE_FLAG_REMOVE, unused otherwise
  210. };
  211. // ------ PK3 files on disk ------ //
  212. // You can get the complete ZIP format description from PKWARE website
  213. typedef struct pk3_endOfCentralDir_s
  214. {
  215. unsigned int signature;
  216. unsigned short disknum;
  217. unsigned short cdir_disknum; ///< number of the disk with the start of the central directory
  218. unsigned short localentries; ///< number of entries in the central directory on this disk
  219. unsigned short nbentries; ///< total number of entries in the central directory on this disk
  220. unsigned int cdir_size; ///< size of the central directory
  221. unsigned int cdir_offset; ///< with respect to the starting disk number
  222. unsigned short comment_size;
  223. fs_offset_t prepended_garbage;
  224. } pk3_endOfCentralDir_t;
  225. // ------ PAK files on disk ------ //
  226. typedef struct dpackfile_s
  227. {
  228. char name[56];
  229. int filepos, filelen;
  230. } dpackfile_t;
  231. typedef struct dpackheader_s
  232. {
  233. char id[4];
  234. int dirofs;
  235. int dirlen;
  236. } dpackheader_t;
  237. /*! \name Packages in memory
  238. * @{
  239. */
  240. /// the offset in packfile_t is the true contents offset
  241. #define PACKFILE_FLAG_TRUEOFFS (1 << 0)
  242. /// file compressed using the deflate algorithm
  243. #define PACKFILE_FLAG_DEFLATED (1 << 1)
  244. /// file is a symbolic link
  245. #define PACKFILE_FLAG_SYMLINK (1 << 2)
  246. typedef struct packfile_s
  247. {
  248. char name [MAX_QPATH];
  249. int flags;
  250. fs_offset_t offset;
  251. fs_offset_t packsize; ///< size in the package
  252. fs_offset_t realsize; ///< real file size (uncompressed)
  253. } packfile_t;
  254. typedef struct pack_s
  255. {
  256. char filename [MAX_OSPATH];
  257. char shortname [MAX_QPATH];
  258. filedesc_t handle;
  259. int ignorecase; ///< PK3 ignores case
  260. int numfiles;
  261. qboolean vpack;
  262. packfile_t *files;
  263. } pack_t;
  264. //@}
  265. /// Search paths for files (including packages)
  266. typedef struct searchpath_s
  267. {
  268. // only one of filename / pack will be used
  269. char filename[MAX_OSPATH];
  270. pack_t *pack;
  271. struct searchpath_s *next;
  272. } searchpath_t;
  273. /*
  274. =============================================================================
  275. FUNCTION PROTOTYPES
  276. =============================================================================
  277. */
  278. void FS_Dir_f(void);
  279. void FS_Ls_f(void);
  280. void FS_Which_f(void);
  281. static searchpath_t *FS_FindFile (const char *name, int* index, qboolean quiet);
  282. static packfile_t* FS_AddFileToPack (const char* name, pack_t* pack,
  283. fs_offset_t offset, fs_offset_t packsize,
  284. fs_offset_t realsize, int flags);
  285. /*
  286. =============================================================================
  287. VARIABLES
  288. =============================================================================
  289. */
  290. mempool_t *fs_mempool;
  291. void *fs_mutex = NULL;
  292. searchpath_t *fs_searchpaths = NULL;
  293. const char *const fs_checkgamedir_missing = "missing";
  294. #define MAX_FILES_IN_PACK 65536
  295. char fs_userdir[MAX_OSPATH];
  296. char fs_gamedir[MAX_OSPATH];
  297. char fs_basedir[MAX_OSPATH];
  298. static pack_t *fs_selfpack = NULL;
  299. // list of active game directories (empty if not running a mod)
  300. int fs_numgamedirs = 0;
  301. char fs_gamedirs[MAX_GAMEDIRS][MAX_QPATH];
  302. // list of all gamedirs with modinfo.txt
  303. gamedir_t *fs_all_gamedirs = NULL;
  304. int fs_all_gamedirs_count = 0;
  305. cvar_t scr_screenshot_name = {CVAR_NORESETTODEFAULTS, "scr_screenshot_name","dp", "prefix name for saved screenshots (changes based on -game commandline, as well as which game mode is running; the date is encoded using strftime escapes)"};
  306. cvar_t fs_empty_files_in_pack_mark_deletions = {0, "fs_empty_files_in_pack_mark_deletions", "0", "if enabled, empty files in a pak/pk3 count as not existing but cancel the search in further packs, effectively allowing patch pak/pk3 files to 'delete' files"};
  307. cvar_t cvar_fs_gamedir = {CVAR_READONLY | CVAR_NORESETTODEFAULTS, "fs_gamedir", "", "the list of currently selected gamedirs (use the 'gamedir' command to change this)"};
  308. /*
  309. =============================================================================
  310. PRIVATE FUNCTIONS - PK3 HANDLING
  311. =============================================================================
  312. */
  313. #ifndef LINK_TO_ZLIB
  314. // Functions exported from zlib
  315. #if defined(WIN32) && defined(ZLIB_USES_WINAPI)
  316. # define ZEXPORT WINAPI
  317. #else
  318. # define ZEXPORT
  319. #endif
  320. static int (ZEXPORT *qz_inflate) (z_stream* strm, int flush);
  321. static int (ZEXPORT *qz_inflateEnd) (z_stream* strm);
  322. static int (ZEXPORT *qz_inflateInit2_) (z_stream* strm, int windowBits, const char *version, int stream_size);
  323. static int (ZEXPORT *qz_inflateReset) (z_stream* strm);
  324. static int (ZEXPORT *qz_deflateInit2_) (z_stream* strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size);
  325. static int (ZEXPORT *qz_deflateEnd) (z_stream* strm);
  326. static int (ZEXPORT *qz_deflate) (z_stream* strm, int flush);
  327. #endif
  328. #define qz_inflateInit2(strm, windowBits) \
  329. qz_inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  330. #define qz_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  331. qz_deflateInit2_((strm), (level), (method), (windowBits), (memLevel), (strategy), ZLIB_VERSION, sizeof(z_stream))
  332. #ifndef LINK_TO_ZLIB
  333. // qz_deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  334. static dllfunction_t zlibfuncs[] =
  335. {
  336. {"inflate", (void **) &qz_inflate},
  337. {"inflateEnd", (void **) &qz_inflateEnd},
  338. {"inflateInit2_", (void **) &qz_inflateInit2_},
  339. {"inflateReset", (void **) &qz_inflateReset},
  340. {"deflateInit2_", (void **) &qz_deflateInit2_},
  341. {"deflateEnd", (void **) &qz_deflateEnd},
  342. {"deflate", (void **) &qz_deflate},
  343. {NULL, NULL}
  344. };
  345. /// Handle for Zlib DLL
  346. static dllhandle_t zlib_dll = NULL;
  347. #endif
  348. #ifdef WIN32
  349. static HRESULT (WINAPI *qSHGetFolderPath) (HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath);
  350. static dllfunction_t shfolderfuncs[] =
  351. {
  352. {"SHGetFolderPathA", (void **) &qSHGetFolderPath},
  353. {NULL, NULL}
  354. };
  355. static const char* shfolderdllnames [] =
  356. {
  357. "shfolder.dll", // IE 4, or Win NT and higher
  358. NULL
  359. };
  360. static dllhandle_t shfolder_dll = NULL;
  361. const GUID qFOLDERID_SavedGames = {0x4C5C32FF, 0xBB9D, 0x43b0, {0xB5, 0xB4, 0x2D, 0x72, 0xE5, 0x4E, 0xAA, 0xA4}};
  362. #define qREFKNOWNFOLDERID const GUID *
  363. #define qKF_FLAG_CREATE 0x8000
  364. #define qKF_FLAG_NO_ALIAS 0x1000
  365. static HRESULT (WINAPI *qSHGetKnownFolderPath) (qREFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
  366. static dllfunction_t shell32funcs[] =
  367. {
  368. {"SHGetKnownFolderPath", (void **) &qSHGetKnownFolderPath},
  369. {NULL, NULL}
  370. };
  371. static const char* shell32dllnames [] =
  372. {
  373. "shell32.dll", // Vista and higher
  374. NULL
  375. };
  376. static dllhandle_t shell32_dll = NULL;
  377. static HRESULT (WINAPI *qCoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit);
  378. static void (WINAPI *qCoUninitialize)(void);
  379. static void (WINAPI *qCoTaskMemFree)(LPVOID pv);
  380. static dllfunction_t ole32funcs[] =
  381. {
  382. {"CoInitializeEx", (void **) &qCoInitializeEx},
  383. {"CoUninitialize", (void **) &qCoUninitialize},
  384. {"CoTaskMemFree", (void **) &qCoTaskMemFree},
  385. {NULL, NULL}
  386. };
  387. static const char* ole32dllnames [] =
  388. {
  389. "ole32.dll", // 2000 and higher
  390. NULL
  391. };
  392. static dllhandle_t ole32_dll = NULL;
  393. #endif
  394. /*
  395. ====================
  396. PK3_CloseLibrary
  397. Unload the Zlib DLL
  398. ====================
  399. */
  400. static void PK3_CloseLibrary (void)
  401. {
  402. #ifndef LINK_TO_ZLIB
  403. Sys_UnloadLibrary (&zlib_dll);
  404. #endif
  405. }
  406. /*
  407. ====================
  408. PK3_OpenLibrary
  409. Try to load the Zlib DLL
  410. ====================
  411. */
  412. static qboolean PK3_OpenLibrary (void)
  413. {
  414. #ifdef LINK_TO_ZLIB
  415. return true;
  416. #else
  417. const char* dllnames [] =
  418. {
  419. #if defined(WIN32)
  420. # ifdef ZLIB_USES_WINAPI
  421. "zlibwapi.dll",
  422. "zlib.dll",
  423. # else
  424. "zlib1.dll",
  425. # endif
  426. #elif defined(MACOSX)
  427. "libz.dylib",
  428. #else
  429. "libz.so.1",
  430. "libz.so",
  431. #endif
  432. NULL
  433. };
  434. // Already loaded?
  435. if (zlib_dll)
  436. return true;
  437. // Load the DLL
  438. return Sys_LoadLibrary (dllnames, &zlib_dll, zlibfuncs);
  439. #endif
  440. }
  441. /*
  442. ====================
  443. FS_HasZlib
  444. See if zlib is available
  445. ====================
  446. */
  447. qboolean FS_HasZlib(void)
  448. {
  449. #ifdef LINK_TO_ZLIB
  450. return true;
  451. #else
  452. PK3_OpenLibrary(); // to be safe
  453. return (zlib_dll != 0);
  454. #endif
  455. }
  456. /*
  457. ====================
  458. PK3_GetEndOfCentralDir
  459. Extract the end of the central directory from a PK3 package
  460. ====================
  461. */
  462. static qboolean PK3_GetEndOfCentralDir (const char *packfile, filedesc_t packhandle, pk3_endOfCentralDir_t *eocd)
  463. {
  464. fs_offset_t filesize, maxsize;
  465. unsigned char *buffer, *ptr;
  466. int ind;
  467. // Get the package size
  468. filesize = FILEDESC_SEEK (packhandle, 0, SEEK_END);
  469. if (filesize < ZIP_END_CDIR_SIZE)
  470. return false;
  471. // Load the end of the file in memory
  472. if (filesize < ZIP_MAX_COMMENTS_SIZE + ZIP_END_CDIR_SIZE)
  473. maxsize = filesize;
  474. else
  475. maxsize = ZIP_MAX_COMMENTS_SIZE + ZIP_END_CDIR_SIZE;
  476. buffer = (unsigned char *)Mem_Alloc (tempmempool, maxsize);
  477. FILEDESC_SEEK (packhandle, filesize - maxsize, SEEK_SET);
  478. if (FILEDESC_READ (packhandle, buffer, maxsize) != (fs_offset_t) maxsize)
  479. {
  480. Mem_Free (buffer);
  481. return false;
  482. }
  483. // Look for the end of central dir signature around the end of the file
  484. maxsize -= ZIP_END_CDIR_SIZE;
  485. ptr = &buffer[maxsize];
  486. ind = 0;
  487. while (BuffBigLong (ptr) != ZIP_END_HEADER)
  488. {
  489. if (ind == maxsize)
  490. {
  491. Mem_Free (buffer);
  492. return false;
  493. }
  494. ind++;
  495. ptr--;
  496. }
  497. memcpy (eocd, ptr, ZIP_END_CDIR_SIZE);
  498. eocd->signature = LittleLong (eocd->signature);
  499. eocd->disknum = LittleShort (eocd->disknum);
  500. eocd->cdir_disknum = LittleShort (eocd->cdir_disknum);
  501. eocd->localentries = LittleShort (eocd->localentries);
  502. eocd->nbentries = LittleShort (eocd->nbentries);
  503. eocd->cdir_size = LittleLong (eocd->cdir_size);
  504. eocd->cdir_offset = LittleLong (eocd->cdir_offset);
  505. eocd->comment_size = LittleShort (eocd->comment_size);
  506. eocd->prepended_garbage = filesize - (ind + ZIP_END_CDIR_SIZE) - eocd->cdir_offset - eocd->cdir_size; // this detects "SFX" zip files
  507. eocd->cdir_offset += eocd->prepended_garbage;
  508. Mem_Free (buffer);
  509. if (
  510. eocd->cdir_size > filesize ||
  511. eocd->cdir_offset >= filesize ||
  512. eocd->cdir_offset + eocd->cdir_size > filesize
  513. )
  514. {
  515. // Obviously invalid central directory.
  516. return false;
  517. }
  518. return true;
  519. }
  520. /*
  521. ====================
  522. PK3_BuildFileList
  523. Extract the file list from a PK3 file
  524. ====================
  525. */
  526. static int PK3_BuildFileList (pack_t *pack, const pk3_endOfCentralDir_t *eocd)
  527. {
  528. unsigned char *central_dir, *ptr;
  529. unsigned int ind;
  530. fs_offset_t remaining;
  531. // Load the central directory in memory
  532. central_dir = (unsigned char *)Mem_Alloc (tempmempool, eocd->cdir_size);
  533. if (FILEDESC_SEEK (pack->handle, eocd->cdir_offset, SEEK_SET) == -1)
  534. {
  535. Mem_Free (central_dir);
  536. return -1;
  537. }
  538. if(FILEDESC_READ (pack->handle, central_dir, eocd->cdir_size) != (fs_offset_t) eocd->cdir_size)
  539. {
  540. Mem_Free (central_dir);
  541. return -1;
  542. }
  543. // Extract the files properties
  544. // The parsing is done "by hand" because some fields have variable sizes and
  545. // the constant part isn't 4-bytes aligned, which makes the use of structs difficult
  546. remaining = eocd->cdir_size;
  547. pack->numfiles = 0;
  548. ptr = central_dir;
  549. for (ind = 0; ind < eocd->nbentries; ind++)
  550. {
  551. fs_offset_t namesize, count;
  552. // Checking the remaining size
  553. if (remaining < ZIP_CDIR_CHUNK_BASE_SIZE)
  554. {
  555. Mem_Free (central_dir);
  556. return -1;
  557. }
  558. remaining -= ZIP_CDIR_CHUNK_BASE_SIZE;
  559. // Check header
  560. if (BuffBigLong (ptr) != ZIP_CDIR_HEADER)
  561. {
  562. Mem_Free (central_dir);
  563. return -1;
  564. }
  565. namesize = BuffLittleShort (&ptr[28]); // filename length
  566. // Check encryption, compression, and attributes
  567. // 1st uint8 : general purpose bit flag
  568. // Check bits 0 (encryption), 3 (data descriptor after the file), and 5 (compressed patched data (?))
  569. //
  570. // LordHavoc: bit 3 would be a problem if we were scanning the archive
  571. // but is not a problem in the central directory where the values are
  572. // always real.
  573. //
  574. // bit 3 seems to always be set by the standard Mac OSX zip maker
  575. //
  576. // 2nd uint8 : external file attributes
  577. // Check bits 3 (file is a directory) and 5 (file is a volume (?))
  578. if ((ptr[8] & 0x21) == 0 && (ptr[38] & 0x18) == 0)
  579. {
  580. // Still enough bytes for the name?
  581. if (namesize < 0 || remaining < namesize || namesize >= (int)sizeof (*pack->files))
  582. {
  583. Mem_Free (central_dir);
  584. return -1;
  585. }
  586. // WinZip doesn't use the "directory" attribute, so we need to check the name directly
  587. if (ptr[ZIP_CDIR_CHUNK_BASE_SIZE + namesize - 1] != '/')
  588. {
  589. char filename [sizeof (pack->files[0].name)];
  590. fs_offset_t offset, packsize, realsize;
  591. int flags;
  592. // Extract the name (strip it if necessary)
  593. namesize = min(namesize, (int)sizeof (filename) - 1);
  594. memcpy (filename, &ptr[ZIP_CDIR_CHUNK_BASE_SIZE], namesize);
  595. filename[namesize] = '\0';
  596. if (BuffLittleShort (&ptr[10]))
  597. flags = PACKFILE_FLAG_DEFLATED;
  598. else
  599. flags = 0;
  600. offset = (unsigned int)(BuffLittleLong (&ptr[42]) + eocd->prepended_garbage);
  601. packsize = (unsigned int)BuffLittleLong (&ptr[20]);
  602. realsize = (unsigned int)BuffLittleLong (&ptr[24]);
  603. switch(ptr[5]) // C_VERSION_MADE_BY_1
  604. {
  605. case 3: // UNIX_
  606. case 2: // VMS_
  607. case 16: // BEOS_
  608. if((BuffLittleShort(&ptr[40]) & 0120000) == 0120000)
  609. // can't use S_ISLNK here, as this has to compile on non-UNIX too
  610. flags |= PACKFILE_FLAG_SYMLINK;
  611. break;
  612. }
  613. FS_AddFileToPack (filename, pack, offset, packsize, realsize, flags);
  614. }
  615. }
  616. // Skip the name, additionnal field, and comment
  617. // 1er uint16 : extra field length
  618. // 2eme uint16 : file comment length
  619. count = namesize + BuffLittleShort (&ptr[30]) + BuffLittleShort (&ptr[32]);
  620. ptr += ZIP_CDIR_CHUNK_BASE_SIZE + count;
  621. remaining -= count;
  622. }
  623. // If the package is empty, central_dir is NULL here
  624. if (central_dir != NULL)
  625. Mem_Free (central_dir);
  626. return pack->numfiles;
  627. }
  628. /*
  629. ====================
  630. FS_LoadPackPK3
  631. Create a package entry associated with a PK3 file
  632. ====================
  633. */
  634. static pack_t *FS_LoadPackPK3FromFD (const char *packfile, filedesc_t packhandle, qboolean silent)
  635. {
  636. pk3_endOfCentralDir_t eocd;
  637. pack_t *pack;
  638. int real_nb_files;
  639. if (! PK3_GetEndOfCentralDir (packfile, packhandle, &eocd))
  640. {
  641. if(!silent)
  642. Con_Printf ("%s is not a PK3 file\n", packfile);
  643. FILEDESC_CLOSE(packhandle);
  644. return NULL;
  645. }
  646. // Multi-volume ZIP archives are NOT allowed
  647. if (eocd.disknum != 0 || eocd.cdir_disknum != 0)
  648. {
  649. Con_Printf ("%s is a multi-volume ZIP archive\n", packfile);
  650. FILEDESC_CLOSE(packhandle);
  651. return NULL;
  652. }
  653. // We only need to do this test if MAX_FILES_IN_PACK is lesser than 65535
  654. // since eocd.nbentries is an unsigned 16 bits integer
  655. #if MAX_FILES_IN_PACK < 65535
  656. if (eocd.nbentries > MAX_FILES_IN_PACK)
  657. {
  658. Con_Printf ("%s contains too many files (%hu)\n", packfile, eocd.nbentries);
  659. FILEDESC_CLOSE(packhandle);
  660. return NULL;
  661. }
  662. #endif
  663. // Create a package structure in memory
  664. pack = (pack_t *)Mem_Alloc(fs_mempool, sizeof (pack_t));
  665. pack->ignorecase = true; // PK3 ignores case
  666. strlcpy (pack->filename, packfile, sizeof (pack->filename));
  667. pack->handle = packhandle;
  668. pack->numfiles = eocd.nbentries;
  669. pack->files = (packfile_t *)Mem_Alloc(fs_mempool, eocd.nbentries * sizeof(packfile_t));
  670. real_nb_files = PK3_BuildFileList (pack, &eocd);
  671. if (real_nb_files < 0)
  672. {
  673. Con_Printf ("%s is not a valid PK3 file\n", packfile);
  674. FILEDESC_CLOSE(pack->handle);
  675. Mem_Free(pack);
  676. return NULL;
  677. }
  678. Con_DPrintf("Added packfile %s (%i files)\n", packfile, real_nb_files);
  679. return pack;
  680. }
  681. static filedesc_t FS_SysOpenFiledesc(const char *filepath, const char *mode, qboolean nonblocking);
  682. static pack_t *FS_LoadPackPK3 (const char *packfile)
  683. {
  684. filedesc_t packhandle;
  685. packhandle = FS_SysOpenFiledesc (packfile, "rb", false);
  686. if (!FILEDESC_ISVALID(packhandle))
  687. return NULL;
  688. return FS_LoadPackPK3FromFD(packfile, packhandle, false);
  689. }
  690. /*
  691. ====================
  692. PK3_GetTrueFileOffset
  693. Find where the true file data offset is
  694. ====================
  695. */
  696. static qboolean PK3_GetTrueFileOffset (packfile_t *pfile, pack_t *pack)
  697. {
  698. unsigned char buffer [ZIP_LOCAL_CHUNK_BASE_SIZE];
  699. fs_offset_t count;
  700. // Already found?
  701. if (pfile->flags & PACKFILE_FLAG_TRUEOFFS)
  702. return true;
  703. // Load the local file description
  704. if (FILEDESC_SEEK (pack->handle, pfile->offset, SEEK_SET) == -1)
  705. {
  706. Con_Printf ("Can't seek in package %s\n", pack->filename);
  707. return false;
  708. }
  709. count = FILEDESC_READ (pack->handle, buffer, ZIP_LOCAL_CHUNK_BASE_SIZE);
  710. if (count != ZIP_LOCAL_CHUNK_BASE_SIZE || BuffBigLong (buffer) != ZIP_DATA_HEADER)
  711. {
  712. Con_Printf ("Can't retrieve file %s in package %s\n", pfile->name, pack->filename);
  713. return false;
  714. }
  715. // Skip name and extra field
  716. pfile->offset += BuffLittleShort (&buffer[26]) + BuffLittleShort (&buffer[28]) + ZIP_LOCAL_CHUNK_BASE_SIZE;
  717. pfile->flags |= PACKFILE_FLAG_TRUEOFFS;
  718. return true;
  719. }
  720. /*
  721. =============================================================================
  722. OTHER PRIVATE FUNCTIONS
  723. =============================================================================
  724. */
  725. /*
  726. ====================
  727. FS_AddFileToPack
  728. Add a file to the list of files contained into a package
  729. ====================
  730. */
  731. static packfile_t* FS_AddFileToPack (const char* name, pack_t* pack,
  732. fs_offset_t offset, fs_offset_t packsize,
  733. fs_offset_t realsize, int flags)
  734. {
  735. int (*strcmp_funct) (const char* str1, const char* str2);
  736. int left, right, middle;
  737. packfile_t *pfile;
  738. strcmp_funct = pack->ignorecase ? strcasecmp : strcmp;
  739. // Look for the slot we should put that file into (binary search)
  740. left = 0;
  741. right = pack->numfiles - 1;
  742. while (left <= right)
  743. {
  744. int diff;
  745. middle = (left + right) / 2;
  746. diff = strcmp_funct (pack->files[middle].name, name);
  747. // If we found the file, there's a problem
  748. if (!diff)
  749. Con_Printf ("Package %s contains the file %s several times\n", pack->filename, name);
  750. // If we're too far in the list
  751. if (diff > 0)
  752. right = middle - 1;
  753. else
  754. left = middle + 1;
  755. }
  756. // We have to move the right of the list by one slot to free the one we need
  757. pfile = &pack->files[left];
  758. memmove (pfile + 1, pfile, (pack->numfiles - left) * sizeof (*pfile));
  759. pack->numfiles++;
  760. strlcpy (pfile->name, name, sizeof (pfile->name));
  761. pfile->offset = offset;
  762. pfile->packsize = packsize;
  763. pfile->realsize = realsize;
  764. pfile->flags = flags;
  765. return pfile;
  766. }
  767. static void FS_mkdir (const char *path)
  768. {
  769. if(COM_CheckParm("-readonly"))
  770. return;
  771. #if WIN32
  772. if (_mkdir (path) == -1)
  773. #else
  774. if (mkdir (path, 0777) == -1)
  775. #endif
  776. {
  777. // No logging for this. The only caller is FS_CreatePath (which
  778. // calls it in ways that will intentionally produce EEXIST),
  779. // and its own callers always use the directory afterwards and
  780. // thus will detect failure that way.
  781. }
  782. }
  783. /*
  784. ============
  785. FS_CreatePath
  786. Only used for FS_OpenRealFile.
  787. ============
  788. */
  789. void FS_CreatePath (char *path)
  790. {
  791. char *ofs, save;
  792. for (ofs = path+1 ; *ofs ; ofs++)
  793. {
  794. if (*ofs == '/' || *ofs == '\\')
  795. {
  796. // create the directory
  797. save = *ofs;
  798. *ofs = 0;
  799. FS_mkdir (path);
  800. *ofs = save;
  801. }
  802. }
  803. }
  804. /*
  805. ============
  806. FS_Path_f
  807. ============
  808. */
  809. static void FS_Path_f (void)
  810. {
  811. searchpath_t *s;
  812. Con_Print("Current search path:\n");
  813. for (s=fs_searchpaths ; s ; s=s->next)
  814. {
  815. if (s->pack)
  816. {
  817. if(s->pack->vpack)
  818. Con_Printf("%sdir (virtual pack)\n", s->pack->filename);
  819. else
  820. Con_Printf("%s (%i files)\n", s->pack->filename, s->pack->numfiles);
  821. }
  822. else
  823. Con_Printf("%s\n", s->filename);
  824. }
  825. }
  826. /*
  827. =================
  828. FS_LoadPackPAK
  829. =================
  830. */
  831. /*! Takes an explicit (not game tree related) path to a pak file.
  832. *Loads the header and directory, adding the files at the beginning
  833. *of the list so they override previous pack files.
  834. */
  835. static pack_t *FS_LoadPackPAK (const char *packfile)
  836. {
  837. dpackheader_t header;
  838. int i, numpackfiles;
  839. filedesc_t packhandle;
  840. pack_t *pack;
  841. dpackfile_t *info;
  842. packhandle = FS_SysOpenFiledesc(packfile, "rb", false);
  843. if (!FILEDESC_ISVALID(packhandle))
  844. return NULL;
  845. if(FILEDESC_READ (packhandle, (void *)&header, sizeof(header)) != sizeof(header))
  846. {
  847. Con_Printf ("%s is not a packfile\n", packfile);
  848. FILEDESC_CLOSE(packhandle);
  849. return NULL;
  850. }
  851. if (memcmp(header.id, "PACK", 4))
  852. {
  853. Con_Printf ("%s is not a packfile\n", packfile);
  854. FILEDESC_CLOSE(packhandle);
  855. return NULL;
  856. }
  857. header.dirofs = LittleLong (header.dirofs);
  858. header.dirlen = LittleLong (header.dirlen);
  859. if (header.dirlen % sizeof(dpackfile_t))
  860. {
  861. Con_Printf ("%s has an invalid directory size\n", packfile);
  862. FILEDESC_CLOSE(packhandle);
  863. return NULL;
  864. }
  865. numpackfiles = header.dirlen / sizeof(dpackfile_t);
  866. if (numpackfiles < 0 || numpackfiles > MAX_FILES_IN_PACK)
  867. {
  868. Con_Printf ("%s has %i files\n", packfile, numpackfiles);
  869. FILEDESC_CLOSE(packhandle);
  870. return NULL;
  871. }
  872. info = (dpackfile_t *)Mem_Alloc(tempmempool, sizeof(*info) * numpackfiles);
  873. FILEDESC_SEEK (packhandle, header.dirofs, SEEK_SET);
  874. if(header.dirlen != FILEDESC_READ (packhandle, (void *)info, header.dirlen))
  875. {
  876. Con_Printf("%s is an incomplete PAK, not loading\n", packfile);
  877. Mem_Free(info);
  878. FILEDESC_CLOSE(packhandle);
  879. return NULL;
  880. }
  881. pack = (pack_t *)Mem_Alloc(fs_mempool, sizeof (pack_t));
  882. pack->ignorecase = true; // PAK is sensitive in Quake1 but insensitive in Quake2
  883. strlcpy (pack->filename, packfile, sizeof (pack->filename));
  884. pack->handle = packhandle;
  885. pack->numfiles = 0;
  886. pack->files = (packfile_t *)Mem_Alloc(fs_mempool, numpackfiles * sizeof(packfile_t));
  887. // parse the directory
  888. for (i = 0;i < numpackfiles;i++)
  889. {
  890. fs_offset_t offset = (unsigned int)LittleLong (info[i].filepos);
  891. fs_offset_t size = (unsigned int)LittleLong (info[i].filelen);
  892. // Ensure a zero terminated file name (required by format).
  893. info[i].name[sizeof(info[i].name) - 1] = 0;
  894. FS_AddFileToPack (info[i].name, pack, offset, size, size, PACKFILE_FLAG_TRUEOFFS);
  895. }
  896. Mem_Free(info);
  897. Con_DPrintf("Added packfile %s (%i files)\n", packfile, numpackfiles);
  898. return pack;
  899. }
  900. /*
  901. ====================
  902. FS_LoadPackVirtual
  903. Create a package entry associated with a directory file
  904. ====================
  905. */
  906. static pack_t *FS_LoadPackVirtual (const char *dirname)
  907. {
  908. pack_t *pack;
  909. pack = (pack_t *)Mem_Alloc(fs_mempool, sizeof (pack_t));
  910. pack->vpack = true;
  911. pack->ignorecase = false;
  912. strlcpy (pack->filename, dirname, sizeof(pack->filename));
  913. pack->handle = FILEDESC_INVALID;
  914. pack->numfiles = -1;
  915. pack->files = NULL;
  916. Con_DPrintf("Added packfile %s (virtual pack)\n", dirname);
  917. return pack;
  918. }
  919. /*
  920. ================
  921. FS_AddPack_Fullpath
  922. ================
  923. */
  924. /*! Adds the given pack to the search path.
  925. * The pack type is autodetected by the file extension.
  926. *
  927. * Returns true if the file was successfully added to the
  928. * search path or if it was already included.
  929. *
  930. * If keep_plain_dirs is set, the pack will be added AFTER the first sequence of
  931. * plain directories.
  932. *
  933. */
  934. static qboolean FS_AddPack_Fullpath(const char *pakfile, const char *shortname, qboolean *already_loaded, qboolean keep_plain_dirs)
  935. {
  936. searchpath_t *search;
  937. pack_t *pak = NULL;
  938. const char *ext = FS_FileExtension(pakfile);
  939. size_t l;
  940. for(search = fs_searchpaths; search; search = search->next)
  941. {
  942. if(search->pack && !strcasecmp(search->pack->filename, pakfile))
  943. {
  944. if(already_loaded)
  945. *already_loaded = true;
  946. return true; // already loaded
  947. }
  948. }
  949. if(already_loaded)
  950. *already_loaded = false;
  951. if(!strcasecmp(ext, "pk3dir"))
  952. pak = FS_LoadPackVirtual (pakfile);
  953. else if(!strcasecmp(ext, "pak"))
  954. pak = FS_LoadPackPAK (pakfile);
  955. else if(!strcasecmp(ext, "pk3"))
  956. pak = FS_LoadPackPK3 (pakfile);
  957. else if(!strcasecmp(ext, "obb")) // android apk expansion
  958. pak = FS_LoadPackPK3 (pakfile);
  959. else
  960. Con_Printf("\"%s\" does not have a pack extension\n", pakfile);
  961. if(pak)
  962. {
  963. strlcpy(pak->shortname, shortname, sizeof(pak->shortname));
  964. //Con_DPrintf(" Registered pack with short name %s\n", shortname);
  965. if(keep_plain_dirs)
  966. {
  967. // find the first item whose next one is a pack or NULL
  968. searchpath_t *insertion_point = 0;
  969. if(fs_searchpaths && !fs_searchpaths->pack)
  970. {
  971. insertion_point = fs_searchpaths;
  972. for(;;)
  973. {
  974. if(!insertion_point->next)
  975. break;
  976. if(insertion_point->next->pack)
  977. break;
  978. insertion_point = insertion_point->next;
  979. }
  980. }
  981. // If insertion_point is NULL, this means that either there is no
  982. // item in the list yet, or that the very first item is a pack. In
  983. // that case, we want to insert at the beginning...
  984. if(!insertion_point)
  985. {
  986. search = (searchpath_t *)Mem_Alloc(fs_mempool, sizeof(searchpath_t));
  987. search->next = fs_searchpaths;
  988. fs_searchpaths = search;
  989. }
  990. else
  991. // otherwise we want to append directly after insertion_point.
  992. {
  993. search = (searchpath_t *)Mem_Alloc(fs_mempool, sizeof(searchpath_t));
  994. search->next = insertion_point->next;
  995. insertion_point->next = search;
  996. }
  997. }
  998. else
  999. {
  1000. search = (searchpath_t *)Mem_Alloc(fs_mempool, sizeof(searchpath_t));
  1001. search->next = fs_searchpaths;
  1002. fs_searchpaths = search;
  1003. }
  1004. search->pack = pak;
  1005. if(pak->vpack)
  1006. {
  1007. dpsnprintf(search->filename, sizeof(search->filename), "%s/", pakfile);
  1008. // if shortname ends with "pk3dir", strip that suffix to make it just "pk3"
  1009. // same goes for the name inside the pack structure
  1010. l = strlen(pak->shortname);
  1011. if(l >= 7)
  1012. if(!strcasecmp(pak->shortname + l - 7, ".pk3dir"))
  1013. pak->shortname[l - 3] = 0;
  1014. l = strlen(pak->filename);
  1015. if(l >= 7)
  1016. if(!strcasecmp(pak->filename + l - 7, ".pk3dir"))
  1017. pak->filename[l - 3] = 0;
  1018. }
  1019. return true;
  1020. }
  1021. else
  1022. {
  1023. Con_Printf("unable to load pak \"%s\"\n", pakfile);
  1024. return false;
  1025. }
  1026. }
  1027. /*
  1028. ================
  1029. FS_AddPack
  1030. ================
  1031. */
  1032. /*! Adds the given pack to the search path and searches for it in the game path.
  1033. * The pack type is autodetected by the file extension.
  1034. *
  1035. * Returns true if the file was successfully added to the
  1036. * search path or if it was already included.
  1037. *
  1038. * If keep_plain_dirs is set, the pack will be added AFTER the first sequence of
  1039. * plain directories.
  1040. */
  1041. qboolean FS_AddPack(const char *pakfile, qboolean *already_loaded, qboolean keep_plain_dirs)
  1042. {
  1043. char fullpath[MAX_OSPATH];
  1044. int index;
  1045. searchpath_t *search;
  1046. if(already_loaded)
  1047. *already_loaded = false;
  1048. // then find the real name...
  1049. search = FS_FindFile(pakfile, &index, true);
  1050. if(!search || search->pack)
  1051. {
  1052. Con_Printf("could not find pak \"%s\"\n", pakfile);
  1053. return false;
  1054. }
  1055. dpsnprintf(fullpath, sizeof(fullpath), "%s%s", search->filename, pakfile);
  1056. return FS_AddPack_Fullpath(fullpath, pakfile, already_loaded, keep_plain_dirs);
  1057. }
  1058. /*
  1059. ================
  1060. FS_AddGameDirectory
  1061. Sets fs_gamedir, adds the directory to the head of the path,
  1062. then loads and adds pak1.pak pak2.pak ...
  1063. ================
  1064. */
  1065. static void FS_AddGameDirectory (const char *dir)
  1066. {
  1067. int i;
  1068. stringlist_t list;
  1069. searchpath_t *search;
  1070. strlcpy (fs_gamedir, dir, sizeof (fs_gamedir));
  1071. stringlistinit(&list);
  1072. listdirectory(&list, "", dir);
  1073. stringlistsort(&list, false);
  1074. // add any PAK package in the directory
  1075. for (i = 0;i < list.numstrings;i++)
  1076. {
  1077. if (!strcasecmp(FS_FileExtension(list.strings[i]), "pak"))
  1078. {
  1079. FS_AddPack_Fullpath(list.strings[i], list.strings[i] + strlen(dir), NULL, false);
  1080. }
  1081. }
  1082. // add any PK3 package in the directory
  1083. for (i = 0;i < list.numstrings;i++)
  1084. {
  1085. if (!strcasecmp(FS_FileExtension(list.strings[i]), "pk3") || !strcasecmp(FS_FileExtension(list.strings[i]), "obb") || !strcasecmp(FS_FileExtension(list.strings[i]), "pk3dir"))
  1086. {
  1087. FS_AddPack_Fullpath(list.strings[i], list.strings[i] + strlen(dir), NULL, false);
  1088. }
  1089. }
  1090. stringlistfreecontents(&list);
  1091. // Add the directory to the search path
  1092. // (unpacked files have the priority over packed files)
  1093. search = (searchpath_t *)Mem_Alloc(fs_mempool, sizeof(searchpath_t));
  1094. strlcpy (search->filename, dir, sizeof (search->filename));
  1095. search->next = fs_searchpaths;
  1096. fs_searchpaths = search;
  1097. }
  1098. /*
  1099. ================
  1100. FS_AddGameHierarchy
  1101. ================
  1102. */
  1103. static void FS_AddGameHierarchy (const char *dir)
  1104. {
  1105. char vabuf[1024];
  1106. // Add the common game directory
  1107. FS_AddGameDirectory (va(vabuf, sizeof(vabuf), "%s%s/", fs_basedir, dir));
  1108. if (*fs_userdir)
  1109. FS_AddGameDirectory(va(vabuf, sizeof(vabuf), "%s%s/", fs_userdir, dir));
  1110. }
  1111. /*
  1112. ============
  1113. FS_FileExtension
  1114. ============
  1115. */
  1116. const char *FS_FileExtension (const char *in)
  1117. {
  1118. const char *separator, *backslash, *colon, *dot;
  1119. separator = strrchr(in, '/');
  1120. backslash = strrchr(in, '\\');
  1121. if (!separator || separator < backslash)
  1122. separator = backslash;
  1123. colon = strrchr(in, ':');
  1124. if (!separator || separator < colon)
  1125. separator = colon;
  1126. dot = strrchr(in, '.');
  1127. if (dot == NULL || (separator && (dot < separator)))
  1128. return "";
  1129. return dot + 1;
  1130. }
  1131. /*
  1132. ============
  1133. FS_FileWithoutPath
  1134. ============
  1135. */
  1136. const char *FS_FileWithoutPath (const char *in)
  1137. {
  1138. const char *separator, *backslash, *colon;
  1139. separator = strrchr(in, '/');
  1140. backslash = strrchr(in, '\\');
  1141. if (!separator || separator < backslash)
  1142. separator = backslash;
  1143. colon = strrchr(in, ':');
  1144. if (!separator || separator < colon)
  1145. separator = colon;
  1146. return separator ? separator + 1 : in;
  1147. }
  1148. /*
  1149. ================
  1150. FS_ClearSearchPath
  1151. ================
  1152. */
  1153. static void FS_ClearSearchPath (void)
  1154. {
  1155. // unload all packs and directory information, close all pack files
  1156. // (if a qfile is still reading a pack it won't be harmed because it used
  1157. // dup() to get its own handle already)
  1158. while (fs_searchpaths)
  1159. {
  1160. searchpath_t *search = fs_searchpaths;
  1161. fs_searchpaths = search->next;
  1162. if (search->pack && search->pack != fs_selfpack)
  1163. {
  1164. if(!search->pack->vpack)
  1165. {
  1166. // close the file
  1167. FILEDESC_CLOSE(search->pack->handle);
  1168. // free any memory associated with it
  1169. if (search->pack->files)
  1170. Mem_Free(search->pack->files);
  1171. }
  1172. Mem_Free(search->pack);
  1173. }
  1174. Mem_Free(search);
  1175. }
  1176. }
  1177. static void FS_AddSelfPack(void)
  1178. {
  1179. if(fs_selfpack)
  1180. {
  1181. searchpath_t *search;
  1182. search = (searchpath_t *)Mem_Alloc(fs_mempool, sizeof(searchpath_t));
  1183. search->next = fs_searchpaths;
  1184. search->pack = fs_selfpack;
  1185. fs_searchpaths = search;
  1186. }
  1187. }
  1188. /*
  1189. ================
  1190. FS_Rescan
  1191. ================
  1192. */
  1193. void FS_Rescan (void)
  1194. {
  1195. int i;
  1196. qboolean fs_modified = false;
  1197. qboolean reset = false;
  1198. char gamedirbuf[MAX_INPUTLINE];
  1199. char vabuf[1024];
  1200. if (fs_searchpaths)
  1201. reset = true;
  1202. FS_ClearSearchPath();
  1203. // automatically activate gamemode for the gamedirs specified
  1204. if (reset)
  1205. COM_ChangeGameTypeForGameDirs();
  1206. // add the game-specific paths
  1207. // gamedirname1 (typically id1)
  1208. FS_AddGameHierarchy (gamedirname1);
  1209. // update the com_modname (used for server info)
  1210. if (gamedirname2 && gamedirname2[0])
  1211. strlcpy(com_modname, gamedirname2, sizeof(com_modname));
  1212. else
  1213. strlcpy(com_modname, gamedirname1, sizeof(com_modname));
  1214. // add the game-specific path, if any
  1215. // (only used for mission packs and the like, which should set fs_modified)
  1216. if (gamedirname2 && gamedirname2[0])
  1217. {
  1218. fs_modified = true;
  1219. FS_AddGameHierarchy (gamedirname2);
  1220. }
  1221. // -game <gamedir>
  1222. // Adds basedir/gamedir as an override game
  1223. // LordHavoc: now supports multiple -game directories
  1224. // set the com_modname (reported in server info)
  1225. *gamedirbuf = 0;
  1226. for (i = 0;i < fs_numgamedirs;i++)
  1227. {
  1228. fs_modified = true;
  1229. FS_AddGameHierarchy (fs_gamedirs[i]);
  1230. // update the com_modname (used server info)
  1231. strlcpy (com_modname, fs_gamedirs[i], sizeof (com_modname));
  1232. if(i)
  1233. strlcat(gamedirbuf, va(vabuf, sizeof(vabuf), " %s", fs_gamedirs[i]), sizeof(gamedirbuf));
  1234. else
  1235. strlcpy(gamedirbuf, fs_gamedirs[i], sizeof(gamedirbuf));
  1236. }
  1237. Cvar_SetQuick(&cvar_fs_gamedir, gamedirbuf); // so QC or console code can query it
  1238. // add back the selfpack as new first item
  1239. FS_AddSelfPack();
  1240. // set the default screenshot name to either the mod name or the
  1241. // gamemode screenshot name
  1242. if (strcmp(com_modname, gamedirname1))
  1243. Cvar_SetQuick (&scr_screenshot_name, com_modname);
  1244. else
  1245. Cvar_SetQuick (&scr_screenshot_name, gamescreenshotname);
  1246. if((i = COM_CheckParm("-modname")) && i < com_argc - 1)
  1247. strlcpy(com_modname, com_argv[i+1], sizeof(com_modname));
  1248. // If "-condebug" is in the command line, remove the previous log file
  1249. if (COM_CheckParm ("-condebug") != 0)
  1250. unlink (va(vabuf, sizeof(vabuf), "%s/qconsole.log", fs_gamedir));
  1251. // look for the pop.lmp file and set registered to true if it is found
  1252. if (FS_FileExists("gfx/pop.lmp"))
  1253. Cvar_Set ("registered", "1");
  1254. switch(gamemode)
  1255. {
  1256. case GAME_NORMAL:
  1257. case GAME_HIPNOTIC:
  1258. case GAME_ROGUE:
  1259. if (!registered.integer)
  1260. {
  1261. if (fs_modified)
  1262. Con_Print("Playing shareware version, with modification.\nwarning: most mods require full quake data.\n");
  1263. else
  1264. Con_Print("Playing shareware version.\n");
  1265. }
  1266. else
  1267. Con_Print("Playing registered version.\n");
  1268. break;
  1269. case GAME_STEELSTORM:
  1270. if (registered.integer)
  1271. Con_Print("Playing registered version.\n");
  1272. else
  1273. Con_Print("Playing shareware version.\n");
  1274. break;
  1275. default:
  1276. break;
  1277. }
  1278. // unload all wads so that future queries will return the new data
  1279. W_UnloadAll();
  1280. }
  1281. static void FS_Rescan_f(void)
  1282. {
  1283. FS_Rescan();
  1284. }
  1285. /*
  1286. ================
  1287. FS_ChangeGameDirs
  1288. ================
  1289. */
  1290. extern qboolean vid_opened;
  1291. qboolean FS_ChangeGameDirs(int numgamedirs, char gamedirs[][MAX_QPATH], qboolean complain, qboolean failmissing)
  1292. {
  1293. int i;
  1294. const char *p;
  1295. if (fs_numgamedirs == numgamedirs)
  1296. {
  1297. for (i = 0;i < numgamedirs;i++)
  1298. if (strcasecmp(fs_gamedirs[i], gamedirs[i]))
  1299. break;
  1300. if (i == numgamedirs)
  1301. return true; // already using this set of gamedirs, do nothing
  1302. }
  1303. if (numgamedirs > MAX_GAMEDIRS)
  1304. {
  1305. if (complain)
  1306. Con_Printf("That is too many gamedirs (%i > %i)\n", numgamedirs, MAX_GAMEDIRS);
  1307. return false; // too many gamedirs
  1308. }
  1309. for (i = 0;i < numgamedirs;i++)
  1310. {
  1311. // if string is nasty, reject it
  1312. p = FS_CheckGameDir(gamedirs[i]);
  1313. if(!p)
  1314. {
  1315. if (complain)
  1316. Con_Printf("Nasty gamedir name rejected: %s\n", gamedirs[i]);
  1317. return false; // nasty gamedirs
  1318. }
  1319. if(p == fs_checkgamedir_missing && failmissing)
  1320. {
  1321. if (complain)
  1322. Con_Printf("Gamedir missing: %s%s/\n", fs_basedir, gamedirs[i]);
  1323. return false; // missing gamedirs
  1324. }
  1325. }
  1326. Host_SaveConfig();
  1327. fs_numgamedirs = numgamedirs;
  1328. for (i = 0;i < fs_numgamedirs;i++)
  1329. strlcpy(fs_gamedirs[i], gamedirs[i], sizeof(fs_gamedirs[i]));
  1330. // reinitialize filesystem to detect the new paks
  1331. FS_Rescan();
  1332. if (cls.demoplayback)
  1333. {
  1334. CL_Disconnect_f();
  1335. cls.demonum = 0;
  1336. }
  1337. // unload all sounds so they will be reloaded from the new files as needed
  1338. S_UnloadAllSounds_f();
  1339. // close down the video subsystem, it will start up again when the config finishes...
  1340. VID_Stop();
  1341. vid_opened = false;
  1342. // restart the video subsystem after the config is executed
  1343. Cbuf_InsertText("\nloadconfig\nvid_restart\n\n");
  1344. return true;
  1345. }
  1346. /*
  1347. ================
  1348. FS_GameDir_f
  1349. ================
  1350. */
  1351. static void FS_GameDir_f (void)
  1352. {
  1353. int i;
  1354. int numgamedirs;
  1355. char gamedirs[MAX_GAMEDIRS][MAX_QPATH];
  1356. if (Cmd_Argc() < 2)
  1357. {
  1358. Con_Printf("gamedirs active:");
  1359. for (i = 0;i < fs_numgamedirs;i++)
  1360. Con_Printf(" %s", fs_gamedirs[i]);
  1361. Con_Printf("\n");
  1362. return;
  1363. }
  1364. numgamedirs = Cmd_Argc() - 1;
  1365. if (numgamedirs > MAX_GAMEDIRS)
  1366. {
  1367. Con_Printf("Too many gamedirs (%i > %i)\n", numgamedirs, MAX_GAMEDIRS);
  1368. return;
  1369. }
  1370. for (i = 0;i < numgamedirs;i++)
  1371. strlcpy(gamedirs[i], Cmd_Argv(i+1), sizeof(gamedirs[i]));
  1372. if ((cls.state == ca_connected && !cls.demoplayback) || sv.active)
  1373. {
  1374. // actually, changing during game would work fine, but would be stupid
  1375. Con_Printf("Can not change gamedir while client is connected or server is running!\n");
  1376. return;
  1377. }
  1378. // halt demo playback to close the file
  1379. CL_Disconnect();
  1380. FS_ChangeGameDirs(numgamedirs, gamedirs, true, true);
  1381. }
  1382. static const char *FS_SysCheckGameDir(const char *gamedir, char *buf, size_t buflength)
  1383. {
  1384. qboolean success;
  1385. qfile_t *f;
  1386. stringlist_t list;
  1387. fs_offset_t n;
  1388. char vabuf[1024];
  1389. stringlistinit(&list);
  1390. listdirectory(&list, gamedir, "");
  1391. success = list.numstrings > 0;
  1392. stringlistfreecontents(&list);
  1393. if(success)
  1394. {
  1395. f = FS_SysOpen(va(vabuf, sizeof(vabuf), "%smodinfo.txt", gamedir), "r", false);
  1396. if(f)
  1397. {
  1398. n = FS_Read (f, buf, buflength - 1);
  1399. if(n >= 0)
  1400. buf[n] = 0;
  1401. else
  1402. *buf = 0;
  1403. FS_Close(f);
  1404. }
  1405. else
  1406. *buf = 0;
  1407. return buf;
  1408. }
  1409. return NULL;
  1410. }
  1411. /*
  1412. ================
  1413. FS_CheckGameDir
  1414. ================
  1415. */
  1416. const char *FS_CheckGameDir(const char *gamedir)
  1417. {
  1418. const char *ret;
  1419. static char buf[8192];
  1420. char vabuf[1024];
  1421. if (FS_CheckNastyPath(gamedir, true))
  1422. return NULL;
  1423. ret = FS_SysCheckGameDir(va(vabuf, sizeof(vabuf), "%s%s/", fs_userdir, gamedir), buf, sizeof(buf));
  1424. if(ret)
  1425. {
  1426. if(!*ret)
  1427. {
  1428. // get description from basedir
  1429. ret = FS_SysCheckGameDir(va(vabuf, sizeof(vabuf), "%s%s/", fs_basedir, gamedir), buf, sizeof(buf));
  1430. if(ret)
  1431. return ret;
  1432. return "";
  1433. }
  1434. return ret;
  1435. }
  1436. ret = FS_SysCheckGameDir(va(vabuf, sizeof(vabuf), "%s%s/", fs_basedir, gamedir), buf, sizeof(buf));
  1437. if(ret)
  1438. return ret;
  1439. return fs_checkgamedir_missing;
  1440. }
  1441. static void FS_ListGameDirs(void)
  1442. {
  1443. stringlist_t list, list2;
  1444. int i;
  1445. const char *info;
  1446. char vabuf[1024];
  1447. fs_all_gamedirs_count = 0;
  1448. if(fs_all_gamedirs)
  1449. Mem_Free(fs_all_gamedirs);
  1450. stringlistinit(&list);
  1451. listdirectory(&list, va(vabuf, sizeof(vabuf), "%s/", fs_basedir), "");
  1452. listdirectory(&list, va(vabuf, sizeof(vabuf), "%s/", fs_userdir), "");
  1453. stringlistsort(&list, false);
  1454. stringlistinit(&list2);
  1455. for(i = 0; i < list.numstrings; ++i)
  1456. {
  1457. if(i)
  1458. if(!strcmp(list.strings[i-1], list.strings[i]))
  1459. continue;
  1460. info = FS_CheckGameDir(list.strings[i]);
  1461. if(!info)
  1462. continue;
  1463. if(info == fs_checkgamedir_missing)
  1464. continue;
  1465. if(!*info)
  1466. continue;
  1467. stringlistappend(&list2, list.strings[i]);
  1468. }
  1469. stringlistfreecontents(&list);
  1470. fs_all_gamedirs = (gamedir_t *)Mem_Alloc(fs_mempool, list2.numstrings * sizeof(*fs_all_gamedirs));
  1471. for(i = 0; i < list2.numstrings; ++i)
  1472. {
  1473. info = FS_CheckGameDir(list2.strings[i]);
  1474. // all this cannot happen any more, but better be safe than sorry
  1475. if(!info)
  1476. continue;
  1477. if(info == fs_checkgamedir_missing)
  1478. continue;
  1479. if(!*info)
  1480. continue;
  1481. strlcpy(fs_all_gamedirs[fs_all_gamedirs_count].name, list2.strings[i], sizeof(fs_all_gamedirs[fs_all_gamedirs_count].name));
  1482. strlcpy(fs_all_gamedirs[fs_all_gamedirs_count].description, info, sizeof(fs_all_gamedirs[fs_all_gamedirs_count].description));
  1483. ++fs_all_gamedirs_count;
  1484. }
  1485. }
  1486. /*
  1487. #ifdef WIN32
  1488. #pragma comment(lib, "shell32.lib")
  1489. #include <ShlObj.h>
  1490. #endif
  1491. */
  1492. static void COM_InsertFlags(const char *buf) {
  1493. const char *p;
  1494. char *q;
  1495. const char **new_argv;
  1496. int i = 0;
  1497. int args_left = 256;
  1498. new_argv = (const char **)Mem_Alloc(fs_mempool, sizeof(*com_argv) * (com_argc + args_left + 2));
  1499. if(com_argc == 0)
  1500. new_argv[0] = "dummy"; // Can't really happen.
  1501. else
  1502. new_argv[0] = com_argv[0];
  1503. ++i;
  1504. p = buf;
  1505. while(COM_ParseToken_Console(&p))
  1506. {
  1507. size_t sz = strlen(com_token) + 1; // shut up clang
  1508. if(i > args_left)
  1509. break;
  1510. q = (char *)Mem_Alloc(fs_mempool, sz);
  1511. strlcpy(q, com_token, sz);
  1512. new_argv[i] = q;
  1513. ++i;
  1514. }
  1515. // Now: i <= args_left + 1.
  1516. if (com_argc >= 1)
  1517. {
  1518. memcpy((char *)(&new_argv[i]), &com_argv[1], sizeof(*com_argv) * (com_argc - 1));
  1519. i += com_argc - 1;
  1520. }
  1521. // Now: i <= args_left + (com_argc || 1).
  1522. new_argv[i] = NULL;
  1523. com_argv = new_argv;
  1524. com_argc = i;
  1525. }
  1526. /*
  1527. ================
  1528. FS_Init_SelfPack
  1529. ================
  1530. */
  1531. void FS_Init_SelfPack (void)
  1532. {
  1533. PK3_OpenLibrary ();
  1534. fs_mempool = Mem_AllocPool("file management", 0, NULL);
  1535. // Load darkplaces.opt from the FS.
  1536. if (!COM_CheckParm("-noopt"))
  1537. {
  1538. char *buf = (char *) FS_SysLoadFile("darkplaces.opt", tempmempool, true, NULL);
  1539. if(buf)
  1540. COM_InsertFlags(buf);
  1541. Mem_Free(buf);
  1542. }
  1543. #ifndef USE_RWOPS
  1544. // Provide the SelfPack.
  1545. if (!COM_CheckParm("-noselfpack"))
  1546. {
  1547. if (com_selffd >= 0)
  1548. {
  1549. fs_selfpack = FS_LoadPackPK3FromFD(com_argv[0], com_selffd, true);
  1550. if(fs_selfpack)
  1551. {
  1552. FS_AddSelfPack();
  1553. if (!COM_CheckParm("-noopt"))
  1554. {
  1555. char *buf = (char *) FS_LoadFile("darkplaces.opt", tempmempool, true, NULL);
  1556. if(buf)
  1557. COM_InsertFlags(buf);
  1558. Mem_Free(buf);
  1559. }
  1560. }
  1561. }
  1562. }
  1563. #endif
  1564. }
  1565. static int FS_ChooseUserDir(userdirmode_t userdirmode, char *userdir, size_t userdirsize)
  1566. {
  1567. #if defined(__IPHONEOS__)
  1568. if (userdirmode == USERDIRMODE_HOME)
  1569. {
  1570. // fs_basedir is "" by default, to utilize this you can simply add your gamedir to the Resources in xcode
  1571. // fs_userdir stores configurations to the Documents folder of the app
  1572. strlcpy(userdir, "../Documents/", MAX_OSPATH);
  1573. return 1;
  1574. }
  1575. return -1;
  1576. #elif defined(WIN32)
  1577. char *homedir;
  1578. #if _MSC_VER >= 1400
  1579. size_t homedirlen;
  1580. #endif
  1581. TCHAR mydocsdir[MAX_PATH + 1];
  1582. wchar_t *savedgamesdirw;
  1583. char savedgamesdir[MAX_OSPATH];
  1584. int fd;
  1585. char vabuf[1024];
  1586. userdir[0] = 0;
  1587. switch(userdirmode)
  1588. {
  1589. default:
  1590. return -1;
  1591. case USERDIRMODE_NOHOME:
  1592. strlcpy(userdir, fs_basedir, userdirsize);
  1593. break;
  1594. case USERDIRMODE_MYGAMES:
  1595. if (!shfolder_dll)
  1596. Sys_LoadLibrary(shfolderdllnames, &shfolder_dll, shfolderfuncs);
  1597. mydocsdir[0] = 0;
  1598. if (qSHGetFolderPath && qSHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, mydocsdir) == S_OK)
  1599. {
  1600. dpsnprintf(userdir, userdirsize, "%s/My Games/%s/", mydocsdir, gameuserdirname);
  1601. break;
  1602. }
  1603. #if _MSC_VER >= 1400
  1604. _dupenv_s(&homedir, &homedirlen, "USERPROFILE");
  1605. if(homedir)
  1606. {
  1607. dpsnprintf(userdir, userdirsize, "%s/.%s/", homedir, gameuserdirname);
  1608. free(homedir);
  1609. break;
  1610. }
  1611. #else
  1612. homedir = getenv("USERPROFILE");
  1613. if(homedir)
  1614. {
  1615. dpsnprintf(userdir, userdirsize, "%s/.%s/", homedir, gameuserdirname);
  1616. break;
  1617. }
  1618. #endif
  1619. return -1;
  1620. case USERDIRMODE_SAVEDGAMES:
  1621. if (!shell32_dll)
  1622. Sys_LoadLibrary(shell32dllnames, &shell32_dll, shell32funcs);
  1623. if (!ole32_dll)
  1624. Sys_LoadLibrary(ole32dllnames, &ole32_dll, ole32funcs);
  1625. if (qSHGetKnownFolderPath && qCoInitializeEx && qCoTaskMemFree && qCoUninitialize)
  1626. {
  1627. savedgamesdir[0] = 0;
  1628. qCoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
  1629. /*
  1630. #ifdef __cplusplus
  1631. if (SHGetKnownFolderPath(FOLDERID_SavedGames, KF_FLAG_CREATE | KF_FLAG_NO_ALIAS, NULL, &savedgamesdirw) == S_OK)
  1632. #else
  1633. if (SHGetKnownFolderPath(&FOLDERID_SavedGames, KF_FLAG_CREATE | KF_FLAG_NO_ALIAS, NULL, &savedgamesdirw) == S_OK)
  1634. #endif
  1635. */
  1636. if (qSHGetKnownFolderPath(&qFOLDERID_SavedGames, qKF_FLAG_CREATE | qKF_FLAG_NO_ALIAS, NULL, &savedgamesdirw) == S_OK)
  1637. {
  1638. memset(savedgamesdir, 0, sizeof(savedgamesdir));
  1639. #if _MSC_VER >= 1400
  1640. wcstombs_s(NULL, savedgamesdir, sizeof(savedgamesdir), savedgamesdirw, sizeof(savedgamesdir)-1);
  1641. #else

Large files files are truncated, but you can click here to view the full file