PageRenderTime 61ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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
  1642. wcstombs(savedgamesdir, savedgamesdirw, sizeof(savedgamesdir)-1);
  1643. #endif
  1644. qCoTaskMemFree(savedgamesdirw);
  1645. }
  1646. qCoUninitialize();
  1647. if (savedgamesdir[0])
  1648. {
  1649. dpsnprintf(userdir, userdirsize, "%s/%s/", savedgamesdir, gameuserdirname);
  1650. break;
  1651. }
  1652. }
  1653. return -1;
  1654. }
  1655. #else
  1656. int fd;
  1657. char *homedir;
  1658. char vabuf[1024];
  1659. userdir[0] = 0;
  1660. switch(userdirmode)
  1661. {
  1662. default:
  1663. return -1;
  1664. case USERDIRMODE_NOHOME:
  1665. strlcpy(userdir, fs_basedir, userdirsize);
  1666. break;
  1667. case USERDIRMODE_HOME:
  1668. homedir = getenv("HOME");
  1669. if(homedir)
  1670. {
  1671. dpsnprintf(userdir, userdirsize, "%s/.%s/", homedir, gameuserdirname);
  1672. break;
  1673. }
  1674. return -1;
  1675. case USERDIRMODE_SAVEDGAMES:
  1676. homedir = getenv("HOME");
  1677. if(homedir)
  1678. {
  1679. #ifdef MACOSX
  1680. dpsnprintf(userdir, userdirsize, "%s/Library/Application Support/%s/", homedir, gameuserdirname);
  1681. #else
  1682. // the XDG say some files would need to go in:
  1683. // XDG_CONFIG_HOME (or ~/.config/%s/)
  1684. // XDG_DATA_HOME (or ~/.local/share/%s/)
  1685. // XDG_CACHE_HOME (or ~/.cache/%s/)
  1686. // and also search the following global locations if defined:
  1687. // XDG_CONFIG_DIRS (normally /etc/xdg/%s/)
  1688. // XDG_DATA_DIRS (normally /usr/share/%s/)
  1689. // this would be too complicated...
  1690. return -1;
  1691. #endif
  1692. break;
  1693. }
  1694. return -1;
  1695. }
  1696. #endif
  1697. #if !defined(__IPHONEOS__)
  1698. #ifdef WIN32
  1699. // historical behavior...
  1700. if (userdirmode == USERDIRMODE_NOHOME && strcmp(gamedirname1, "id1"))
  1701. return 0; // don't bother checking if the basedir folder is writable, it's annoying... unless it is Quake on Windows where NOHOME is the default preferred and we have to check for an error case
  1702. #endif
  1703. // see if we can write to this path (note: won't create path)
  1704. #ifdef WIN32
  1705. // no access() here, we must try to open the file for appending
  1706. fd = FS_SysOpenFiledesc(va(vabuf, sizeof(vabuf), "%s%s/config.cfg", userdir, gamedirname1), "a", false);
  1707. if(fd >= 0)
  1708. FILEDESC_CLOSE(fd);
  1709. #else
  1710. // on Unix, we don't need to ACTUALLY attempt to open the file
  1711. if(access(va(vabuf, sizeof(vabuf), "%s%s/", userdir, gamedirname1), W_OK | X_OK) >= 0)
  1712. fd = 1;
  1713. else
  1714. fd = -1;
  1715. #endif
  1716. if(fd >= 0)
  1717. {
  1718. return 1; // good choice - the path exists and is writable
  1719. }
  1720. else
  1721. {
  1722. if (userdirmode == USERDIRMODE_NOHOME)
  1723. return -1; // path usually already exists, we lack permissions
  1724. else
  1725. return 0; // probably good - failed to write but maybe we need to create path
  1726. }
  1727. #endif
  1728. }
  1729. /*
  1730. ================
  1731. FS_Init
  1732. ================
  1733. */
  1734. void FS_Init (void)
  1735. {
  1736. const char *p;
  1737. int i;
  1738. *fs_basedir = 0;
  1739. *fs_userdir = 0;
  1740. *fs_gamedir = 0;
  1741. // -basedir <path>
  1742. // Overrides the system supplied base directory (under GAMENAME)
  1743. // COMMANDLINEOPTION: Filesystem: -basedir <path> chooses what base directory the game data is in, inside this there should be a data directory for the game (for example id1)
  1744. i = COM_CheckParm ("-basedir");
  1745. if (i && i < com_argc-1)
  1746. {
  1747. strlcpy (fs_basedir, com_argv[i+1], sizeof (fs_basedir));
  1748. i = (int)strlen (fs_basedir);
  1749. if (i > 0 && (fs_basedir[i-1] == '\\' || fs_basedir[i-1] == '/'))
  1750. fs_basedir[i-1] = 0;
  1751. }
  1752. else
  1753. {
  1754. // If the base directory is explicitly defined by the compilation process
  1755. #ifdef DP_FS_BASEDIR
  1756. strlcpy(fs_basedir, DP_FS_BASEDIR, sizeof(fs_basedir));
  1757. #elif defined(__ANDROID__)
  1758. dpsnprintf(fs_basedir, sizeof(fs_basedir), "/sdcard/%s/", gameuserdirname);
  1759. #elif defined(MACOSX)
  1760. // FIXME: is there a better way to find the directory outside the .app, without using Objective-C?
  1761. if (strstr(com_argv[0], ".app/"))
  1762. {
  1763. char *split;
  1764. strlcpy(fs_basedir, com_argv[0], sizeof(fs_basedir));
  1765. split = strstr(fs_basedir, ".app/");
  1766. if (split)
  1767. {
  1768. struct stat statresult;
  1769. char vabuf[1024];
  1770. // truncate to just after the .app/
  1771. split[5] = 0;
  1772. // see if gamedir exists in Resources
  1773. if (stat(va(vabuf, sizeof(vabuf), "%s/Contents/Resources/%s", fs_basedir, gamedirname1), &statresult) == 0)
  1774. {
  1775. // found gamedir inside Resources, use it
  1776. strlcat(fs_basedir, "Contents/Resources/", sizeof(fs_basedir));
  1777. }
  1778. else
  1779. {
  1780. // no gamedir found in Resources, gamedir is probably
  1781. // outside the .app, remove .app part of path
  1782. while (split > fs_basedir && *split != '/')
  1783. split--;
  1784. *split = 0;
  1785. }
  1786. }
  1787. }
  1788. #endif
  1789. }
  1790. // make sure the appending of a path separator won't create an unterminated string
  1791. memset(fs_basedir + sizeof(fs_basedir) - 2, 0, 2);
  1792. // add a path separator to the end of the basedir if it lacks one
  1793. if (fs_basedir[0] && fs_basedir[strlen(fs_basedir) - 1] != '/' && fs_basedir[strlen(fs_basedir) - 1] != '\\')
  1794. strlcat(fs_basedir, "/", sizeof(fs_basedir));
  1795. // Add the personal game directory
  1796. if((i = COM_CheckParm("-userdir")) && i < com_argc - 1)
  1797. dpsnprintf(fs_userdir, sizeof(fs_userdir), "%s/", com_argv[i+1]);
  1798. else if (COM_CheckParm("-nohome"))
  1799. *fs_userdir = 0; // user wants roaming installation, no userdir
  1800. else
  1801. {
  1802. #ifdef DP_FS_USERDIR
  1803. strlcpy(fs_userdir, DP_FS_USERDIR, sizeof(fs_userdir));
  1804. #else
  1805. int dirmode;
  1806. int highestuserdirmode = USERDIRMODE_COUNT - 1;
  1807. int preferreduserdirmode = USERDIRMODE_COUNT - 1;
  1808. int userdirstatus[USERDIRMODE_COUNT];
  1809. # ifdef WIN32
  1810. // historical behavior...
  1811. if (!strcmp(gamedirname1, "id1"))
  1812. preferreduserdirmode = USERDIRMODE_NOHOME;
  1813. # endif
  1814. // check what limitations the user wants to impose
  1815. if (COM_CheckParm("-home")) preferreduserdirmode = USERDIRMODE_HOME;
  1816. if (COM_CheckParm("-mygames")) preferreduserdirmode = USERDIRMODE_MYGAMES;
  1817. if (COM_CheckParm("-savedgames")) preferreduserdirmode = USERDIRMODE_SAVEDGAMES;
  1818. // gather the status of the possible userdirs
  1819. for (dirmode = 0;dirmode < USERDIRMODE_COUNT;dirmode++)
  1820. {
  1821. userdirstatus[dirmode] = FS_ChooseUserDir((userdirmode_t)dirmode, fs_userdir, sizeof(fs_userdir));
  1822. if (userdirstatus[dirmode] == 1)
  1823. Con_DPrintf("userdir %i = %s (writable)\n", dirmode, fs_userdir);
  1824. else if (userdirstatus[dirmode] == 0)
  1825. Con_DPrintf("userdir %i = %s (not writable or does not exist)\n", dirmode, fs_userdir);
  1826. else
  1827. Con_DPrintf("userdir %i (not applicable)\n", dirmode);
  1828. }
  1829. // some games may prefer writing to basedir, but if write fails we
  1830. // have to search for a real userdir...
  1831. if (preferreduserdirmode == 0 && userdirstatus[0] < 1)
  1832. preferreduserdirmode = highestuserdirmode;
  1833. // check for an existing userdir and continue using it if possible...
  1834. for (dirmode = USERDIRMODE_COUNT - 1;dirmode > 0;dirmode--)
  1835. if (userdirstatus[dirmode] == 1)
  1836. break;
  1837. // if no existing userdir found, make a new one...
  1838. if (dirmode == 0 && preferreduserdirmode > 0)
  1839. for (dirmode = preferreduserdirmode;dirmode > 0;dirmode--)
  1840. if (userdirstatus[dirmode] >= 0)
  1841. break;
  1842. // and finally, we picked one...
  1843. FS_ChooseUserDir((userdirmode_t)dirmode, fs_userdir, sizeof(fs_userdir));
  1844. Con_DPrintf("userdir %i is the winner\n", dirmode);
  1845. #endif
  1846. }
  1847. // if userdir equal to basedir, clear it to avoid confusion later
  1848. if (!strcmp(fs_basedir, fs_userdir))
  1849. fs_userdir[0] = 0;
  1850. FS_ListGameDirs();
  1851. p = FS_CheckGameDir(gamedirname1);
  1852. if(!p || p == fs_checkgamedir_missing)
  1853. Con_Printf("WARNING: base gamedir %s%s/ not found!\n", fs_basedir, gamedirname1);
  1854. if(gamedirname2)
  1855. {
  1856. p = FS_CheckGameDir(gamedirname2);
  1857. if(!p || p == fs_checkgamedir_missing)
  1858. Con_Printf("WARNING: base gamedir %s%s/ not found!\n", fs_basedir, gamedirname2);
  1859. }
  1860. // -game <gamedir>
  1861. // Adds basedir/gamedir as an override game
  1862. // LordHavoc: now supports multiple -game directories
  1863. for (i = 1;i < com_argc && fs_numgamedirs < MAX_GAMEDIRS;i++)
  1864. {
  1865. if (!com_argv[i])
  1866. continue;
  1867. if (!strcmp (com_argv[i], "-game") && i < com_argc-1)
  1868. {
  1869. i++;
  1870. p = FS_CheckGameDir(com_argv[i]);
  1871. if(!p)
  1872. Sys_Error("Nasty -game name rejected: %s", com_argv[i]);
  1873. if(p == fs_checkgamedir_missing)
  1874. Con_Printf("WARNING: -game %s%s/ not found!\n", fs_basedir, com_argv[i]);
  1875. // add the gamedir to the list of active gamedirs
  1876. strlcpy (fs_gamedirs[fs_numgamedirs], com_argv[i], sizeof(fs_gamedirs[fs_numgamedirs]));
  1877. fs_numgamedirs++;
  1878. }
  1879. }
  1880. // generate the searchpath
  1881. FS_Rescan();
  1882. if (Thread_HasThreads())
  1883. fs_mutex = Thread_CreateMutex();
  1884. }
  1885. void FS_Init_Commands(void)
  1886. {
  1887. Cvar_RegisterVariable (&scr_screenshot_name);
  1888. Cvar_RegisterVariable (&fs_empty_files_in_pack_mark_deletions);
  1889. Cvar_RegisterVariable (&cvar_fs_gamedir);
  1890. Cmd_AddCommand ("gamedir", FS_GameDir_f, "changes active gamedir list (can take multiple arguments), not including base directory (example usage: gamedir ctf)");
  1891. Cmd_AddCommand ("fs_rescan", FS_Rescan_f, "rescans filesystem for new pack archives and any other changes");
  1892. Cmd_AddCommand ("path", FS_Path_f, "print searchpath (game directories and archives)");
  1893. Cmd_AddCommand ("dir", FS_Dir_f, "list files in searchpath matching an * filename pattern, one per line");
  1894. Cmd_AddCommand ("ls", FS_Ls_f, "list files in searchpath matching an * filename pattern, multiple per line");
  1895. Cmd_AddCommand ("which", FS_Which_f, "accepts a file name as argument and reports where the file is taken from");
  1896. }
  1897. /*
  1898. ================
  1899. FS_Shutdown
  1900. ================
  1901. */
  1902. void FS_Shutdown (void)
  1903. {
  1904. // close all pack files and such
  1905. // (hopefully there aren't any other open files, but they'll be cleaned up
  1906. // by the OS anyway)
  1907. FS_ClearSearchPath();
  1908. Mem_FreePool (&fs_mempool);
  1909. PK3_CloseLibrary ();
  1910. #ifdef WIN32
  1911. Sys_UnloadLibrary (&shfolder_dll);
  1912. Sys_UnloadLibrary (&shell32_dll);
  1913. Sys_UnloadLibrary (&ole32_dll);
  1914. #endif
  1915. if (fs_mutex)
  1916. Thread_DestroyMutex(fs_mutex);
  1917. }
  1918. static filedesc_t FS_SysOpenFiledesc(const char *filepath, const char *mode, qboolean nonblocking)
  1919. {
  1920. filedesc_t handle = FILEDESC_INVALID;
  1921. int mod, opt;
  1922. unsigned int ind;
  1923. qboolean dolock = false;
  1924. // Parse the mode string
  1925. switch (mode[0])
  1926. {
  1927. case 'r':
  1928. mod = O_RDONLY;
  1929. opt = 0;
  1930. break;
  1931. case 'w':
  1932. mod = O_WRONLY;
  1933. opt = O_CREAT | O_TRUNC;
  1934. break;
  1935. case 'a':
  1936. mod = O_WRONLY;
  1937. opt = O_CREAT | O_APPEND;
  1938. break;
  1939. default:
  1940. Con_Printf ("FS_SysOpen(%s, %s): invalid mode\n", filepath, mode);
  1941. return FILEDESC_INVALID;
  1942. }
  1943. for (ind = 1; mode[ind] != '\0'; ind++)
  1944. {
  1945. switch (mode[ind])
  1946. {
  1947. case '+':
  1948. mod = O_RDWR;
  1949. break;
  1950. case 'b':
  1951. opt |= O_BINARY;
  1952. break;
  1953. case 'l':
  1954. dolock = true;
  1955. break;
  1956. default:
  1957. Con_Printf ("FS_SysOpen(%s, %s): unknown character in mode (%c)\n",
  1958. filepath, mode, mode[ind]);
  1959. }
  1960. }
  1961. if (nonblocking)
  1962. opt |= O_NONBLOCK;
  1963. if(COM_CheckParm("-readonly") && mod != O_RDONLY)
  1964. return FILEDESC_INVALID;
  1965. #if USE_RWOPS
  1966. if (dolock)
  1967. return FILEDESC_INVALID;
  1968. handle = SDL_RWFromFile(filepath, mode);
  1969. #else
  1970. # ifdef WIN32
  1971. # if _MSC_VER >= 1400
  1972. _sopen_s(&handle, filepath, mod | opt, (dolock ? ((mod == O_RDONLY) ? _SH_DENYRD : _SH_DENYRW) : _SH_DENYNO), _S_IREAD | _S_IWRITE);
  1973. # else
  1974. handle = _sopen (filepath, mod | opt, (dolock ? ((mod == O_RDONLY) ? _SH_DENYRD : _SH_DENYRW) : _SH_DENYNO), _S_IREAD | _S_IWRITE);
  1975. # endif
  1976. # else
  1977. handle = open (filepath, mod | opt, 0666);
  1978. if(handle >= 0 && dolock)
  1979. {
  1980. struct flock l;
  1981. l.l_type = ((mod == O_RDONLY) ? F_RDLCK : F_WRLCK);
  1982. l.l_whence = SEEK_SET;
  1983. l.l_start = 0;
  1984. l.l_len = 0;
  1985. if(fcntl(handle, F_SETLK, &l) == -1)
  1986. {
  1987. FILEDESC_CLOSE(handle);
  1988. handle = -1;
  1989. }
  1990. }
  1991. # endif
  1992. #endif
  1993. return handle;
  1994. }
  1995. int FS_SysOpenFD(const char *filepath, const char *mode, qboolean nonblocking)
  1996. {
  1997. #ifdef USE_RWOPS
  1998. return -1;
  1999. #else
  2000. return FS_SysOpenFiledesc(filepath, mode, nonblocking);
  2001. #endif
  2002. }
  2003. /*
  2004. ====================
  2005. FS_SysOpen
  2006. Internal function used to create a qfile_t and open the relevant non-packed file on disk
  2007. ====================
  2008. */
  2009. qfile_t* FS_SysOpen (const char* filepath, const char* mode, qboolean nonblocking)
  2010. {
  2011. qfile_t* file;
  2012. file = (qfile_t *)Mem_Alloc (fs_mempool, sizeof (*file));
  2013. file->ungetc = EOF;
  2014. file->handle = FS_SysOpenFiledesc(filepath, mode, nonblocking);
  2015. if (!FILEDESC_ISVALID(file->handle))
  2016. {
  2017. Mem_Free (file);
  2018. return NULL;
  2019. }
  2020. file->filename = Mem_strdup(fs_mempool, filepath);
  2021. file->real_length = FILEDESC_SEEK (file->handle, 0, SEEK_END);
  2022. // For files opened in append mode, we start at the end of the file
  2023. if (mode[0] == 'a')
  2024. file->position = file->real_length;
  2025. else
  2026. FILEDESC_SEEK (file->handle, 0, SEEK_SET);
  2027. return file;
  2028. }
  2029. /*
  2030. ===========
  2031. FS_OpenPackedFile
  2032. Open a packed file using its package file descriptor
  2033. ===========
  2034. */
  2035. static qfile_t *FS_OpenPackedFile (pack_t* pack, int pack_ind)
  2036. {
  2037. packfile_t *pfile;
  2038. filedesc_t dup_handle;
  2039. qfile_t* file;
  2040. pfile = &pack->files[pack_ind];
  2041. // If we don't have the true offset, get it now
  2042. if (! (pfile->flags & PACKFILE_FLAG_TRUEOFFS))
  2043. if (!PK3_GetTrueFileOffset (pfile, pack))
  2044. return NULL;
  2045. #ifndef LINK_TO_ZLIB
  2046. // No Zlib DLL = no compressed files
  2047. if (!zlib_dll && (pfile->flags & PACKFILE_FLAG_DEFLATED))
  2048. {
  2049. Con_Printf("WARNING: can't open the compressed file %s\n"
  2050. "You need the Zlib DLL to use compressed files\n",
  2051. pfile->name);
  2052. return NULL;
  2053. }
  2054. #endif
  2055. // LordHavoc: FILEDESC_SEEK affects all duplicates of a handle so we do it before
  2056. // the dup() call to avoid having to close the dup_handle on error here
  2057. if (FILEDESC_SEEK (pack->handle, pfile->offset, SEEK_SET) == -1)
  2058. {
  2059. Con_Printf ("FS_OpenPackedFile: can't lseek to %s in %s (offset: %08x%08x)\n",
  2060. pfile->name, pack->filename, (unsigned int)(pfile->offset >> 32), (unsigned int)(pfile->offset));
  2061. return NULL;
  2062. }
  2063. dup_handle = FILEDESC_DUP (pack->filename, pack->handle);
  2064. if (!FILEDESC_ISVALID(dup_handle))
  2065. {
  2066. Con_Printf ("FS_OpenPackedFile: can't dup package's handle (pack: %s)\n", pack->filename);
  2067. return NULL;
  2068. }
  2069. file = (qfile_t *)Mem_Alloc (fs_mempool, sizeof (*file));
  2070. memset (file, 0, sizeof (*file));
  2071. file->handle = dup_handle;
  2072. file->flags = QFILE_FLAG_PACKED;
  2073. file->real_length = pfile->realsize;
  2074. file->offset = pfile->offset;
  2075. file->position = 0;
  2076. file->ungetc = EOF;
  2077. if (pfile->flags & PACKFILE_FLAG_DEFLATED)
  2078. {
  2079. ztoolkit_t *ztk;
  2080. file->flags |= QFILE_FLAG_DEFLATED;
  2081. // We need some more variables
  2082. ztk = (ztoolkit_t *)Mem_Alloc (fs_mempool, sizeof (*ztk));
  2083. ztk->comp_length = pfile->packsize;
  2084. // Initialize zlib stream
  2085. ztk->zstream.next_in = ztk->input;
  2086. ztk->zstream.avail_in = 0;
  2087. /* From Zlib's "unzip.c":
  2088. *
  2089. * windowBits is passed < 0 to tell that there is no zlib header.
  2090. * Note that in this case inflate *requires* an extra "dummy" byte
  2091. * after the compressed stream in order to complete decompression and
  2092. * return Z_STREAM_END.
  2093. * In unzip, i don't wait absolutely Z_STREAM_END because I known the
  2094. * size of both compressed and uncompressed data
  2095. */
  2096. if (qz_inflateInit2 (&ztk->zstream, -MAX_WBITS) != Z_OK)
  2097. {
  2098. Con_Printf ("FS_OpenPackedFile: inflate init error (file: %s)\n", pfile->name);
  2099. FILEDESC_CLOSE(dup_handle);
  2100. Mem_Free(file);
  2101. return NULL;
  2102. }
  2103. ztk->zstream.next_out = file->buff;
  2104. ztk->zstream.avail_out = sizeof (file->buff);
  2105. file->ztk = ztk;
  2106. }
  2107. return file;
  2108. }
  2109. /*
  2110. ====================
  2111. FS_CheckNastyPath
  2112. Return true if the path should be rejected due to one of the following:
  2113. 1: path elements that are non-portable
  2114. 2: path elements that would allow access to files outside the game directory,
  2115. or are just not a good idea for a mod to be using.
  2116. ====================
  2117. */
  2118. int FS_CheckNastyPath (const char *path, qboolean isgamedir)
  2119. {
  2120. // all: never allow an empty path, as for gamedir it would access the parent directory and a non-gamedir path it is just useless
  2121. if (!path[0])
  2122. return 2;
  2123. // Windows: don't allow \ in filenames (windows-only), period.
  2124. // (on Windows \ is a directory separator, but / is also supported)
  2125. if (strstr(path, "\\"))
  2126. return 1; // non-portable
  2127. // Mac: don't allow Mac-only filenames - : is a directory separator
  2128. // instead of /, but we rely on / working already, so there's no reason to
  2129. // support a Mac-only path
  2130. // Amiga and Windows: : tries to go to root of drive
  2131. if (strstr(path, ":"))
  2132. return 1; // non-portable attempt to go to root of drive
  2133. // Amiga: // is parent directory
  2134. if (strstr(path, "//"))
  2135. return 1; // non-portable attempt to go to parent directory
  2136. // all: don't allow going to parent directory (../ or /../)
  2137. if (strstr(path, ".."))
  2138. return 2; // attempt to go outside the game directory
  2139. // Windows and UNIXes: don't allow absolute paths
  2140. if (path[0] == '/')
  2141. return 2; // attempt to go outside the game directory
  2142. // all: don't allow . character immediately before a slash, this catches all imaginable cases of ./, ../, .../, etc
  2143. if (strstr(path, "./"))
  2144. return 2; // possible attempt to go outside the game directory
  2145. // all: forbid trailing slash on gamedir
  2146. if (isgamedir && path[strlen(path)-1] == '/')
  2147. return 2;
  2148. // all: forbid leading dot on any filename for any reason
  2149. if (strstr(path, "/."))
  2150. return 2; // attempt to go outside the game directory
  2151. // after all these checks we're pretty sure it's a / separated filename
  2152. // and won't do much if any harm
  2153. return false;
  2154. }
  2155. /*
  2156. ====================
  2157. FS_FindFile
  2158. Look for a file in the packages and in the filesystem
  2159. Return the searchpath where the file was found (or NULL)
  2160. and the file index in the package if relevant
  2161. ====================
  2162. */
  2163. static searchpath_t *FS_FindFile (const char *name, int* index, qboolean quiet)
  2164. {
  2165. searchpath_t *search;
  2166. pack_t *pak;
  2167. // search through the path, one element at a time
  2168. for (search = fs_searchpaths;search;search = search->next)
  2169. {
  2170. // is the element a pak file?
  2171. if (search->pack && !search->pack->vpack)
  2172. {
  2173. int (*strcmp_funct) (const char* str1, const char* str2);
  2174. int left, right, middle;
  2175. pak = search->pack;
  2176. strcmp_funct = pak->ignorecase ? strcasecmp : strcmp;
  2177. // Look for the file (binary search)
  2178. left = 0;
  2179. right = pak->numfiles - 1;
  2180. while (left <= right)
  2181. {
  2182. int diff;
  2183. middle = (left + right) / 2;
  2184. diff = strcmp_funct (pak->files[middle].name, name);
  2185. // Found it
  2186. if (!diff)
  2187. {
  2188. if (fs_empty_files_in_pack_mark_deletions.integer && pak->files[middle].realsize == 0)
  2189. {
  2190. // yes, but the first one is empty so we treat it as not being there
  2191. if (!quiet && developer_extra.integer)
  2192. Con_DPrintf("FS_FindFile: %s is marked as deleted\n", name);
  2193. if (index != NULL)
  2194. *index = -1;
  2195. return NULL;
  2196. }
  2197. if (!quiet && developer_extra.integer)
  2198. Con_DPrintf("FS_FindFile: %s in %s\n",
  2199. pak->files[middle].name, pak->filename);
  2200. if (index != NULL)
  2201. *index = middle;
  2202. return search;
  2203. }
  2204. // If we're too far in the list
  2205. if (diff > 0)
  2206. right = middle - 1;
  2207. else
  2208. left = middle + 1;
  2209. }
  2210. }
  2211. else
  2212. {
  2213. char netpath[MAX_OSPATH];
  2214. dpsnprintf(netpath, sizeof(netpath), "%s%s", search->filename, name);
  2215. if (FS_SysFileExists (netpath))
  2216. {
  2217. if (!quiet && developer_extra.integer)
  2218. Con_DPrintf("FS_FindFile: %s\n", netpath);
  2219. if (index != NULL)
  2220. *index = -1;
  2221. return search;
  2222. }
  2223. }
  2224. }
  2225. if (!quiet && developer_extra.integer)
  2226. Con_DPrintf("FS_FindFile: can't find %s\n", name);
  2227. if (index != NULL)
  2228. *index = -1;
  2229. return NULL;
  2230. }
  2231. /*
  2232. ===========
  2233. FS_OpenReadFile
  2234. Look for a file in the search paths and open it in read-only mode
  2235. ===========
  2236. */
  2237. static qfile_t *FS_OpenReadFile (const char *filename, qboolean quiet, qboolean nonblocking, int symlinkLevels)
  2238. {
  2239. searchpath_t *search;
  2240. int pack_ind;
  2241. search = FS_FindFile (filename, &pack_ind, quiet);
  2242. // Not found?
  2243. if (search == NULL)
  2244. return NULL;
  2245. // Found in the filesystem?
  2246. if (pack_ind < 0)
  2247. {
  2248. // this works with vpacks, so we are fine
  2249. char path [MAX_OSPATH];
  2250. dpsnprintf (path, sizeof (path), "%s%s", search->filename, filename);
  2251. return FS_SysOpen (path, "rb", nonblocking);
  2252. }
  2253. // So, we found it in a package...
  2254. // Is it a PK3 symlink?
  2255. // TODO also handle directory symlinks by parsing the whole structure...
  2256. // but heck, file symlinks are good enough for now
  2257. if(search->pack->files[pack_ind].flags & PACKFILE_FLAG_SYMLINK)
  2258. {
  2259. if(symlinkLevels <= 0)
  2260. {
  2261. Con_Printf("symlink: %s: too many levels of symbolic links\n", filename);
  2262. return NULL;
  2263. }
  2264. else
  2265. {
  2266. char linkbuf[MAX_QPATH];
  2267. fs_offset_t count;
  2268. qfile_t *linkfile = FS_OpenPackedFile (search->pack, pack_ind);
  2269. const char *mergeslash;
  2270. char *mergestart;
  2271. if(!linkfile)
  2272. return NULL;
  2273. count = FS_Read(linkfile, linkbuf, sizeof(linkbuf) - 1);
  2274. FS_Close(linkfile);
  2275. if(count < 0)
  2276. return NULL;
  2277. linkbuf[count] = 0;
  2278. // Now combine the paths...
  2279. mergeslash = strrchr(filename, '/');
  2280. mergestart = linkbuf;
  2281. if(!mergeslash)
  2282. mergeslash = filename;
  2283. while(!strncmp(mergestart, "../", 3))
  2284. {
  2285. mergestart += 3;
  2286. while(mergeslash > filename)
  2287. {
  2288. --mergeslash;
  2289. if(*mergeslash == '/')
  2290. break;
  2291. }
  2292. }
  2293. // Now, mergestart will point to the path to be appended, and mergeslash points to where it should be appended
  2294. if(mergeslash == filename)
  2295. {
  2296. // Either mergeslash == filename, then we just replace the name (done below)
  2297. }
  2298. else
  2299. {
  2300. // Or, we append the name after mergeslash;
  2301. // or rather, we can also shift the linkbuf so we can put everything up to and including mergeslash first
  2302. int spaceNeeded = mergeslash - filename + 1;
  2303. int spaceRemoved = mergestart - linkbuf;
  2304. if(count - spaceRemoved + spaceNeeded >= MAX_QPATH)
  2305. {
  2306. Con_DPrintf("symlink: too long path rejected\n");
  2307. return NULL;
  2308. }
  2309. memmove(linkbuf + spaceNeeded, linkbuf + spaceRemoved, count - spaceRemoved);
  2310. memcpy(linkbuf, filename, spaceNeeded);
  2311. linkbuf[count - spaceRemoved + spaceNeeded] = 0;
  2312. mergestart = linkbuf;
  2313. }
  2314. if (!quiet && developer_loading.integer)
  2315. Con_DPrintf("symlink: %s -> %s\n", filename, mergestart);
  2316. if(FS_CheckNastyPath (mergestart, false))
  2317. {
  2318. Con_DPrintf("symlink: nasty path %s rejected\n", mergestart);
  2319. return NULL;
  2320. }
  2321. return FS_OpenReadFile(mergestart, quiet, nonblocking, symlinkLevels - 1);
  2322. }
  2323. }
  2324. return FS_OpenPackedFile (search->pack, pack_ind);
  2325. }
  2326. /*
  2327. =============================================================================
  2328. MAIN PUBLIC FUNCTIONS
  2329. =============================================================================
  2330. */
  2331. /*
  2332. ====================
  2333. FS_OpenRealFile
  2334. Open a file in the userpath. The syntax is the same as fopen
  2335. Used for savegame scanning in menu, and all file writing.
  2336. ====================
  2337. */
  2338. qfile_t* FS_OpenRealFile (const char* filepath, const char* mode, qboolean quiet)
  2339. {
  2340. char real_path [MAX_OSPATH];
  2341. if (FS_CheckNastyPath(filepath, false))
  2342. {
  2343. Con_Printf("FS_OpenRealFile(\"%s\", \"%s\", %s): nasty filename rejected\n", filepath, mode, quiet ? "true" : "false");
  2344. return NULL;
  2345. }
  2346. dpsnprintf (real_path, sizeof (real_path), "%s/%s", fs_gamedir, filepath); // this is never a vpack
  2347. // If the file is opened in "write", "append", or "read/write" mode,
  2348. // create directories up to the file.
  2349. if (mode[0] == 'w' || mode[0] == 'a' || strchr (mode, '+'))
  2350. FS_CreatePath (real_path);
  2351. return FS_SysOpen (real_path, mode, false);
  2352. }
  2353. /*
  2354. ====================
  2355. FS_OpenVirtualFile
  2356. Open a file. The syntax is the same as fopen
  2357. ====================
  2358. */
  2359. qfile_t* FS_OpenVirtualFile (const char* filepath, qboolean quiet)
  2360. {
  2361. qfile_t *result = NULL;
  2362. if (FS_CheckNastyPath(filepath, false))
  2363. {
  2364. Con_Printf("FS_OpenVirtualFile(\"%s\", %s): nasty filename rejected\n", filepath, quiet ? "true" : "false");
  2365. return NULL;
  2366. }
  2367. if (fs_mutex) Thread_LockMutex(fs_mutex);
  2368. result = FS_OpenReadFile (filepath, quiet, false, 16);
  2369. if (fs_mutex) Thread_UnlockMutex(fs_mutex);
  2370. return result;
  2371. }
  2372. /*
  2373. ====================
  2374. FS_FileFromData
  2375. Open a file. The syntax is the same as fopen
  2376. ====================
  2377. */
  2378. qfile_t* FS_FileFromData (const unsigned char *data, const size_t size, qboolean quiet)
  2379. {
  2380. qfile_t* file;
  2381. file = (qfile_t *)Mem_Alloc (fs_mempool, sizeof (*file));
  2382. memset (file, 0, sizeof (*file));
  2383. file->flags = QFILE_FLAG_DATA;
  2384. file->ungetc = EOF;
  2385. file->real_length = size;
  2386. file->data = data;
  2387. return file;
  2388. }
  2389. /*
  2390. ====================
  2391. FS_Close
  2392. Close a file
  2393. ====================
  2394. */
  2395. int FS_Close (qfile_t* file)
  2396. {
  2397. if(file->flags & QFILE_FLAG_DATA)
  2398. {
  2399. Mem_Free(file);
  2400. return 0;
  2401. }
  2402. if (FILEDESC_CLOSE (file->handle))
  2403. return EOF;
  2404. if (file->filename)
  2405. {
  2406. if (file->flags & QFILE_FLAG_REMOVE)
  2407. {
  2408. if (remove(file->filename) == -1)
  2409. {
  2410. // No need to report this. If removing a just
  2411. // written file failed, this most likely means
  2412. // someone else deleted it first - which we
  2413. // like.
  2414. }
  2415. }
  2416. Mem_Free((void *) file->filename);
  2417. }
  2418. if (file->ztk)
  2419. {
  2420. qz_inflateEnd (&file->ztk->zstream);
  2421. Mem_Free (file->ztk);
  2422. }
  2423. Mem_Free (file);
  2424. return 0;
  2425. }
  2426. void FS_RemoveOnClose(qfile_t* file)
  2427. {
  2428. file->flags |= QFILE_FLAG_REMOVE;
  2429. }
  2430. /*
  2431. ====================
  2432. FS_Write
  2433. Write "datasize" bytes into a file
  2434. ====================
  2435. */
  2436. fs_offset_t FS_Write (qfile_t* file, const void* data, size_t datasize)
  2437. {
  2438. fs_offset_t written = 0;
  2439. // If necessary, seek to the exact file position we're supposed to be
  2440. if (file->buff_ind != file->buff_len)
  2441. {
  2442. if (FILEDESC_SEEK (file->handle, file->buff_ind - file->buff_len, SEEK_CUR) == -1)
  2443. {
  2444. Con_Printf("WARNING: could not seek in %s.\n", file->filename);
  2445. }
  2446. }
  2447. // Purge cached data
  2448. FS_Purge (file);
  2449. // Write the buffer and update the position
  2450. // LordHavoc: to hush a warning about passing size_t to an unsigned int parameter on Win64 we do this as multiple writes if the size would be too big for an integer (we never write that big in one go, but it's a theory)
  2451. while (written < (fs_offset_t)datasize)
  2452. {
  2453. // figure out how much to write in one chunk
  2454. fs_offset_t maxchunk = 1<<30; // 1 GiB
  2455. int chunk = (int)min((fs_offset_t)datasize - written, maxchunk);
  2456. int result = (int)FILEDESC_WRITE (file->handle, (const unsigned char *)data + written, chunk);
  2457. // if at least some was written, add it to our accumulator
  2458. if (result > 0)
  2459. written += result;
  2460. // if the result is not what we expected, consider the write to be incomplete
  2461. if (result != chunk)
  2462. break;
  2463. }
  2464. file->position = FILEDESC_SEEK (file->handle, 0, SEEK_CUR);
  2465. if (file->real_length < file->position)
  2466. file->real_length = file->position;
  2467. // note that this will never be less than 0 even if the write failed
  2468. return written;
  2469. }
  2470. /*
  2471. ====================
  2472. FS_Read
  2473. Read up to "buffersize" bytes from a file
  2474. ====================
  2475. */
  2476. fs_offset_t FS_Read (qfile_t* file, void* buffer, size_t buffersize)
  2477. {
  2478. fs_offset_t count, done;
  2479. if (buffersize == 0)
  2480. return 0;
  2481. // Get rid of the ungetc character
  2482. if (file->ungetc != EOF)
  2483. {
  2484. ((char*)buffer)[0] = file->ungetc;
  2485. buffersize--;
  2486. file->ungetc = EOF;
  2487. done = 1;
  2488. }
  2489. else
  2490. done = 0;
  2491. if(file->flags & QFILE_FLAG_DATA)
  2492. {
  2493. size_t left = file->real_length - file->position;
  2494. if(buffersize > left)
  2495. buffersize = left;
  2496. memcpy(buffer, file->data + file->position, buffersize);
  2497. file->position += buffersize;
  2498. return buffersize;
  2499. }
  2500. // First, we copy as many bytes as we can from "buff"
  2501. if (file->buff_ind < file->buff_len)
  2502. {
  2503. count = file->buff_len - file->buff_ind;
  2504. count = ((fs_offset_t)buffersize > count) ? count : (fs_offset_t)buffersize;
  2505. done += count;
  2506. memcpy (buffer, &file->buff[file->buff_ind], count);
  2507. file->buff_ind += count;
  2508. buffersize -= count;
  2509. if (buffersize == 0)
  2510. return done;
  2511. }
  2512. // NOTE: at this point, the read buffer is always empty
  2513. // If the file isn't compressed
  2514. if (! (file->flags & QFILE_FLAG_DEFLATED))
  2515. {
  2516. fs_offset_t nb;
  2517. // We must take care to not read after the end of the file
  2518. count = file->real_length - file->position;
  2519. // If we have a lot of data to get, put them directly into "buffer"
  2520. if (buffersize > sizeof (file->buff) / 2)
  2521. {
  2522. if (count > (fs_offset_t)buffersize)
  2523. count = (fs_offset_t)buffersize;
  2524. if (FILEDESC_SEEK (file->handle, file->offset + file->position, SEEK_SET) == -1)
  2525. {
  2526. // Seek failed. When reading from a pipe, and
  2527. // the caller never called FS_Seek, this still
  2528. // works fine. So no reporting this error.
  2529. }
  2530. nb = FILEDESC_READ (file->handle, &((unsigned char*)buffer)[done], count);
  2531. if (nb > 0)
  2532. {
  2533. done += nb;
  2534. file->position += nb;
  2535. // Purge cached data
  2536. FS_Purge (file);
  2537. }
  2538. }
  2539. else
  2540. {
  2541. if (count > (fs_offset_t)sizeof (file->buff))
  2542. count = (fs_offset_t)sizeof (file->buff);
  2543. if (FILEDESC_SEEK (file->handle, file->offset + file->position, SEEK_SET) == -1)
  2544. {
  2545. // Seek failed. When reading from a pipe, and
  2546. // the caller never called FS_Seek, this still
  2547. // works fine. So no reporting this error.
  2548. }
  2549. nb = FILEDESC_READ (file->handle, file->buff, count);
  2550. if (nb > 0)
  2551. {
  2552. file->buff_len = nb;
  2553. file->position += nb;
  2554. // Copy the requested data in "buffer" (as much as we can)
  2555. count = (fs_offset_t)buffersize > file->buff_len ? file->buff_len : (fs_offset_t)buffersize;
  2556. memcpy (&((unsigned char*)buffer)[done], file->buff, count);
  2557. file->buff_ind = count;
  2558. done += count;
  2559. }
  2560. }
  2561. return done;
  2562. }
  2563. // If the file is compressed, it's more complicated...
  2564. // We cycle through a few operations until we have read enough data
  2565. while (buffersize > 0)
  2566. {
  2567. ztoolkit_t *ztk = file->ztk;
  2568. int error;
  2569. // NOTE: at this point, the read buffer is always empty
  2570. // If "input" is also empty, we need to refill it
  2571. if (ztk->in_ind == ztk->in_len)
  2572. {
  2573. // If we are at the end of the file
  2574. if (file->position == file->real_length)
  2575. return done;
  2576. count = (fs_offset_t)(ztk->comp_length - ztk->in_position);
  2577. if (count > (fs_offset_t)sizeof (ztk->input))
  2578. count = (fs_offset_t)sizeof (ztk->input);
  2579. FILEDESC_SEEK (file->handle, file->offset + (fs_offset_t)ztk->in_position, SEEK_SET);
  2580. if (FILEDESC_READ (file->handle, ztk->input, count) != count)
  2581. {
  2582. Con_Printf ("FS_Read: unexpected end of file\n");
  2583. break;
  2584. }
  2585. ztk->in_ind = 0;
  2586. ztk->in_len = count;
  2587. ztk->in_position += count;
  2588. }
  2589. ztk->zstream.next_in = &ztk->input[ztk->in_ind];
  2590. ztk->zstream.avail_in = (unsigned int)(ztk->in_len - ztk->in_ind);
  2591. // Now that we are sure we have compressed data available, we need to determine
  2592. // if it's better to inflate it in "file->buff" or directly in "buffer"
  2593. // Inflate the data in "file->buff"
  2594. if (buffersize < sizeof (file->buff) / 2)
  2595. {
  2596. ztk->zstream.next_out = file->buff;
  2597. ztk->zstream.avail_out = sizeof (file->buff);
  2598. error = qz_inflate (&ztk->zstream, Z_SYNC_FLUSH);
  2599. if (error != Z_OK && error != Z_STREAM_END)
  2600. {
  2601. Con_Printf ("FS_Read: Can't inflate file\n");
  2602. break;
  2603. }
  2604. ztk->in_ind = ztk->in_len - ztk->zstream.avail_in;
  2605. file->buff_len = (fs_offset_t)sizeof (file->buff) - ztk->zstream.avail_out;
  2606. file->position += file->buff_len;
  2607. // Copy the requested data in "buffer" (as much as we can)
  2608. count = (fs_offset_t)buffersize > file->buff_len ? file->buff_len : (fs_offset_t)buffersize;
  2609. memcpy (&((unsigned char*)buffer)[done], file->buff, count);
  2610. file->buff_ind = count;
  2611. }
  2612. // Else, we inflate directly in "buffer"
  2613. else
  2614. {
  2615. ztk->zstream.next_out = &((unsigned char*)buffer)[done];
  2616. ztk->zstream.avail_out = (unsigned int)buffersize;
  2617. error = qz_inflate (&ztk->zstream, Z_SYNC_FLUSH);
  2618. if (error != Z_OK && error != Z_STREAM_END)
  2619. {
  2620. Con_Printf ("FS_Read: Can't inflate file\n");
  2621. break;
  2622. }
  2623. ztk->in_ind = ztk->in_len - ztk->zstream.avail_in;
  2624. // How much data did it inflate?
  2625. count = (fs_offset_t)(buffersize - ztk->zstream.avail_out);
  2626. file->position += count;
  2627. // Purge cached data
  2628. FS_Purge (file);
  2629. }
  2630. done += count;
  2631. buffersize -= count;
  2632. }
  2633. return done;
  2634. }
  2635. /*
  2636. ====================
  2637. FS_Print
  2638. Print a string into a file
  2639. ====================
  2640. */
  2641. int FS_Print (qfile_t* file, const char *msg)
  2642. {
  2643. return (int)FS_Write (file, msg, strlen (msg));
  2644. }
  2645. /*
  2646. ====================
  2647. FS_Printf
  2648. Print a string into a file
  2649. ====================
  2650. */
  2651. int FS_Printf(qfile_t* file, const char* format, ...)
  2652. {
  2653. int result;
  2654. va_list args;
  2655. va_start (args, format);
  2656. result = FS_VPrintf (file, format, args);
  2657. va_end (args);
  2658. return result;
  2659. }
  2660. /*
  2661. ====================
  2662. FS_VPrintf
  2663. Print a string into a file
  2664. ====================
  2665. */
  2666. int FS_VPrintf (qfile_t* file, const char* format, va_list ap)
  2667. {
  2668. int len;
  2669. fs_offset_t buff_size = MAX_INPUTLINE;
  2670. char *tempbuff;
  2671. for (;;)
  2672. {
  2673. tempbuff = (char *)Mem_Alloc (tempmempool, buff_size);
  2674. len = dpvsnprintf (tempbuff, buff_size, format, ap);
  2675. if (len >= 0 && len < buff_size)
  2676. break;
  2677. Mem_Free (tempbuff);
  2678. buff_size *= 2;
  2679. }
  2680. len = FILEDESC_WRITE (file->handle, tempbuff, len);
  2681. Mem_Free (tempbuff);
  2682. return len;
  2683. }
  2684. /*
  2685. ====================
  2686. FS_Getc
  2687. Get the next character of a file
  2688. ====================
  2689. */
  2690. int FS_Getc (qfile_t* file)
  2691. {
  2692. unsigned char c;
  2693. if (FS_Read (file, &c, 1) != 1)
  2694. return EOF;
  2695. return c;
  2696. }
  2697. /*
  2698. ====================
  2699. FS_UnGetc
  2700. Put a character back into the read buffer (only supports one character!)
  2701. ====================
  2702. */
  2703. int FS_UnGetc (qfile_t* file, unsigned char c)
  2704. {
  2705. // If there's already a character waiting to be read
  2706. if (file->ungetc != EOF)
  2707. return EOF;
  2708. file->ungetc = c;
  2709. return c;
  2710. }
  2711. /*
  2712. ====================
  2713. FS_Seek
  2714. Move the position index in a file
  2715. ====================
  2716. */
  2717. int FS_Seek (qfile_t* file, fs_offset_t offset, int whence)
  2718. {
  2719. ztoolkit_t *ztk;
  2720. unsigned char* buffer;
  2721. fs_offset_t buffersize;
  2722. // Compute the file offset
  2723. switch (whence)
  2724. {
  2725. case SEEK_CUR:
  2726. offset += file->position - file->buff_len + file->buff_ind;
  2727. break;
  2728. case SEEK_SET:
  2729. break;
  2730. case SEEK_END:
  2731. offset += file->real_length;
  2732. break;
  2733. default:
  2734. return -1;
  2735. }
  2736. if (offset < 0 || offset > file->real_length)
  2737. return -1;
  2738. if(file->flags & QFILE_FLAG_DATA)
  2739. {
  2740. file->position = offset;
  2741. return 0;
  2742. }
  2743. // If we have the data in our read buffer, we don't need to actually seek
  2744. if (file->position - file->buff_len <= offset && offset <= file->position)
  2745. {
  2746. file->buff_ind = offset + file->buff_len - file->position;
  2747. return 0;
  2748. }
  2749. // Purge cached data
  2750. FS_Purge (file);
  2751. // Unpacked or uncompressed files can seek directly
  2752. if (! (file->flags & QFILE_FLAG_DEFLATED))
  2753. {
  2754. if (FILEDESC_SEEK (file->handle, file->offset + offset, SEEK_SET) == -1)
  2755. return -1;
  2756. file->position = offset;
  2757. return 0;
  2758. }
  2759. // Seeking in compressed files is more a hack than anything else,
  2760. // but we need to support it, so here we go.
  2761. ztk = file->ztk;
  2762. // If we have to go back in the file, we need to restart from the beginning
  2763. if (offset <= file->position)
  2764. {
  2765. ztk->in_ind = 0;
  2766. ztk->in_len = 0;
  2767. ztk->in_position = 0;
  2768. file->position = 0;
  2769. if (FILEDESC_SEEK (file->handle, file->offset, SEEK_SET) == -1)
  2770. Con_Printf("IMPOSSIBLE: couldn't seek in already opened pk3 file.\n");
  2771. // Reset the Zlib stream
  2772. ztk->zstream.next_in = ztk->input;
  2773. ztk->zstream.avail_in = 0;
  2774. qz_inflateReset (&ztk->zstream);
  2775. }
  2776. // We need a big buffer to force inflating into it directly
  2777. buffersize = 2 * sizeof (file->buff);
  2778. buffer = (unsigned char *)Mem_Alloc (tempmempool, buffersize);
  2779. // Skip all data until we reach the requested offset
  2780. while (offset > file->position)
  2781. {
  2782. fs_offset_t diff = offset - file->position;
  2783. fs_offset_t count, len;
  2784. count = (diff > buffersize) ? buffersize : diff;
  2785. len = FS_Read (file, buffer, count);
  2786. if (len != count)
  2787. {
  2788. Mem_Free (buffer);
  2789. return -1;
  2790. }
  2791. }
  2792. Mem_Free (buffer);
  2793. return 0;
  2794. }
  2795. /*
  2796. ====================
  2797. FS_Tell
  2798. Give the current position in a file
  2799. ====================
  2800. */
  2801. fs_offset_t FS_Tell (qfile_t* file)
  2802. {
  2803. return file->position - file->buff_len + file->buff_ind;
  2804. }
  2805. /*
  2806. ====================
  2807. FS_FileSize
  2808. Give the total size of a file
  2809. ====================
  2810. */
  2811. fs_offset_t FS_FileSize (qfile_t* file)
  2812. {
  2813. return file->real_length;
  2814. }
  2815. /*
  2816. ====================
  2817. FS_Purge
  2818. Erases any buffered input or output data
  2819. ====================
  2820. */
  2821. void FS_Purge (qfile_t* file)
  2822. {
  2823. file->buff_len = 0;
  2824. file->buff_ind = 0;
  2825. file->ungetc = EOF;
  2826. }
  2827. /*
  2828. ============
  2829. FS_LoadAndCloseQFile
  2830. Loads full content of a qfile_t and closes it.
  2831. Always appends a 0 byte.
  2832. ============
  2833. */
  2834. static unsigned char *FS_LoadAndCloseQFile (qfile_t *file, const char *path, mempool_t *pool, qboolean quiet, fs_offset_t *filesizepointer)
  2835. {
  2836. unsigned char *buf = NULL;
  2837. fs_offset_t filesize = 0;
  2838. if (file)
  2839. {
  2840. filesize = file->real_length;
  2841. if(filesize < 0)
  2842. {
  2843. Con_Printf("FS_LoadFile(\"%s\", pool, %s, filesizepointer): trying to open a non-regular file\n", path, quiet ? "true" : "false");
  2844. FS_Close(file);
  2845. return NULL;
  2846. }
  2847. buf = (unsigned char *)Mem_Alloc (pool, filesize + 1);
  2848. buf[filesize] = '\0';
  2849. FS_Read (file, buf, filesize);
  2850. FS_Close (file);
  2851. if (developer_loadfile.integer)
  2852. Con_Printf("loaded file \"%s\" (%u bytes)\n", path, (unsigned int)filesize);
  2853. }
  2854. if (filesizepointer)
  2855. *filesizepointer = filesize;
  2856. return buf;
  2857. }
  2858. /*
  2859. ============
  2860. FS_LoadFile
  2861. Filename are relative to the quake directory.
  2862. Always appends a 0 byte.
  2863. ============
  2864. */
  2865. unsigned char *FS_LoadFile (const char *path, mempool_t *pool, qboolean quiet, fs_offset_t *filesizepointer)
  2866. {
  2867. qfile_t *file = FS_OpenVirtualFile(path, quiet);
  2868. return FS_LoadAndCloseQFile(file, path, pool, quiet, filesizepointer);
  2869. }
  2870. /*
  2871. ============
  2872. FS_SysLoadFile
  2873. Filename are OS paths.
  2874. Always appends a 0 byte.
  2875. ============
  2876. */
  2877. unsigned char *FS_SysLoadFile (const char *path, mempool_t *pool, qboolean quiet, fs_offset_t *filesizepointer)
  2878. {
  2879. qfile_t *file = FS_SysOpen(path, "rb", false);
  2880. return FS_LoadAndCloseQFile(file, path, pool, quiet, filesizepointer);
  2881. }
  2882. /*
  2883. ============
  2884. FS_WriteFile
  2885. The filename will be prefixed by the current game directory
  2886. ============
  2887. */
  2888. qboolean FS_WriteFileInBlocks (const char *filename, const void *const *data, const fs_offset_t *len, size_t count)
  2889. {
  2890. qfile_t *file;
  2891. size_t i;
  2892. fs_offset_t lentotal;
  2893. file = FS_OpenRealFile(filename, "wb", false);
  2894. if (!file)
  2895. {
  2896. Con_Printf("FS_WriteFile: failed on %s\n", filename);
  2897. return false;
  2898. }
  2899. lentotal = 0;
  2900. for(i = 0; i < count; ++i)
  2901. lentotal += len[i];
  2902. Con_DPrintf("FS_WriteFile: %s (%u bytes)\n", filename, (unsigned int)lentotal);
  2903. for(i = 0; i < count; ++i)
  2904. FS_Write (file, data[i], len[i]);
  2905. FS_Close (file);
  2906. return true;
  2907. }
  2908. qboolean FS_WriteFile (const char *filename, const void *data, fs_offset_t len)
  2909. {
  2910. return FS_WriteFileInBlocks(filename, &data, &len, 1);
  2911. }
  2912. /*
  2913. =============================================================================
  2914. OTHERS PUBLIC FUNCTIONS
  2915. =============================================================================
  2916. */
  2917. /*
  2918. ============
  2919. FS_StripExtension
  2920. ============
  2921. */
  2922. void FS_StripExtension (const char *in, char *out, size_t size_out)
  2923. {
  2924. char *last = NULL;
  2925. char currentchar;
  2926. if (size_out == 0)
  2927. return;
  2928. while ((currentchar = *in) && size_out > 1)
  2929. {
  2930. if (currentchar == '.')
  2931. last = out;
  2932. else if (currentchar == '/' || currentchar == '\\' || currentchar == ':')
  2933. last = NULL;
  2934. *out++ = currentchar;
  2935. in++;
  2936. size_out--;
  2937. }
  2938. if (last)
  2939. *last = 0;
  2940. else
  2941. *out = 0;
  2942. }
  2943. /*
  2944. ==================
  2945. FS_DefaultExtension
  2946. ==================
  2947. */
  2948. void FS_DefaultExtension (char *path, const char *extension, size_t size_path)
  2949. {
  2950. const char *src;
  2951. // if path doesn't have a .EXT, append extension
  2952. // (extension should include the .)
  2953. src = path + strlen(path);
  2954. while (*src != '/' && src != path)
  2955. {
  2956. if (*src == '.')
  2957. return; // it has an extension
  2958. src--;
  2959. }
  2960. strlcat (path, extension, size_path);
  2961. }
  2962. /*
  2963. ==================
  2964. FS_FileType
  2965. Look for a file in the packages and in the filesystem
  2966. ==================
  2967. */
  2968. int FS_FileType (const char *filename)
  2969. {
  2970. searchpath_t *search;
  2971. char fullpath[MAX_OSPATH];
  2972. search = FS_FindFile (filename, NULL, true);
  2973. if(!search)
  2974. return FS_FILETYPE_NONE;
  2975. if(search->pack && !search->pack->vpack)
  2976. return FS_FILETYPE_FILE; // TODO can't check directories in paks yet, maybe later
  2977. dpsnprintf(fullpath, sizeof(fullpath), "%s%s", search->filename, filename);
  2978. return FS_SysFileType(fullpath);
  2979. }
  2980. /*
  2981. ==================
  2982. FS_FileExists
  2983. Look for a file in the packages and in the filesystem
  2984. ==================
  2985. */
  2986. qboolean FS_FileExists (const char *filename)
  2987. {
  2988. return (FS_FindFile (filename, NULL, true) != NULL);
  2989. }
  2990. /*
  2991. ==================
  2992. FS_SysFileExists
  2993. Look for a file in the filesystem only
  2994. ==================
  2995. */
  2996. int FS_SysFileType (const char *path)
  2997. {
  2998. #if WIN32
  2999. // Sajt - some older sdks are missing this define
  3000. # ifndef INVALID_FILE_ATTRIBUTES
  3001. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  3002. # endif
  3003. DWORD result = GetFileAttributes(path);
  3004. if(result == INVALID_FILE_ATTRIBUTES)
  3005. return FS_FILETYPE_NONE;
  3006. if(result & FILE_ATTRIBUTE_DIRECTORY)
  3007. return FS_FILETYPE_DIRECTORY;
  3008. return FS_FILETYPE_FILE;
  3009. #else
  3010. struct stat buf;
  3011. if (stat (path,&buf) == -1)
  3012. return FS_FILETYPE_NONE;
  3013. #ifndef S_ISDIR
  3014. #define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
  3015. #endif
  3016. if(S_ISDIR(buf.st_mode))
  3017. return FS_FILETYPE_DIRECTORY;
  3018. return FS_FILETYPE_FILE;
  3019. #endif
  3020. }
  3021. qboolean FS_SysFileExists (const char *path)
  3022. {
  3023. return FS_SysFileType (path) != FS_FILETYPE_NONE;
  3024. }
  3025. /*
  3026. ===========
  3027. FS_Search
  3028. Allocate and fill a search structure with information on matching filenames.
  3029. ===========
  3030. */
  3031. fssearch_t *FS_Search(const char *pattern, int caseinsensitive, int quiet)
  3032. {
  3033. fssearch_t *search;
  3034. searchpath_t *searchpath;
  3035. pack_t *pak;
  3036. int i, basepathlength, numfiles, numchars, resultlistindex, dirlistindex;
  3037. stringlist_t resultlist;
  3038. stringlist_t dirlist;
  3039. const char *slash, *backslash, *colon, *separator;
  3040. char *basepath;
  3041. for (i = 0;pattern[i] == '.' || pattern[i] == ':' || pattern[i] == '/' || pattern[i] == '\\';i++)
  3042. ;
  3043. if (i > 0)
  3044. {
  3045. Con_Printf("Don't use punctuation at the beginning of a search pattern!\n");
  3046. return NULL;
  3047. }
  3048. stringlistinit(&resultlist);
  3049. stringlistinit(&dirlist);
  3050. search = NULL;
  3051. slash = strrchr(pattern, '/');
  3052. backslash = strrchr(pattern, '\\');
  3053. colon = strrchr(pattern, ':');
  3054. separator = max(slash, backslash);
  3055. separator = max(separator, colon);
  3056. basepathlength = separator ? (separator + 1 - pattern) : 0;
  3057. basepath = (char *)Mem_Alloc (tempmempool, basepathlength + 1);
  3058. if (basepathlength)
  3059. memcpy(basepath, pattern, basepathlength);
  3060. basepath[basepathlength] = 0;
  3061. // search through the path, one element at a time
  3062. for (searchpath = fs_searchpaths;searchpath;searchpath = searchpath->next)
  3063. {
  3064. // is the element a pak file?
  3065. if (searchpath->pack && !searchpath->pack->vpack)
  3066. {
  3067. // look through all the pak file elements
  3068. pak = searchpath->pack;
  3069. for (i = 0;i < pak->numfiles;i++)
  3070. {
  3071. char temp[MAX_OSPATH];
  3072. strlcpy(temp, pak->files[i].name, sizeof(temp));
  3073. while (temp[0])
  3074. {
  3075. if (matchpattern(temp, (char *)pattern, true))
  3076. {
  3077. for (resultlistindex = 0;resultlistindex < resultlist.numstrings;resultlistindex++)
  3078. if (!strcmp(resultlist.strings[resultlistindex], temp))
  3079. break;
  3080. if (resultlistindex == resultlist.numstrings)
  3081. {
  3082. stringlistappend(&resultlist, temp);
  3083. if (!quiet && developer_loading.integer)
  3084. Con_Printf("SearchPackFile: %s : %s\n", pak->filename, temp);
  3085. }
  3086. }
  3087. // strip off one path element at a time until empty
  3088. // this way directories are added to the listing if they match the pattern
  3089. slash = strrchr(temp, '/');
  3090. backslash = strrchr(temp, '\\');
  3091. colon = strrchr(temp, ':');
  3092. separator = temp;
  3093. if (separator < slash)
  3094. separator = slash;
  3095. if (separator < backslash)
  3096. separator = backslash;
  3097. if (separator < colon)
  3098. separator = colon;
  3099. *((char *)separator) = 0;
  3100. }
  3101. }
  3102. }
  3103. else
  3104. {
  3105. stringlist_t matchedSet, foundSet;
  3106. const char *start = pattern;
  3107. stringlistinit(&matchedSet);
  3108. stringlistinit(&foundSet);
  3109. // add a first entry to the set
  3110. stringlistappend(&matchedSet, "");
  3111. // iterate through pattern's path
  3112. while (*start)
  3113. {
  3114. const char *asterisk, *wildcard, *nextseparator, *prevseparator;
  3115. char subpath[MAX_OSPATH];
  3116. char subpattern[MAX_OSPATH];
  3117. // find the next wildcard
  3118. wildcard = strchr(start, '?');
  3119. asterisk = strchr(start, '*');
  3120. if (asterisk && (!wildcard || asterisk < wildcard))
  3121. {
  3122. wildcard = asterisk;
  3123. }
  3124. if (wildcard)
  3125. {
  3126. nextseparator = strchr( wildcard, '/' );
  3127. }
  3128. else
  3129. {
  3130. nextseparator = NULL;
  3131. }
  3132. if( !nextseparator ) {
  3133. nextseparator = start + strlen( start );
  3134. }
  3135. // prevseparator points past the '/' right before the wildcard and nextseparator at the one following it (or at the end of the string)
  3136. // copy everything up except nextseperator
  3137. strlcpy(subpattern, pattern, min(sizeof(subpattern), (size_t) (nextseparator - pattern + 1)));
  3138. // find the last '/' before the wildcard
  3139. prevseparator = strrchr( subpattern, '/' );
  3140. if (!prevseparator)
  3141. prevseparator = subpattern;
  3142. else
  3143. prevseparator++;
  3144. // copy everything from start to the previous including the '/' (before the wildcard)
  3145. // everything up to start is already included in the path of matchedSet's entries
  3146. strlcpy(subpath, start, min(sizeof(subpath), (size_t) ((prevseparator - subpattern) - (start - pattern) + 1)));
  3147. // for each entry in matchedSet try to open the subdirectories specified in subpath
  3148. for( dirlistindex = 0 ; dirlistindex < matchedSet.numstrings ; dirlistindex++ ) {
  3149. char temp[MAX_OSPATH];
  3150. strlcpy( temp, matchedSet.strings[ dirlistindex ], sizeof(temp) );
  3151. strlcat( temp, subpath, sizeof(temp) );
  3152. listdirectory( &foundSet, searchpath->filename, temp );
  3153. }
  3154. if( dirlistindex == 0 ) {
  3155. break;
  3156. }
  3157. // reset the current result set
  3158. stringlistfreecontents( &matchedSet );
  3159. // match against the pattern
  3160. for( dirlistindex = 0 ; dirlistindex < foundSet.numstrings ; dirlistindex++ ) {
  3161. const char *direntry = foundSet.strings[ dirlistindex ];
  3162. if (matchpattern(direntry, subpattern, true)) {
  3163. stringlistappend( &matchedSet, direntry );
  3164. }
  3165. }
  3166. stringlistfreecontents( &foundSet );
  3167. start = nextseparator;
  3168. }
  3169. for (dirlistindex = 0;dirlistindex < matchedSet.numstrings;dirlistindex++)
  3170. {
  3171. const char *matchtemp = matchedSet.strings[dirlistindex];
  3172. if (matchpattern(matchtemp, (char *)pattern, true))
  3173. {
  3174. for (resultlistindex = 0;resultlistindex < resultlist.numstrings;resultlistindex++)
  3175. if (!strcmp(resultlist.strings[resultlistindex], matchtemp))
  3176. break;
  3177. if (resultlistindex == resultlist.numstrings)
  3178. {
  3179. stringlistappend(&resultlist, matchtemp);
  3180. if (!quiet && developer_loading.integer)
  3181. Con_Printf("SearchDirFile: %s\n", matchtemp);
  3182. }
  3183. }
  3184. }
  3185. stringlistfreecontents( &matchedSet );
  3186. }
  3187. }
  3188. if (resultlist.numstrings)
  3189. {
  3190. stringlistsort(&resultlist, true);
  3191. numfiles = resultlist.numstrings;
  3192. numchars = 0;
  3193. for (resultlistindex = 0;resultlistindex < resultlist.numstrings;resultlistindex++)
  3194. numchars += (int)strlen(resultlist.strings[resultlistindex]) + 1;
  3195. search = (fssearch_t *)Z_Malloc(sizeof(fssearch_t) + numchars + numfiles * sizeof(char *));
  3196. search->filenames = (char **)((char *)search + sizeof(fssearch_t));
  3197. search->filenamesbuffer = (char *)((char *)search + sizeof(fssearch_t) + numfiles * sizeof(char *));
  3198. search->numfilenames = (int)numfiles;
  3199. numfiles = 0;
  3200. numchars = 0;
  3201. for (resultlistindex = 0;resultlistindex < resultlist.numstrings;resultlistindex++)
  3202. {
  3203. size_t textlen;
  3204. search->filenames[numfiles] = search->filenamesbuffer + numchars;
  3205. textlen = strlen(resultlist.strings[resultlistindex]) + 1;
  3206. memcpy(search->filenames[numfiles], resultlist.strings[resultlistindex], textlen);
  3207. numfiles++;
  3208. numchars += (int)textlen;
  3209. }
  3210. }
  3211. stringlistfreecontents(&resultlist);
  3212. Mem_Free(basepath);
  3213. return search;
  3214. }
  3215. void FS_FreeSearch(fssearch_t *search)
  3216. {
  3217. Z_Free(search);
  3218. }
  3219. extern int con_linewidth;
  3220. static int FS_ListDirectory(const char *pattern, int oneperline)
  3221. {
  3222. int numfiles;
  3223. int numcolumns;
  3224. int numlines;
  3225. int columnwidth;
  3226. int linebufpos;
  3227. int i, j, k, l;
  3228. const char *name;
  3229. char linebuf[MAX_INPUTLINE];
  3230. fssearch_t *search;
  3231. search = FS_Search(pattern, true, true);
  3232. if (!search)
  3233. return 0;
  3234. numfiles = search->numfilenames;
  3235. if (!oneperline)
  3236. {
  3237. // FIXME: the names could be added to one column list and then
  3238. // gradually shifted into the next column if they fit, and then the
  3239. // next to make a compact variable width listing but it's a lot more
  3240. // complicated...
  3241. // find width for columns
  3242. columnwidth = 0;
  3243. for (i = 0;i < numfiles;i++)
  3244. {
  3245. l = (int)strlen(search->filenames[i]);
  3246. if (columnwidth < l)
  3247. columnwidth = l;
  3248. }
  3249. // count the spacing character
  3250. columnwidth++;
  3251. // calculate number of columns
  3252. numcolumns = con_linewidth / columnwidth;
  3253. // don't bother with the column printing if it's only one column
  3254. if (numcolumns >= 2)
  3255. {
  3256. numlines = (numfiles + numcolumns - 1) / numcolumns;
  3257. for (i = 0;i < numlines;i++)
  3258. {
  3259. linebufpos = 0;
  3260. for (k = 0;k < numcolumns;k++)
  3261. {
  3262. l = i * numcolumns + k;
  3263. if (l < numfiles)
  3264. {
  3265. name = search->filenames[l];
  3266. for (j = 0;name[j] && linebufpos + 1 < (int)sizeof(linebuf);j++)
  3267. linebuf[linebufpos++] = name[j];
  3268. // space out name unless it's the last on the line
  3269. if (k + 1 < numcolumns && l + 1 < numfiles)
  3270. for (;j < columnwidth && linebufpos + 1 < (int)sizeof(linebuf);j++)
  3271. linebuf[linebufpos++] = ' ';
  3272. }
  3273. }
  3274. linebuf[linebufpos] = 0;
  3275. Con_Printf("%s\n", linebuf);
  3276. }
  3277. }
  3278. else
  3279. oneperline = true;
  3280. }
  3281. if (oneperline)
  3282. for (i = 0;i < numfiles;i++)
  3283. Con_Printf("%s\n", search->filenames[i]);
  3284. FS_FreeSearch(search);
  3285. return (int)numfiles;
  3286. }
  3287. static void FS_ListDirectoryCmd (const char* cmdname, int oneperline)
  3288. {
  3289. const char *pattern;
  3290. if (Cmd_Argc() >= 3)
  3291. {
  3292. Con_Printf("usage:\n%s [path/pattern]\n", cmdname);
  3293. return;
  3294. }
  3295. if (Cmd_Argc() == 2)
  3296. pattern = Cmd_Argv(1);
  3297. else
  3298. pattern = "*";
  3299. if (!FS_ListDirectory(pattern, oneperline))
  3300. Con_Print("No files found.\n");
  3301. }
  3302. void FS_Dir_f(void)
  3303. {
  3304. FS_ListDirectoryCmd("dir", true);
  3305. }
  3306. void FS_Ls_f(void)
  3307. {
  3308. FS_ListDirectoryCmd("ls", false);
  3309. }
  3310. void FS_Which_f(void)
  3311. {
  3312. const char *filename;
  3313. int index;
  3314. searchpath_t *sp;
  3315. if (Cmd_Argc() != 2)
  3316. {
  3317. Con_Printf("usage:\n%s <file>\n", Cmd_Argv(0));
  3318. return;
  3319. }
  3320. filename = Cmd_Argv(1);
  3321. sp = FS_FindFile(filename, &index, true);
  3322. if (!sp) {
  3323. Con_Printf("%s isn't anywhere\n", filename);
  3324. return;
  3325. }
  3326. if (sp->pack)
  3327. {
  3328. if(sp->pack->vpack)
  3329. Con_Printf("%s is in virtual package %sdir\n", filename, sp->pack->shortname);
  3330. else
  3331. Con_Printf("%s is in package %s\n", filename, sp->pack->shortname);
  3332. }
  3333. else
  3334. Con_Printf("%s is file %s%s\n", filename, sp->filename, filename);
  3335. }
  3336. const char *FS_WhichPack(const char *filename)
  3337. {
  3338. int index;
  3339. searchpath_t *sp = FS_FindFile(filename, &index, true);
  3340. if(sp && sp->pack)
  3341. return sp->pack->shortname;
  3342. else if(sp)
  3343. return "";
  3344. else
  3345. return 0;
  3346. }
  3347. /*
  3348. ====================
  3349. FS_IsRegisteredQuakePack
  3350. Look for a proof of purchase file file in the requested package
  3351. If it is found, this file should NOT be downloaded.
  3352. ====================
  3353. */
  3354. qboolean FS_IsRegisteredQuakePack(const char *name)
  3355. {
  3356. searchpath_t *search;
  3357. pack_t *pak;
  3358. // search through the path, one element at a time
  3359. for (search = fs_searchpaths;search;search = search->next)
  3360. {
  3361. if (search->pack && !search->pack->vpack && !strcasecmp(FS_FileWithoutPath(search->filename), name))
  3362. // TODO do we want to support vpacks in here too?
  3363. {
  3364. int (*strcmp_funct) (const char* str1, const char* str2);
  3365. int left, right, middle;
  3366. pak = search->pack;
  3367. strcmp_funct = pak->ignorecase ? strcasecmp : strcmp;
  3368. // Look for the file (binary search)
  3369. left = 0;
  3370. right = pak->numfiles - 1;
  3371. while (left <= right)
  3372. {
  3373. int diff;
  3374. middle = (left + right) / 2;
  3375. diff = strcmp_funct (pak->files[middle].name, "gfx/pop.lmp");
  3376. // Found it
  3377. if (!diff)
  3378. return true;
  3379. // If we're too far in the list
  3380. if (diff > 0)
  3381. right = middle - 1;
  3382. else
  3383. left = middle + 1;
  3384. }
  3385. // we found the requested pack but it is not registered quake
  3386. return false;
  3387. }
  3388. }
  3389. return false;
  3390. }
  3391. int FS_CRCFile(const char *filename, size_t *filesizepointer)
  3392. {
  3393. int crc = -1;
  3394. unsigned char *filedata;
  3395. fs_offset_t filesize;
  3396. if (filesizepointer)
  3397. *filesizepointer = 0;
  3398. if (!filename || !*filename)
  3399. return crc;
  3400. filedata = FS_LoadFile(filename, tempmempool, true, &filesize);
  3401. if (filedata)
  3402. {
  3403. if (filesizepointer)
  3404. *filesizepointer = filesize;
  3405. crc = CRC_Block(filedata, filesize);
  3406. Mem_Free(filedata);
  3407. }
  3408. return crc;
  3409. }
  3410. unsigned char *FS_Deflate(const unsigned char *data, size_t size, size_t *deflated_size, int level, mempool_t *mempool)
  3411. {
  3412. z_stream strm;
  3413. unsigned char *out = NULL;
  3414. unsigned char *tmp;
  3415. *deflated_size = 0;
  3416. #ifndef LINK_TO_ZLIB
  3417. if(!zlib_dll)
  3418. return NULL;
  3419. #endif
  3420. memset(&strm, 0, sizeof(strm));
  3421. strm.zalloc = Z_NULL;
  3422. strm.zfree = Z_NULL;
  3423. strm.opaque = Z_NULL;
  3424. if(level < 0)
  3425. level = Z_DEFAULT_COMPRESSION;
  3426. if(qz_deflateInit2(&strm, level, Z_DEFLATED, -MAX_WBITS, Z_MEMLEVEL_DEFAULT, Z_BINARY) != Z_OK)
  3427. {
  3428. Con_Printf("FS_Deflate: deflate init error!\n");
  3429. return NULL;
  3430. }
  3431. strm.next_in = (unsigned char*)data;
  3432. strm.avail_in = (unsigned int)size;
  3433. tmp = (unsigned char *) Mem_Alloc(tempmempool, size);
  3434. if(!tmp)
  3435. {
  3436. Con_Printf("FS_Deflate: not enough memory in tempmempool!\n");
  3437. qz_deflateEnd(&strm);
  3438. return NULL;
  3439. }
  3440. strm.next_out = tmp;
  3441. strm.avail_out = (unsigned int)size;
  3442. if(qz_deflate(&strm, Z_FINISH) != Z_STREAM_END)
  3443. {
  3444. Con_Printf("FS_Deflate: deflate failed!\n");
  3445. qz_deflateEnd(&strm);
  3446. Mem_Free(tmp);
  3447. return NULL;
  3448. }
  3449. if(qz_deflateEnd(&strm) != Z_OK)
  3450. {
  3451. Con_Printf("FS_Deflate: deflateEnd failed\n");
  3452. Mem_Free(tmp);
  3453. return NULL;
  3454. }
  3455. if(strm.total_out >= size)
  3456. {
  3457. Con_Printf("FS_Deflate: deflate is useless on this data!\n");
  3458. Mem_Free(tmp);
  3459. return NULL;
  3460. }
  3461. out = (unsigned char *) Mem_Alloc(mempool, strm.total_out);
  3462. if(!out)
  3463. {
  3464. Con_Printf("FS_Deflate: not enough memory in target mempool!\n");
  3465. Mem_Free(tmp);
  3466. return NULL;
  3467. }
  3468. *deflated_size = (size_t)strm.total_out;
  3469. memcpy(out, tmp, strm.total_out);
  3470. Mem_Free(tmp);
  3471. return out;
  3472. }
  3473. static void AssertBufsize(sizebuf_t *buf, int length)
  3474. {
  3475. if(buf->cursize + length > buf->maxsize)
  3476. {
  3477. int oldsize = buf->maxsize;
  3478. unsigned char *olddata;
  3479. olddata = buf->data;
  3480. buf->maxsize += length;
  3481. buf->data = (unsigned char *) Mem_Alloc(tempmempool, buf->maxsize);
  3482. if(olddata)
  3483. {
  3484. memcpy(buf->data, olddata, oldsize);
  3485. Mem_Free(olddata);
  3486. }
  3487. }
  3488. }
  3489. unsigned char *FS_Inflate(const unsigned char *data, size_t size, size_t *inflated_size, mempool_t *mempool)
  3490. {
  3491. int ret;
  3492. z_stream strm;
  3493. unsigned char *out = NULL;
  3494. unsigned char tmp[2048];
  3495. unsigned int have;
  3496. sizebuf_t outbuf;
  3497. *inflated_size = 0;
  3498. #ifndef LINK_TO_ZLIB
  3499. if(!zlib_dll)
  3500. return NULL;
  3501. #endif
  3502. memset(&outbuf, 0, sizeof(outbuf));
  3503. outbuf.data = (unsigned char *) Mem_Alloc(tempmempool, sizeof(tmp));
  3504. outbuf.maxsize = sizeof(tmp);
  3505. memset(&strm, 0, sizeof(strm));
  3506. strm.zalloc = Z_NULL;
  3507. strm.zfree = Z_NULL;
  3508. strm.opaque = Z_NULL;
  3509. if(qz_inflateInit2(&strm, -MAX_WBITS) != Z_OK)
  3510. {
  3511. Con_Printf("FS_Inflate: inflate init error!\n");
  3512. Mem_Free(outbuf.data);
  3513. return NULL;
  3514. }
  3515. strm.next_in = (unsigned char*)data;
  3516. strm.avail_in = (unsigned int)size;
  3517. do
  3518. {
  3519. strm.next_out = tmp;
  3520. strm.avail_out = sizeof(tmp);
  3521. ret = qz_inflate(&strm, Z_NO_FLUSH);
  3522. // it either returns Z_OK on progress, Z_STREAM_END on end
  3523. // or an error code
  3524. switch(ret)
  3525. {
  3526. case Z_STREAM_END:
  3527. case Z_OK:
  3528. break;
  3529. case Z_STREAM_ERROR:
  3530. Con_Print("FS_Inflate: stream error!\n");
  3531. break;
  3532. case Z_DATA_ERROR:
  3533. Con_Print("FS_Inflate: data error!\n");
  3534. break;
  3535. case Z_MEM_ERROR:
  3536. Con_Print("FS_Inflate: mem error!\n");
  3537. break;
  3538. case Z_BUF_ERROR:
  3539. Con_Print("FS_Inflate: buf error!\n");
  3540. break;
  3541. default:
  3542. Con_Print("FS_Inflate: unknown error!\n");
  3543. break;
  3544. }
  3545. if(ret != Z_OK && ret != Z_STREAM_END)
  3546. {
  3547. Con_Printf("Error after inflating %u bytes\n", (unsigned)strm.total_in);
  3548. Mem_Free(outbuf.data);
  3549. qz_inflateEnd(&strm);
  3550. return NULL;
  3551. }
  3552. have = sizeof(tmp) - strm.avail_out;
  3553. AssertBufsize(&outbuf, max(have, sizeof(tmp)));
  3554. SZ_Write(&outbuf, tmp, have);
  3555. } while(ret != Z_STREAM_END);
  3556. qz_inflateEnd(&strm);
  3557. out = (unsigned char *) Mem_Alloc(mempool, outbuf.cursize);
  3558. if(!out)
  3559. {
  3560. Con_Printf("FS_Inflate: not enough memory in target mempool!\n");
  3561. Mem_Free(outbuf.data);
  3562. return NULL;
  3563. }
  3564. memcpy(out, outbuf.data, outbuf.cursize);
  3565. Mem_Free(outbuf.data);
  3566. *inflated_size = (size_t)outbuf.cursize;
  3567. return out;
  3568. }