physfs.c 56 KB

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