physfs.c 60 KB

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