physfs.c 60 KB

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