physfs.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  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 in the source's root directory.
  7. *
  8. * This file written by Ryan C. Gordon.
  9. */
  10. #if HAVE_CONFIG_H
  11. # include <config.h>
  12. #endif
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include "physfs.h"
  17. #define __PHYSICSFS_INTERNAL__
  18. #include "physfs_internal.h"
  19. typedef struct __PHYSFS_DIRHANDLE__
  20. {
  21. void *opaque; /* Instance data unique to the archiver. */
  22. char *dirName; /* Path to archive in platform-dependent notation. */
  23. char *mountPoint; /* Mountpoint in virtual file tree. */
  24. const PHYSFS_Archiver *funcs; /* Ptr to archiver info for this handle. */
  25. struct __PHYSFS_DIRHANDLE__ *next; /* linked list stuff. */
  26. } DirHandle;
  27. typedef struct __PHYSFS_FILEHANDLE__
  28. {
  29. void *opaque; /* Instance data unique to the archiver for this file. */
  30. PHYSFS_uint8 forReading; /* Non-zero if reading, zero if write/append */
  31. const DirHandle *dirHandle; /* Archiver instance that created this */
  32. const PHYSFS_Archiver *funcs; /* Ptr to archiver info for this handle. */
  33. PHYSFS_uint8 *buffer; /* Buffer, if set (NULL otherwise). Don't touch! */
  34. PHYSFS_uint32 bufsize; /* Bufsize, if set (0 otherwise). Don't touch! */
  35. PHYSFS_uint32 buffill; /* Buffer fill size. Don't touch! */
  36. PHYSFS_uint32 bufpos; /* Buffer position. Don't touch! */
  37. struct __PHYSFS_FILEHANDLE__ *next; /* linked list stuff. */
  38. } FileHandle;
  39. typedef struct __PHYSFS_ERRMSGTYPE__
  40. {
  41. PHYSFS_uint64 tid;
  42. int errorAvailable;
  43. char errorString[80];
  44. struct __PHYSFS_ERRMSGTYPE__ *next;
  45. } ErrMsg;
  46. /* The various i/o drivers... */
  47. #if (defined PHYSFS_SUPPORTS_ZIP)
  48. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_ZIP;
  49. extern const PHYSFS_Archiver __PHYSFS_Archiver_ZIP;
  50. #endif
  51. #if (defined PHYSFS_SUPPORTS_GRP)
  52. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_GRP;
  53. extern const PHYSFS_Archiver __PHYSFS_Archiver_GRP;
  54. #endif
  55. #if (defined PHYSFS_SUPPORTS_QPAK)
  56. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_QPAK;
  57. extern const PHYSFS_Archiver __PHYSFS_Archiver_QPAK;
  58. #endif
  59. #if (defined PHYSFS_SUPPORTS_HOG)
  60. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_HOG;
  61. extern const PHYSFS_Archiver __PHYSFS_Archiver_HOG;
  62. #endif
  63. #if (defined PHYSFS_SUPPORTS_MVL)
  64. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_MVL;
  65. extern const PHYSFS_Archiver __PHYSFS_Archiver_MVL;
  66. #endif
  67. #if (defined PHYSFS_SUPPORTS_WAD)
  68. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_WAD;
  69. extern const PHYSFS_Archiver __PHYSFS_Archiver_WAD;
  70. #endif
  71. #if (defined PHYSFS_SUPPORTS_MIX)
  72. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_MIX;
  73. extern const PHYSFS_Archiver __PHYSFS_Archiver_MIX;
  74. #endif
  75. extern const PHYSFS_Archiver __PHYSFS_Archiver_DIR;
  76. static const PHYSFS_ArchiveInfo *supported_types[] =
  77. {
  78. #if (defined PHYSFS_SUPPORTS_ZIP)
  79. &__PHYSFS_ArchiveInfo_ZIP,
  80. #endif
  81. #if (defined PHYSFS_SUPPORTS_GRP)
  82. &__PHYSFS_ArchiveInfo_GRP,
  83. #endif
  84. #if (defined PHYSFS_SUPPORTS_QPAK)
  85. &__PHYSFS_ArchiveInfo_QPAK,
  86. #endif
  87. #if (defined PHYSFS_SUPPORTS_HOG)
  88. &__PHYSFS_ArchiveInfo_HOG,
  89. #endif
  90. #if (defined PHYSFS_SUPPORTS_MVL)
  91. &__PHYSFS_ArchiveInfo_MVL,
  92. #endif
  93. #if (defined PHYSFS_SUPPORTS_WAD)
  94. &__PHYSFS_ArchiveInfo_WAD,
  95. #endif
  96. #if (defined PHYSFS_SUPPORTS_MIX)
  97. &__PHYSFS_ArchiveInfo_MIX,
  98. #endif
  99. NULL
  100. };
  101. static const PHYSFS_Archiver *archivers[] =
  102. {
  103. #if (defined PHYSFS_SUPPORTS_ZIP)
  104. &__PHYSFS_Archiver_ZIP,
  105. #endif
  106. #if (defined PHYSFS_SUPPORTS_GRP)
  107. &__PHYSFS_Archiver_GRP,
  108. #endif
  109. #if (defined PHYSFS_SUPPORTS_QPAK)
  110. &__PHYSFS_Archiver_QPAK,
  111. #endif
  112. #if (defined PHYSFS_SUPPORTS_HOG)
  113. &__PHYSFS_Archiver_HOG,
  114. #endif
  115. #if (defined PHYSFS_SUPPORTS_MVL)
  116. &__PHYSFS_Archiver_MVL,
  117. #endif
  118. #if (defined PHYSFS_SUPPORTS_WAD)
  119. &__PHYSFS_Archiver_WAD,
  120. #endif
  121. #if (defined PHYSFS_SUPPORTS_MIX)
  122. &__PHYSFS_Archiver_MIX,
  123. #endif
  124. &__PHYSFS_Archiver_DIR,
  125. NULL
  126. };
  127. /* General PhysicsFS state ... */
  128. static int initialized = 0;
  129. static ErrMsg *errorMessages = NULL;
  130. static DirHandle *searchPath = NULL;
  131. static DirHandle *writeDir = NULL;
  132. static FileHandle *openWriteList = NULL;
  133. static FileHandle *openReadList = NULL;
  134. static char *baseDir = NULL;
  135. static char *userDir = NULL;
  136. static int allowSymLinks = 0;
  137. /* mutexes ... */
  138. static void *errorLock = NULL; /* protects error message list. */
  139. static void *stateLock = NULL; /* protects other PhysFS static state. */
  140. /* allocator ... */
  141. static int externalAllocator = 0;
  142. static PHYSFS_Allocator allocator;
  143. /* functions ... */
  144. typedef struct
  145. {
  146. char **list;
  147. PHYSFS_uint32 size;
  148. const char *errorstr;
  149. } EnumStringListCallbackData;
  150. static void enumStringListCallback(void *data, const char *str)
  151. {
  152. void *ptr;
  153. char *newstr;
  154. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  155. if (pecd->errorstr)
  156. return;
  157. ptr = realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  158. newstr = malloc(strlen(str) + 1);
  159. if (ptr != NULL)
  160. pecd->list = (char **) ptr;
  161. if ((ptr == NULL) || (newstr == NULL))
  162. {
  163. pecd->errorstr = ERR_OUT_OF_MEMORY;
  164. pecd->list[pecd->size] = NULL;
  165. PHYSFS_freeList(pecd->list);
  166. return;
  167. } /* if */
  168. strcpy(newstr, str);
  169. pecd->list[pecd->size] = newstr;
  170. pecd->size++;
  171. } /* enumStringListCallback */
  172. static char **doEnumStringList(void (*func)(PHYSFS_StringCallback, void *))
  173. {
  174. EnumStringListCallbackData ecd;
  175. memset(&ecd, '\0', sizeof (ecd));
  176. ecd.list = (char **) malloc(sizeof (char *));
  177. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  178. func(enumStringListCallback, &ecd);
  179. BAIL_IF_MACRO(ecd.errorstr != NULL, ecd.errorstr, NULL);
  180. ecd.list[ecd.size] = NULL;
  181. return(ecd.list);
  182. } /* doEnumStringList */
  183. static void __PHYSFS_bubble_sort(void *a, PHYSFS_uint32 lo, PHYSFS_uint32 hi,
  184. int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
  185. void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
  186. {
  187. PHYSFS_uint32 i;
  188. int sorted;
  189. do
  190. {
  191. sorted = 1;
  192. for (i = lo; i < hi; i++)
  193. {
  194. if (cmpfn(a, i, i + 1) > 0)
  195. {
  196. swapfn(a, i, i + 1);
  197. sorted = 0;
  198. } /* if */
  199. } /* for */
  200. } while (!sorted);
  201. } /* __PHYSFS_bubble_sort */
  202. static void __PHYSFS_quick_sort(void *a, PHYSFS_uint32 lo, PHYSFS_uint32 hi,
  203. int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
  204. void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
  205. {
  206. PHYSFS_uint32 i;
  207. PHYSFS_uint32 j;
  208. PHYSFS_uint32 v;
  209. if ((hi - lo) <= PHYSFS_QUICKSORT_THRESHOLD)
  210. __PHYSFS_bubble_sort(a, lo, hi, cmpfn, swapfn);
  211. else
  212. {
  213. i = (hi + lo) / 2;
  214. if (cmpfn(a, lo, i) > 0) swapfn(a, lo, i);
  215. if (cmpfn(a, lo, hi) > 0) swapfn(a, lo, hi);
  216. if (cmpfn(a, i, hi) > 0) swapfn(a, i, hi);
  217. j = hi - 1;
  218. swapfn(a, i, j);
  219. i = lo;
  220. v = j;
  221. while (1)
  222. {
  223. while(cmpfn(a, ++i, v) < 0) { /* do nothing */ }
  224. while(cmpfn(a, --j, v) > 0) { /* do nothing */ }
  225. if (j < i)
  226. break;
  227. swapfn(a, i, j);
  228. } /* while */
  229. swapfn(a, i, hi-1);
  230. __PHYSFS_quick_sort(a, lo, j, cmpfn, swapfn);
  231. __PHYSFS_quick_sort(a, i+1, hi, cmpfn, swapfn);
  232. } /* else */
  233. } /* __PHYSFS_quick_sort */
  234. void __PHYSFS_sort(void *entries, PHYSFS_uint32 max,
  235. int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
  236. void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
  237. {
  238. /*
  239. * Quicksort w/ Bubblesort fallback algorithm inspired by code from here:
  240. * http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html
  241. */
  242. __PHYSFS_quick_sort(entries, 0, max - 1, cmpfn, swapfn);
  243. } /* __PHYSFS_sort */
  244. static ErrMsg *findErrorForCurrentThread(void)
  245. {
  246. ErrMsg *i;
  247. PHYSFS_uint64 tid;
  248. if (errorLock != NULL)
  249. __PHYSFS_platformGrabMutex(errorLock);
  250. if (errorMessages != NULL)
  251. {
  252. tid = __PHYSFS_platformGetThreadID();
  253. for (i = errorMessages; i != NULL; i = i->next)
  254. {
  255. if (i->tid == tid)
  256. {
  257. if (errorLock != NULL)
  258. __PHYSFS_platformReleaseMutex(errorLock);
  259. return(i);
  260. } /* if */
  261. } /* for */
  262. } /* if */
  263. if (errorLock != NULL)
  264. __PHYSFS_platformReleaseMutex(errorLock);
  265. return(NULL); /* no error available. */
  266. } /* findErrorForCurrentThread */
  267. void __PHYSFS_setError(const char *str)
  268. {
  269. ErrMsg *err;
  270. if (str == NULL)
  271. return;
  272. err = findErrorForCurrentThread();
  273. if (err == NULL)
  274. {
  275. err = (ErrMsg *) malloc(sizeof (ErrMsg));
  276. if (err == NULL)
  277. return; /* uhh...? */
  278. memset((void *) err, '\0', sizeof (ErrMsg));
  279. err->tid = __PHYSFS_platformGetThreadID();
  280. if (errorLock != NULL)
  281. __PHYSFS_platformGrabMutex(errorLock);
  282. err->next = errorMessages;
  283. errorMessages = err;
  284. if (errorLock != NULL)
  285. __PHYSFS_platformReleaseMutex(errorLock);
  286. } /* if */
  287. err->errorAvailable = 1;
  288. strncpy(err->errorString, str, sizeof (err->errorString));
  289. err->errorString[sizeof (err->errorString) - 1] = '\0';
  290. } /* __PHYSFS_setError */
  291. const char *PHYSFS_getLastError(void)
  292. {
  293. ErrMsg *err = findErrorForCurrentThread();
  294. if ((err == NULL) || (!err->errorAvailable))
  295. return(NULL);
  296. err->errorAvailable = 0;
  297. return(err->errorString);
  298. } /* PHYSFS_getLastError */
  299. /* MAKE SURE that errorLock is held before calling this! */
  300. static void freeErrorMessages(void)
  301. {
  302. ErrMsg *i;
  303. ErrMsg *next;
  304. for (i = errorMessages; i != NULL; i = next)
  305. {
  306. next = i->next;
  307. free(i);
  308. } /* for */
  309. errorMessages = NULL;
  310. } /* freeErrorMessages */
  311. void PHYSFS_getLinkedVersion(PHYSFS_Version *ver)
  312. {
  313. if (ver != NULL)
  314. {
  315. ver->major = PHYSFS_VER_MAJOR;
  316. ver->minor = PHYSFS_VER_MINOR;
  317. ver->patch = PHYSFS_VER_PATCH;
  318. } /* if */
  319. } /* PHYSFS_getLinkedVersion */
  320. static const char *find_filename_extension(const char *fname)
  321. {
  322. const char *retval = strchr(fname, '.');
  323. const char *p = retval;
  324. while (p != NULL)
  325. {
  326. p = strchr(p + 1, '.');
  327. if (p != NULL)
  328. retval = p;
  329. } /* while */
  330. if (retval != NULL)
  331. retval++; /* skip '.' */
  332. return(retval);
  333. } /* find_filename_extension */
  334. static DirHandle *tryOpenDir(const PHYSFS_Archiver *funcs,
  335. const char *d, int forWriting)
  336. {
  337. DirHandle *retval = NULL;
  338. if (funcs->isArchive(d, forWriting))
  339. {
  340. void *opaque = funcs->openArchive(d, forWriting);
  341. if (opaque != NULL)
  342. {
  343. retval = (DirHandle *) allocator.malloc(sizeof (DirHandle));
  344. if (retval == NULL)
  345. funcs->dirClose(opaque);
  346. else
  347. {
  348. memset(retval, '\0', sizeof (DirHandle));
  349. retval->mountPoint = NULL;
  350. retval->funcs = funcs;
  351. retval->opaque = opaque;
  352. } /* else */
  353. } /* if */
  354. } /* if */
  355. return(retval);
  356. } /* tryOpenDir */
  357. static DirHandle *openDirectory(const char *d, int forWriting)
  358. {
  359. DirHandle *retval = NULL;
  360. const PHYSFS_Archiver **i;
  361. const char *ext;
  362. BAIL_IF_MACRO(!__PHYSFS_platformExists(d), ERR_NO_SUCH_FILE, NULL);
  363. ext = find_filename_extension(d);
  364. if (ext != NULL)
  365. {
  366. /* Look for archivers with matching file extensions first... */
  367. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  368. {
  369. if (__PHYSFS_platformStricmp(ext, (*i)->info->extension) == 0)
  370. retval = tryOpenDir(*i, d, forWriting);
  371. } /* for */
  372. /* failing an exact file extension match, try all the others... */
  373. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  374. {
  375. if (__PHYSFS_platformStricmp(ext, (*i)->info->extension) != 0)
  376. retval = tryOpenDir(*i, d, forWriting);
  377. } /* for */
  378. } /* if */
  379. else /* no extension? Try them all. */
  380. {
  381. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  382. retval = tryOpenDir(*i, d, forWriting);
  383. } /* else */
  384. BAIL_IF_MACRO(retval == NULL, ERR_UNSUPPORTED_ARCHIVE, NULL);
  385. return(retval);
  386. } /* openDirectory */
  387. static DirHandle *createDirHandle(const char *newDir,
  388. const char *mountPoint,
  389. int forWriting)
  390. {
  391. DirHandle *dirHandle = NULL;
  392. GOTO_IF_MACRO(!newDir, ERR_INVALID_ARGUMENT, badDirHandle);
  393. dirHandle = openDirectory(newDir, forWriting);
  394. GOTO_IF_MACRO(!dirHandle, NULL, badDirHandle);
  395. dirHandle->dirName = (char *) malloc(strlen(newDir) + 1);
  396. GOTO_IF_MACRO(!dirHandle->dirName, ERR_OUT_OF_MEMORY, badDirHandle);
  397. strcpy(dirHandle->dirName, newDir);
  398. if ((mountPoint != NULL) && (*mountPoint != '\0'))
  399. {
  400. /* !!! FIXME: Sanitize the string here. */
  401. dirHandle->mountPoint = (char *) malloc(strlen(mountPoint) + 2);
  402. GOTO_IF_MACRO(!dirHandle->mountPoint, ERR_OUT_OF_MEMORY, badDirHandle);
  403. strcpy(dirHandle->mountPoint, mountPoint);
  404. strcat(dirHandle->mountPoint, "/");
  405. } /* if */
  406. return(dirHandle);
  407. badDirHandle:
  408. if (dirHandle != NULL)
  409. {
  410. dirHandle->funcs->dirClose(dirHandle->opaque);
  411. free(dirHandle->dirName);
  412. free(dirHandle->mountPoint);
  413. free(dirHandle);
  414. } /* if */
  415. return(NULL);
  416. } /* createDirHandle */
  417. /* MAKE SURE you've got the stateLock held before calling this! */
  418. static int freeDirHandle(DirHandle *dh, FileHandle *openList)
  419. {
  420. FileHandle *i;
  421. if (dh == NULL)
  422. return(1);
  423. for (i = openList; i != NULL; i = i->next)
  424. BAIL_IF_MACRO(i->dirHandle == dh, ERR_FILES_STILL_OPEN, 0);
  425. dh->funcs->dirClose(dh->opaque);
  426. free(dh->dirName);
  427. free(dh);
  428. return(1);
  429. } /* freeDirHandle */
  430. static char *calculateUserDir(void)
  431. {
  432. char *retval = NULL;
  433. const char *str = NULL;
  434. str = __PHYSFS_platformGetUserDir();
  435. if (str != NULL)
  436. retval = (char *) str;
  437. else
  438. {
  439. const char *dirsep = PHYSFS_getDirSeparator();
  440. const char *uname = __PHYSFS_platformGetUserName();
  441. str = (uname != NULL) ? uname : "default";
  442. retval = (char *) malloc(strlen(baseDir) + strlen(str) +
  443. strlen(dirsep) + 6);
  444. if (retval == NULL)
  445. __PHYSFS_setError(ERR_OUT_OF_MEMORY);
  446. else
  447. sprintf(retval, "%susers%s%s", baseDir, dirsep, str);
  448. if (uname != NULL)
  449. free((void *) uname);
  450. } /* else */
  451. return(retval);
  452. } /* calculateUserDir */
  453. static int appendDirSep(char **dir)
  454. {
  455. const char *dirsep = PHYSFS_getDirSeparator();
  456. char *ptr;
  457. if (strcmp((*dir + strlen(*dir)) - strlen(dirsep), dirsep) == 0)
  458. return(1);
  459. ptr = realloc(*dir, strlen(*dir) + strlen(dirsep) + 1);
  460. if (!ptr)
  461. {
  462. free(*dir);
  463. return(0);
  464. } /* if */
  465. strcat(ptr, dirsep);
  466. *dir = ptr;
  467. return(1);
  468. } /* appendDirSep */
  469. static char *calculateBaseDir(const char *argv0)
  470. {
  471. const char *dirsep = PHYSFS_getDirSeparator();
  472. char *retval;
  473. char *ptr;
  474. /*
  475. * See if the platform driver wants to handle this for us...
  476. */
  477. retval = __PHYSFS_platformCalcBaseDir(argv0);
  478. if (retval != NULL)
  479. return(retval);
  480. /*
  481. * Determine if there's a path on argv0. If there is, that's the base dir.
  482. */
  483. ptr = strstr(argv0, dirsep);
  484. if (ptr != NULL)
  485. {
  486. char *p = ptr;
  487. size_t size;
  488. while (p != NULL)
  489. {
  490. ptr = p;
  491. p = strstr(p + 1, dirsep);
  492. } /* while */
  493. size = (size_t) (ptr - argv0);
  494. retval = (char *) malloc(size + 1);
  495. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  496. memcpy(retval, argv0, size);
  497. retval[size] = '\0';
  498. return(retval);
  499. } /* if */
  500. /*
  501. * Last ditch effort: it's the current working directory. (*shrug*)
  502. */
  503. retval = __PHYSFS_platformCurrentDir();
  504. if (retval != NULL)
  505. return(retval);
  506. /*
  507. * Ok, current directory doesn't exist, use the root directory.
  508. * Not a good alternative, but it only happens if the current
  509. * directory was deleted from under the program.
  510. */
  511. retval = (char *) malloc(strlen(dirsep) + 1);
  512. strcpy(retval, dirsep);
  513. return(retval);
  514. } /* calculateBaseDir */
  515. static int initializeMutexes(void)
  516. {
  517. errorLock = __PHYSFS_platformCreateMutex();
  518. if (errorLock == NULL)
  519. goto initializeMutexes_failed;
  520. stateLock = __PHYSFS_platformCreateMutex();
  521. if (stateLock == NULL)
  522. goto initializeMutexes_failed;
  523. return(1); /* success. */
  524. initializeMutexes_failed:
  525. if (errorLock != NULL)
  526. __PHYSFS_platformDestroyMutex(errorLock);
  527. if (stateLock != NULL)
  528. __PHYSFS_platformDestroyMutex(stateLock);
  529. errorLock = stateLock = NULL;
  530. return(0); /* failed. */
  531. } /* initializeMutexes */
  532. static void setDefaultAllocator(void);
  533. int PHYSFS_init(const char *argv0)
  534. {
  535. char *ptr;
  536. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  537. if (!externalAllocator)
  538. setDefaultAllocator();
  539. BAIL_IF_MACRO(!allocator.init(), NULL, 0);
  540. BAIL_IF_MACRO(!__PHYSFS_platformInit(), NULL, 0);
  541. BAIL_IF_MACRO(!initializeMutexes(), NULL, 0);
  542. baseDir = calculateBaseDir(argv0);
  543. BAIL_IF_MACRO(baseDir == NULL, NULL, 0);
  544. ptr = __PHYSFS_platformRealPath(baseDir);
  545. free(baseDir);
  546. BAIL_IF_MACRO(ptr == NULL, NULL, 0);
  547. baseDir = ptr;
  548. BAIL_IF_MACRO(!appendDirSep(&baseDir), NULL, 0);
  549. userDir = calculateUserDir();
  550. if (userDir != NULL)
  551. {
  552. ptr = __PHYSFS_platformRealPath(userDir);
  553. free(userDir);
  554. userDir = ptr;
  555. } /* if */
  556. if ((userDir == NULL) || (!appendDirSep(&userDir)))
  557. {
  558. free(baseDir);
  559. baseDir = NULL;
  560. return(0);
  561. } /* if */
  562. initialized = 1;
  563. /* This makes sure that the error subsystem is initialized. */
  564. __PHYSFS_setError(PHYSFS_getLastError());
  565. return(1);
  566. } /* PHYSFS_init */
  567. /* MAKE SURE you hold stateLock before calling this! */
  568. static int closeFileHandleList(FileHandle **list)
  569. {
  570. FileHandle *i;
  571. FileHandle *next = NULL;
  572. for (i = *list; i != NULL; i = next)
  573. {
  574. next = i->next;
  575. if (!i->funcs->fileClose(i->opaque))
  576. {
  577. *list = i;
  578. return(0);
  579. } /* if */
  580. free(i);
  581. } /* for */
  582. *list = NULL;
  583. return(1);
  584. } /* closeFileHandleList */
  585. /* MAKE SURE you hold the stateLock before calling this! */
  586. static void freeSearchPath(void)
  587. {
  588. DirHandle *i;
  589. DirHandle *next = NULL;
  590. closeFileHandleList(&openReadList);
  591. if (searchPath != NULL)
  592. {
  593. for (i = searchPath; i != NULL; i = next)
  594. {
  595. next = i->next;
  596. freeDirHandle(i, openReadList);
  597. } /* for */
  598. searchPath = NULL;
  599. } /* if */
  600. } /* freeSearchPath */
  601. int PHYSFS_deinit(void)
  602. {
  603. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  604. BAIL_IF_MACRO(!__PHYSFS_platformDeinit(), NULL, 0);
  605. closeFileHandleList(&openWriteList);
  606. BAIL_IF_MACRO(!PHYSFS_setWriteDir(NULL), ERR_FILES_STILL_OPEN, 0);
  607. freeSearchPath();
  608. freeErrorMessages();
  609. if (baseDir != NULL)
  610. {
  611. free(baseDir);
  612. baseDir = NULL;
  613. } /* if */
  614. if (userDir != NULL)
  615. {
  616. free(userDir);
  617. userDir = NULL;
  618. } /* if */
  619. allowSymLinks = 0;
  620. initialized = 0;
  621. __PHYSFS_platformDestroyMutex(errorLock);
  622. __PHYSFS_platformDestroyMutex(stateLock);
  623. allocator.deinit();
  624. errorLock = stateLock = NULL;
  625. return(1);
  626. } /* PHYSFS_deinit */
  627. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  628. {
  629. return(supported_types);
  630. } /* PHYSFS_supportedArchiveTypes */
  631. void PHYSFS_freeList(void *list)
  632. {
  633. void **i;
  634. for (i = (void **) list; *i != NULL; i++)
  635. free(*i);
  636. free(list);
  637. } /* PHYSFS_freeList */
  638. const char *PHYSFS_getDirSeparator(void)
  639. {
  640. return(__PHYSFS_platformDirSeparator);
  641. } /* PHYSFS_getDirSeparator */
  642. char **PHYSFS_getCdRomDirs(void)
  643. {
  644. return(doEnumStringList(__PHYSFS_platformDetectAvailableCDs));
  645. } /* PHYSFS_getCdRomDirs */
  646. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  647. {
  648. __PHYSFS_platformDetectAvailableCDs(callback, data);
  649. } /* PHYSFS_getCdRomDirsCallback */
  650. const char *PHYSFS_getBaseDir(void)
  651. {
  652. return(baseDir); /* this is calculated in PHYSFS_init()... */
  653. } /* PHYSFS_getBaseDir */
  654. const char *PHYSFS_getUserDir(void)
  655. {
  656. return(userDir); /* this is calculated in PHYSFS_init()... */
  657. } /* PHYSFS_getUserDir */
  658. const char *PHYSFS_getWriteDir(void)
  659. {
  660. const char *retval = NULL;
  661. __PHYSFS_platformGrabMutex(stateLock);
  662. if (writeDir != NULL)
  663. retval = writeDir->dirName;
  664. __PHYSFS_platformReleaseMutex(stateLock);
  665. return(retval);
  666. } /* PHYSFS_getWriteDir */
  667. int PHYSFS_setWriteDir(const char *newDir)
  668. {
  669. int retval = 1;
  670. __PHYSFS_platformGrabMutex(stateLock);
  671. if (writeDir != NULL)
  672. {
  673. BAIL_IF_MACRO_MUTEX(!freeDirHandle(writeDir, openWriteList), NULL,
  674. stateLock, 0);
  675. writeDir = NULL;
  676. } /* if */
  677. if (newDir != NULL)
  678. {
  679. writeDir = createDirHandle(newDir, NULL, 1);
  680. retval = (writeDir != NULL);
  681. } /* if */
  682. __PHYSFS_platformReleaseMutex(stateLock);
  683. return(retval);
  684. } /* PHYSFS_setWriteDir */
  685. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  686. {
  687. DirHandle *dh;
  688. DirHandle *prev = NULL;
  689. DirHandle *i;
  690. BAIL_IF_MACRO(newDir == NULL, ERR_INVALID_ARGUMENT, 0);
  691. BAIL_IF_MACRO(mountPoint == NULL, ERR_INVALID_ARGUMENT, 0);
  692. __PHYSFS_platformGrabMutex(stateLock);
  693. for (i = searchPath; i != NULL; i = i->next)
  694. {
  695. /* already in search path? */
  696. BAIL_IF_MACRO_MUTEX(strcmp(newDir, i->dirName)==0, NULL, stateLock, 1);
  697. prev = i;
  698. } /* for */
  699. dh = createDirHandle(newDir, mountPoint, 0);
  700. BAIL_IF_MACRO_MUTEX(dh == NULL, NULL, stateLock, 0);
  701. if (appendToPath)
  702. {
  703. if (prev == NULL)
  704. searchPath = dh;
  705. else
  706. prev->next = dh;
  707. } /* if */
  708. else
  709. {
  710. dh->next = searchPath;
  711. searchPath = dh;
  712. } /* else */
  713. __PHYSFS_platformReleaseMutex(stateLock);
  714. return(1);
  715. } /* PHYSFS_mount */
  716. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  717. {
  718. return(PHYSFS_mount(newDir, "/", appendToPath));
  719. } /* PHYSFS_addToSearchPath */
  720. int PHYSFS_removeFromSearchPath(const char *oldDir)
  721. {
  722. DirHandle *i;
  723. DirHandle *prev = NULL;
  724. DirHandle *next = NULL;
  725. BAIL_IF_MACRO(oldDir == NULL, ERR_INVALID_ARGUMENT, 0);
  726. __PHYSFS_platformGrabMutex(stateLock);
  727. for (i = searchPath; i != NULL; i = i->next)
  728. {
  729. if (strcmp(i->dirName, oldDir) == 0)
  730. {
  731. next = i->next;
  732. BAIL_IF_MACRO_MUTEX(!freeDirHandle(i, openReadList), NULL,
  733. stateLock, 0);
  734. if (prev == NULL)
  735. searchPath = next;
  736. else
  737. prev->next = next;
  738. BAIL_MACRO_MUTEX(NULL, stateLock, 1);
  739. } /* if */
  740. prev = i;
  741. } /* for */
  742. BAIL_MACRO_MUTEX(ERR_NOT_IN_SEARCH_PATH, stateLock, 0);
  743. } /* PHYSFS_removeFromSearchPath */
  744. char **PHYSFS_getSearchPath(void)
  745. {
  746. return(doEnumStringList(PHYSFS_getSearchPathCallback));
  747. } /* PHYSFS_getSearchPath */
  748. void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
  749. {
  750. DirHandle *i;
  751. __PHYSFS_platformGrabMutex(stateLock);
  752. for (i = searchPath; i != NULL; i = i->next)
  753. callback(data, i->dirName);
  754. __PHYSFS_platformReleaseMutex(stateLock);
  755. } /* PHYSFS_getSearchPathCallback */
  756. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  757. const char *archiveExt, int includeCdRoms,
  758. int archivesFirst)
  759. {
  760. const char *basedir = PHYSFS_getBaseDir();
  761. const char *userdir = PHYSFS_getUserDir();
  762. const char *dirsep = PHYSFS_getDirSeparator();
  763. char *str;
  764. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  765. /* set write dir... */
  766. str = malloc(strlen(userdir) + (strlen(organization) * 2) +
  767. (strlen(appName) * 2) + (strlen(dirsep) * 3) + 2);
  768. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, 0);
  769. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  770. if (!PHYSFS_setWriteDir(str))
  771. {
  772. int no_write = 0;
  773. sprintf(str, ".%s/%s", organization, appName);
  774. if ( (PHYSFS_setWriteDir(userdir)) &&
  775. (PHYSFS_mkdir(str)) )
  776. {
  777. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  778. if (!PHYSFS_setWriteDir(str))
  779. no_write = 1;
  780. } /* if */
  781. else
  782. {
  783. no_write = 1;
  784. } /* else */
  785. if (no_write)
  786. {
  787. PHYSFS_setWriteDir(NULL); /* just in case. */
  788. free(str);
  789. BAIL_MACRO(ERR_CANT_SET_WRITE_DIR, 0);
  790. } /* if */
  791. } /* if */
  792. /* Put write dir first in search path... */
  793. PHYSFS_addToSearchPath(str, 0);
  794. free(str);
  795. /* Put base path on search path... */
  796. PHYSFS_addToSearchPath(basedir, 1);
  797. /* handle CD-ROMs... */
  798. if (includeCdRoms)
  799. {
  800. char **cds = PHYSFS_getCdRomDirs();
  801. char **i;
  802. for (i = cds; *i != NULL; i++)
  803. PHYSFS_addToSearchPath(*i, 1);
  804. PHYSFS_freeList(cds);
  805. } /* if */
  806. /* Root out archives, and add them to search path... */
  807. if (archiveExt != NULL)
  808. {
  809. char **rc = PHYSFS_enumerateFiles("/");
  810. char **i;
  811. size_t extlen = strlen(archiveExt);
  812. char *ext;
  813. for (i = rc; *i != NULL; i++)
  814. {
  815. size_t l = strlen(*i);
  816. if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
  817. {
  818. ext = (*i) + (l - extlen);
  819. if (__PHYSFS_platformStricmp(ext, archiveExt) == 0)
  820. {
  821. const char *d = PHYSFS_getRealDir(*i);
  822. str = malloc(strlen(d) + strlen(dirsep) + l + 1);
  823. if (str != NULL)
  824. {
  825. sprintf(str, "%s%s%s", d, dirsep, *i);
  826. PHYSFS_addToSearchPath(str, archivesFirst == 0);
  827. free(str);
  828. } /* if */
  829. } /* if */
  830. } /* if */
  831. } /* for */
  832. PHYSFS_freeList(rc);
  833. } /* if */
  834. return(1);
  835. } /* PHYSFS_setSaneConfig */
  836. void PHYSFS_permitSymbolicLinks(int allow)
  837. {
  838. allowSymLinks = allow;
  839. } /* PHYSFS_permitSymbolicLinks */
  840. /* string manipulation in C makes my ass itch. */
  841. char * __PHYSFS_convertToDependent(const char *prepend,
  842. const char *dirName,
  843. const char *append)
  844. {
  845. const char *dirsep = __PHYSFS_platformDirSeparator;
  846. size_t sepsize = strlen(dirsep);
  847. char *str;
  848. char *i1;
  849. char *i2;
  850. size_t allocSize;
  851. while (*dirName == '/')
  852. dirName++;
  853. allocSize = strlen(dirName) + 1;
  854. if (prepend != NULL)
  855. allocSize += strlen(prepend) + sepsize;
  856. if (append != NULL)
  857. allocSize += strlen(append) + sepsize;
  858. /* make sure there's enough space if the dir separator is bigger. */
  859. if (sepsize > 1)
  860. {
  861. str = (char *) dirName;
  862. do
  863. {
  864. str = strchr(str, '/');
  865. if (str != NULL)
  866. {
  867. allocSize += (sepsize - 1);
  868. str++;
  869. } /* if */
  870. } while (str != NULL);
  871. } /* if */
  872. str = (char *) malloc(allocSize);
  873. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, NULL);
  874. if (prepend == NULL)
  875. *str = '\0';
  876. else
  877. {
  878. strcpy(str, prepend);
  879. strcat(str, dirsep);
  880. } /* else */
  881. for (i1 = (char *) dirName, i2 = str + strlen(str); *i1; i1++, i2++)
  882. {
  883. if (*i1 == '/')
  884. {
  885. strcpy(i2, dirsep);
  886. i2 += sepsize;
  887. } /* if */
  888. else
  889. {
  890. *i2 = *i1;
  891. } /* else */
  892. } /* for */
  893. *i2 = '\0';
  894. if (append)
  895. {
  896. strcat(str, dirsep);
  897. strcat(str, append);
  898. } /* if */
  899. return(str);
  900. } /* __PHYSFS_convertToDependent */
  901. /*
  902. * Verify that (fname) (in platform-independent notation), in relation
  903. * to (h) is secure. That means that each element of fname is checked
  904. * for symlinks (if they aren't permitted). Also, elements such as
  905. * ".", "..", or ":" are flagged. This also allows for quick rejection of
  906. * files that exist outside an archive's mountpoint.
  907. *
  908. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  909. * at a time), you should always pass zero for "allowMissing" for efficiency.
  910. *
  911. * Returns non-zero if string is safe, zero if there's a security issue.
  912. * PHYSFS_getLastError() will specify what was wrong.
  913. */
  914. int __PHYSFS_verifySecurity(DirHandle *h, const char *fname, int allowMissing)
  915. {
  916. int retval = 1;
  917. char *start;
  918. char *end;
  919. char *str;
  920. if (*fname == '\0') /* quick rejection. */
  921. return(1);
  922. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  923. {
  924. /* !!! FIXME: Case insensitive? */
  925. size_t mntpntlen = strlen(h->mountPoint);
  926. assert(mntpntlen > 1); /* root mount points should be NULL. */
  927. if (strncmp(h->mountPoint, fname, mntpntlen) != 0)
  928. return(0); /* not under the mountpoint, so skip this archive. */
  929. fname += mntpntlen; /* move to start of actual archive path. */
  930. } /* if */
  931. /* !!! FIXME: Can we ditch this malloc()? */
  932. start = str = malloc(strlen(fname) + 1);
  933. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, 0);
  934. strcpy(str, fname);
  935. while (1)
  936. {
  937. end = strchr(start, '/');
  938. if (end != NULL)
  939. *end = '\0';
  940. if ( (strcmp(start, ".") == 0) ||
  941. (strcmp(start, "..") == 0) ||
  942. (strchr(start, '\\') != NULL) ||
  943. (strchr(start, ':') != NULL) )
  944. {
  945. __PHYSFS_setError(ERR_INSECURE_FNAME);
  946. retval = 0;
  947. break;
  948. } /* if */
  949. if (!allowSymLinks)
  950. {
  951. if (h->funcs->isSymLink(h->opaque, str, &retval))
  952. {
  953. __PHYSFS_setError(ERR_SYMLINK_DISALLOWED);
  954. free(str);
  955. return(0); /* insecure. */
  956. } /* if */
  957. /* break out early if path element is missing. */
  958. if (!retval)
  959. {
  960. /*
  961. * We need to clear it if it's the last element of the path,
  962. * since this might be a non-existant file we're opening
  963. * for writing...
  964. */
  965. if ((end == NULL) || (allowMissing))
  966. retval = 1;
  967. break;
  968. } /* if */
  969. } /* if */
  970. if (end == NULL)
  971. break;
  972. *end = '/';
  973. start = end + 1;
  974. } /* while */
  975. free(str);
  976. return(retval);
  977. } /* __PHYSFS_verifySecurity */
  978. int PHYSFS_mkdir(const char *dname)
  979. {
  980. DirHandle *h;
  981. char *str;
  982. char *start;
  983. char *end;
  984. int retval = 0;
  985. int exists = 1; /* force existance check on first path element. */
  986. BAIL_IF_MACRO(dname == NULL, ERR_INVALID_ARGUMENT, 0);
  987. while (*dname == '/')
  988. dname++;
  989. __PHYSFS_platformGrabMutex(stateLock);
  990. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  991. h = writeDir;
  992. BAIL_IF_MACRO_MUTEX(!__PHYSFS_verifySecurity(h,dname,1),NULL,stateLock,0);
  993. start = str = malloc(strlen(dname) + 1);
  994. BAIL_IF_MACRO_MUTEX(str == NULL, ERR_OUT_OF_MEMORY, stateLock, 0);
  995. strcpy(str, dname);
  996. while (1)
  997. {
  998. end = strchr(start, '/');
  999. if (end != NULL)
  1000. *end = '\0';
  1001. /* only check for existance if all parent dirs existed, too... */
  1002. if (exists)
  1003. retval = h->funcs->isDirectory(h->opaque, str, &exists);
  1004. if (!exists)
  1005. retval = h->funcs->mkdir(h->opaque, str);
  1006. if (!retval)
  1007. break;
  1008. if (end == NULL)
  1009. break;
  1010. *end = '/';
  1011. start = end + 1;
  1012. } /* while */
  1013. __PHYSFS_platformReleaseMutex(stateLock);
  1014. free(str);
  1015. return(retval);
  1016. } /* PHYSFS_mkdir */
  1017. int PHYSFS_delete(const char *fname)
  1018. {
  1019. int retval;
  1020. DirHandle *h;
  1021. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1022. while (*fname == '/')
  1023. fname++;
  1024. __PHYSFS_platformGrabMutex(stateLock);
  1025. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1026. h = writeDir;
  1027. BAIL_IF_MACRO_MUTEX(!__PHYSFS_verifySecurity(h,fname,0),NULL,stateLock,0);
  1028. retval = h->funcs->remove(h->opaque, fname);
  1029. __PHYSFS_platformReleaseMutex(stateLock);
  1030. return(retval);
  1031. } /* PHYSFS_delete */
  1032. const char *PHYSFS_getRealDir(const char *filename)
  1033. {
  1034. DirHandle *i;
  1035. const char *retval = NULL;
  1036. while (*filename == '/')
  1037. filename++;
  1038. __PHYSFS_platformGrabMutex(stateLock);
  1039. for (i = searchPath; ((i != NULL) && (retval == NULL)); i = i->next)
  1040. {
  1041. if (__PHYSFS_verifySecurity(i, filename, 0))
  1042. {
  1043. if (i->funcs->exists(i->opaque, filename))
  1044. retval = i->dirName;
  1045. } /* if */
  1046. } /* for */
  1047. __PHYSFS_platformReleaseMutex(stateLock);
  1048. return(retval);
  1049. } /* PHYSFS_getRealDir */
  1050. static int locateInStringList(const char *str,
  1051. char **list,
  1052. PHYSFS_uint32 *pos)
  1053. {
  1054. PHYSFS_uint32 hi = *pos - 1;
  1055. PHYSFS_uint32 lo = 0;
  1056. PHYSFS_uint32 i = hi >> 1;
  1057. int cmp;
  1058. assert(*pos != 0); /* this doesn't work with empty lists! */
  1059. while (hi != lo)
  1060. {
  1061. cmp = strcmp(list[i], str);
  1062. if (cmp == 0) /* it's in the list already. */
  1063. return(1);
  1064. else if (cmp < 0)
  1065. {
  1066. hi = i;
  1067. i = lo + ((hi - lo) >> 1);
  1068. } /* else if */
  1069. else
  1070. {
  1071. lo = i + 1;
  1072. i = lo + ((1 + hi - lo) >> 1);
  1073. } /* else */
  1074. } /* while */
  1075. /* hi == lo, check it in case it's the match... */
  1076. cmp = strcmp(list[lo], str);
  1077. if (cmp == 0)
  1078. return(1);
  1079. /* not in the list, set insertion point... */
  1080. *pos = (cmp < 0) ? lo : lo + 1;
  1081. return(0);
  1082. } /* locateInStringList */
  1083. static void enumFilesCallback(void *data, const char *str)
  1084. {
  1085. PHYSFS_uint32 pos;
  1086. void *ptr;
  1087. char *newstr;
  1088. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1089. /*
  1090. * See if file is in the list already, and if not, insert it in there
  1091. * alphabetically...
  1092. */
  1093. pos = pecd->size;
  1094. if (pos > 0)
  1095. {
  1096. if (locateInStringList(str, pecd->list, &pos))
  1097. return; /* already in the list. */
  1098. } /* if */
  1099. ptr = realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1100. newstr = malloc(strlen(str) + 1);
  1101. if (ptr != NULL)
  1102. pecd->list = (char **) ptr;
  1103. if ((ptr == NULL) || (newstr == NULL))
  1104. return; /* better luck next time. */
  1105. strcpy(newstr, str);
  1106. if (pos != pecd->size)
  1107. {
  1108. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1109. sizeof (char *) * ((pecd->size) - pos));
  1110. } /* if */
  1111. pecd->list[pos] = newstr;
  1112. pecd->size++;
  1113. } /* enumFilesCallback */
  1114. char **PHYSFS_enumerateFiles(const char *path)
  1115. {
  1116. EnumStringListCallbackData ecd;
  1117. memset(&ecd, '\0', sizeof (ecd));
  1118. ecd.list = (char **) malloc(sizeof (char *));
  1119. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  1120. PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
  1121. ecd.list[ecd.size] = NULL;
  1122. return(ecd.list);
  1123. } /* PHYSFS_enumerateFiles */
  1124. void PHYSFS_enumerateFilesCallback(const char *path,
  1125. PHYSFS_StringCallback callback,
  1126. void *data)
  1127. {
  1128. DirHandle *i;
  1129. int noSyms;
  1130. if ((path == NULL) || (callback == NULL))
  1131. return;
  1132. while (*path == '/')
  1133. path++;
  1134. __PHYSFS_platformGrabMutex(stateLock);
  1135. noSyms = !allowSymLinks;
  1136. for (i = searchPath; i != NULL; i = i->next)
  1137. {
  1138. if (__PHYSFS_verifySecurity(i, path, 0))
  1139. i->funcs->enumerateFiles(i->opaque, path, noSyms, callback, data);
  1140. } /* for */
  1141. __PHYSFS_platformReleaseMutex(stateLock);
  1142. } /* PHYSFS_enumerateFilesCallback */
  1143. int PHYSFS_exists(const char *fname)
  1144. {
  1145. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1146. while (*fname == '/')
  1147. fname++;
  1148. return(PHYSFS_getRealDir(fname) != NULL);
  1149. } /* PHYSFS_exists */
  1150. PHYSFS_sint64 PHYSFS_getLastModTime(const char *fname)
  1151. {
  1152. DirHandle *i;
  1153. PHYSFS_sint64 retval = -1;
  1154. int fileExists = 0;
  1155. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1156. while (*fname == '/')
  1157. fname++;
  1158. if (*fname == '\0') /* eh...punt if it's the root dir. */
  1159. return(1);
  1160. __PHYSFS_platformGrabMutex(stateLock);
  1161. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1162. {
  1163. if (__PHYSFS_verifySecurity(i, fname, 0))
  1164. retval = i->funcs->getLastModTime(i->opaque, fname, &fileExists);
  1165. } /* for */
  1166. __PHYSFS_platformReleaseMutex(stateLock);
  1167. return(retval);
  1168. } /* PHYSFS_getLastModTime */
  1169. int PHYSFS_isDirectory(const char *fname)
  1170. {
  1171. DirHandle *i;
  1172. int retval = 0;
  1173. int fileExists = 0;
  1174. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1175. while (*fname == '/')
  1176. fname++;
  1177. BAIL_IF_MACRO(*fname == '\0', NULL, 1); /* Root is always a dir. :) */
  1178. __PHYSFS_platformGrabMutex(stateLock);
  1179. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1180. {
  1181. if (__PHYSFS_verifySecurity(i, fname, 0))
  1182. retval = i->funcs->isDirectory(i->opaque, fname, &fileExists);
  1183. } /* for */
  1184. __PHYSFS_platformReleaseMutex(stateLock);
  1185. return(retval);
  1186. } /* PHYSFS_isDirectory */
  1187. int PHYSFS_isSymbolicLink(const char *fname)
  1188. {
  1189. DirHandle *i;
  1190. int retval = 0;
  1191. int fileExists = 0;
  1192. BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
  1193. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1194. while (*fname == '/')
  1195. fname++;
  1196. BAIL_IF_MACRO(*fname == '\0', NULL, 0); /* Root is never a symlink */
  1197. __PHYSFS_platformGrabMutex(stateLock);
  1198. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1199. {
  1200. if (__PHYSFS_verifySecurity(i, fname, 0))
  1201. retval = i->funcs->isSymLink(i->opaque, fname, &fileExists);
  1202. } /* for */
  1203. __PHYSFS_platformReleaseMutex(stateLock);
  1204. return(retval);
  1205. } /* PHYSFS_isSymbolicLink */
  1206. static PHYSFS_File *doOpenWrite(const char *fname, int appending)
  1207. {
  1208. void *opaque = NULL;
  1209. FileHandle *fh = NULL;
  1210. DirHandle *h = NULL;
  1211. const PHYSFS_Archiver *f;
  1212. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1213. while (*fname == '/')
  1214. fname++;
  1215. __PHYSFS_platformGrabMutex(stateLock);
  1216. BAIL_IF_MACRO_MUTEX(!writeDir, ERR_NO_WRITE_DIR, stateLock, NULL);
  1217. h = writeDir;
  1218. BAIL_IF_MACRO_MUTEX(!__PHYSFS_verifySecurity(h, fname, 0), NULL,
  1219. stateLock, NULL);
  1220. f = h->funcs;
  1221. if (appending)
  1222. opaque = f->openAppend(h->opaque, fname);
  1223. else
  1224. opaque = f->openWrite(h->opaque, fname);
  1225. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1226. fh = (FileHandle *) malloc(sizeof (FileHandle));
  1227. if (fh == NULL)
  1228. {
  1229. f->fileClose(opaque);
  1230. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1231. } /* if */
  1232. else
  1233. {
  1234. memset(fh, '\0', sizeof (FileHandle));
  1235. fh->opaque = opaque;
  1236. fh->dirHandle = h;
  1237. fh->funcs = h->funcs;
  1238. fh->next = openWriteList;
  1239. openWriteList = fh;
  1240. } /* else */
  1241. __PHYSFS_platformReleaseMutex(stateLock);
  1242. return((PHYSFS_File *) fh);
  1243. } /* doOpenWrite */
  1244. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1245. {
  1246. return(doOpenWrite(filename, 0));
  1247. } /* PHYSFS_openWrite */
  1248. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1249. {
  1250. return(doOpenWrite(filename, 1));
  1251. } /* PHYSFS_openAppend */
  1252. PHYSFS_File *PHYSFS_openRead(const char *fname)
  1253. {
  1254. FileHandle *fh = NULL;
  1255. int fileExists = 0;
  1256. DirHandle *i = NULL;
  1257. fvoid *opaque = NULL;
  1258. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1259. while (*fname == '/')
  1260. fname++;
  1261. __PHYSFS_platformGrabMutex(stateLock);
  1262. BAIL_IF_MACRO_MUTEX(!searchPath, ERR_NOT_IN_SEARCH_PATH, stateLock, NULL);
  1263. i = searchPath;
  1264. do
  1265. {
  1266. if (__PHYSFS_verifySecurity(i, fname, 0))
  1267. {
  1268. opaque = i->funcs->openRead(i->opaque, fname, &fileExists);
  1269. if (opaque)
  1270. break;
  1271. } /* if */
  1272. i = i->next;
  1273. } while ((i != NULL) && (!fileExists));
  1274. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1275. fh = (FileHandle *) malloc(sizeof (FileHandle));
  1276. if (fh == NULL)
  1277. {
  1278. i->funcs->fileClose(opaque);
  1279. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1280. } /* if */
  1281. memset(fh, '\0', sizeof (FileHandle));
  1282. fh->opaque = opaque;
  1283. fh->forReading = 1;
  1284. fh->dirHandle = i;
  1285. fh->funcs = i->funcs;
  1286. fh->next = openReadList;
  1287. openReadList = fh;
  1288. __PHYSFS_platformReleaseMutex(stateLock);
  1289. return((PHYSFS_File *) fh);
  1290. } /* PHYSFS_openRead */
  1291. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  1292. {
  1293. FileHandle *prev = NULL;
  1294. FileHandle *i;
  1295. int rc = 1;
  1296. for (i = *list; i != NULL; i = i->next)
  1297. {
  1298. if (i == handle) /* handle is in this list? */
  1299. {
  1300. PHYSFS_uint8 *tmp = handle->buffer;
  1301. rc = PHYSFS_flush((PHYSFS_File *) handle);
  1302. if (rc)
  1303. rc = handle->funcs->fileClose(handle->opaque);
  1304. if (!rc)
  1305. return(-1);
  1306. if (tmp != NULL) /* free any associated buffer. */
  1307. free(tmp);
  1308. if (prev == NULL)
  1309. *list = handle->next;
  1310. else
  1311. prev->next = handle->next;
  1312. free(handle);
  1313. return(1);
  1314. } /* if */
  1315. prev = i;
  1316. } /* for */
  1317. return(0);
  1318. } /* closeHandleInOpenList */
  1319. int PHYSFS_close(PHYSFS_File *_handle)
  1320. {
  1321. FileHandle *handle = (FileHandle *) _handle;
  1322. int rc;
  1323. __PHYSFS_platformGrabMutex(stateLock);
  1324. /* -1 == close failure. 0 == not found. 1 == success. */
  1325. rc = closeHandleInOpenList(&openReadList, handle);
  1326. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1327. if (!rc)
  1328. {
  1329. rc = closeHandleInOpenList(&openWriteList, handle);
  1330. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1331. } /* if */
  1332. __PHYSFS_platformReleaseMutex(stateLock);
  1333. BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
  1334. return(1);
  1335. } /* PHYSFS_close */
  1336. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
  1337. PHYSFS_uint32 objSize,
  1338. PHYSFS_uint32 objCount)
  1339. {
  1340. PHYSFS_sint64 retval = 0;
  1341. PHYSFS_uint32 remainder = 0;
  1342. while (objCount > 0)
  1343. {
  1344. PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
  1345. PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
  1346. PHYSFS_uint32 copied;
  1347. if (buffered == 0) /* need to refill buffer? */
  1348. {
  1349. PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
  1350. 1, fh->bufsize);
  1351. if (rc <= 0)
  1352. {
  1353. fh->bufpos -= remainder;
  1354. return(((rc == -1) && (retval == 0)) ? -1 : retval);
  1355. } /* if */
  1356. buffered = fh->buffill = (PHYSFS_uint32) rc;
  1357. fh->bufpos = 0;
  1358. } /* if */
  1359. if (buffered > mustread)
  1360. buffered = (PHYSFS_uint32) mustread;
  1361. memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
  1362. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  1363. fh->bufpos += buffered;
  1364. buffered += remainder; /* take remainder into account. */
  1365. copied = (buffered / objSize);
  1366. remainder = (buffered % objSize);
  1367. retval += copied;
  1368. objCount -= copied;
  1369. } /* while */
  1370. return(retval);
  1371. } /* doBufferedRead */
  1372. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  1373. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1374. {
  1375. FileHandle *fh = (FileHandle *) handle;
  1376. BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
  1377. if (fh->buffer != NULL)
  1378. return(doBufferedRead(fh, buffer, objSize, objCount));
  1379. return(fh->funcs->read(fh->opaque, buffer, objSize, objCount));
  1380. } /* PHYSFS_read */
  1381. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  1382. PHYSFS_uint32 objSize,
  1383. PHYSFS_uint32 objCount)
  1384. {
  1385. FileHandle *fh = (FileHandle *) handle;
  1386. /* whole thing fits in the buffer? */
  1387. if (fh->buffill + (objSize * objCount) < fh->bufsize)
  1388. {
  1389. memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
  1390. fh->buffill += (objSize * objCount);
  1391. return(objCount);
  1392. } /* if */
  1393. /* would overflow buffer. Flush and then write the new objects, too. */
  1394. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
  1395. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1396. } /* doBufferedWrite */
  1397. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  1398. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1399. {
  1400. FileHandle *fh = (FileHandle *) handle;
  1401. BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
  1402. if (fh->buffer != NULL)
  1403. return(doBufferedWrite(handle, buffer, objSize, objCount));
  1404. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1405. } /* PHYSFS_write */
  1406. int PHYSFS_eof(PHYSFS_File *handle)
  1407. {
  1408. FileHandle *fh = (FileHandle *) handle;
  1409. if (!fh->forReading) /* never EOF on files opened for write/append. */
  1410. return(0);
  1411. /* eof if buffer is empty and archiver says so. */
  1412. return((fh->bufpos == fh->buffill) && (fh->funcs->eof(fh->opaque)));
  1413. } /* PHYSFS_eof */
  1414. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  1415. {
  1416. FileHandle *fh = (FileHandle *) handle;
  1417. PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
  1418. PHYSFS_sint64 retval = fh->forReading ?
  1419. (pos - fh->buffill) + fh->bufpos :
  1420. (pos + fh->buffill);
  1421. return(retval);
  1422. } /* PHYSFS_tell */
  1423. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  1424. {
  1425. FileHandle *fh = (FileHandle *) handle;
  1426. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1427. if (fh->buffer && fh->forReading)
  1428. {
  1429. /* avoid throwing away our precious buffer if seeking within it. */
  1430. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  1431. if ( /* seeking within the already-buffered range? */
  1432. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  1433. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  1434. {
  1435. fh->bufpos += offset;
  1436. return(1); /* successful seek */
  1437. } /* if */
  1438. } /* if */
  1439. /* we have to fall back to a 'raw' seek. */
  1440. fh->buffill = fh->bufpos = 0;
  1441. return(fh->funcs->seek(fh->opaque, pos));
  1442. } /* PHYSFS_seek */
  1443. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  1444. {
  1445. FileHandle *fh = (FileHandle *) handle;
  1446. return(fh->funcs->fileLength(fh->opaque));
  1447. } /* PHYSFS_filelength */
  1448. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  1449. {
  1450. FileHandle *fh = (FileHandle *) handle;
  1451. PHYSFS_uint32 bufsize;
  1452. BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
  1453. bufsize = (PHYSFS_uint32) _bufsize;
  1454. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1455. /*
  1456. * For reads, we need to move the file pointer to where it would be
  1457. * if we weren't buffering, so that the next read will get the
  1458. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  1459. */
  1460. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  1461. {
  1462. PHYSFS_uint64 pos;
  1463. PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
  1464. BAIL_IF_MACRO(curpos == -1, NULL, 0);
  1465. pos = ((curpos - fh->buffill) + fh->bufpos);
  1466. BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
  1467. } /* if */
  1468. if (bufsize == 0) /* delete existing buffer. */
  1469. {
  1470. if (fh->buffer != NULL)
  1471. {
  1472. free(fh->buffer);
  1473. fh->buffer = NULL;
  1474. } /* if */
  1475. } /* if */
  1476. else
  1477. {
  1478. PHYSFS_uint8 *newbuf = realloc(fh->buffer, bufsize);
  1479. BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
  1480. fh->buffer = newbuf;
  1481. } /* else */
  1482. fh->bufsize = bufsize;
  1483. fh->buffill = fh->bufpos = 0;
  1484. return(1);
  1485. } /* PHYSFS_setBuffer */
  1486. int PHYSFS_flush(PHYSFS_File *handle)
  1487. {
  1488. FileHandle *fh = (FileHandle *) handle;
  1489. PHYSFS_sint64 rc;
  1490. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  1491. return(1); /* open for read or buffer empty are successful no-ops. */
  1492. /* dump buffer to disk. */
  1493. rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
  1494. fh->buffill - fh->bufpos, 1);
  1495. BAIL_IF_MACRO(rc <= 0, NULL, 0);
  1496. fh->bufpos = fh->buffill = 0;
  1497. return(1);
  1498. } /* PHYSFS_flush */
  1499. int PHYSFS_setAllocator(PHYSFS_Allocator *a)
  1500. {
  1501. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  1502. externalAllocator = (a != NULL);
  1503. if (externalAllocator)
  1504. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  1505. return(1);
  1506. } /* PHYSFS_setAllocator */
  1507. static void setDefaultAllocator(void)
  1508. {
  1509. assert(!externalAllocator);
  1510. allocator.init = __PHYSFS_platformAllocatorInit;
  1511. allocator.deinit = __PHYSFS_platformAllocatorDeinit;
  1512. allocator.malloc = __PHYSFS_platformAllocatorMalloc;
  1513. allocator.realloc = __PHYSFS_platformAllocatorRealloc;
  1514. allocator.free = __PHYSFS_platformAllocatorFree;
  1515. } /* setDefaultAllocator */
  1516. PHYSFS_Allocator *__PHYSFS_getAllocator(void)
  1517. {
  1518. return(&allocator);
  1519. } /* __PHYFS_getAllocator */
  1520. /* end of physfs.c ... */