🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3318 lines
93 KiB

  1. /**
  2. * PhysicsFS; a portable, flexible file i/o abstraction.
  3. *
  4. * Documentation is in physfs.h. It's verbose, honest. :)
  5. *
  6. * Please see the file LICENSE.txt in the source's root directory.
  7. *
  8. * This file written by Ryan C. Gordon.
  9. */
  10. #define __PHYSICSFS_INTERNAL__
  11. #include "physfs_internal.h"
  12. #if defined(_MSC_VER)
  13. #include <stdarg.h>
  14. /* this code came from https://stackoverflow.com/a/8712996 */
  15. int __PHYSFS_msvc_vsnprintf(char *outBuf, size_t size, const char *format, va_list ap)
  16. {
  17. int count = -1;
  18. if (size != 0)
  19. count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap);
  20. if (count == -1)
  21. count = _vscprintf(format, ap);
  22. return count;
  23. }
  24. int __PHYSFS_msvc_snprintf(char *outBuf, size_t size, const char *format, ...)
  25. {
  26. int count;
  27. va_list ap;
  28. va_start(ap, format);
  29. count = __PHYSFS_msvc_vsnprintf(outBuf, size, format, ap);
  30. va_end(ap);
  31. return count;
  32. }
  33. #endif
  34. typedef struct __PHYSFS_DIRHANDLE__
  35. {
  36. void *opaque; /* Instance data unique to the archiver. */
  37. char *dirName; /* Path to archive in platform-dependent notation. */
  38. char *mountPoint; /* Mountpoint in virtual file tree. */
  39. const PHYSFS_Archiver *funcs; /* Ptr to archiver info for this handle. */
  40. struct __PHYSFS_DIRHANDLE__ *next; /* linked list stuff. */
  41. } DirHandle;
  42. typedef struct __PHYSFS_FILEHANDLE__
  43. {
  44. PHYSFS_Io *io; /* Instance data unique to the archiver for this file. */
  45. PHYSFS_uint8 forReading; /* Non-zero if reading, zero if write/append */
  46. const DirHandle *dirHandle; /* Archiver instance that created this */
  47. PHYSFS_uint8 *buffer; /* Buffer, if set (NULL otherwise). Don't touch! */
  48. size_t bufsize; /* Bufsize, if set (0 otherwise). Don't touch! */
  49. size_t buffill; /* Buffer fill size. Don't touch! */
  50. size_t bufpos; /* Buffer position. Don't touch! */
  51. struct __PHYSFS_FILEHANDLE__ *next; /* linked list stuff. */
  52. } FileHandle;
  53. typedef struct __PHYSFS_ERRSTATETYPE__
  54. {
  55. void *tid;
  56. PHYSFS_ErrorCode code;
  57. struct __PHYSFS_ERRSTATETYPE__ *next;
  58. } ErrState;
  59. /* General PhysicsFS state ... */
  60. static int initialized = 0;
  61. static ErrState *errorStates = NULL;
  62. static DirHandle *searchPath = NULL;
  63. static DirHandle *writeDir = NULL;
  64. static FileHandle *openWriteList = NULL;
  65. static FileHandle *openReadList = NULL;
  66. static char *baseDir = NULL;
  67. static char *userDir = NULL;
  68. static char *prefDir = NULL;
  69. static int allowSymLinks = 0;
  70. static PHYSFS_Archiver **archivers = NULL;
  71. static PHYSFS_ArchiveInfo **archiveInfo = NULL;
  72. static volatile size_t numArchivers = 0;
  73. /* mutexes ... */
  74. static void *errorLock = NULL; /* protects error message list. */
  75. static void *stateLock = NULL; /* protects other PhysFS static state. */
  76. /* allocator ... */
  77. static int externalAllocator = 0;
  78. PHYSFS_Allocator allocator;
  79. #ifdef PHYSFS_NEED_ATOMIC_OP_FALLBACK
  80. static inline int __PHYSFS_atomicAdd(int *ptrval, const int val)
  81. {
  82. int retval;
  83. __PHYSFS_platformGrabMutex(stateLock);
  84. retval = *ptrval;
  85. *ptrval = retval + val;
  86. __PHYSFS_platformReleaseMutex(stateLock);
  87. return retval;
  88. } /* __PHYSFS_atomicAdd */
  89. int __PHYSFS_ATOMIC_INCR(int *ptrval)
  90. {
  91. return __PHYSFS_atomicAdd(ptrval, 1);
  92. } /* __PHYSFS_ATOMIC_INCR */
  93. int __PHYSFS_ATOMIC_DECR(int *ptrval)
  94. {
  95. return __PHYSFS_atomicAdd(ptrval, -1);
  96. } /* __PHYSFS_ATOMIC_DECR */
  97. #endif
  98. /* PHYSFS_Io implementation for i/o to physical filesystem... */
  99. /* !!! FIXME: maybe refcount the paths in a string pool? */
  100. typedef struct __PHYSFS_NativeIoInfo
  101. {
  102. void *handle;
  103. const char *path;
  104. int mode; /* 'r', 'w', or 'a' */
  105. } NativeIoInfo;
  106. static PHYSFS_sint64 nativeIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
  107. {
  108. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  109. return __PHYSFS_platformRead(info->handle, buf, len);
  110. } /* nativeIo_read */
  111. static PHYSFS_sint64 nativeIo_write(PHYSFS_Io *io, const void *buffer,
  112. PHYSFS_uint64 len)
  113. {
  114. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  115. return __PHYSFS_platformWrite(info->handle, buffer, len);
  116. } /* nativeIo_write */
  117. static int nativeIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
  118. {
  119. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  120. return __PHYSFS_platformSeek(info->handle, offset);
  121. } /* nativeIo_seek */
  122. static PHYSFS_sint64 nativeIo_tell(PHYSFS_Io *io)
  123. {
  124. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  125. return __PHYSFS_platformTell(info->handle);
  126. } /* nativeIo_tell */
  127. static PHYSFS_sint64 nativeIo_length(PHYSFS_Io *io)
  128. {
  129. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  130. return __PHYSFS_platformFileLength(info->handle);
  131. } /* nativeIo_length */
  132. static PHYSFS_Io *nativeIo_duplicate(PHYSFS_Io *io)
  133. {
  134. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  135. return __PHYSFS_createNativeIo(info->path, info->mode);
  136. } /* nativeIo_duplicate */
  137. static int nativeIo_flush(PHYSFS_Io *io)
  138. {
  139. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  140. return __PHYSFS_platformFlush(info->handle);
  141. } /* nativeIo_flush */
  142. static void nativeIo_destroy(PHYSFS_Io *io)
  143. {
  144. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  145. __PHYSFS_platformClose(info->handle);
  146. allocator.Free((void *) info->path);
  147. allocator.Free(info);
  148. allocator.Free(io);
  149. } /* nativeIo_destroy */
  150. static const PHYSFS_Io __PHYSFS_nativeIoInterface =
  151. {
  152. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  153. nativeIo_read,
  154. nativeIo_write,
  155. nativeIo_seek,
  156. nativeIo_tell,
  157. nativeIo_length,
  158. nativeIo_duplicate,
  159. nativeIo_flush,
  160. nativeIo_destroy
  161. };
  162. PHYSFS_Io *__PHYSFS_createNativeIo(const char *path, const int mode)
  163. {
  164. PHYSFS_Io *io = NULL;
  165. NativeIoInfo *info = NULL;
  166. void *handle = NULL;
  167. char *pathdup = NULL;
  168. assert((mode == 'r') || (mode == 'w') || (mode == 'a'));
  169. io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  170. GOTO_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  171. info = (NativeIoInfo *) allocator.Malloc(sizeof (NativeIoInfo));
  172. GOTO_IF(!info, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  173. pathdup = (char *) allocator.Malloc(strlen(path) + 1);
  174. GOTO_IF(!pathdup, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  175. if (mode == 'r')
  176. handle = __PHYSFS_platformOpenRead(path);
  177. else if (mode == 'w')
  178. handle = __PHYSFS_platformOpenWrite(path);
  179. else if (mode == 'a')
  180. handle = __PHYSFS_platformOpenAppend(path);
  181. GOTO_IF_ERRPASS(!handle, createNativeIo_failed);
  182. strcpy(pathdup, path);
  183. info->handle = handle;
  184. info->path = pathdup;
  185. info->mode = mode;
  186. memcpy(io, &__PHYSFS_nativeIoInterface, sizeof (*io));
  187. io->opaque = info;
  188. return io;
  189. createNativeIo_failed:
  190. if (handle != NULL) __PHYSFS_platformClose(handle);
  191. if (pathdup != NULL) allocator.Free(pathdup);
  192. if (info != NULL) allocator.Free(info);
  193. if (io != NULL) allocator.Free(io);
  194. return NULL;
  195. } /* __PHYSFS_createNativeIo */
  196. /* PHYSFS_Io implementation for i/o to a memory buffer... */
  197. typedef struct __PHYSFS_MemoryIoInfo
  198. {
  199. const PHYSFS_uint8 *buf;
  200. PHYSFS_uint64 len;
  201. PHYSFS_uint64 pos;
  202. PHYSFS_Io *parent;
  203. int refcount;
  204. void (*destruct)(void *);
  205. } MemoryIoInfo;
  206. static PHYSFS_sint64 memoryIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
  207. {
  208. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  209. const PHYSFS_uint64 avail = info->len - info->pos;
  210. assert(avail <= info->len);
  211. if (avail == 0)
  212. return 0; /* we're at EOF; nothing to do. */
  213. if (len > avail)
  214. len = avail;
  215. memcpy(buf, info->buf + info->pos, (size_t) len);
  216. info->pos += len;
  217. return len;
  218. } /* memoryIo_read */
  219. static PHYSFS_sint64 memoryIo_write(PHYSFS_Io *io, const void *buffer,
  220. PHYSFS_uint64 len)
  221. {
  222. BAIL(PHYSFS_ERR_OPEN_FOR_READING, -1);
  223. } /* memoryIo_write */
  224. static int memoryIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
  225. {
  226. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  227. BAIL_IF(offset > info->len, PHYSFS_ERR_PAST_EOF, 0);
  228. info->pos = offset;
  229. return 1;
  230. } /* memoryIo_seek */
  231. static PHYSFS_sint64 memoryIo_tell(PHYSFS_Io *io)
  232. {
  233. const MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  234. return (PHYSFS_sint64) info->pos;
  235. } /* memoryIo_tell */
  236. static PHYSFS_sint64 memoryIo_length(PHYSFS_Io *io)
  237. {
  238. const MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  239. return (PHYSFS_sint64) info->len;
  240. } /* memoryIo_length */
  241. static PHYSFS_Io *memoryIo_duplicate(PHYSFS_Io *io)
  242. {
  243. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  244. MemoryIoInfo *newinfo = NULL;
  245. PHYSFS_Io *parent = info->parent;
  246. PHYSFS_Io *retval = NULL;
  247. /* avoid deep copies. */
  248. assert((!parent) || (!((MemoryIoInfo *) parent->opaque)->parent) );
  249. /* share the buffer between duplicates. */
  250. if (parent != NULL) /* dup the parent, increment its refcount. */
  251. return parent->duplicate(parent);
  252. /* we're the parent. */
  253. retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  254. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  255. newinfo = (MemoryIoInfo *) allocator.Malloc(sizeof (MemoryIoInfo));
  256. if (!newinfo)
  257. {
  258. allocator.Free(retval);
  259. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  260. } /* if */
  261. __PHYSFS_ATOMIC_INCR(&info->refcount);
  262. memset(newinfo, '\0', sizeof (*info));
  263. newinfo->buf = info->buf;
  264. newinfo->len = info->len;
  265. newinfo->pos = 0;
  266. newinfo->parent = io;
  267. newinfo->refcount = 0;
  268. newinfo->destruct = NULL;
  269. memcpy(retval, io, sizeof (*retval));
  270. retval->opaque = newinfo;
  271. return retval;
  272. } /* memoryIo_duplicate */
  273. static int memoryIo_flush(PHYSFS_Io *io) { return 1; /* it's read-only. */ }
  274. static void memoryIo_destroy(PHYSFS_Io *io)
  275. {
  276. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  277. PHYSFS_Io *parent = info->parent;
  278. if (parent != NULL)
  279. {
  280. assert(info->buf == ((MemoryIoInfo *) info->parent->opaque)->buf);
  281. assert(info->len == ((MemoryIoInfo *) info->parent->opaque)->len);
  282. assert(info->refcount == 0);
  283. assert(info->destruct == NULL);
  284. allocator.Free(info);
  285. allocator.Free(io);
  286. parent->destroy(parent); /* decrements refcount. */
  287. return;
  288. } /* if */
  289. /* we _are_ the parent. */
  290. assert(info->refcount > 0); /* even in a race, we hold a reference. */
  291. if (__PHYSFS_ATOMIC_DECR(&info->refcount) == 0)
  292. {
  293. void (*destruct)(void *) = info->destruct;
  294. void *buf = (void *) info->buf;
  295. io->opaque = NULL; /* kill this here in case of race. */
  296. allocator.Free(info);
  297. allocator.Free(io);
  298. if (destruct != NULL)
  299. destruct(buf);
  300. } /* if */
  301. } /* memoryIo_destroy */
  302. static const PHYSFS_Io __PHYSFS_memoryIoInterface =
  303. {
  304. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  305. memoryIo_read,
  306. memoryIo_write,
  307. memoryIo_seek,
  308. memoryIo_tell,
  309. memoryIo_length,
  310. memoryIo_duplicate,
  311. memoryIo_flush,
  312. memoryIo_destroy
  313. };
  314. PHYSFS_Io *__PHYSFS_createMemoryIo(const void *buf, PHYSFS_uint64 len,
  315. void (*destruct)(void *))
  316. {
  317. PHYSFS_Io *io = NULL;
  318. MemoryIoInfo *info = NULL;
  319. io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  320. GOTO_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, createMemoryIo_failed);
  321. info = (MemoryIoInfo *) allocator.Malloc(sizeof (MemoryIoInfo));
  322. GOTO_IF(!info, PHYSFS_ERR_OUT_OF_MEMORY, createMemoryIo_failed);
  323. memset(info, '\0', sizeof (*info));
  324. info->buf = (const PHYSFS_uint8 *) buf;
  325. info->len = len;
  326. info->pos = 0;
  327. info->parent = NULL;
  328. info->refcount = 1;
  329. info->destruct = destruct;
  330. memcpy(io, &__PHYSFS_memoryIoInterface, sizeof (*io));
  331. io->opaque = info;
  332. return io;
  333. createMemoryIo_failed:
  334. if (info != NULL) allocator.Free(info);
  335. if (io != NULL) allocator.Free(io);
  336. return NULL;
  337. } /* __PHYSFS_createMemoryIo */
  338. /* PHYSFS_Io implementation for i/o to a PHYSFS_File... */
  339. static PHYSFS_sint64 handleIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
  340. {
  341. return PHYSFS_readBytes((PHYSFS_File *) io->opaque, buf, len);
  342. } /* handleIo_read */
  343. static PHYSFS_sint64 handleIo_write(PHYSFS_Io *io, const void *buffer,
  344. PHYSFS_uint64 len)
  345. {
  346. return PHYSFS_writeBytes((PHYSFS_File *) io->opaque, buffer, len);
  347. } /* handleIo_write */
  348. static int handleIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
  349. {
  350. return PHYSFS_seek((PHYSFS_File *) io->opaque, offset);
  351. } /* handleIo_seek */
  352. static PHYSFS_sint64 handleIo_tell(PHYSFS_Io *io)
  353. {
  354. return PHYSFS_tell((PHYSFS_File *) io->opaque);
  355. } /* handleIo_tell */
  356. static PHYSFS_sint64 handleIo_length(PHYSFS_Io *io)
  357. {
  358. return PHYSFS_fileLength((PHYSFS_File *) io->opaque);
  359. } /* handleIo_length */
  360. static PHYSFS_Io *handleIo_duplicate(PHYSFS_Io *io)
  361. {
  362. /*
  363. * There's no duplicate at the PHYSFS_File level, so we break the
  364. * abstraction. We're allowed to: we're physfs.c!
  365. */
  366. FileHandle *origfh = (FileHandle *) io->opaque;
  367. FileHandle *newfh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  368. PHYSFS_Io *retval = NULL;
  369. GOTO_IF(!newfh, PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  370. memset(newfh, '\0', sizeof (*newfh));
  371. retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  372. GOTO_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  373. #if 0 /* we don't buffer the duplicate, at least not at the moment. */
  374. if (origfh->buffer != NULL)
  375. {
  376. newfh->buffer = (PHYSFS_uint8 *) allocator.Malloc(origfh->bufsize);
  377. if (!newfh->buffer)
  378. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  379. newfh->bufsize = origfh->bufsize;
  380. } /* if */
  381. #endif
  382. newfh->io = origfh->io->duplicate(origfh->io);
  383. GOTO_IF_ERRPASS(!newfh->io, handleIo_dupe_failed);
  384. newfh->forReading = origfh->forReading;
  385. newfh->dirHandle = origfh->dirHandle;
  386. __PHYSFS_platformGrabMutex(stateLock);
  387. if (newfh->forReading)
  388. {
  389. newfh->next = openReadList;
  390. openReadList = newfh;
  391. } /* if */
  392. else
  393. {
  394. newfh->next = openWriteList;
  395. openWriteList = newfh;
  396. } /* else */
  397. __PHYSFS_platformReleaseMutex(stateLock);
  398. memcpy(retval, io, sizeof (PHYSFS_Io));
  399. retval->opaque = newfh;
  400. return retval;
  401. handleIo_dupe_failed:
  402. if (newfh)
  403. {
  404. if (newfh->io != NULL) newfh->io->destroy(newfh->io);
  405. if (newfh->buffer != NULL) allocator.Free(newfh->buffer);
  406. allocator.Free(newfh);
  407. } /* if */
  408. return NULL;
  409. } /* handleIo_duplicate */
  410. static int handleIo_flush(PHYSFS_Io *io)
  411. {
  412. return PHYSFS_flush((PHYSFS_File *) io->opaque);
  413. } /* handleIo_flush */
  414. static void handleIo_destroy(PHYSFS_Io *io)
  415. {
  416. if (io->opaque != NULL)
  417. PHYSFS_close((PHYSFS_File *) io->opaque);
  418. allocator.Free(io);
  419. } /* handleIo_destroy */
  420. static const PHYSFS_Io __PHYSFS_handleIoInterface =
  421. {
  422. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  423. handleIo_read,
  424. handleIo_write,
  425. handleIo_seek,
  426. handleIo_tell,
  427. handleIo_length,
  428. handleIo_duplicate,
  429. handleIo_flush,
  430. handleIo_destroy
  431. };
  432. static PHYSFS_Io *__PHYSFS_createHandleIo(PHYSFS_File *f)
  433. {
  434. PHYSFS_Io *io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  435. BAIL_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  436. memcpy(io, &__PHYSFS_handleIoInterface, sizeof (*io));
  437. io->opaque = f;
  438. return io;
  439. } /* __PHYSFS_createHandleIo */
  440. /* functions ... */
  441. typedef struct
  442. {
  443. char **list;
  444. PHYSFS_uint32 size;
  445. PHYSFS_ErrorCode errcode;
  446. } EnumStringListCallbackData;
  447. static void enumStringListCallback(void *data, const char *str)
  448. {
  449. void *ptr;
  450. char *newstr;
  451. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  452. if (pecd->errcode)
  453. return;
  454. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  455. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  456. if (ptr != NULL)
  457. pecd->list = (char **) ptr;
  458. if ((ptr == NULL) || (newstr == NULL))
  459. {
  460. pecd->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  461. pecd->list[pecd->size] = NULL;
  462. PHYSFS_freeList(pecd->list);
  463. return;
  464. } /* if */
  465. strcpy(newstr, str);
  466. pecd->list[pecd->size] = newstr;
  467. pecd->size++;
  468. } /* enumStringListCallback */
  469. static char **doEnumStringList(void (*func)(PHYSFS_StringCallback, void *))
  470. {
  471. EnumStringListCallbackData ecd;
  472. memset(&ecd, '\0', sizeof (ecd));
  473. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  474. BAIL_IF(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  475. func(enumStringListCallback, &ecd);
  476. if (ecd.errcode)
  477. {
  478. PHYSFS_setErrorCode(ecd.errcode);
  479. return NULL;
  480. } /* if */
  481. ecd.list[ecd.size] = NULL;
  482. return ecd.list;
  483. } /* doEnumStringList */
  484. static void __PHYSFS_bubble_sort(void *a, size_t lo, size_t hi,
  485. int (*cmpfn)(void *, size_t, size_t),
  486. void (*swapfn)(void *, size_t, size_t))
  487. {
  488. size_t i;
  489. int sorted;
  490. do
  491. {
  492. sorted = 1;
  493. for (i = lo; i < hi; i++)
  494. {
  495. if (cmpfn(a, i, i + 1) > 0)
  496. {
  497. swapfn(a, i, i + 1);
  498. sorted = 0;
  499. } /* if */
  500. } /* for */
  501. } while (!sorted);
  502. } /* __PHYSFS_bubble_sort */
  503. static void __PHYSFS_quick_sort(void *a, size_t lo, size_t hi,
  504. int (*cmpfn)(void *, size_t, size_t),
  505. void (*swapfn)(void *, size_t, size_t))
  506. {
  507. size_t i;
  508. size_t j;
  509. size_t v;
  510. if ((hi - lo) <= PHYSFS_QUICKSORT_THRESHOLD)
  511. __PHYSFS_bubble_sort(a, lo, hi, cmpfn, swapfn);
  512. else
  513. {
  514. i = (hi + lo) / 2;
  515. if (cmpfn(a, lo, i) > 0) swapfn(a, lo, i);
  516. if (cmpfn(a, lo, hi) > 0) swapfn(a, lo, hi);
  517. if (cmpfn(a, i, hi) > 0) swapfn(a, i, hi);
  518. j = hi - 1;
  519. swapfn(a, i, j);
  520. i = lo;
  521. v = j;
  522. while (1)
  523. {
  524. while(cmpfn(a, ++i, v) < 0) { /* do nothing */ }
  525. while(cmpfn(a, --j, v) > 0) { /* do nothing */ }
  526. if (j < i)
  527. break;
  528. swapfn(a, i, j);
  529. } /* while */
  530. if (i != (hi-1))
  531. swapfn(a, i, hi-1);
  532. __PHYSFS_quick_sort(a, lo, j, cmpfn, swapfn);
  533. __PHYSFS_quick_sort(a, i+1, hi, cmpfn, swapfn);
  534. } /* else */
  535. } /* __PHYSFS_quick_sort */
  536. void __PHYSFS_sort(void *entries, size_t max,
  537. int (*cmpfn)(void *, size_t, size_t),
  538. void (*swapfn)(void *, size_t, size_t))
  539. {
  540. /*
  541. * Quicksort w/ Bubblesort fallback algorithm inspired by code from here:
  542. * https://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html
  543. */
  544. if (max > 0)
  545. __PHYSFS_quick_sort(entries, 0, max - 1, cmpfn, swapfn);
  546. } /* __PHYSFS_sort */
  547. static ErrState *findErrorForCurrentThread(void)
  548. {
  549. ErrState *i;
  550. void *tid;
  551. if (errorLock != NULL)
  552. __PHYSFS_platformGrabMutex(errorLock);
  553. if (errorStates != NULL)
  554. {
  555. tid = __PHYSFS_platformGetThreadID();
  556. for (i = errorStates; i != NULL; i = i->next)
  557. {
  558. if (i->tid == tid)
  559. {
  560. if (errorLock != NULL)
  561. __PHYSFS_platformReleaseMutex(errorLock);
  562. return i;
  563. } /* if */
  564. } /* for */
  565. } /* if */
  566. if (errorLock != NULL)
  567. __PHYSFS_platformReleaseMutex(errorLock);
  568. return NULL; /* no error available. */
  569. } /* findErrorForCurrentThread */
  570. /* this doesn't reset the error state. */
  571. static inline PHYSFS_ErrorCode currentErrorCode(void)
  572. {
  573. const ErrState *err = findErrorForCurrentThread();
  574. return err ? err->code : PHYSFS_ERR_OK;
  575. } /* currentErrorCode */
  576. PHYSFS_ErrorCode PHYSFS_getLastErrorCode(void)
  577. {
  578. ErrState *err = findErrorForCurrentThread();
  579. const PHYSFS_ErrorCode retval = (err) ? err->code : PHYSFS_ERR_OK;
  580. if (err)
  581. err->code = PHYSFS_ERR_OK;
  582. return retval;
  583. } /* PHYSFS_getLastErrorCode */
  584. PHYSFS_DECL const char *PHYSFS_getErrorByCode(PHYSFS_ErrorCode code)
  585. {
  586. switch (code)
  587. {
  588. case PHYSFS_ERR_OK: return "no error";
  589. case PHYSFS_ERR_OTHER_ERROR: return "unknown error";
  590. case PHYSFS_ERR_OUT_OF_MEMORY: return "out of memory";
  591. case PHYSFS_ERR_NOT_INITIALIZED: return "not initialized";
  592. case PHYSFS_ERR_IS_INITIALIZED: return "already initialized";
  593. case PHYSFS_ERR_ARGV0_IS_NULL: return "argv[0] is NULL";
  594. case PHYSFS_ERR_UNSUPPORTED: return "unsupported";
  595. case PHYSFS_ERR_PAST_EOF: return "past end of file";
  596. case PHYSFS_ERR_FILES_STILL_OPEN: return "files still open";
  597. case PHYSFS_ERR_INVALID_ARGUMENT: return "invalid argument";
  598. case PHYSFS_ERR_NOT_MOUNTED: return "not mounted";
  599. case PHYSFS_ERR_NOT_FOUND: return "not found";
  600. case PHYSFS_ERR_SYMLINK_FORBIDDEN: return "symlinks are forbidden";
  601. case PHYSFS_ERR_NO_WRITE_DIR: return "write directory is not set";
  602. case PHYSFS_ERR_OPEN_FOR_READING: return "file open for reading";
  603. case PHYSFS_ERR_OPEN_FOR_WRITING: return "file open for writing";
  604. case PHYSFS_ERR_NOT_A_FILE: return "not a file";
  605. case PHYSFS_ERR_READ_ONLY: return "read-only filesystem";
  606. case PHYSFS_ERR_CORRUPT: return "corrupted";
  607. case PHYSFS_ERR_SYMLINK_LOOP: return "infinite symbolic link loop";
  608. case PHYSFS_ERR_IO: return "i/o error";
  609. case PHYSFS_ERR_PERMISSION: return "permission denied";
  610. case PHYSFS_ERR_NO_SPACE: return "no space available for writing";
  611. case PHYSFS_ERR_BAD_FILENAME: return "filename is illegal or insecure";
  612. case PHYSFS_ERR_BUSY: return "tried to modify a file the OS needs";
  613. case PHYSFS_ERR_DIR_NOT_EMPTY: return "directory isn't empty";
  614. case PHYSFS_ERR_OS_ERROR: return "OS reported an error";
  615. case PHYSFS_ERR_DUPLICATE: return "duplicate resource";
  616. case PHYSFS_ERR_BAD_PASSWORD: return "bad password";
  617. case PHYSFS_ERR_APP_CALLBACK: return "app callback reported error";
  618. } /* switch */
  619. return NULL; /* don't know this error code. */
  620. } /* PHYSFS_getErrorByCode */
  621. void PHYSFS_setErrorCode(PHYSFS_ErrorCode errcode)
  622. {
  623. ErrState *err;
  624. if (!errcode)
  625. return;
  626. err = findErrorForCurrentThread();
  627. if (err == NULL)
  628. {
  629. err = (ErrState *) allocator.Malloc(sizeof (ErrState));
  630. if (err == NULL)
  631. return; /* uhh...? */
  632. memset(err, '\0', sizeof (ErrState));
  633. err->tid = __PHYSFS_platformGetThreadID();
  634. if (errorLock != NULL)
  635. __PHYSFS_platformGrabMutex(errorLock);
  636. err->next = errorStates;
  637. errorStates = err;
  638. if (errorLock != NULL)
  639. __PHYSFS_platformReleaseMutex(errorLock);
  640. } /* if */
  641. err->code = errcode;
  642. } /* PHYSFS_setErrorCode */
  643. const char *PHYSFS_getLastError(void)
  644. {
  645. const PHYSFS_ErrorCode err = PHYSFS_getLastErrorCode();
  646. return (err) ? PHYSFS_getErrorByCode(err) : NULL;
  647. } /* PHYSFS_getLastError */
  648. /* MAKE SURE that errorLock is held before calling this! */
  649. static void freeErrorStates(void)
  650. {
  651. ErrState *i;
  652. ErrState *next;
  653. for (i = errorStates; i != NULL; i = next)
  654. {
  655. next = i->next;
  656. allocator.Free(i);
  657. } /* for */
  658. errorStates = NULL;
  659. } /* freeErrorStates */
  660. void PHYSFS_getLinkedVersion(PHYSFS_Version *ver)
  661. {
  662. if (ver != NULL)
  663. {
  664. ver->major = PHYSFS_VER_MAJOR;
  665. ver->minor = PHYSFS_VER_MINOR;
  666. ver->patch = PHYSFS_VER_PATCH;
  667. } /* if */
  668. } /* PHYSFS_getLinkedVersion */
  669. static const char *find_filename_extension(const char *fname)
  670. {
  671. const char *retval = NULL;
  672. if (fname != NULL)
  673. {
  674. const char *p = strchr(fname, '.');
  675. retval = p;
  676. while (p != NULL)
  677. {
  678. p = strchr(p + 1, '.');
  679. if (p != NULL)
  680. retval = p;
  681. } /* while */
  682. if (retval != NULL)
  683. retval++; /* skip '.' */
  684. } /* if */
  685. return retval;
  686. } /* find_filename_extension */
  687. static DirHandle *tryOpenDir(PHYSFS_Io *io, const PHYSFS_Archiver *funcs,
  688. const char *d, int forWriting, int *_claimed)
  689. {
  690. DirHandle *retval = NULL;
  691. void *opaque = NULL;
  692. if (io != NULL)
  693. BAIL_IF_ERRPASS(!io->seek(io, 0), NULL);
  694. opaque = funcs->openArchive(io, d, forWriting, _claimed);
  695. if (opaque != NULL)
  696. {
  697. retval = (DirHandle *) allocator.Malloc(sizeof (DirHandle));
  698. if (retval == NULL)
  699. funcs->closeArchive(opaque);
  700. else
  701. {
  702. memset(retval, '\0', sizeof (DirHandle));
  703. retval->mountPoint = NULL;
  704. retval->funcs = funcs;
  705. retval->opaque = opaque;
  706. } /* else */
  707. } /* if */
  708. return retval;
  709. } /* tryOpenDir */
  710. static DirHandle *openDirectory(PHYSFS_Io *io, const char *d, int forWriting)
  711. {
  712. DirHandle *retval = NULL;
  713. PHYSFS_Archiver **i;
  714. const char *ext;
  715. int created_io = 0;
  716. int claimed = 0;
  717. PHYSFS_ErrorCode errcode;
  718. assert((io != NULL) || (d != NULL));
  719. if (io == NULL)
  720. {
  721. /* file doesn't exist, etc? Just fail out. */
  722. PHYSFS_Stat statbuf;
  723. BAIL_IF_ERRPASS(!__PHYSFS_platformStat(d, &statbuf, 1), NULL);
  724. /* DIR gets first shot (unlike the rest, it doesn't deal with files). */
  725. if (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY)
  726. {
  727. retval = tryOpenDir(io, &__PHYSFS_Archiver_DIR, d, forWriting, &claimed);
  728. if (retval || claimed)
  729. return retval;
  730. } /* if */
  731. io = __PHYSFS_createNativeIo(d, forWriting ? 'w' : 'r');
  732. BAIL_IF_ERRPASS(!io, NULL);
  733. created_io = 1;
  734. } /* if */
  735. ext = find_filename_extension(d);
  736. if (ext != NULL)
  737. {
  738. /* Look for archivers with matching file extensions first... */
  739. for (i = archivers; (*i != NULL) && (retval == NULL) && !claimed; i++)
  740. {
  741. if (PHYSFS_utf8stricmp(ext, (*i)->info.extension) == 0)
  742. retval = tryOpenDir(io, *i, d, forWriting, &claimed);
  743. } /* for */
  744. /* failing an exact file extension match, try all the others... */
  745. for (i = archivers; (*i != NULL) && (retval == NULL) && !claimed; i++)
  746. {
  747. if (PHYSFS_utf8stricmp(ext, (*i)->info.extension) != 0)
  748. retval = tryOpenDir(io, *i, d, forWriting, &claimed);
  749. } /* for */
  750. } /* if */
  751. else /* no extension? Try them all. */
  752. {
  753. for (i = archivers; (*i != NULL) && (retval == NULL) && !claimed; i++)
  754. retval = tryOpenDir(io, *i, d, forWriting, &claimed);
  755. } /* else */
  756. errcode = currentErrorCode();
  757. if ((!retval) && (created_io))
  758. io->destroy(io);
  759. BAIL_IF(!retval, claimed ? errcode : PHYSFS_ERR_UNSUPPORTED, NULL);
  760. return retval;
  761. } /* openDirectory */
  762. /*
  763. * Make a platform-independent path string sane. Doesn't actually check the
  764. * file hierarchy, it just cleans up the string.
  765. * (dst) must be a buffer at least as big as (src), as this is where the
  766. * cleaned up string is deposited.
  767. * If there are illegal bits in the path (".." entries, etc) then we
  768. * return zero and (dst) is undefined. Non-zero if the path was sanitized.
  769. */
  770. static int sanitizePlatformIndependentPath(const char *src, char *dst)
  771. {
  772. char *prev;
  773. char ch;
  774. while (*src == '/') /* skip initial '/' chars... */
  775. src++;
  776. /* Make sure the entire string isn't "." or ".." */
  777. if ((strcmp(src, ".") == 0) || (strcmp(src, "..") == 0))
  778. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  779. prev = dst;
  780. do
  781. {
  782. ch = *(src++);
  783. if ((ch == ':') || (ch == '\\')) /* illegal chars in a physfs path. */
  784. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  785. if (ch == '/') /* path separator. */
  786. {
  787. *dst = '\0'; /* "." and ".." are illegal pathnames. */
  788. if ((strcmp(prev, ".") == 0) || (strcmp(prev, "..") == 0))
  789. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  790. while (*src == '/') /* chop out doubles... */
  791. src++;
  792. if (*src == '\0') /* ends with a pathsep? */
  793. break; /* we're done, don't add final pathsep to dst. */
  794. prev = dst + 1;
  795. } /* if */
  796. *(dst++) = ch;
  797. } while (ch != '\0');
  798. return 1;
  799. } /* sanitizePlatformIndependentPath */
  800. /*
  801. * Figure out if (fname) is part of (h)'s mountpoint. (fname) must be an
  802. * output from sanitizePlatformIndependentPath(), so that it is in a known
  803. * state.
  804. *
  805. * This only finds legitimate segments of a mountpoint. If the mountpoint is
  806. * "/a/b/c" and (fname) is "/a/b/c", "/", or "/a/b/c/d", then the results are
  807. * all zero. "/a/b" will succeed, though.
  808. */
  809. static int partOfMountPoint(DirHandle *h, char *fname)
  810. {
  811. int rc;
  812. size_t len, mntpntlen;
  813. if (h->mountPoint == NULL)
  814. return 0;
  815. else if (*fname == '\0')
  816. return 1;
  817. len = strlen(fname);
  818. mntpntlen = strlen(h->mountPoint);
  819. if (len > mntpntlen) /* can't be a subset of mountpoint. */
  820. return 0;
  821. /* if true, must be not a match or a complete match, but not a subset. */
  822. if ((len + 1) == mntpntlen)
  823. return 0;
  824. rc = strncmp(fname, h->mountPoint, len); /* !!! FIXME: case insensitive? */
  825. if (rc != 0)
  826. return 0; /* not a match. */
  827. /* make sure /a/b matches /a/b/ and not /a/bc ... */
  828. return h->mountPoint[len] == '/';
  829. } /* partOfMountPoint */
  830. static DirHandle *createDirHandle(PHYSFS_Io *io, const char *newDir,
  831. const char *mountPoint, int forWriting)
  832. {
  833. DirHandle *dirHandle = NULL;
  834. char *tmpmntpnt = NULL;
  835. assert(newDir != NULL); /* should have caught this higher up. */
  836. if (mountPoint != NULL)
  837. {
  838. const size_t len = strlen(mountPoint) + 1;
  839. tmpmntpnt = (char *) __PHYSFS_smallAlloc(len);
  840. GOTO_IF(!tmpmntpnt, PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  841. if (!sanitizePlatformIndependentPath(mountPoint, tmpmntpnt))
  842. goto badDirHandle;
  843. mountPoint = tmpmntpnt; /* sanitized version. */
  844. } /* if */
  845. dirHandle = openDirectory(io, newDir, forWriting);
  846. GOTO_IF_ERRPASS(!dirHandle, badDirHandle);
  847. dirHandle->dirName = (char *) allocator.Malloc(strlen(newDir) + 1);
  848. GOTO_IF(!dirHandle->dirName, PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  849. strcpy(dirHandle->dirName, newDir);
  850. if ((mountPoint != NULL) && (*mountPoint != '\0'))
  851. {
  852. dirHandle->mountPoint = (char *)allocator.Malloc(strlen(mountPoint)+2);
  853. if (!dirHandle->mountPoint)
  854. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  855. strcpy(dirHandle->mountPoint, mountPoint);
  856. strcat(dirHandle->mountPoint, "/");
  857. } /* if */
  858. __PHYSFS_smallFree(tmpmntpnt);
  859. return dirHandle;
  860. badDirHandle:
  861. if (dirHandle != NULL)
  862. {
  863. dirHandle->funcs->closeArchive(dirHandle->opaque);
  864. allocator.Free(dirHandle->dirName);
  865. allocator.Free(dirHandle->mountPoint);
  866. allocator.Free(dirHandle);
  867. } /* if */
  868. __PHYSFS_smallFree(tmpmntpnt);
  869. return NULL;
  870. } /* createDirHandle */
  871. /* MAKE SURE you've got the stateLock held before calling this! */
  872. static int freeDirHandle(DirHandle *dh, FileHandle *openList)
  873. {
  874. FileHandle *i;
  875. if (dh == NULL)
  876. return 1;
  877. for (i = openList; i != NULL; i = i->next)
  878. BAIL_IF(i->dirHandle == dh, PHYSFS_ERR_FILES_STILL_OPEN, 0);
  879. dh->funcs->closeArchive(dh->opaque);
  880. allocator.Free(dh->dirName);
  881. allocator.Free(dh->mountPoint);
  882. allocator.Free(dh);
  883. return 1;
  884. } /* freeDirHandle */
  885. static char *calculateBaseDir(const char *argv0)
  886. {
  887. const char dirsep = __PHYSFS_platformDirSeparator;
  888. char *retval = NULL;
  889. char *ptr = NULL;
  890. /* Give the platform layer first shot at this. */
  891. retval = __PHYSFS_platformCalcBaseDir(argv0);
  892. if (retval != NULL)
  893. return retval;
  894. /* We need argv0 to go on. */
  895. BAIL_IF(argv0 == NULL, PHYSFS_ERR_ARGV0_IS_NULL, NULL);
  896. ptr = strrchr(argv0, dirsep);
  897. if (ptr != NULL)
  898. {
  899. const size_t size = ((size_t) (ptr - argv0)) + 1;
  900. retval = (char *) allocator.Malloc(size + 1);
  901. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  902. memcpy(retval, argv0, size);
  903. retval[size] = '\0';
  904. return retval;
  905. } /* if */
  906. /* argv0 wasn't helpful. */
  907. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  908. } /* calculateBaseDir */
  909. static int initializeMutexes(void)
  910. {
  911. errorLock = __PHYSFS_platformCreateMutex();
  912. if (errorLock == NULL)
  913. goto initializeMutexes_failed;
  914. stateLock = __PHYSFS_platformCreateMutex();
  915. if (stateLock == NULL)
  916. goto initializeMutexes_failed;
  917. return 1; /* success. */
  918. initializeMutexes_failed:
  919. if (errorLock != NULL)
  920. __PHYSFS_platformDestroyMutex(errorLock);
  921. if (stateLock != NULL)
  922. __PHYSFS_platformDestroyMutex(stateLock);
  923. errorLock = stateLock = NULL;
  924. return 0; /* failed. */
  925. } /* initializeMutexes */
  926. static int doRegisterArchiver(const PHYSFS_Archiver *_archiver);
  927. static int initStaticArchivers(void)
  928. {
  929. #define REGISTER_STATIC_ARCHIVER(arc) { \
  930. if (!doRegisterArchiver(&__PHYSFS_Archiver_##arc)) { \
  931. return 0; \
  932. } \
  933. }
  934. #if PHYSFS_SUPPORTS_ZIP
  935. REGISTER_STATIC_ARCHIVER(ZIP);
  936. #endif
  937. #if PHYSFS_SUPPORTS_7Z
  938. SZIP_global_init();
  939. REGISTER_STATIC_ARCHIVER(7Z);
  940. #endif
  941. #if PHYSFS_SUPPORTS_GRP
  942. REGISTER_STATIC_ARCHIVER(GRP);
  943. #endif
  944. #if PHYSFS_SUPPORTS_QPAK
  945. REGISTER_STATIC_ARCHIVER(QPAK);
  946. #endif
  947. #if PHYSFS_SUPPORTS_HOG
  948. REGISTER_STATIC_ARCHIVER(HOG);
  949. #endif
  950. #if PHYSFS_SUPPORTS_MVL
  951. REGISTER_STATIC_ARCHIVER(MVL);
  952. #endif
  953. #if PHYSFS_SUPPORTS_WAD
  954. REGISTER_STATIC_ARCHIVER(WAD);
  955. #endif
  956. #if PHYSFS_SUPPORTS_SLB
  957. REGISTER_STATIC_ARCHIVER(SLB);
  958. #endif
  959. #if PHYSFS_SUPPORTS_ISO9660
  960. REGISTER_STATIC_ARCHIVER(ISO9660);
  961. #endif
  962. #if PHYSFS_SUPPORTS_VDF
  963. REGISTER_STATIC_ARCHIVER(VDF)
  964. #endif
  965. #undef REGISTER_STATIC_ARCHIVER
  966. return 1;
  967. } /* initStaticArchivers */
  968. static void setDefaultAllocator(void);
  969. static int doDeinit(void);
  970. int PHYSFS_init(const char *argv0)
  971. {
  972. BAIL_IF(initialized, PHYSFS_ERR_IS_INITIALIZED, 0);
  973. if (!externalAllocator)
  974. setDefaultAllocator();
  975. if ((allocator.Init != NULL) && (!allocator.Init())) return 0;
  976. if (!__PHYSFS_platformInit())
  977. {
  978. if (allocator.Deinit != NULL) allocator.Deinit();
  979. return 0;
  980. } /* if */
  981. /* everything below here can be cleaned up safely by doDeinit(). */
  982. if (!initializeMutexes()) goto initFailed;
  983. baseDir = calculateBaseDir(argv0);
  984. if (!baseDir) goto initFailed;
  985. userDir = __PHYSFS_platformCalcUserDir();
  986. if (!userDir) goto initFailed;
  987. /* Platform layer is required to append a dirsep. */
  988. assert(baseDir[strlen(baseDir) - 1] == __PHYSFS_platformDirSeparator);
  989. assert(userDir[strlen(userDir) - 1] == __PHYSFS_platformDirSeparator);
  990. if (!initStaticArchivers()) goto initFailed;
  991. initialized = 1;
  992. /* This makes sure that the error subsystem is initialized. */
  993. PHYSFS_setErrorCode(PHYSFS_getLastErrorCode());
  994. return 1;
  995. initFailed:
  996. doDeinit();
  997. return 0;
  998. } /* PHYSFS_init */
  999. /* MAKE SURE you hold stateLock before calling this! */
  1000. static int closeFileHandleList(FileHandle **list)
  1001. {
  1002. FileHandle *i;
  1003. FileHandle *next = NULL;
  1004. for (i = *list; i != NULL; i = next)
  1005. {
  1006. PHYSFS_Io *io = i->io;
  1007. next = i->next;
  1008. if (io->flush && !io->flush(io))
  1009. {
  1010. *list = i;
  1011. return 0;
  1012. } /* if */
  1013. io->destroy(io);
  1014. allocator.Free(i);
  1015. } /* for */
  1016. *list = NULL;
  1017. return 1;
  1018. } /* closeFileHandleList */
  1019. /* MAKE SURE you hold the stateLock before calling this! */
  1020. static void freeSearchPath(void)
  1021. {
  1022. DirHandle *i;
  1023. DirHandle *next = NULL;
  1024. closeFileHandleList(&openReadList);
  1025. if (searchPath != NULL)
  1026. {
  1027. for (i = searchPath; i != NULL; i = next)
  1028. {
  1029. next = i->next;
  1030. freeDirHandle(i, openReadList);
  1031. } /* for */
  1032. searchPath = NULL;
  1033. } /* if */
  1034. } /* freeSearchPath */
  1035. /* MAKE SURE you hold stateLock before calling this! */
  1036. static int archiverInUse(const PHYSFS_Archiver *arc, const DirHandle *list)
  1037. {
  1038. const DirHandle *i;
  1039. for (i = list; i != NULL; i = i->next)
  1040. {
  1041. if (i->funcs == arc)
  1042. return 1;
  1043. } /* for */
  1044. return 0; /* not in use */
  1045. } /* archiverInUse */
  1046. /* MAKE SURE you hold stateLock before calling this! */
  1047. static int doDeregisterArchiver(const size_t idx)
  1048. {
  1049. const size_t len = (numArchivers - idx) * sizeof (void *);
  1050. PHYSFS_ArchiveInfo *info = archiveInfo[idx];
  1051. PHYSFS_Archiver *arc = archivers[idx];
  1052. /* make sure nothing is still using this archiver */
  1053. if (archiverInUse(arc, searchPath) || archiverInUse(arc, writeDir))
  1054. BAIL(PHYSFS_ERR_FILES_STILL_OPEN, 0);
  1055. allocator.Free((void *) info->extension);
  1056. allocator.Free((void *) info->description);
  1057. allocator.Free((void *) info->author);
  1058. allocator.Free((void *) info->url);
  1059. allocator.Free((void *) arc);
  1060. memmove(&archiveInfo[idx], &archiveInfo[idx+1], len);
  1061. memmove(&archivers[idx], &archivers[idx+1], len);
  1062. assert(numArchivers > 0);
  1063. numArchivers--;
  1064. return 1;
  1065. } /* doDeregisterArchiver */
  1066. /* Does NOT hold the state lock; we're shutting down. */
  1067. static void freeArchivers(void)
  1068. {
  1069. while (numArchivers > 0)
  1070. {
  1071. if (!doDeregisterArchiver(numArchivers - 1))
  1072. assert(!"nothing should be mounted during shutdown.");
  1073. } /* while */
  1074. allocator.Free(archivers);
  1075. allocator.Free(archiveInfo);
  1076. archivers = NULL;
  1077. archiveInfo = NULL;
  1078. } /* freeArchivers */
  1079. static int doDeinit(void)
  1080. {
  1081. closeFileHandleList(&openWriteList);
  1082. BAIL_IF(!PHYSFS_setWriteDir(NULL), PHYSFS_ERR_FILES_STILL_OPEN, 0);
  1083. freeSearchPath();
  1084. freeArchivers();
  1085. freeErrorStates();
  1086. if (baseDir != NULL)
  1087. {
  1088. allocator.Free(baseDir);
  1089. baseDir = NULL;
  1090. } /* if */
  1091. if (userDir != NULL)
  1092. {
  1093. allocator.Free(userDir);
  1094. userDir = NULL;
  1095. } /* if */
  1096. if (prefDir != NULL)
  1097. {
  1098. allocator.Free(prefDir);
  1099. prefDir = NULL;
  1100. } /* if */
  1101. if (archiveInfo != NULL)
  1102. {
  1103. allocator.Free(archiveInfo);
  1104. archiveInfo = NULL;
  1105. } /* if */
  1106. if (archivers != NULL)
  1107. {
  1108. allocator.Free(archivers);
  1109. archivers = NULL;
  1110. } /* if */
  1111. allowSymLinks = 0;
  1112. initialized = 0;
  1113. if (errorLock) __PHYSFS_platformDestroyMutex(errorLock);
  1114. if (stateLock) __PHYSFS_platformDestroyMutex(stateLock);
  1115. if (allocator.Deinit != NULL)
  1116. allocator.Deinit();
  1117. errorLock = stateLock = NULL;
  1118. __PHYSFS_platformDeinit();
  1119. return 1;
  1120. } /* doDeinit */
  1121. int PHYSFS_deinit(void)
  1122. {
  1123. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1124. return doDeinit();
  1125. } /* PHYSFS_deinit */
  1126. int PHYSFS_isInit(void)
  1127. {
  1128. return initialized;
  1129. } /* PHYSFS_isInit */
  1130. char *__PHYSFS_strdup(const char *str)
  1131. {
  1132. char *retval = (char *) allocator.Malloc(strlen(str) + 1);
  1133. if (retval)
  1134. strcpy(retval, str);
  1135. return retval;
  1136. } /* __PHYSFS_strdup */
  1137. PHYSFS_uint32 __PHYSFS_hashString(const char *str, size_t len)
  1138. {
  1139. PHYSFS_uint32 hash = 5381;
  1140. while (len--)
  1141. hash = ((hash << 5) + hash) ^ *(str++);
  1142. return hash;
  1143. } /* __PHYSFS_hashString */
  1144. /* MAKE SURE you hold stateLock before calling this! */
  1145. static int doRegisterArchiver(const PHYSFS_Archiver *_archiver)
  1146. {
  1147. const PHYSFS_uint32 maxver = CURRENT_PHYSFS_ARCHIVER_API_VERSION;
  1148. const size_t len = (numArchivers + 2) * sizeof (void *);
  1149. PHYSFS_Archiver *archiver = NULL;
  1150. PHYSFS_ArchiveInfo *info = NULL;
  1151. const char *ext = NULL;
  1152. void *ptr = NULL;
  1153. size_t i;
  1154. BAIL_IF(!_archiver, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1155. BAIL_IF(_archiver->version > maxver, PHYSFS_ERR_UNSUPPORTED, 0);
  1156. BAIL_IF(!_archiver->info.extension, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1157. BAIL_IF(!_archiver->info.description, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1158. BAIL_IF(!_archiver->info.author, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1159. BAIL_IF(!_archiver->info.url, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1160. BAIL_IF(!_archiver->openArchive, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1161. BAIL_IF(!_archiver->enumerate, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1162. BAIL_IF(!_archiver->openRead, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1163. BAIL_IF(!_archiver->openWrite, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1164. BAIL_IF(!_archiver->openAppend, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1165. BAIL_IF(!_archiver->remove, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1166. BAIL_IF(!_archiver->mkdir, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1167. BAIL_IF(!_archiver->closeArchive, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1168. BAIL_IF(!_archiver->stat, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1169. ext = _archiver->info.extension;
  1170. for (i = 0; i < numArchivers; i++)
  1171. {
  1172. if (PHYSFS_utf8stricmp(archiveInfo[i]->extension, ext) == 0)
  1173. BAIL(PHYSFS_ERR_DUPLICATE, 0);
  1174. } /* for */
  1175. /* make a copy of the data. */
  1176. archiver = (PHYSFS_Archiver *) allocator.Malloc(sizeof (*archiver));
  1177. GOTO_IF(!archiver, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1178. /* Must copy sizeof (OLD_VERSION_OF_STRUCT) when version changes! */
  1179. memcpy(archiver, _archiver, sizeof (*archiver));
  1180. info = (PHYSFS_ArchiveInfo *) &archiver->info;
  1181. memset(info, '\0', sizeof (*info)); /* NULL in case an alloc fails. */
  1182. #define CPYSTR(item) \
  1183. info->item = __PHYSFS_strdup(_archiver->info.item); \
  1184. GOTO_IF(!info->item, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1185. CPYSTR(extension);
  1186. CPYSTR(description);
  1187. CPYSTR(author);
  1188. CPYSTR(url);
  1189. info->supportsSymlinks = _archiver->info.supportsSymlinks;
  1190. #undef CPYSTR
  1191. ptr = allocator.Realloc(archiveInfo, len);
  1192. GOTO_IF(!ptr, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1193. archiveInfo = (PHYSFS_ArchiveInfo **) ptr;
  1194. ptr = allocator.Realloc(archivers, len);
  1195. GOTO_IF(!ptr, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1196. archivers = (PHYSFS_Archiver **) ptr;
  1197. archiveInfo[numArchivers] = info;
  1198. archiveInfo[numArchivers + 1] = NULL;
  1199. archivers[numArchivers] = archiver;
  1200. archivers[numArchivers + 1] = NULL;
  1201. numArchivers++;
  1202. return 1;
  1203. regfailed:
  1204. if (info != NULL)
  1205. {
  1206. allocator.Free((void *) info->extension);
  1207. allocator.Free((void *) info->description);
  1208. allocator.Free((void *) info->author);
  1209. allocator.Free((void *) info->url);
  1210. } /* if */
  1211. allocator.Free(archiver);
  1212. return 0;
  1213. } /* doRegisterArchiver */
  1214. int PHYSFS_registerArchiver(const PHYSFS_Archiver *archiver)
  1215. {
  1216. int retval;
  1217. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1218. __PHYSFS_platformGrabMutex(stateLock);
  1219. retval = doRegisterArchiver(archiver);
  1220. __PHYSFS_platformReleaseMutex(stateLock);
  1221. return retval;
  1222. } /* PHYSFS_registerArchiver */
  1223. int PHYSFS_deregisterArchiver(const char *ext)
  1224. {
  1225. size_t i;
  1226. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1227. BAIL_IF(!ext, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1228. __PHYSFS_platformGrabMutex(stateLock);
  1229. for (i = 0; i < numArchivers; i++)
  1230. {
  1231. if (PHYSFS_utf8stricmp(archiveInfo[i]->extension, ext) == 0)
  1232. {
  1233. const int retval = doDeregisterArchiver(i);
  1234. __PHYSFS_platformReleaseMutex(stateLock);
  1235. return retval;
  1236. } /* if */
  1237. } /* for */
  1238. __PHYSFS_platformReleaseMutex(stateLock);
  1239. BAIL(PHYSFS_ERR_NOT_FOUND, 0);
  1240. } /* PHYSFS_deregisterArchiver */
  1241. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  1242. {
  1243. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, NULL);
  1244. return (const PHYSFS_ArchiveInfo **) archiveInfo;
  1245. } /* PHYSFS_supportedArchiveTypes */
  1246. void PHYSFS_freeList(void *list)
  1247. {
  1248. void **i;
  1249. if (list != NULL)
  1250. {
  1251. for (i = (void **) list; *i != NULL; i++)
  1252. allocator.Free(*i);
  1253. allocator.Free(list);
  1254. } /* if */
  1255. } /* PHYSFS_freeList */
  1256. const char *PHYSFS_getDirSeparator(void)
  1257. {
  1258. static char retval[2] = { __PHYSFS_platformDirSeparator, '\0' };
  1259. return retval;
  1260. } /* PHYSFS_getDirSeparator */
  1261. char **PHYSFS_getCdRomDirs(void)
  1262. {
  1263. return doEnumStringList(__PHYSFS_platformDetectAvailableCDs);
  1264. } /* PHYSFS_getCdRomDirs */
  1265. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  1266. {
  1267. __PHYSFS_platformDetectAvailableCDs(callback, data);
  1268. } /* PHYSFS_getCdRomDirsCallback */
  1269. const char *PHYSFS_getPrefDir(const char *org, const char *app)
  1270. {
  1271. const char dirsep = __PHYSFS_platformDirSeparator;
  1272. PHYSFS_Stat statbuf;
  1273. char *ptr = NULL;
  1274. char *endstr = NULL;
  1275. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1276. BAIL_IF(!org, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1277. BAIL_IF(*org == '\0', PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1278. BAIL_IF(!app, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1279. BAIL_IF(*app == '\0', PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1280. allocator.Free(prefDir);
  1281. prefDir = __PHYSFS_platformCalcPrefDir(org, app);
  1282. BAIL_IF_ERRPASS(!prefDir, NULL);
  1283. assert(strlen(prefDir) > 0);
  1284. endstr = prefDir + (strlen(prefDir) - 1);
  1285. assert(*endstr == dirsep);
  1286. *endstr = '\0'; /* mask out the final dirsep for now. */
  1287. if (!__PHYSFS_platformStat(prefDir, &statbuf, 1))
  1288. {
  1289. for (ptr = strchr(prefDir, dirsep); ptr; ptr = strchr(ptr+1, dirsep))
  1290. {
  1291. *ptr = '\0';
  1292. __PHYSFS_platformMkDir(prefDir);
  1293. *ptr = dirsep;
  1294. } /* for */
  1295. if (!__PHYSFS_platformMkDir(prefDir))
  1296. {
  1297. allocator.Free(prefDir);
  1298. prefDir = NULL;
  1299. } /* if */
  1300. } /* if */
  1301. *endstr = dirsep; /* readd the final dirsep. */
  1302. return prefDir;
  1303. } /* PHYSFS_getPrefDir */
  1304. const char *PHYSFS_getBaseDir(void)
  1305. {
  1306. return baseDir; /* this is calculated in PHYSFS_init()... */
  1307. } /* PHYSFS_getBaseDir */
  1308. const char *__PHYSFS_getUserDir(void) /* not deprecated internal version. */
  1309. {
  1310. return userDir; /* this is calculated in PHYSFS_init()... */
  1311. } /* __PHYSFS_getUserDir */
  1312. const char *PHYSFS_getUserDir(void)
  1313. {
  1314. return __PHYSFS_getUserDir();
  1315. } /* PHYSFS_getUserDir */
  1316. const char *PHYSFS_getWriteDir(void)
  1317. {
  1318. const char *retval = NULL;
  1319. __PHYSFS_platformGrabMutex(stateLock);
  1320. if (writeDir != NULL)
  1321. retval = writeDir->dirName;
  1322. __PHYSFS_platformReleaseMutex(stateLock);
  1323. return retval;
  1324. } /* PHYSFS_getWriteDir */
  1325. int PHYSFS_setWriteDir(const char *newDir)
  1326. {
  1327. int retval = 1;
  1328. __PHYSFS_platformGrabMutex(stateLock);
  1329. if (writeDir != NULL)
  1330. {
  1331. BAIL_IF_MUTEX_ERRPASS(!freeDirHandle(writeDir, openWriteList),
  1332. stateLock, 0);
  1333. writeDir = NULL;
  1334. } /* if */
  1335. if (newDir != NULL)
  1336. {
  1337. writeDir = createDirHandle(NULL, newDir, NULL, 1);
  1338. retval = (writeDir != NULL);
  1339. } /* if */
  1340. __PHYSFS_platformReleaseMutex(stateLock);
  1341. return retval;
  1342. } /* PHYSFS_setWriteDir */
  1343. static int doMount(PHYSFS_Io *io, const char *fname,
  1344. const char *mountPoint, int appendToPath)
  1345. {
  1346. DirHandle *dh;
  1347. DirHandle *prev = NULL;
  1348. DirHandle *i;
  1349. BAIL_IF(!fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1350. if (mountPoint == NULL)
  1351. mountPoint = "/";
  1352. __PHYSFS_platformGrabMutex(stateLock);
  1353. for (i = searchPath; i != NULL; i = i->next)
  1354. {
  1355. /* already in search path? */
  1356. if ((i->dirName != NULL) && (strcmp(fname, i->dirName) == 0))
  1357. BAIL_MUTEX_ERRPASS(stateLock, 1);
  1358. prev = i;
  1359. } /* for */
  1360. dh = createDirHandle(io, fname, mountPoint, 0);
  1361. BAIL_IF_MUTEX_ERRPASS(!dh, stateLock, 0);
  1362. if (appendToPath)
  1363. {
  1364. if (prev == NULL)
  1365. searchPath = dh;
  1366. else
  1367. prev->next = dh;
  1368. } /* if */
  1369. else
  1370. {
  1371. dh->next = searchPath;
  1372. searchPath = dh;
  1373. } /* else */
  1374. __PHYSFS_platformReleaseMutex(stateLock);
  1375. return 1;
  1376. } /* doMount */
  1377. int PHYSFS_mountIo(PHYSFS_Io *io, const char *fname,
  1378. const char *mountPoint, int appendToPath)
  1379. {
  1380. BAIL_IF(!io, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1381. BAIL_IF(!fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1382. BAIL_IF(io->version != 0, PHYSFS_ERR_UNSUPPORTED, 0);
  1383. return doMount(io, fname, mountPoint, appendToPath);
  1384. } /* PHYSFS_mountIo */
  1385. int PHYSFS_mountMemory(const void *buf, PHYSFS_uint64 len, void (*del)(void *),
  1386. const char *fname, const char *mountPoint,
  1387. int appendToPath)
  1388. {
  1389. int retval = 0;
  1390. PHYSFS_Io *io = NULL;
  1391. BAIL_IF(!buf, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1392. BAIL_IF(!fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1393. io = __PHYSFS_createMemoryIo(buf, len, del);
  1394. BAIL_IF_ERRPASS(!io, 0);
  1395. retval = doMount(io, fname, mountPoint, appendToPath);
  1396. if (!retval)
  1397. {
  1398. /* docs say not to call (del) in case of failure, so cheat. */
  1399. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  1400. info->destruct = NULL;
  1401. io->destroy(io);
  1402. } /* if */
  1403. return retval;
  1404. } /* PHYSFS_mountMemory */
  1405. int PHYSFS_mountHandle(PHYSFS_File *file, const char *fname,
  1406. const char *mountPoint, int appendToPath)
  1407. {
  1408. int retval = 0;
  1409. PHYSFS_Io *io = NULL;
  1410. BAIL_IF(!file, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1411. BAIL_IF(!fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1412. io = __PHYSFS_createHandleIo(file);
  1413. BAIL_IF_ERRPASS(!io, 0);
  1414. retval = doMount(io, fname, mountPoint, appendToPath);
  1415. if (!retval)
  1416. {
  1417. /* docs say not to destruct in case of failure, so cheat. */
  1418. io->opaque = NULL;
  1419. io->destroy(io);
  1420. } /* if */
  1421. return retval;
  1422. } /* PHYSFS_mountHandle */
  1423. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  1424. {
  1425. BAIL_IF(!newDir, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1426. return doMount(NULL, newDir, mountPoint, appendToPath);
  1427. } /* PHYSFS_mount */
  1428. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  1429. {
  1430. return PHYSFS_mount(newDir, NULL, appendToPath);
  1431. } /* PHYSFS_addToSearchPath */
  1432. int PHYSFS_removeFromSearchPath(const char *oldDir)
  1433. {
  1434. return PHYSFS_unmount(oldDir);
  1435. } /* PHYSFS_removeFromSearchPath */
  1436. int PHYSFS_unmount(const char *oldDir)
  1437. {
  1438. DirHandle *i;
  1439. DirHandle *prev = NULL;
  1440. DirHandle *next = NULL;
  1441. BAIL_IF(oldDir == NULL, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1442. __PHYSFS_platformGrabMutex(stateLock);
  1443. for (i = searchPath; i != NULL; i = i->next)
  1444. {
  1445. if (strcmp(i->dirName, oldDir) == 0)
  1446. {
  1447. next = i->next;
  1448. BAIL_IF_MUTEX_ERRPASS(!freeDirHandle(i, openReadList),
  1449. stateLock, 0);
  1450. if (prev == NULL)
  1451. searchPath = next;
  1452. else
  1453. prev->next = next;
  1454. BAIL_MUTEX_ERRPASS(stateLock, 1);
  1455. } /* if */
  1456. prev = i;
  1457. } /* for */
  1458. BAIL_MUTEX(PHYSFS_ERR_NOT_MOUNTED, stateLock, 0);
  1459. } /* PHYSFS_unmount */
  1460. char **PHYSFS_getSearchPath(void)
  1461. {
  1462. return doEnumStringList(PHYSFS_getSearchPathCallback);
  1463. } /* PHYSFS_getSearchPath */
  1464. const char *PHYSFS_getMountPoint(const char *dir)
  1465. {
  1466. DirHandle *i;
  1467. __PHYSFS_platformGrabMutex(stateLock);
  1468. for (i = searchPath; i != NULL; i = i->next)
  1469. {
  1470. if (strcmp(i->dirName, dir) == 0)
  1471. {
  1472. const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
  1473. __PHYSFS_platformReleaseMutex(stateLock);
  1474. return retval;
  1475. } /* if */
  1476. } /* for */
  1477. __PHYSFS_platformReleaseMutex(stateLock);
  1478. BAIL(PHYSFS_ERR_NOT_MOUNTED, NULL);
  1479. } /* PHYSFS_getMountPoint */
  1480. void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
  1481. {
  1482. DirHandle *i;
  1483. __PHYSFS_platformGrabMutex(stateLock);
  1484. for (i = searchPath; i != NULL; i = i->next)
  1485. callback(data, i->dirName);
  1486. __PHYSFS_platformReleaseMutex(stateLock);
  1487. } /* PHYSFS_getSearchPathCallback */
  1488. typedef struct setSaneCfgEnumData
  1489. {
  1490. const char *archiveExt;
  1491. size_t archiveExtLen;
  1492. int archivesFirst;
  1493. PHYSFS_ErrorCode errcode;
  1494. } setSaneCfgEnumData;
  1495. static PHYSFS_EnumerateCallbackResult setSaneCfgEnumCallback(void *_data,
  1496. const char *dir, const char *f)
  1497. {
  1498. setSaneCfgEnumData *data = (setSaneCfgEnumData *) _data;
  1499. const size_t extlen = data->archiveExtLen;
  1500. const size_t l = strlen(f);
  1501. const char *ext;
  1502. if ((l > extlen) && (f[l - extlen - 1] == '.'))
  1503. {
  1504. ext = f + (l - extlen);
  1505. if (PHYSFS_utf8stricmp(ext, data->archiveExt) == 0)
  1506. {
  1507. const char dirsep = __PHYSFS_platformDirSeparator;
  1508. const char *d = PHYSFS_getRealDir(f);
  1509. const size_t allocsize = strlen(d) + l + 2;
  1510. char *str = (char *) __PHYSFS_smallAlloc(allocsize);
  1511. if (str == NULL)
  1512. data->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  1513. else
  1514. {
  1515. snprintf(str, allocsize, "%s%c%s", d, dirsep, f);
  1516. if (!PHYSFS_mount(str, NULL, data->archivesFirst == 0))
  1517. data->errcode = currentErrorCode();
  1518. __PHYSFS_smallFree(str);
  1519. } /* else */
  1520. } /* if */
  1521. } /* if */
  1522. /* !!! FIXME: if we want to abort on errors... */
  1523. /*return (data->errcode != PHYSFS_ERR_OK) ? PHYSFS_ENUM_ERROR : PHYSFS_ENUM_OK;*/
  1524. return PHYSFS_ENUM_OK; /* keep going */
  1525. } /* setSaneCfgEnumCallback */
  1526. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  1527. const char *archiveExt, int includeCdRoms,
  1528. int archivesFirst)
  1529. {
  1530. const char *basedir;
  1531. const char *prefdir;
  1532. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1533. prefdir = PHYSFS_getPrefDir(organization, appName);
  1534. BAIL_IF_ERRPASS(!prefdir, 0);
  1535. basedir = PHYSFS_getBaseDir();
  1536. BAIL_IF_ERRPASS(!basedir, 0);
  1537. BAIL_IF(!PHYSFS_setWriteDir(prefdir), PHYSFS_ERR_NO_WRITE_DIR, 0);
  1538. /* !!! FIXME: these can fail and we should report that... */
  1539. /* Put write dir first in search path... */
  1540. PHYSFS_mount(prefdir, NULL, 0);
  1541. /* Put base path on search path... */
  1542. PHYSFS_mount(basedir, NULL, 1);
  1543. /* handle CD-ROMs... */
  1544. if (includeCdRoms)
  1545. {
  1546. char **cds = PHYSFS_getCdRomDirs();
  1547. char **i;
  1548. for (i = cds; *i != NULL; i++)
  1549. PHYSFS_mount(*i, NULL, 1);
  1550. PHYSFS_freeList(cds);
  1551. } /* if */
  1552. /* Root out archives, and add them to search path... */
  1553. if (archiveExt != NULL)
  1554. {
  1555. setSaneCfgEnumData data;
  1556. memset(&data, '\0', sizeof (data));
  1557. data.archiveExt = archiveExt;
  1558. data.archiveExtLen = strlen(archiveExt);
  1559. data.archivesFirst = archivesFirst;
  1560. data.errcode = PHYSFS_ERR_OK;
  1561. if (!PHYSFS_enumerate("/", setSaneCfgEnumCallback, &data))
  1562. {
  1563. /* !!! FIXME: use this if we're reporting errors.
  1564. PHYSFS_ErrorCode errcode = currentErrorCode();
  1565. if (errcode == PHYSFS_ERR_APP_CALLBACK)
  1566. errcode = data->errcode; */
  1567. } /* if */
  1568. } /* if */
  1569. return 1;
  1570. } /* PHYSFS_setSaneConfig */
  1571. void PHYSFS_permitSymbolicLinks(int allow)
  1572. {
  1573. allowSymLinks = allow;
  1574. } /* PHYSFS_permitSymbolicLinks */
  1575. int PHYSFS_symbolicLinksPermitted(void)
  1576. {
  1577. return allowSymLinks;
  1578. } /* PHYSFS_symbolicLinksPermitted */
  1579. /*
  1580. * Verify that (fname) (in platform-independent notation), in relation
  1581. * to (h) is secure. That means that each element of fname is checked
  1582. * for symlinks (if they aren't permitted). This also allows for quick
  1583. * rejection of files that exist outside an archive's mountpoint.
  1584. *
  1585. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  1586. * at a time), you should always pass zero for "allowMissing" for efficiency.
  1587. *
  1588. * (fname) must point to an output from sanitizePlatformIndependentPath(),
  1589. * since it will make sure that path names are in the right format for
  1590. * passing certain checks. It will also do checks for "insecure" pathnames
  1591. * like ".." which should be done once instead of once per archive. This also
  1592. * gives us license to treat (fname) as scratch space in this function.
  1593. *
  1594. * Returns non-zero if string is safe, zero if there's a security issue.
  1595. * PHYSFS_getLastError() will specify what was wrong. (*fname) will be
  1596. * updated to point past any mount point elements so it is prepared to
  1597. * be used with the archiver directly.
  1598. */
  1599. static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
  1600. {
  1601. char *fname = *_fname;
  1602. int retval = 1;
  1603. char *start;
  1604. char *end;
  1605. if (*fname == '\0') /* quick rejection. */
  1606. return 1;
  1607. /* !!! FIXME: This codeblock sucks. */
  1608. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  1609. {
  1610. size_t mntpntlen = strlen(h->mountPoint);
  1611. size_t len = strlen(fname);
  1612. assert(mntpntlen > 1); /* root mount points should be NULL. */
  1613. /* not under the mountpoint, so skip this archive. */
  1614. BAIL_IF(len < mntpntlen-1, PHYSFS_ERR_NOT_FOUND, 0);
  1615. /* !!! FIXME: Case insensitive? */
  1616. retval = strncmp(h->mountPoint, fname, mntpntlen-1);
  1617. BAIL_IF(retval != 0, PHYSFS_ERR_NOT_FOUND, 0);
  1618. if (len > mntpntlen-1) /* corner case... */
  1619. BAIL_IF(fname[mntpntlen-1]!='/', PHYSFS_ERR_NOT_FOUND, 0);
  1620. fname += mntpntlen-1; /* move to start of actual archive path. */
  1621. if (*fname == '/')
  1622. fname++;
  1623. *_fname = fname; /* skip mountpoint for later use. */
  1624. retval = 1; /* may be reset, below. */
  1625. } /* if */
  1626. start = fname;
  1627. if (!allowSymLinks)
  1628. {
  1629. while (1)
  1630. {
  1631. PHYSFS_Stat statbuf;
  1632. int rc = 0;
  1633. end = strchr(start, '/');
  1634. if (end != NULL) *end = '\0';
  1635. rc = h->funcs->stat(h->opaque, fname, &statbuf);
  1636. if (rc)
  1637. rc = (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
  1638. else if (currentErrorCode() == PHYSFS_ERR_NOT_FOUND)
  1639. retval = 0;
  1640. if (end != NULL) *end = '/';
  1641. /* insecure path (has a disallowed symlink in it)? */
  1642. BAIL_IF(rc, PHYSFS_ERR_SYMLINK_FORBIDDEN, 0);
  1643. /* break out early if path element is missing. */
  1644. if (!retval)
  1645. {
  1646. /*
  1647. * We need to clear it if it's the last element of the path,
  1648. * since this might be a non-existant file we're opening
  1649. * for writing...
  1650. */
  1651. if ((end == NULL) || (allowMissing))
  1652. retval = 1;
  1653. break;
  1654. } /* if */
  1655. if (end == NULL)
  1656. break;
  1657. start = end + 1;
  1658. } /* while */
  1659. } /* if */
  1660. return retval;
  1661. } /* verifyPath */
  1662. static int doMkdir(const char *_dname, char *dname)
  1663. {
  1664. DirHandle *h;
  1665. char *start;
  1666. char *end;
  1667. int retval = 0;
  1668. int exists = 1; /* force existance check on first path element. */
  1669. BAIL_IF_ERRPASS(!sanitizePlatformIndependentPath(_dname, dname), 0);
  1670. __PHYSFS_platformGrabMutex(stateLock);
  1671. BAIL_IF_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  1672. h = writeDir;
  1673. BAIL_IF_MUTEX_ERRPASS(!verifyPath(h, &dname, 1), stateLock, 0);
  1674. start = dname;
  1675. while (1)
  1676. {
  1677. end = strchr(start, '/');
  1678. if (end != NULL)
  1679. *end = '\0';
  1680. /* only check for existance if all parent dirs existed, too... */
  1681. if (exists)
  1682. {
  1683. PHYSFS_Stat statbuf;
  1684. const int rc = h->funcs->stat(h->opaque, dname, &statbuf);
  1685. if ((!rc) && (currentErrorCode() == PHYSFS_ERR_NOT_FOUND))
  1686. exists = 0;
  1687. retval = ((rc) && (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY));
  1688. } /* if */
  1689. if (!exists)
  1690. retval = h->funcs->mkdir(h->opaque, dname);
  1691. if (!retval)
  1692. break;
  1693. if (end == NULL)
  1694. break;
  1695. *end = '/';
  1696. start = end + 1;
  1697. } /* while */
  1698. __PHYSFS_platformReleaseMutex(stateLock);
  1699. return retval;
  1700. } /* doMkdir */
  1701. int PHYSFS_mkdir(const char *_dname)
  1702. {
  1703. int retval = 0;
  1704. char *dname;
  1705. size_t len;
  1706. BAIL_IF(!_dname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1707. len = strlen(_dname) + 1;
  1708. dname = (char *) __PHYSFS_smallAlloc(len);
  1709. BAIL_IF(!dname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1710. retval = doMkdir(_dname, dname);
  1711. __PHYSFS_smallFree(dname);
  1712. return retval;
  1713. } /* PHYSFS_mkdir */
  1714. static int doDelete(const char *_fname, char *fname)
  1715. {
  1716. int retval;
  1717. DirHandle *h;
  1718. BAIL_IF_ERRPASS(!sanitizePlatformIndependentPath(_fname, fname), 0);
  1719. __PHYSFS_platformGrabMutex(stateLock);
  1720. BAIL_IF_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  1721. h = writeDir;
  1722. BAIL_IF_MUTEX_ERRPASS(!verifyPath(h, &fname, 0), stateLock, 0);
  1723. retval = h->funcs->remove(h->opaque, fname);
  1724. __PHYSFS_platformReleaseMutex(stateLock);
  1725. return retval;
  1726. } /* doDelete */
  1727. int PHYSFS_delete(const char *_fname)
  1728. {
  1729. int retval;
  1730. char *fname;
  1731. size_t len;
  1732. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1733. len = strlen(_fname) + 1;
  1734. fname = (char *) __PHYSFS_smallAlloc(len);
  1735. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1736. retval = doDelete(_fname, fname);
  1737. __PHYSFS_smallFree(fname);
  1738. return retval;
  1739. } /* PHYSFS_delete */
  1740. static DirHandle *getRealDirHandle(const char *_fname)
  1741. {
  1742. DirHandle *retval = NULL;
  1743. char *fname = NULL;
  1744. size_t len;
  1745. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1746. len = strlen(_fname) + 1;
  1747. fname = __PHYSFS_smallAlloc(len);
  1748. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  1749. if (sanitizePlatformIndependentPath(_fname, fname))
  1750. {
  1751. DirHandle *i;
  1752. __PHYSFS_platformGrabMutex(stateLock);
  1753. for (i = searchPath; i != NULL; i = i->next)
  1754. {
  1755. char *arcfname = fname;
  1756. if (partOfMountPoint(i, arcfname))
  1757. {
  1758. retval = i;
  1759. break;
  1760. } /* if */
  1761. else if (verifyPath(i, &arcfname, 0))
  1762. {
  1763. PHYSFS_Stat statbuf;
  1764. if (i->funcs->stat(i->opaque, arcfname, &statbuf))
  1765. {
  1766. retval = i;
  1767. break;
  1768. } /* if */
  1769. } /* if */
  1770. } /* for */
  1771. __PHYSFS_platformReleaseMutex(stateLock);
  1772. } /* if */
  1773. __PHYSFS_smallFree(fname);
  1774. return retval;
  1775. } /* getRealDirHandle */
  1776. const char *PHYSFS_getRealDir(const char *fname)
  1777. {
  1778. DirHandle *dh = getRealDirHandle(fname);
  1779. return dh ? dh->dirName : NULL;
  1780. } /* PHYSFS_getRealDir */
  1781. static int locateInStringList(const char *str,
  1782. char **list,
  1783. PHYSFS_uint32 *pos)
  1784. {
  1785. PHYSFS_uint32 len = *pos;
  1786. PHYSFS_uint32 half_len;
  1787. PHYSFS_uint32 lo = 0;
  1788. PHYSFS_uint32 middle;
  1789. int cmp;
  1790. while (len > 0)
  1791. {
  1792. half_len = len >> 1;
  1793. middle = lo + half_len;
  1794. cmp = strcmp(list[middle], str);
  1795. if (cmp == 0) /* it's in the list already. */
  1796. return 1;
  1797. else if (cmp > 0)
  1798. len = half_len;
  1799. else
  1800. {
  1801. lo = middle + 1;
  1802. len -= half_len + 1;
  1803. } /* else */
  1804. } /* while */
  1805. *pos = lo;
  1806. return 0;
  1807. } /* locateInStringList */
  1808. static PHYSFS_EnumerateCallbackResult enumFilesCallback(void *data,
  1809. const char *origdir, const char *str)
  1810. {
  1811. PHYSFS_uint32 pos;
  1812. void *ptr;
  1813. char *newstr;
  1814. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1815. /*
  1816. * See if file is in the list already, and if not, insert it in there
  1817. * alphabetically...
  1818. */
  1819. pos = pecd->size;
  1820. if (locateInStringList(str, pecd->list, &pos))
  1821. return PHYSFS_ENUM_OK; /* already in the list, but keep going. */
  1822. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1823. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1824. if (ptr != NULL)
  1825. pecd->list = (char **) ptr;
  1826. if ((ptr == NULL) || (newstr == NULL))
  1827. {
  1828. if (newstr)
  1829. allocator.Free(newstr);
  1830. pecd->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  1831. return PHYSFS_ENUM_ERROR; /* better luck next time. */
  1832. } /* if */
  1833. strcpy(newstr, str);
  1834. if (pos != pecd->size)
  1835. {
  1836. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1837. sizeof (char *) * ((pecd->size) - pos));
  1838. } /* if */
  1839. pecd->list[pos] = newstr;
  1840. pecd->size++;
  1841. return PHYSFS_ENUM_OK;
  1842. } /* enumFilesCallback */
  1843. char **PHYSFS_enumerateFiles(const char *path)
  1844. {
  1845. EnumStringListCallbackData ecd;
  1846. memset(&ecd, '\0', sizeof (ecd));
  1847. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1848. BAIL_IF(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  1849. if (!PHYSFS_enumerate(path, enumFilesCallback, &ecd))
  1850. {
  1851. const PHYSFS_ErrorCode errcode = currentErrorCode();
  1852. PHYSFS_uint32 i;
  1853. for (i = 0; i < ecd.size; i++)
  1854. allocator.Free(ecd.list[i]);
  1855. allocator.Free(ecd.list);
  1856. BAIL_IF(errcode == PHYSFS_ERR_APP_CALLBACK, ecd.errcode, NULL);
  1857. return NULL;
  1858. } /* if */
  1859. ecd.list[ecd.size] = NULL;
  1860. return ecd.list;
  1861. } /* PHYSFS_enumerateFiles */
  1862. /*
  1863. * Broke out to seperate function so we can use stack allocation gratuitously.
  1864. */
  1865. static PHYSFS_EnumerateCallbackResult enumerateFromMountPoint(DirHandle *i,
  1866. const char *arcfname,
  1867. PHYSFS_EnumerateCallback callback,
  1868. const char *_fname, void *data)
  1869. {
  1870. PHYSFS_EnumerateCallbackResult retval;
  1871. const size_t len = strlen(arcfname);
  1872. char *ptr = NULL;
  1873. char *end = NULL;
  1874. const size_t slen = strlen(i->mountPoint) + 1;
  1875. char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
  1876. BAIL_IF(!mountPoint, PHYSFS_ERR_OUT_OF_MEMORY, PHYSFS_ENUM_ERROR);
  1877. strcpy(mountPoint, i->mountPoint);
  1878. ptr = mountPoint + ((len) ? len + 1 : 0);
  1879. end = strchr(ptr, '/');
  1880. assert(end); /* should always find a terminating '/'. */
  1881. *end = '\0';
  1882. retval = callback(data, _fname, ptr);
  1883. __PHYSFS_smallFree(mountPoint);
  1884. BAIL_IF(retval == PHYSFS_ENUM_ERROR, PHYSFS_ERR_APP_CALLBACK, retval);
  1885. return retval;
  1886. } /* enumerateFromMountPoint */
  1887. typedef struct SymlinkFilterData
  1888. {
  1889. PHYSFS_EnumerateCallback callback;
  1890. void *callbackData;
  1891. DirHandle *dirhandle;
  1892. const char *arcfname;
  1893. PHYSFS_ErrorCode errcode;
  1894. } SymlinkFilterData;
  1895. static PHYSFS_EnumerateCallbackResult enumCallbackFilterSymLinks(void *_data,
  1896. const char *origdir, const char *fname)
  1897. {
  1898. SymlinkFilterData *data = (SymlinkFilterData *) _data;
  1899. const DirHandle *dh = data->dirhandle;
  1900. const char *arcfname = data->arcfname;
  1901. PHYSFS_Stat statbuf;
  1902. const char *trimmedDir = (*arcfname == '/') ? (arcfname + 1) : arcfname;
  1903. const size_t slen = strlen(trimmedDir) + strlen(fname) + 2;
  1904. char *path = (char *) __PHYSFS_smallAlloc(slen);
  1905. PHYSFS_EnumerateCallbackResult retval = PHYSFS_ENUM_OK;
  1906. if (path == NULL)
  1907. {
  1908. data->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  1909. return PHYSFS_ENUM_ERROR;
  1910. } /* if */
  1911. snprintf(path, slen, "%s%s%s", trimmedDir, *trimmedDir ? "/" : "", fname);
  1912. if (!dh->funcs->stat(dh->opaque, path, &statbuf))
  1913. {
  1914. data->errcode = currentErrorCode();
  1915. retval = PHYSFS_ENUM_ERROR;
  1916. } /* if */
  1917. else
  1918. {
  1919. /* Pass it on to the application if it's not a symlink. */
  1920. if (statbuf.filetype != PHYSFS_FILETYPE_SYMLINK)
  1921. {
  1922. retval = data->callback(data->callbackData, origdir, fname);
  1923. if (retval == PHYSFS_ENUM_ERROR)
  1924. data->errcode = PHYSFS_ERR_APP_CALLBACK;
  1925. } /* if */
  1926. } /* else */
  1927. __PHYSFS_smallFree(path);
  1928. return retval;
  1929. } /* enumCallbackFilterSymLinks */
  1930. int PHYSFS_enumerate(const char *_fn, PHYSFS_EnumerateCallback cb, void *data)
  1931. {
  1932. PHYSFS_EnumerateCallbackResult retval = PHYSFS_ENUM_OK;
  1933. size_t len;
  1934. char *fname;
  1935. BAIL_IF(!_fn, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1936. BAIL_IF(!cb, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1937. len = strlen(_fn) + 1;
  1938. fname = (char *) __PHYSFS_smallAlloc(len);
  1939. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1940. if (!sanitizePlatformIndependentPath(_fn, fname))
  1941. retval = PHYSFS_ENUM_STOP;
  1942. else
  1943. {
  1944. DirHandle *i;
  1945. SymlinkFilterData filterdata;
  1946. __PHYSFS_platformGrabMutex(stateLock);
  1947. if (!allowSymLinks)
  1948. {
  1949. memset(&filterdata, '\0', sizeof (filterdata));
  1950. filterdata.callback = cb;
  1951. filterdata.callbackData = data;
  1952. } /* if */
  1953. for (i = searchPath; (retval == PHYSFS_ENUM_OK) && i; i = i->next)
  1954. {
  1955. char *arcfname = fname;
  1956. if (partOfMountPoint(i, arcfname))
  1957. retval = enumerateFromMountPoint(i, arcfname, cb, _fn, data);
  1958. else if (verifyPath(i, &arcfname, 0))
  1959. {
  1960. PHYSFS_Stat statbuf;
  1961. if (!i->funcs->stat(i->opaque, arcfname, &statbuf))
  1962. {
  1963. if (currentErrorCode() == PHYSFS_ERR_NOT_FOUND)
  1964. continue; /* no such dir in this archive, skip it. */
  1965. } /* if */
  1966. if (statbuf.filetype != PHYSFS_FILETYPE_DIRECTORY)
  1967. continue; /* not a directory in this archive, skip it. */
  1968. else if ((!allowSymLinks) && (i->funcs->info.supportsSymlinks))
  1969. {
  1970. filterdata.dirhandle = i;
  1971. filterdata.arcfname = arcfname;
  1972. filterdata.errcode = PHYSFS_ERR_OK;
  1973. retval = i->funcs->enumerate(i->opaque, arcfname,
  1974. enumCallbackFilterSymLinks,
  1975. _fn, &filterdata);
  1976. if (retval == PHYSFS_ENUM_ERROR)
  1977. {
  1978. if (currentErrorCode() == PHYSFS_ERR_APP_CALLBACK)
  1979. PHYSFS_setErrorCode(filterdata.errcode);
  1980. } /* if */
  1981. } /* else if */
  1982. else
  1983. {
  1984. retval = i->funcs->enumerate(i->opaque, arcfname,
  1985. cb, _fn, data);
  1986. } /* else */
  1987. } /* else if */
  1988. } /* for */
  1989. __PHYSFS_platformReleaseMutex(stateLock);
  1990. } /* if */
  1991. __PHYSFS_smallFree(fname);
  1992. return (retval == PHYSFS_ENUM_ERROR) ? 0 : 1;
  1993. } /* PHYSFS_enumerate */
  1994. typedef struct
  1995. {
  1996. PHYSFS_EnumFilesCallback callback;
  1997. void *data;
  1998. } LegacyEnumFilesCallbackData;
  1999. static PHYSFS_EnumerateCallbackResult enumFilesCallbackAlwaysSucceed(void *d,
  2000. const char *origdir, const char *fname)
  2001. {
  2002. LegacyEnumFilesCallbackData *cbdata = (LegacyEnumFilesCallbackData *) d;
  2003. cbdata->callback(cbdata->data, origdir, fname);
  2004. return PHYSFS_ENUM_OK;
  2005. } /* enumFilesCallbackAlwaysSucceed */
  2006. void PHYSFS_enumerateFilesCallback(const char *fname,
  2007. PHYSFS_EnumFilesCallback callback,
  2008. void *data)
  2009. {
  2010. LegacyEnumFilesCallbackData cbdata;
  2011. cbdata.callback = callback;
  2012. cbdata.data = data;
  2013. (void) PHYSFS_enumerate(fname, enumFilesCallbackAlwaysSucceed, &cbdata);
  2014. } /* PHYSFS_enumerateFilesCallback */
  2015. int PHYSFS_exists(const char *fname)
  2016. {
  2017. return (getRealDirHandle(fname) != NULL);
  2018. } /* PHYSFS_exists */
  2019. PHYSFS_sint64 PHYSFS_getLastModTime(const char *fname)
  2020. {
  2021. PHYSFS_Stat statbuf;
  2022. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), -1);
  2023. return statbuf.modtime;
  2024. } /* PHYSFS_getLastModTime */
  2025. int PHYSFS_isDirectory(const char *fname)
  2026. {
  2027. PHYSFS_Stat statbuf;
  2028. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), 0);
  2029. return (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY);
  2030. } /* PHYSFS_isDirectory */
  2031. int PHYSFS_isSymbolicLink(const char *fname)
  2032. {
  2033. PHYSFS_Stat statbuf;
  2034. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), 0);
  2035. return (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
  2036. } /* PHYSFS_isSymbolicLink */
  2037. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  2038. {
  2039. FileHandle *fh = NULL;
  2040. size_t len;
  2041. char *fname;
  2042. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2043. len = strlen(_fname) + 1;
  2044. fname = (char *) __PHYSFS_smallAlloc(len);
  2045. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2046. if (sanitizePlatformIndependentPath(_fname, fname))
  2047. {
  2048. PHYSFS_Io *io = NULL;
  2049. DirHandle *h = NULL;
  2050. const PHYSFS_Archiver *f;
  2051. __PHYSFS_platformGrabMutex(stateLock);
  2052. GOTO_IF(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, doOpenWriteEnd);
  2053. h = writeDir;
  2054. GOTO_IF_ERRPASS(!verifyPath(h, &fname, 0), doOpenWriteEnd);
  2055. f = h->funcs;
  2056. if (appending)
  2057. io = f->openAppend(h->opaque, fname);
  2058. else
  2059. io = f->openWrite(h->opaque, fname);
  2060. GOTO_IF_ERRPASS(!io, doOpenWriteEnd);
  2061. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  2062. if (fh == NULL)
  2063. {
  2064. io->destroy(io);
  2065. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, doOpenWriteEnd);
  2066. } /* if */
  2067. else
  2068. {
  2069. memset(fh, '\0', sizeof (FileHandle));
  2070. fh->io = io;
  2071. fh->dirHandle = h;
  2072. fh->next = openWriteList;
  2073. openWriteList = fh;
  2074. } /* else */
  2075. doOpenWriteEnd:
  2076. __PHYSFS_platformReleaseMutex(stateLock);
  2077. } /* if */
  2078. __PHYSFS_smallFree(fname);
  2079. return ((PHYSFS_File *) fh);
  2080. } /* doOpenWrite */
  2081. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  2082. {
  2083. return doOpenWrite(filename, 0);
  2084. } /* PHYSFS_openWrite */
  2085. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  2086. {
  2087. return doOpenWrite(filename, 1);
  2088. } /* PHYSFS_openAppend */
  2089. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  2090. {
  2091. FileHandle *fh = NULL;
  2092. char *fname;
  2093. size_t len;
  2094. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2095. len = strlen(_fname) + 1;
  2096. fname = (char *) __PHYSFS_smallAlloc(len);
  2097. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2098. if (sanitizePlatformIndependentPath(_fname, fname))
  2099. {
  2100. DirHandle *i = NULL;
  2101. PHYSFS_Io *io = NULL;
  2102. __PHYSFS_platformGrabMutex(stateLock);
  2103. GOTO_IF(!searchPath, PHYSFS_ERR_NOT_FOUND, openReadEnd);
  2104. for (i = searchPath; i != NULL; i = i->next)
  2105. {
  2106. char *arcfname = fname;
  2107. if (verifyPath(i, &arcfname, 0))
  2108. {
  2109. io = i->funcs->openRead(i->opaque, arcfname);
  2110. if (io)
  2111. break;
  2112. } /* if */
  2113. } /* for */
  2114. GOTO_IF_ERRPASS(!io, openReadEnd);
  2115. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  2116. if (fh == NULL)
  2117. {
  2118. io->destroy(io);
  2119. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, openReadEnd);
  2120. } /* if */
  2121. memset(fh, '\0', sizeof (FileHandle));
  2122. fh->io = io;
  2123. fh->forReading = 1;
  2124. fh->dirHandle = i;
  2125. fh->next = openReadList;
  2126. openReadList = fh;
  2127. openReadEnd:
  2128. __PHYSFS_platformReleaseMutex(stateLock);
  2129. } /* if */
  2130. __PHYSFS_smallFree(fname);
  2131. return ((PHYSFS_File *) fh);
  2132. } /* PHYSFS_openRead */
  2133. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  2134. {
  2135. FileHandle *prev = NULL;
  2136. FileHandle *i;
  2137. for (i = *list; i != NULL; i = i->next)
  2138. {
  2139. if (i == handle) /* handle is in this list? */
  2140. {
  2141. PHYSFS_Io *io = handle->io;
  2142. PHYSFS_uint8 *tmp = handle->buffer;
  2143. /* send our buffer to io... */
  2144. if (!handle->forReading)
  2145. {
  2146. if (!PHYSFS_flush((PHYSFS_File *) handle))
  2147. return -1;
  2148. /* ...then have io send it to the disk... */
  2149. else if (io->flush && !io->flush(io))
  2150. return -1;
  2151. } /* if */
  2152. /* ...then close the underlying file. */
  2153. io->destroy(io);
  2154. if (tmp != NULL) /* free any associated buffer. */
  2155. allocator.Free(tmp);
  2156. if (prev == NULL)
  2157. *list = handle->next;
  2158. else
  2159. prev->next = handle->next;
  2160. allocator.Free(handle);
  2161. return 1;
  2162. } /* if */
  2163. prev = i;
  2164. } /* for */
  2165. return 0;
  2166. } /* closeHandleInOpenList */
  2167. int PHYSFS_close(PHYSFS_File *_handle)
  2168. {
  2169. FileHandle *handle = (FileHandle *) _handle;
  2170. int rc;
  2171. __PHYSFS_platformGrabMutex(stateLock);
  2172. /* -1 == close failure. 0 == not found. 1 == success. */
  2173. rc = closeHandleInOpenList(&openReadList, handle);
  2174. BAIL_IF_MUTEX_ERRPASS(rc == -1, stateLock, 0);
  2175. if (!rc)
  2176. {
  2177. rc = closeHandleInOpenList(&openWriteList, handle);
  2178. BAIL_IF_MUTEX_ERRPASS(rc == -1, stateLock, 0);
  2179. } /* if */
  2180. __PHYSFS_platformReleaseMutex(stateLock);
  2181. BAIL_IF(!rc, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2182. return 1;
  2183. } /* PHYSFS_close */
  2184. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *_buffer, size_t len)
  2185. {
  2186. PHYSFS_uint8 *buffer = (PHYSFS_uint8 *) _buffer;
  2187. PHYSFS_sint64 retval = 0;
  2188. while (len > 0)
  2189. {
  2190. const size_t avail = fh->buffill - fh->bufpos;
  2191. if (avail > 0) /* data available in the buffer. */
  2192. {
  2193. const size_t cpy = (len < avail) ? len : avail;
  2194. memcpy(buffer, fh->buffer + fh->bufpos, cpy);
  2195. assert(len >= cpy);
  2196. buffer += cpy;
  2197. len -= cpy;
  2198. fh->bufpos += cpy;
  2199. retval += cpy;
  2200. } /* if */
  2201. else /* buffer is empty, refill it. */
  2202. {
  2203. PHYSFS_Io *io = fh->io;
  2204. const PHYSFS_sint64 rc = io->read(io, fh->buffer, fh->bufsize);
  2205. fh->bufpos = 0;
  2206. if (rc > 0)
  2207. fh->buffill = (size_t) rc;
  2208. else
  2209. {
  2210. fh->buffill = 0;
  2211. if (retval == 0) /* report already-read data, or failure. */
  2212. retval = rc;
  2213. break;
  2214. } /* else */
  2215. } /* else */
  2216. } /* while */
  2217. return retval;
  2218. } /* doBufferedRead */
  2219. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  2220. PHYSFS_uint32 size, PHYSFS_uint32 count)
  2221. {
  2222. const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
  2223. const PHYSFS_sint64 retval = PHYSFS_readBytes(handle, buffer, len);
  2224. return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
  2225. } /* PHYSFS_read */
  2226. PHYSFS_sint64 PHYSFS_readBytes(PHYSFS_File *handle, void *buffer,
  2227. PHYSFS_uint64 _len)
  2228. {
  2229. const size_t len = (size_t) _len;
  2230. FileHandle *fh = (FileHandle *) handle;
  2231. #ifdef PHYSFS_NO_64BIT_SUPPORT
  2232. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
  2233. #else
  2234. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
  2235. #endif
  2236. if (!__PHYSFS_ui64FitsAddressSpace(_len))
  2237. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2238. BAIL_IF(_len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2239. BAIL_IF(!fh->forReading, PHYSFS_ERR_OPEN_FOR_WRITING, -1);
  2240. BAIL_IF_ERRPASS(len == 0, 0);
  2241. if (fh->buffer)
  2242. return doBufferedRead(fh, buffer, len);
  2243. return fh->io->read(fh->io, buffer, len);
  2244. } /* PHYSFS_readBytes */
  2245. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  2246. const size_t len)
  2247. {
  2248. FileHandle *fh = (FileHandle *) handle;
  2249. /* whole thing fits in the buffer? */
  2250. if ((fh->buffill + len) < fh->bufsize)
  2251. {
  2252. memcpy(fh->buffer + fh->buffill, buffer, len);
  2253. fh->buffill += len;
  2254. return (PHYSFS_sint64) len;
  2255. } /* if */
  2256. /* would overflow buffer. Flush and then write the new objects, too. */
  2257. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), -1);
  2258. return fh->io->write(fh->io, buffer, len);
  2259. } /* doBufferedWrite */
  2260. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  2261. PHYSFS_uint32 size, PHYSFS_uint32 count)
  2262. {
  2263. const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
  2264. const PHYSFS_sint64 retval = PHYSFS_writeBytes(handle, buffer, len);
  2265. return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
  2266. } /* PHYSFS_write */
  2267. PHYSFS_sint64 PHYSFS_writeBytes(PHYSFS_File *handle, const void *buffer,
  2268. PHYSFS_uint64 _len)
  2269. {
  2270. const size_t len = (size_t) _len;
  2271. FileHandle *fh = (FileHandle *) handle;
  2272. #ifdef PHYSFS_NO_64BIT_SUPPORT
  2273. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
  2274. #else
  2275. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
  2276. #endif
  2277. if (!__PHYSFS_ui64FitsAddressSpace(_len))
  2278. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2279. BAIL_IF(_len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2280. BAIL_IF(fh->forReading, PHYSFS_ERR_OPEN_FOR_READING, -1);
  2281. BAIL_IF_ERRPASS(len == 0, 0);
  2282. if (fh->buffer)
  2283. return doBufferedWrite(handle, buffer, len);
  2284. return fh->io->write(fh->io, buffer, len);
  2285. } /* PHYSFS_write */
  2286. int PHYSFS_eof(PHYSFS_File *handle)
  2287. {
  2288. FileHandle *fh = (FileHandle *) handle;
  2289. if (!fh->forReading) /* never EOF on files opened for write/append. */
  2290. return 0;
  2291. /* can't be eof if buffer isn't empty */
  2292. if (fh->bufpos == fh->buffill)
  2293. {
  2294. /* check the Io. */
  2295. PHYSFS_Io *io = fh->io;
  2296. const PHYSFS_sint64 pos = io->tell(io);
  2297. const PHYSFS_sint64 len = io->length(io);
  2298. if ((pos < 0) || (len < 0))
  2299. return 0; /* beats me. */
  2300. return (pos >= len);
  2301. } /* if */
  2302. return 0;
  2303. } /* PHYSFS_eof */
  2304. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  2305. {
  2306. FileHandle *fh = (FileHandle *) handle;
  2307. const PHYSFS_sint64 pos = fh->io->tell(fh->io);
  2308. const PHYSFS_sint64 retval = fh->forReading ?
  2309. (pos - fh->buffill) + fh->bufpos :
  2310. (pos + fh->buffill);
  2311. return retval;
  2312. } /* PHYSFS_tell */
  2313. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  2314. {
  2315. FileHandle *fh = (FileHandle *) handle;
  2316. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), 0);
  2317. if (fh->buffer && fh->forReading)
  2318. {
  2319. /* avoid throwing away our precious buffer if seeking within it. */
  2320. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  2321. if ( /* seeking within the already-buffered range? */
  2322. /* forward? */
  2323. ((offset >= 0) && (((size_t)offset) <= fh->buffill-fh->bufpos)) ||
  2324. /* backward? */
  2325. ((offset < 0) && (((size_t) -offset) <= fh->bufpos)) )
  2326. {
  2327. fh->bufpos = (size_t) (((PHYSFS_sint64) fh->bufpos) + offset);
  2328. return 1; /* successful seek */
  2329. } /* if */
  2330. } /* if */
  2331. /* we have to fall back to a 'raw' seek. */
  2332. fh->buffill = fh->bufpos = 0;
  2333. return fh->io->seek(fh->io, pos);
  2334. } /* PHYSFS_seek */
  2335. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  2336. {
  2337. PHYSFS_Io *io = ((FileHandle *) handle)->io;
  2338. return io->length(io);
  2339. } /* PHYSFS_filelength */
  2340. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  2341. {
  2342. FileHandle *fh = (FileHandle *) handle;
  2343. const size_t bufsize = (size_t) _bufsize;
  2344. if (!__PHYSFS_ui64FitsAddressSpace(_bufsize))
  2345. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2346. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), 0);
  2347. /*
  2348. * For reads, we need to move the file pointer to where it would be
  2349. * if we weren't buffering, so that the next read will get the
  2350. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  2351. */
  2352. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  2353. {
  2354. PHYSFS_uint64 pos;
  2355. const PHYSFS_sint64 curpos = fh->io->tell(fh->io);
  2356. BAIL_IF_ERRPASS(curpos == -1, 0);
  2357. pos = ((curpos - fh->buffill) + fh->bufpos);
  2358. BAIL_IF_ERRPASS(!fh->io->seek(fh->io, pos), 0);
  2359. } /* if */
  2360. if (bufsize == 0) /* delete existing buffer. */
  2361. {
  2362. if (fh->buffer)
  2363. {
  2364. allocator.Free(fh->buffer);
  2365. fh->buffer = NULL;
  2366. } /* if */
  2367. } /* if */
  2368. else
  2369. {
  2370. PHYSFS_uint8 *newbuf;
  2371. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  2372. BAIL_IF(!newbuf, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2373. fh->buffer = newbuf;
  2374. } /* else */
  2375. fh->bufsize = bufsize;
  2376. fh->buffill = fh->bufpos = 0;
  2377. return 1;
  2378. } /* PHYSFS_setBuffer */
  2379. int PHYSFS_flush(PHYSFS_File *handle)
  2380. {
  2381. FileHandle *fh = (FileHandle *) handle;
  2382. PHYSFS_Io *io;
  2383. PHYSFS_sint64 rc;
  2384. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  2385. return 1; /* open for read or buffer empty are successful no-ops. */
  2386. /* dump buffer to disk. */
  2387. io = fh->io;
  2388. rc = io->write(io, fh->buffer + fh->bufpos, fh->buffill - fh->bufpos);
  2389. BAIL_IF_ERRPASS(rc <= 0, 0);
  2390. fh->bufpos = fh->buffill = 0;
  2391. return 1;
  2392. } /* PHYSFS_flush */
  2393. int PHYSFS_stat(const char *_fname, PHYSFS_Stat *stat)
  2394. {
  2395. int retval = 0;
  2396. char *fname;
  2397. size_t len;
  2398. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2399. BAIL_IF(!stat, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2400. len = strlen(_fname) + 1;
  2401. fname = (char *) __PHYSFS_smallAlloc(len);
  2402. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2403. /* set some sane defaults... */
  2404. stat->filesize = -1;
  2405. stat->modtime = -1;
  2406. stat->createtime = -1;
  2407. stat->accesstime = -1;
  2408. stat->filetype = PHYSFS_FILETYPE_OTHER;
  2409. stat->readonly = 1;
  2410. if (sanitizePlatformIndependentPath(_fname, fname))
  2411. {
  2412. if (*fname == '\0')
  2413. {
  2414. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  2415. stat->readonly = !writeDir; /* Writeable if we have a writeDir */
  2416. retval = 1;
  2417. } /* if */
  2418. else
  2419. {
  2420. DirHandle *i;
  2421. int exists = 0;
  2422. __PHYSFS_platformGrabMutex(stateLock);
  2423. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  2424. {
  2425. char *arcfname = fname;
  2426. exists = partOfMountPoint(i, arcfname);
  2427. if (exists)
  2428. {
  2429. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  2430. stat->readonly = 1;
  2431. retval = 1;
  2432. } /* if */
  2433. else if (verifyPath(i, &arcfname, 0))
  2434. {
  2435. retval = i->funcs->stat(i->opaque, arcfname, stat);
  2436. if ((retval) || (currentErrorCode() != PHYSFS_ERR_NOT_FOUND))
  2437. exists = 1;
  2438. } /* else if */
  2439. } /* for */
  2440. __PHYSFS_platformReleaseMutex(stateLock);
  2441. } /* else */
  2442. } /* if */
  2443. __PHYSFS_smallFree(fname);
  2444. return retval;
  2445. } /* PHYSFS_stat */
  2446. int __PHYSFS_readAll(PHYSFS_Io *io, void *buf, const size_t _len)
  2447. {
  2448. const PHYSFS_uint64 len = (PHYSFS_uint64) _len;
  2449. return (io->read(io, buf, len) == len);
  2450. } /* __PHYSFS_readAll */
  2451. void *__PHYSFS_initSmallAlloc(void *ptr, const size_t len)
  2452. {
  2453. void *useHeap = ((ptr == NULL) ? ((void *) 1) : ((void *) 0));
  2454. if (useHeap) /* too large for stack allocation or alloca() failed. */
  2455. ptr = allocator.Malloc(len+sizeof (void *));
  2456. if (ptr != NULL)
  2457. {
  2458. void **retval = (void **) ptr;
  2459. /*printf("%s alloc'd (%lld) bytes at (%p).\n",
  2460. useHeap ? "heap" : "stack", (long long) len, ptr);*/
  2461. *retval = useHeap;
  2462. return retval + 1;
  2463. } /* if */
  2464. return NULL; /* allocation failed. */
  2465. } /* __PHYSFS_initSmallAlloc */
  2466. void __PHYSFS_smallFree(void *ptr)
  2467. {
  2468. if (ptr != NULL)
  2469. {
  2470. void **block = ((void **) ptr) - 1;
  2471. const int useHeap = (*block != NULL);
  2472. if (useHeap)
  2473. allocator.Free(block);
  2474. /*printf("%s free'd (%p).\n", useHeap ? "heap" : "stack", block);*/
  2475. } /* if */
  2476. } /* __PHYSFS_smallFree */
  2477. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  2478. {
  2479. BAIL_IF(initialized, PHYSFS_ERR_IS_INITIALIZED, 0);
  2480. externalAllocator = (a != NULL);
  2481. if (externalAllocator)
  2482. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  2483. return 1;
  2484. } /* PHYSFS_setAllocator */
  2485. const PHYSFS_Allocator *PHYSFS_getAllocator(void)
  2486. {
  2487. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, NULL);
  2488. return &allocator;
  2489. } /* PHYSFS_getAllocator */
  2490. static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
  2491. {
  2492. if (!__PHYSFS_ui64FitsAddressSpace(s))
  2493. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2494. #undef malloc
  2495. return malloc((size_t) s);
  2496. } /* mallocAllocatorMalloc */
  2497. static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
  2498. {
  2499. if (!__PHYSFS_ui64FitsAddressSpace(s))
  2500. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2501. #undef realloc
  2502. return realloc(ptr, (size_t) s);
  2503. } /* mallocAllocatorRealloc */
  2504. static void mallocAllocatorFree(void *ptr)
  2505. {
  2506. #undef free
  2507. free(ptr);
  2508. } /* mallocAllocatorFree */
  2509. static void setDefaultAllocator(void)
  2510. {
  2511. assert(!externalAllocator);
  2512. allocator.Init = NULL;
  2513. allocator.Deinit = NULL;
  2514. allocator.Malloc = mallocAllocatorMalloc;
  2515. allocator.Realloc = mallocAllocatorRealloc;
  2516. allocator.Free = mallocAllocatorFree;
  2517. } /* setDefaultAllocator */
  2518. int __PHYSFS_DirTreeInit(__PHYSFS_DirTree *dt, const size_t entrylen)
  2519. {
  2520. static char rootpath[2] = { '/', '\0' };
  2521. size_t alloclen;
  2522. assert(entrylen >= sizeof (__PHYSFS_DirTreeEntry));
  2523. memset(dt, '\0', sizeof (*dt));
  2524. dt->root = (__PHYSFS_DirTreeEntry *) allocator.Malloc(entrylen);
  2525. BAIL_IF(!dt->root, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2526. memset(dt->root, '\0', entrylen);
  2527. dt->root->name = rootpath;
  2528. dt->root->isdir = 1;
  2529. dt->hashBuckets = 64;
  2530. if (!dt->hashBuckets)
  2531. dt->hashBuckets = 1;
  2532. dt->entrylen = entrylen;
  2533. alloclen = dt->hashBuckets * sizeof (__PHYSFS_DirTreeEntry *);
  2534. dt->hash = (__PHYSFS_DirTreeEntry **) allocator.Malloc(alloclen);
  2535. BAIL_IF(!dt->hash, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2536. memset(dt->hash, '\0', alloclen);
  2537. return 1;
  2538. } /* __PHYSFS_DirTreeInit */
  2539. static inline PHYSFS_uint32 hashPathName(__PHYSFS_DirTree *dt, const char *name)
  2540. {
  2541. return __PHYSFS_hashString(name, strlen(name)) % dt->hashBuckets;
  2542. } /* hashPathName */
  2543. /* Fill in missing parent directories. */
  2544. static __PHYSFS_DirTreeEntry *addAncestors(__PHYSFS_DirTree *dt, char *name)
  2545. {
  2546. __PHYSFS_DirTreeEntry *retval = dt->root;
  2547. char *sep = strrchr(name, '/');
  2548. if (sep)
  2549. {
  2550. *sep = '\0'; /* chop off last piece. */
  2551. retval = (__PHYSFS_DirTreeEntry *) __PHYSFS_DirTreeFind(dt, name);
  2552. if (retval != NULL)
  2553. {
  2554. *sep = '/';
  2555. BAIL_IF(!retval->isdir, PHYSFS_ERR_CORRUPT, NULL);
  2556. return retval; /* already hashed. */
  2557. } /* if */
  2558. /* okay, this is a new dir. Build and hash us. */
  2559. retval = (__PHYSFS_DirTreeEntry*)__PHYSFS_DirTreeAdd(dt, name, 1);
  2560. *sep = '/';
  2561. } /* if */
  2562. return retval;
  2563. } /* addAncestors */
  2564. void *__PHYSFS_DirTreeAdd(__PHYSFS_DirTree *dt, char *name, const int isdir)
  2565. {
  2566. __PHYSFS_DirTreeEntry *retval = __PHYSFS_DirTreeFind(dt, name);
  2567. if (!retval)
  2568. {
  2569. const size_t alloclen = strlen(name) + 1 + dt->entrylen;
  2570. PHYSFS_uint32 hashval;
  2571. __PHYSFS_DirTreeEntry *parent = addAncestors(dt, name);
  2572. BAIL_IF_ERRPASS(!parent, NULL);
  2573. assert(dt->entrylen >= sizeof (__PHYSFS_DirTreeEntry));
  2574. retval = (__PHYSFS_DirTreeEntry *) allocator.Malloc(alloclen);
  2575. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2576. memset(retval, '\0', dt->entrylen);
  2577. retval->name = ((char *) retval) + dt->entrylen;
  2578. strcpy(retval->name, name);
  2579. hashval = hashPathName(dt, name);
  2580. retval->hashnext = dt->hash[hashval];
  2581. dt->hash[hashval] = retval;
  2582. retval->sibling = parent->children;
  2583. retval->isdir = isdir;
  2584. parent->children = retval;
  2585. } /* if */
  2586. return retval;
  2587. } /* __PHYSFS_DirTreeAdd */
  2588. /* Find the __PHYSFS_DirTreeEntry for a path in platform-independent notation. */
  2589. void *__PHYSFS_DirTreeFind(__PHYSFS_DirTree *dt, const char *path)
  2590. {
  2591. PHYSFS_uint32 hashval;
  2592. __PHYSFS_DirTreeEntry *prev = NULL;
  2593. __PHYSFS_DirTreeEntry *retval;
  2594. if (*path == '\0')
  2595. return dt->root;
  2596. hashval = hashPathName(dt, path);
  2597. for (retval = dt->hash[hashval]; retval; retval = retval->hashnext)
  2598. {
  2599. if (strcmp(retval->name, path) == 0)
  2600. {
  2601. if (prev != NULL) /* move this to the front of the list */
  2602. {
  2603. prev->hashnext = retval->hashnext;
  2604. retval->hashnext = dt->hash[hashval];
  2605. dt->hash[hashval] = retval;
  2606. } /* if */
  2607. return retval;
  2608. } /* if */
  2609. prev = retval;
  2610. } /* for */
  2611. BAIL(PHYSFS_ERR_NOT_FOUND, NULL);
  2612. } /* __PHYSFS_DirTreeFind */
  2613. PHYSFS_EnumerateCallbackResult __PHYSFS_DirTreeEnumerate(void *opaque,
  2614. const char *dname, PHYSFS_EnumerateCallback cb,
  2615. const char *origdir, void *callbackdata)
  2616. {
  2617. PHYSFS_EnumerateCallbackResult retval = PHYSFS_ENUM_OK;
  2618. __PHYSFS_DirTree *tree = (__PHYSFS_DirTree *) opaque;
  2619. const __PHYSFS_DirTreeEntry *entry = __PHYSFS_DirTreeFind(tree, dname);
  2620. BAIL_IF(!entry, PHYSFS_ERR_NOT_FOUND, PHYSFS_ENUM_ERROR);
  2621. entry = entry->children;
  2622. while (entry && (retval == PHYSFS_ENUM_OK))
  2623. {
  2624. const char *name = entry->name;
  2625. const char *ptr = strrchr(name, '/');
  2626. retval = cb(callbackdata, origdir, ptr ? ptr + 1 : name);
  2627. BAIL_IF(retval == PHYSFS_ENUM_ERROR, PHYSFS_ERR_APP_CALLBACK, retval);
  2628. entry = entry->sibling;
  2629. } /* while */
  2630. return retval;
  2631. } /* __PHYSFS_DirTreeEnumerate */
  2632. void __PHYSFS_DirTreeDeinit(__PHYSFS_DirTree *dt)
  2633. {
  2634. if (!dt)
  2635. return;
  2636. if (dt->root)
  2637. {
  2638. assert(dt->root->sibling == NULL);
  2639. assert(dt->hash || (dt->root->children == NULL));
  2640. allocator.Free(dt->root);
  2641. } /* if */
  2642. if (dt->hash)
  2643. {
  2644. size_t i;
  2645. for (i = 0; i < dt->hashBuckets; i++)
  2646. {
  2647. __PHYSFS_DirTreeEntry *entry;
  2648. __PHYSFS_DirTreeEntry *next;
  2649. for (entry = dt->hash[i]; entry; entry = next)
  2650. {
  2651. next = entry->hashnext;
  2652. allocator.Free(entry);
  2653. } /* for */
  2654. } /* for */
  2655. allocator.Free(dt->hash);
  2656. } /* if */
  2657. } /* __PHYSFS_DirTreeDeinit */
  2658. /* end of physfs.c ... */