physfs.c 56 KB

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