physfs.c 53 KB

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