physfs.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193
  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. #if 0
  1161. static int countList(LinkedStringList *list)
  1162. {
  1163. int retval = 0;
  1164. LinkedStringList *i;
  1165. for (i = list; i != NULL; i = i->next)
  1166. retval++;
  1167. return(retval);
  1168. } /* countList */
  1169. static char **convertStringListToPhysFSList(LinkedStringList *finalList)
  1170. {
  1171. int i;
  1172. LinkedStringList *next = NULL;
  1173. int len = countList(finalList);
  1174. char **retval = (char **) malloc((len + 1) * sizeof (char *));
  1175. if (retval == NULL)
  1176. __PHYSFS_setError(ERR_OUT_OF_MEMORY);
  1177. for (i = 0; i < len; i++)
  1178. {
  1179. next = finalList->next;
  1180. if (retval == NULL)
  1181. free(finalList->str);
  1182. else
  1183. retval[i] = finalList->str;
  1184. free(finalList);
  1185. finalList = next;
  1186. } /* for */
  1187. if (retval != NULL)
  1188. retval[i] = NULL;
  1189. return(retval);
  1190. } /* convertStringListToPhysFSList */
  1191. static void insertStringListItem(LinkedStringList **final,
  1192. LinkedStringList *item)
  1193. {
  1194. LinkedStringList *i;
  1195. LinkedStringList *prev = NULL;
  1196. int rc;
  1197. for (i = *final; i != NULL; i = i->next)
  1198. {
  1199. rc = strcmp(i->str, item->str);
  1200. if (rc > 0) /* insertion point. */
  1201. break;
  1202. else if (rc == 0) /* already in list. */
  1203. {
  1204. free(item->str);
  1205. free(item);
  1206. return;
  1207. } /* else if */
  1208. prev = i;
  1209. } /* for */
  1210. /*
  1211. * If we are here, we are either at the insertion point.
  1212. * This may be the end of the list, or the list may be empty, too.
  1213. */
  1214. if (prev == NULL)
  1215. *final = item;
  1216. else
  1217. prev->next = item;
  1218. item->next = i;
  1219. } /* insertStringListItem */
  1220. /* if we run out of memory anywhere in here, we give back what we can. */
  1221. static void interpolateStringLists(LinkedStringList **final,
  1222. LinkedStringList *newList)
  1223. {
  1224. LinkedStringList *next = NULL;
  1225. while (newList != NULL)
  1226. {
  1227. next = newList->next;
  1228. insertStringListItem(final, newList);
  1229. newList = next;
  1230. } /* while */
  1231. } /* interpolateStringLists */
  1232. #endif
  1233. static int locateInStringList(const char *str,
  1234. char **list,
  1235. PHYSFS_uint32 *pos)
  1236. {
  1237. PHYSFS_uint32 hi = *pos - 1;
  1238. PHYSFS_uint32 lo = 0;
  1239. PHYSFS_uint32 i = hi / 2;
  1240. int cmp;
  1241. while (hi != lo)
  1242. {
  1243. cmp = strcmp(list[i], str);
  1244. if (cmp == 0) /* it's in the list already. */
  1245. return(1);
  1246. else if (cmp < 0)
  1247. hi = i;
  1248. else
  1249. lo = i;
  1250. i = lo + ((hi - lo) / 2);
  1251. } /* while */
  1252. /* hi == lo, check it in case it's the match... */
  1253. cmp = strcmp(list[lo], str);
  1254. if (cmp == 0)
  1255. return(1);
  1256. /* not in the list, set insertion point... */
  1257. *pos = (cmp < 0) ? lo : lo + 1;
  1258. return(0);
  1259. } /* locateInStringList */
  1260. static void enumFilesCallback(void *data, const char *str)
  1261. {
  1262. PHYSFS_uint32 pos;
  1263. void *ptr;
  1264. char *newstr;
  1265. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1266. /*
  1267. * See if file is in the list already, and if not, insert it in there
  1268. * alphabetically...
  1269. */
  1270. pos = pecd->size;
  1271. if (pos > 0)
  1272. {
  1273. if (locateInStringList(str, pecd->list, &pos))
  1274. return; /* already in the list. */
  1275. } /* if */
  1276. ptr = realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1277. newstr = malloc(strlen(str) + 1);
  1278. if (ptr != NULL)
  1279. pecd->list = (char **) ptr;
  1280. if ((ptr == NULL) || (newstr == NULL))
  1281. return; /* better luck next time. */
  1282. strcpy(newstr, str);
  1283. if (pos != pecd->size)
  1284. {
  1285. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1286. sizeof (char *) * ((pecd->size) - pos));
  1287. } /* if */
  1288. pecd->list[pos] = newstr;
  1289. pecd->size++;
  1290. } /* enumFilesCallback */
  1291. char **PHYSFS_enumerateFiles(const char *path)
  1292. {
  1293. EnumStringListCallbackData ecd;
  1294. memset(&ecd, '\0', sizeof (ecd));
  1295. ecd.list = (char **) malloc(sizeof (char *));
  1296. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  1297. PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
  1298. ecd.list[ecd.size] = NULL;
  1299. return(ecd.list);
  1300. } /* PHYSFS_enumerateFiles */
  1301. void PHYSFS_enumerateFilesCallback(const char *path,
  1302. PHYSFS_StringCallback callback,
  1303. void *data)
  1304. {
  1305. DirHandle *i;
  1306. int noSyms;
  1307. if ((path == NULL) || (callback == NULL))
  1308. return;
  1309. while (*path == '/')
  1310. path++;
  1311. __PHYSFS_platformGrabMutex(stateLock);
  1312. noSyms = !allowSymLinks;
  1313. for (i = searchPath; i != NULL; i = i->next)
  1314. {
  1315. if (__PHYSFS_verifySecurity(i, path, 0))
  1316. i->funcs->enumerateFiles(i->opaque, path, noSyms, callback, data);
  1317. } /* for */
  1318. __PHYSFS_platformReleaseMutex(stateLock);
  1319. } /* PHYSFS_enumerateFilesCallback */
  1320. int PHYSFS_exists(const char *fname)
  1321. {
  1322. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1323. while (*fname == '/')
  1324. fname++;
  1325. return(PHYSFS_getRealDir(fname) != NULL);
  1326. } /* PHYSFS_exists */
  1327. PHYSFS_sint64 PHYSFS_getLastModTime(const char *fname)
  1328. {
  1329. DirHandle *i;
  1330. PHYSFS_sint64 retval = -1;
  1331. int fileExists = 0;
  1332. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1333. while (*fname == '/')
  1334. fname++;
  1335. if (*fname == '\0') /* eh...punt if it's the root dir. */
  1336. return(1);
  1337. __PHYSFS_platformGrabMutex(stateLock);
  1338. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1339. {
  1340. if (__PHYSFS_verifySecurity(i, fname, 0))
  1341. retval = i->funcs->getLastModTime(i->opaque, fname, &fileExists);
  1342. } /* for */
  1343. __PHYSFS_platformReleaseMutex(stateLock);
  1344. return(retval);
  1345. } /* PHYSFS_getLastModTime */
  1346. int PHYSFS_isDirectory(const char *fname)
  1347. {
  1348. DirHandle *i;
  1349. int retval = 0;
  1350. int fileExists = 0;
  1351. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1352. while (*fname == '/')
  1353. fname++;
  1354. BAIL_IF_MACRO(*fname == '\0', NULL, 1); /* Root is always a dir. :) */
  1355. __PHYSFS_platformGrabMutex(stateLock);
  1356. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1357. {
  1358. if (__PHYSFS_verifySecurity(i, fname, 0))
  1359. retval = i->funcs->isDirectory(i->opaque, fname, &fileExists);
  1360. } /* for */
  1361. __PHYSFS_platformReleaseMutex(stateLock);
  1362. return(retval);
  1363. } /* PHYSFS_isDirectory */
  1364. int PHYSFS_isSymbolicLink(const char *fname)
  1365. {
  1366. DirHandle *i;
  1367. int retval = 0;
  1368. int fileExists = 0;
  1369. BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
  1370. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1371. while (*fname == '/')
  1372. fname++;
  1373. BAIL_IF_MACRO(*fname == '\0', NULL, 0); /* Root is never a symlink */
  1374. __PHYSFS_platformGrabMutex(stateLock);
  1375. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1376. {
  1377. if (__PHYSFS_verifySecurity(i, fname, 0))
  1378. retval = i->funcs->isSymLink(i->opaque, fname, &fileExists);
  1379. } /* for */
  1380. __PHYSFS_platformReleaseMutex(stateLock);
  1381. return(retval);
  1382. } /* PHYSFS_isSymbolicLink */
  1383. static PHYSFS_File *doOpenWrite(const char *fname, int appending)
  1384. {
  1385. void *opaque = NULL;
  1386. FileHandle *fh = NULL;
  1387. DirHandle *h = NULL;
  1388. const PHYSFS_Archiver *f;
  1389. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1390. while (*fname == '/')
  1391. fname++;
  1392. __PHYSFS_platformGrabMutex(stateLock);
  1393. BAIL_IF_MACRO_MUTEX(!writeDir, ERR_NO_WRITE_DIR, stateLock, NULL);
  1394. h = writeDir;
  1395. BAIL_IF_MACRO_MUTEX(!__PHYSFS_verifySecurity(h, fname, 0), NULL,
  1396. stateLock, NULL);
  1397. f = h->funcs;
  1398. if (appending)
  1399. opaque = f->openAppend(h->opaque, fname);
  1400. else
  1401. opaque = f->openWrite(h->opaque, fname);
  1402. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1403. fh = (FileHandle *) malloc(sizeof (FileHandle));
  1404. if (fh == NULL)
  1405. {
  1406. f->fileClose(opaque);
  1407. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1408. } /* if */
  1409. else
  1410. {
  1411. memset(fh, '\0', sizeof (FileHandle));
  1412. fh->opaque = opaque;
  1413. fh->dirHandle = h;
  1414. fh->funcs = h->funcs;
  1415. fh->next = openWriteList;
  1416. openWriteList = fh;
  1417. } /* else */
  1418. __PHYSFS_platformReleaseMutex(stateLock);
  1419. return((PHYSFS_File *) fh);
  1420. } /* doOpenWrite */
  1421. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1422. {
  1423. return(doOpenWrite(filename, 0));
  1424. } /* PHYSFS_openWrite */
  1425. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1426. {
  1427. return(doOpenWrite(filename, 1));
  1428. } /* PHYSFS_openAppend */
  1429. PHYSFS_File *PHYSFS_openRead(const char *fname)
  1430. {
  1431. FileHandle *fh = NULL;
  1432. int fileExists = 0;
  1433. DirHandle *i = NULL;
  1434. fvoid *opaque = NULL;
  1435. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1436. while (*fname == '/')
  1437. fname++;
  1438. __PHYSFS_platformGrabMutex(stateLock);
  1439. BAIL_IF_MACRO_MUTEX(!searchPath, ERR_NOT_IN_SEARCH_PATH, stateLock, NULL);
  1440. i = searchPath;
  1441. do
  1442. {
  1443. if (__PHYSFS_verifySecurity(i, fname, 0))
  1444. {
  1445. opaque = i->funcs->openRead(i->opaque, fname, &fileExists);
  1446. if (opaque)
  1447. break;
  1448. } /* if */
  1449. i = i->next;
  1450. } while ((i != NULL) && (!fileExists));
  1451. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1452. fh = (FileHandle *) malloc(sizeof (FileHandle));
  1453. if (fh == NULL)
  1454. {
  1455. i->funcs->fileClose(opaque);
  1456. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1457. } /* if */
  1458. memset(fh, '\0', sizeof (FileHandle));
  1459. fh->opaque = opaque;
  1460. fh->forReading = 1;
  1461. fh->dirHandle = i;
  1462. fh->funcs = i->funcs;
  1463. fh->next = openReadList;
  1464. openReadList = fh;
  1465. __PHYSFS_platformReleaseMutex(stateLock);
  1466. return((PHYSFS_File *) fh);
  1467. } /* PHYSFS_openRead */
  1468. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  1469. {
  1470. FileHandle *prev = NULL;
  1471. FileHandle *i;
  1472. int rc = 1;
  1473. for (i = *list; i != NULL; i = i->next)
  1474. {
  1475. if (i == handle) /* handle is in this list? */
  1476. {
  1477. PHYSFS_uint8 *tmp = handle->buffer;
  1478. rc = PHYSFS_flush((PHYSFS_File *) handle);
  1479. if (rc)
  1480. rc = handle->funcs->fileClose(handle->opaque);
  1481. if (!rc)
  1482. return(-1);
  1483. if (tmp != NULL) /* free any associated buffer. */
  1484. free(tmp);
  1485. if (prev == NULL)
  1486. *list = handle->next;
  1487. else
  1488. prev->next = handle->next;
  1489. free(handle);
  1490. return(1);
  1491. } /* if */
  1492. prev = i;
  1493. } /* for */
  1494. return(0);
  1495. } /* closeHandleInOpenList */
  1496. int PHYSFS_close(PHYSFS_File *_handle)
  1497. {
  1498. FileHandle *handle = (FileHandle *) _handle;
  1499. int rc;
  1500. __PHYSFS_platformGrabMutex(stateLock);
  1501. /* -1 == close failure. 0 == not found. 1 == success. */
  1502. rc = closeHandleInOpenList(&openReadList, handle);
  1503. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1504. if (!rc)
  1505. {
  1506. rc = closeHandleInOpenList(&openWriteList, handle);
  1507. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1508. } /* if */
  1509. __PHYSFS_platformReleaseMutex(stateLock);
  1510. BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
  1511. return(1);
  1512. } /* PHYSFS_close */
  1513. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
  1514. PHYSFS_uint32 objSize,
  1515. PHYSFS_uint32 objCount)
  1516. {
  1517. PHYSFS_sint64 retval = 0;
  1518. PHYSFS_uint32 remainder = 0;
  1519. while (objCount > 0)
  1520. {
  1521. PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
  1522. PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
  1523. PHYSFS_uint32 copied;
  1524. if (buffered == 0) /* need to refill buffer? */
  1525. {
  1526. PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
  1527. 1, fh->bufsize);
  1528. if (rc <= 0)
  1529. {
  1530. fh->bufpos -= remainder;
  1531. return(((rc == -1) && (retval == 0)) ? -1 : retval);
  1532. } /* if */
  1533. buffered = fh->buffill = (PHYSFS_uint32) rc;
  1534. fh->bufpos = 0;
  1535. } /* if */
  1536. if (buffered > mustread)
  1537. buffered = (PHYSFS_uint32) mustread;
  1538. memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
  1539. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  1540. fh->bufpos += buffered;
  1541. buffered += remainder; /* take remainder into account. */
  1542. copied = (buffered / objSize);
  1543. remainder = (buffered % objSize);
  1544. retval += copied;
  1545. objCount -= copied;
  1546. } /* while */
  1547. return(retval);
  1548. } /* doBufferedRead */
  1549. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  1550. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1551. {
  1552. FileHandle *fh = (FileHandle *) handle;
  1553. BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
  1554. if (fh->buffer != NULL)
  1555. return(doBufferedRead(fh, buffer, objSize, objCount));
  1556. return(fh->funcs->read(fh->opaque, buffer, objSize, objCount));
  1557. } /* PHYSFS_read */
  1558. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  1559. PHYSFS_uint32 objSize,
  1560. PHYSFS_uint32 objCount)
  1561. {
  1562. FileHandle *fh = (FileHandle *) handle;
  1563. /* whole thing fits in the buffer? */
  1564. if (fh->buffill + (objSize * objCount) < fh->bufsize)
  1565. {
  1566. memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
  1567. fh->buffill += (objSize * objCount);
  1568. return(objCount);
  1569. } /* if */
  1570. /* would overflow buffer. Flush and then write the new objects, too. */
  1571. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
  1572. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1573. } /* doBufferedWrite */
  1574. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  1575. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1576. {
  1577. FileHandle *fh = (FileHandle *) handle;
  1578. BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
  1579. if (fh->buffer != NULL)
  1580. return(doBufferedWrite(handle, buffer, objSize, objCount));
  1581. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1582. } /* PHYSFS_write */
  1583. int PHYSFS_eof(PHYSFS_File *handle)
  1584. {
  1585. FileHandle *fh = (FileHandle *) handle;
  1586. if (!fh->forReading) /* never EOF on files opened for write/append. */
  1587. return(0);
  1588. /* eof if buffer is empty and archiver says so. */
  1589. return((fh->bufpos == fh->buffill) && (fh->funcs->eof(fh->opaque)));
  1590. } /* PHYSFS_eof */
  1591. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  1592. {
  1593. FileHandle *fh = (FileHandle *) handle;
  1594. PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
  1595. PHYSFS_sint64 retval = fh->forReading ?
  1596. (pos - fh->buffill) + fh->bufpos :
  1597. (pos + fh->buffill);
  1598. return(retval);
  1599. } /* PHYSFS_tell */
  1600. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  1601. {
  1602. FileHandle *fh = (FileHandle *) handle;
  1603. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1604. if (fh->buffer && fh->forReading)
  1605. {
  1606. /* avoid throwing away our precious buffer if seeking within it. */
  1607. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  1608. if ( /* seeking within the already-buffered range? */
  1609. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  1610. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  1611. {
  1612. fh->bufpos += offset;
  1613. return(1); /* successful seek */
  1614. } /* if */
  1615. } /* if */
  1616. /* we have to fall back to a 'raw' seek. */
  1617. fh->buffill = fh->bufpos = 0;
  1618. return(fh->funcs->seek(fh->opaque, pos));
  1619. } /* PHYSFS_seek */
  1620. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  1621. {
  1622. FileHandle *fh = (FileHandle *) handle;
  1623. return(fh->funcs->fileLength(fh->opaque));
  1624. } /* PHYSFS_filelength */
  1625. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  1626. {
  1627. FileHandle *fh = (FileHandle *) handle;
  1628. PHYSFS_uint32 bufsize;
  1629. BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
  1630. bufsize = (PHYSFS_uint32) _bufsize;
  1631. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1632. /*
  1633. * For reads, we need to move the file pointer to where it would be
  1634. * if we weren't buffering, so that the next read will get the
  1635. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  1636. */
  1637. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  1638. {
  1639. PHYSFS_uint64 pos;
  1640. PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
  1641. BAIL_IF_MACRO(curpos == -1, NULL, 0);
  1642. pos = ((curpos - fh->buffill) + fh->bufpos);
  1643. BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
  1644. } /* if */
  1645. if (bufsize == 0) /* delete existing buffer. */
  1646. {
  1647. if (fh->buffer != NULL)
  1648. {
  1649. free(fh->buffer);
  1650. fh->buffer = NULL;
  1651. } /* if */
  1652. } /* if */
  1653. else
  1654. {
  1655. PHYSFS_uint8 *newbuf = realloc(fh->buffer, bufsize);
  1656. BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
  1657. fh->buffer = newbuf;
  1658. } /* else */
  1659. fh->bufsize = bufsize;
  1660. fh->buffill = fh->bufpos = 0;
  1661. return(1);
  1662. } /* PHYSFS_setBuffer */
  1663. int PHYSFS_flush(PHYSFS_File *handle)
  1664. {
  1665. FileHandle *fh = (FileHandle *) handle;
  1666. PHYSFS_sint64 rc;
  1667. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  1668. return(1); /* open for read or buffer empty are successful no-ops. */
  1669. /* dump buffer to disk. */
  1670. rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
  1671. fh->buffill - fh->bufpos, 1);
  1672. BAIL_IF_MACRO(rc <= 0, NULL, 0);
  1673. fh->bufpos = fh->buffill = 0;
  1674. return(1);
  1675. } /* PHYSFS_flush */
  1676. LinkedStringList *__PHYSFS_addToLinkedStringList(LinkedStringList *retval,
  1677. LinkedStringList **prev,
  1678. const char *str,
  1679. PHYSFS_sint32 len)
  1680. {
  1681. LinkedStringList *l;
  1682. l = (LinkedStringList *) malloc(sizeof (LinkedStringList));
  1683. BAIL_IF_MACRO(l == NULL, ERR_OUT_OF_MEMORY, retval);
  1684. if (len < 0)
  1685. len = strlen(str);
  1686. l->str = (char *) malloc(len + 1);
  1687. if (l->str == NULL)
  1688. {
  1689. free(l);
  1690. BAIL_MACRO(ERR_OUT_OF_MEMORY, retval);
  1691. } /* if */
  1692. strncpy(l->str, str, len);
  1693. l->str[len] = '\0';
  1694. if (retval == NULL)
  1695. retval = l;
  1696. else
  1697. (*prev)->next = l;
  1698. *prev = l;
  1699. l->next = NULL;
  1700. return(retval);
  1701. } /* __PHYSFS_addToLinkedStringList */
  1702. int PHYSFS_setAllocator(PHYSFS_Allocator *a)
  1703. {
  1704. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  1705. externalAllocator = (a != NULL);
  1706. if (externalAllocator)
  1707. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  1708. return(1);
  1709. } /* PHYSFS_setAllocator */
  1710. static void setDefaultAllocator(void)
  1711. {
  1712. assert(!externalAllocator);
  1713. allocator.init = __PHYSFS_platformAllocatorInit;
  1714. allocator.deinit = __PHYSFS_platformAllocatorDeinit;
  1715. allocator.malloc = __PHYSFS_platformAllocatorMalloc;
  1716. allocator.realloc = __PHYSFS_platformAllocatorRealloc;
  1717. allocator.free = __PHYSFS_platformAllocatorFree;
  1718. } /* setDefaultAllocator */
  1719. PHYSFS_Allocator *__PHYSFS_getAllocator(void)
  1720. {
  1721. return(&allocator);
  1722. } /* __PHYFS_getAllocator */
  1723. /* end of physfs.c ... */