physfs.c 56 KB

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