physfs.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. /**
  2. * PhysicsFS; a portable, flexible file i/o abstraction.
  3. *
  4. * Documentation is in physfs.h. It's verbose, honest. :)
  5. *
  6. * Please see the file LICENSE.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_stricmpASCII(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_stricmpASCII(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. /* we need argv0 to be sane to go on. */
  538. BAIL_IF_MACRO(argv0 == NULL, ERR_INVALID_ARGUMENT, NULL);
  539. /*
  540. * Determine if there's a path on argv0. If there is, that's the base dir.
  541. */
  542. ptr = strstr(argv0, dirsep);
  543. if (ptr != NULL)
  544. {
  545. char *p = ptr;
  546. size_t size;
  547. while (p != NULL)
  548. {
  549. ptr = p;
  550. p = strstr(p + 1, dirsep);
  551. } /* while */
  552. size = (size_t) (ptr - argv0);
  553. retval = (char *) allocator.Malloc(size + 1);
  554. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  555. memcpy(retval, argv0, size);
  556. retval[size] = '\0';
  557. return(retval);
  558. } /* if */
  559. /* !!! FIXME: should probably just fail here instead of being heroic. */
  560. /*
  561. * Last ditch effort: it's the current working directory. (*shrug*)
  562. */
  563. retval = __PHYSFS_platformCurrentDir();
  564. if (retval != NULL)
  565. return(retval);
  566. /*
  567. * Ok, current directory doesn't exist, use the root directory.
  568. * Not a good alternative, but it only happens if the current
  569. * directory was deleted from under the program.
  570. */
  571. retval = (char *) allocator.Malloc(strlen(dirsep) + 1);
  572. strcpy(retval, dirsep);
  573. return(retval);
  574. } /* calculateBaseDir */
  575. static int initializeMutexes(void)
  576. {
  577. errorLock = __PHYSFS_platformCreateMutex();
  578. if (errorLock == NULL)
  579. goto initializeMutexes_failed;
  580. stateLock = __PHYSFS_platformCreateMutex();
  581. if (stateLock == NULL)
  582. goto initializeMutexes_failed;
  583. return(1); /* success. */
  584. initializeMutexes_failed:
  585. if (errorLock != NULL)
  586. __PHYSFS_platformDestroyMutex(errorLock);
  587. if (stateLock != NULL)
  588. __PHYSFS_platformDestroyMutex(stateLock);
  589. errorLock = stateLock = NULL;
  590. return(0); /* failed. */
  591. } /* initializeMutexes */
  592. static void setDefaultAllocator(void);
  593. int PHYSFS_init(const char *argv0)
  594. {
  595. char *ptr;
  596. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  597. if (!externalAllocator)
  598. setDefaultAllocator();
  599. if (allocator.Init != NULL)
  600. BAIL_IF_MACRO(!allocator.Init(), NULL, 0);
  601. BAIL_IF_MACRO(!__PHYSFS_platformInit(), NULL, 0);
  602. BAIL_IF_MACRO(!initializeMutexes(), NULL, 0);
  603. baseDir = calculateBaseDir(argv0);
  604. BAIL_IF_MACRO(baseDir == NULL, NULL, 0);
  605. ptr = __PHYSFS_platformRealPath(baseDir);
  606. allocator.Free(baseDir);
  607. BAIL_IF_MACRO(ptr == NULL, NULL, 0);
  608. baseDir = ptr;
  609. BAIL_IF_MACRO(!appendDirSep(&baseDir), NULL, 0);
  610. userDir = calculateUserDir();
  611. if (userDir != NULL)
  612. {
  613. ptr = __PHYSFS_platformRealPath(userDir);
  614. allocator.Free(userDir);
  615. userDir = ptr;
  616. } /* if */
  617. if ((userDir == NULL) || (!appendDirSep(&userDir)))
  618. {
  619. allocator.Free(baseDir);
  620. baseDir = NULL;
  621. return(0);
  622. } /* if */
  623. initialized = 1;
  624. /* This makes sure that the error subsystem is initialized. */
  625. __PHYSFS_setError(PHYSFS_getLastError());
  626. return(1);
  627. } /* PHYSFS_init */
  628. /* MAKE SURE you hold stateLock before calling this! */
  629. static int closeFileHandleList(FileHandle **list)
  630. {
  631. FileHandle *i;
  632. FileHandle *next = NULL;
  633. for (i = *list; i != NULL; i = next)
  634. {
  635. next = i->next;
  636. if (!i->funcs->fileClose(i->opaque))
  637. {
  638. *list = i;
  639. return(0);
  640. } /* if */
  641. allocator.Free(i);
  642. } /* for */
  643. *list = NULL;
  644. return(1);
  645. } /* closeFileHandleList */
  646. /* MAKE SURE you hold the stateLock before calling this! */
  647. static void freeSearchPath(void)
  648. {
  649. DirHandle *i;
  650. DirHandle *next = NULL;
  651. closeFileHandleList(&openReadList);
  652. if (searchPath != NULL)
  653. {
  654. for (i = searchPath; i != NULL; i = next)
  655. {
  656. next = i->next;
  657. freeDirHandle(i, openReadList);
  658. } /* for */
  659. searchPath = NULL;
  660. } /* if */
  661. } /* freeSearchPath */
  662. int PHYSFS_deinit(void)
  663. {
  664. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  665. BAIL_IF_MACRO(!__PHYSFS_platformDeinit(), NULL, 0);
  666. closeFileHandleList(&openWriteList);
  667. BAIL_IF_MACRO(!PHYSFS_setWriteDir(NULL), ERR_FILES_STILL_OPEN, 0);
  668. freeSearchPath();
  669. freeErrorMessages();
  670. if (baseDir != NULL)
  671. {
  672. allocator.Free(baseDir);
  673. baseDir = NULL;
  674. } /* if */
  675. if (userDir != NULL)
  676. {
  677. allocator.Free(userDir);
  678. userDir = NULL;
  679. } /* if */
  680. allowSymLinks = 0;
  681. initialized = 0;
  682. __PHYSFS_platformDestroyMutex(errorLock);
  683. __PHYSFS_platformDestroyMutex(stateLock);
  684. if (allocator.Deinit != NULL)
  685. allocator.Deinit();
  686. errorLock = stateLock = NULL;
  687. return(1);
  688. } /* PHYSFS_deinit */
  689. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  690. {
  691. return(supported_types);
  692. } /* PHYSFS_supportedArchiveTypes */
  693. void PHYSFS_freeList(void *list)
  694. {
  695. void **i;
  696. for (i = (void **) list; *i != NULL; i++)
  697. allocator.Free(*i);
  698. allocator.Free(list);
  699. } /* PHYSFS_freeList */
  700. const char *PHYSFS_getDirSeparator(void)
  701. {
  702. return(__PHYSFS_platformDirSeparator);
  703. } /* PHYSFS_getDirSeparator */
  704. char **PHYSFS_getCdRomDirs(void)
  705. {
  706. return(doEnumStringList(__PHYSFS_platformDetectAvailableCDs));
  707. } /* PHYSFS_getCdRomDirs */
  708. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  709. {
  710. __PHYSFS_platformDetectAvailableCDs(callback, data);
  711. } /* PHYSFS_getCdRomDirsCallback */
  712. const char *PHYSFS_getBaseDir(void)
  713. {
  714. return(baseDir); /* this is calculated in PHYSFS_init()... */
  715. } /* PHYSFS_getBaseDir */
  716. const char *PHYSFS_getUserDir(void)
  717. {
  718. return(userDir); /* this is calculated in PHYSFS_init()... */
  719. } /* PHYSFS_getUserDir */
  720. const char *PHYSFS_getWriteDir(void)
  721. {
  722. const char *retval = NULL;
  723. __PHYSFS_platformGrabMutex(stateLock);
  724. if (writeDir != NULL)
  725. retval = writeDir->dirName;
  726. __PHYSFS_platformReleaseMutex(stateLock);
  727. return(retval);
  728. } /* PHYSFS_getWriteDir */
  729. int PHYSFS_setWriteDir(const char *newDir)
  730. {
  731. int retval = 1;
  732. __PHYSFS_platformGrabMutex(stateLock);
  733. if (writeDir != NULL)
  734. {
  735. BAIL_IF_MACRO_MUTEX(!freeDirHandle(writeDir, openWriteList), NULL,
  736. stateLock, 0);
  737. writeDir = NULL;
  738. } /* if */
  739. if (newDir != NULL)
  740. {
  741. writeDir = createDirHandle(newDir, NULL, 1);
  742. retval = (writeDir != NULL);
  743. } /* if */
  744. __PHYSFS_platformReleaseMutex(stateLock);
  745. return(retval);
  746. } /* PHYSFS_setWriteDir */
  747. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  748. {
  749. DirHandle *dh;
  750. DirHandle *prev = NULL;
  751. DirHandle *i;
  752. BAIL_IF_MACRO(newDir == NULL, ERR_INVALID_ARGUMENT, 0);
  753. if (mountPoint == NULL)
  754. mountPoint = "/";
  755. __PHYSFS_platformGrabMutex(stateLock);
  756. for (i = searchPath; i != NULL; i = i->next)
  757. {
  758. /* already in search path? */
  759. BAIL_IF_MACRO_MUTEX(strcmp(newDir, i->dirName)==0, NULL, stateLock, 1);
  760. prev = i;
  761. } /* for */
  762. dh = createDirHandle(newDir, mountPoint, 0);
  763. BAIL_IF_MACRO_MUTEX(dh == NULL, NULL, stateLock, 0);
  764. if (appendToPath)
  765. {
  766. if (prev == NULL)
  767. searchPath = dh;
  768. else
  769. prev->next = dh;
  770. } /* if */
  771. else
  772. {
  773. dh->next = searchPath;
  774. searchPath = dh;
  775. } /* else */
  776. __PHYSFS_platformReleaseMutex(stateLock);
  777. return(1);
  778. } /* PHYSFS_mount */
  779. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  780. {
  781. return(PHYSFS_mount(newDir, NULL, appendToPath));
  782. } /* PHYSFS_addToSearchPath */
  783. int PHYSFS_removeFromSearchPath(const char *oldDir)
  784. {
  785. DirHandle *i;
  786. DirHandle *prev = NULL;
  787. DirHandle *next = NULL;
  788. BAIL_IF_MACRO(oldDir == NULL, ERR_INVALID_ARGUMENT, 0);
  789. __PHYSFS_platformGrabMutex(stateLock);
  790. for (i = searchPath; i != NULL; i = i->next)
  791. {
  792. if (strcmp(i->dirName, oldDir) == 0)
  793. {
  794. next = i->next;
  795. BAIL_IF_MACRO_MUTEX(!freeDirHandle(i, openReadList), NULL,
  796. stateLock, 0);
  797. if (prev == NULL)
  798. searchPath = next;
  799. else
  800. prev->next = next;
  801. BAIL_MACRO_MUTEX(NULL, stateLock, 1);
  802. } /* if */
  803. prev = i;
  804. } /* for */
  805. BAIL_MACRO_MUTEX(ERR_NOT_IN_SEARCH_PATH, stateLock, 0);
  806. } /* PHYSFS_removeFromSearchPath */
  807. char **PHYSFS_getSearchPath(void)
  808. {
  809. return(doEnumStringList(PHYSFS_getSearchPathCallback));
  810. } /* PHYSFS_getSearchPath */
  811. const char *PHYSFS_getMountPoint(const char *dir)
  812. {
  813. DirHandle *i;
  814. __PHYSFS_platformGrabMutex(stateLock);
  815. for (i = searchPath; i != NULL; i = i->next)
  816. {
  817. if (strcmp(i->dirName, dir) == 0)
  818. {
  819. const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
  820. __PHYSFS_platformReleaseMutex(stateLock);
  821. return(retval);
  822. } /* if */
  823. } /* for */
  824. __PHYSFS_platformReleaseMutex(stateLock);
  825. BAIL_MACRO(ERR_NOT_IN_SEARCH_PATH, NULL);
  826. } /* PHYSFS_getMountPoint */
  827. void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
  828. {
  829. DirHandle *i;
  830. __PHYSFS_platformGrabMutex(stateLock);
  831. for (i = searchPath; i != NULL; i = i->next)
  832. callback(data, i->dirName);
  833. __PHYSFS_platformReleaseMutex(stateLock);
  834. } /* PHYSFS_getSearchPathCallback */
  835. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  836. const char *archiveExt, int includeCdRoms,
  837. int archivesFirst)
  838. {
  839. const char *basedir = PHYSFS_getBaseDir();
  840. const char *userdir = PHYSFS_getUserDir();
  841. const char *dirsep = PHYSFS_getDirSeparator();
  842. char *str;
  843. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  844. /* set write dir... */
  845. str = (char *) allocator.Malloc(
  846. strlen(userdir) + (strlen(organization) * 2) +
  847. (strlen(appName) * 2) + (strlen(dirsep) * 3) + 2);
  848. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, 0);
  849. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  850. if (!PHYSFS_setWriteDir(str))
  851. {
  852. int no_write = 0;
  853. sprintf(str, ".%s/%s", organization, appName);
  854. if ( (PHYSFS_setWriteDir(userdir)) &&
  855. (PHYSFS_mkdir(str)) )
  856. {
  857. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  858. if (!PHYSFS_setWriteDir(str))
  859. no_write = 1;
  860. } /* if */
  861. else
  862. {
  863. no_write = 1;
  864. } /* else */
  865. if (no_write)
  866. {
  867. PHYSFS_setWriteDir(NULL); /* just in case. */
  868. allocator.Free(str);
  869. BAIL_MACRO(ERR_CANT_SET_WRITE_DIR, 0);
  870. } /* if */
  871. } /* if */
  872. /* Put write dir first in search path... */
  873. PHYSFS_addToSearchPath(str, 0);
  874. allocator.Free(str);
  875. /* Put base path on search path... */
  876. PHYSFS_addToSearchPath(basedir, 1);
  877. /* handle CD-ROMs... */
  878. if (includeCdRoms)
  879. {
  880. char **cds = PHYSFS_getCdRomDirs();
  881. char **i;
  882. for (i = cds; *i != NULL; i++)
  883. PHYSFS_addToSearchPath(*i, 1);
  884. PHYSFS_freeList(cds);
  885. } /* if */
  886. /* Root out archives, and add them to search path... */
  887. if (archiveExt != NULL)
  888. {
  889. char **rc = PHYSFS_enumerateFiles("/");
  890. char **i;
  891. size_t extlen = strlen(archiveExt);
  892. char *ext;
  893. for (i = rc; *i != NULL; i++)
  894. {
  895. size_t l = strlen(*i);
  896. if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
  897. {
  898. ext = (*i) + (l - extlen);
  899. if (__PHYSFS_stricmpASCII(ext, archiveExt) == 0)
  900. {
  901. const char *d = PHYSFS_getRealDir(*i);
  902. size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
  903. str = (char *) allocator.Malloc(allocsize);
  904. if (str != NULL)
  905. {
  906. sprintf(str, "%s%s%s", d, dirsep, *i);
  907. PHYSFS_addToSearchPath(str, archivesFirst == 0);
  908. allocator.Free(str);
  909. } /* if */
  910. } /* if */
  911. } /* if */
  912. } /* for */
  913. PHYSFS_freeList(rc);
  914. } /* if */
  915. return(1);
  916. } /* PHYSFS_setSaneConfig */
  917. void PHYSFS_permitSymbolicLinks(int allow)
  918. {
  919. allowSymLinks = allow;
  920. } /* PHYSFS_permitSymbolicLinks */
  921. /* string manipulation in C makes my ass itch. */
  922. char *__PHYSFS_convertToDependent(const char *prepend,
  923. const char *dirName,
  924. const char *append)
  925. {
  926. const char *dirsep = __PHYSFS_platformDirSeparator;
  927. size_t sepsize = strlen(dirsep);
  928. char *str;
  929. char *i1;
  930. char *i2;
  931. size_t allocSize;
  932. while (*dirName == '/') /* !!! FIXME: pass through sanitize function. */
  933. dirName++;
  934. allocSize = strlen(dirName) + 1;
  935. if (prepend != NULL)
  936. allocSize += strlen(prepend) + sepsize;
  937. if (append != NULL)
  938. allocSize += strlen(append) + sepsize;
  939. /* make sure there's enough space if the dir separator is bigger. */
  940. if (sepsize > 1)
  941. {
  942. str = (char *) dirName;
  943. do
  944. {
  945. str = strchr(str, '/');
  946. if (str != NULL)
  947. {
  948. allocSize += (sepsize - 1);
  949. str++;
  950. } /* if */
  951. } while (str != NULL);
  952. } /* if */
  953. str = (char *) allocator.Malloc(allocSize);
  954. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, NULL);
  955. if (prepend == NULL)
  956. *str = '\0';
  957. else
  958. {
  959. strcpy(str, prepend);
  960. strcat(str, dirsep);
  961. } /* else */
  962. for (i1 = (char *) dirName, i2 = str + strlen(str); *i1; i1++, i2++)
  963. {
  964. if (*i1 == '/')
  965. {
  966. strcpy(i2, dirsep);
  967. i2 += sepsize;
  968. } /* if */
  969. else
  970. {
  971. *i2 = *i1;
  972. } /* else */
  973. } /* for */
  974. *i2 = '\0';
  975. if (append)
  976. {
  977. strcat(str, dirsep);
  978. strcat(str, append);
  979. } /* if */
  980. return(str);
  981. } /* __PHYSFS_convertToDependent */
  982. /*
  983. * Verify that (fname) (in platform-independent notation), in relation
  984. * to (h) is secure. That means that each element of fname is checked
  985. * for symlinks (if they aren't permitted). This also allows for quick
  986. * rejection of files that exist outside an archive's mountpoint.
  987. *
  988. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  989. * at a time), you should always pass zero for "allowMissing" for efficiency.
  990. *
  991. * (fname) must point to an output from sanitizePlatformIndependentPath(),
  992. * since it will make sure that path names are in the right format for
  993. * passing certain checks. It will also do checks for "insecure" pathnames
  994. * like ".." which should be done once instead of once per archive. This also
  995. * gives us license to treat (fname) as scratch space in this function.
  996. *
  997. * Returns non-zero if string is safe, zero if there's a security issue.
  998. * PHYSFS_getLastError() will specify what was wrong. (*fname) will be
  999. * updated to point past any mount point elements so it is prepared to
  1000. * be used with the archiver directly.
  1001. */
  1002. static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
  1003. {
  1004. char *fname = *_fname;
  1005. int retval = 1;
  1006. char *start;
  1007. char *end;
  1008. if (*fname == '\0') /* quick rejection. */
  1009. return(1);
  1010. /* !!! FIXME: This codeblock sucks. */
  1011. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  1012. {
  1013. size_t mntpntlen = strlen(h->mountPoint);
  1014. size_t len = strlen(fname);
  1015. assert(mntpntlen > 1); /* root mount points should be NULL. */
  1016. /* not under the mountpoint, so skip this archive. */
  1017. BAIL_IF_MACRO(len < mntpntlen-1, ERR_NO_SUCH_PATH, 0);
  1018. /* !!! FIXME: Case insensitive? */
  1019. retval = strncmp(h->mountPoint, fname, mntpntlen-1);
  1020. BAIL_IF_MACRO(retval != 0, ERR_NO_SUCH_PATH, 0);
  1021. if (len > mntpntlen-1) /* corner case... */
  1022. BAIL_IF_MACRO(fname[mntpntlen-1] != '/', ERR_NO_SUCH_PATH, 0);
  1023. fname += mntpntlen-1; /* move to start of actual archive path. */
  1024. if (*fname == '/')
  1025. fname++;
  1026. *_fname = fname; /* skip mountpoint for later use. */
  1027. retval = 1; /* may be reset, below. */
  1028. } /* if */
  1029. start = fname;
  1030. if (!allowSymLinks)
  1031. {
  1032. while (1)
  1033. {
  1034. int rc = 0;
  1035. end = strchr(start, '/');
  1036. if (end != NULL) *end = '\0';
  1037. rc = h->funcs->isSymLink(h->opaque, fname, &retval);
  1038. if (end != NULL) *end = '/';
  1039. BAIL_IF_MACRO(rc, ERR_SYMLINK_DISALLOWED, 0); /* insecure. */
  1040. /* break out early if path element is missing. */
  1041. if (!retval)
  1042. {
  1043. /*
  1044. * We need to clear it if it's the last element of the path,
  1045. * since this might be a non-existant file we're opening
  1046. * for writing...
  1047. */
  1048. if ((end == NULL) || (allowMissing))
  1049. retval = 1;
  1050. break;
  1051. } /* if */
  1052. if (end == NULL)
  1053. break;
  1054. start = end + 1;
  1055. } /* while */
  1056. } /* if */
  1057. return(retval);
  1058. } /* verifyPath */
  1059. int PHYSFS_mkdir(const char *_dname)
  1060. {
  1061. DirHandle *h;
  1062. char *start;
  1063. char *end;
  1064. int retval = 0;
  1065. int exists = 1; /* force existance check on first path element. */
  1066. char *dname;
  1067. dname = ((_dname) ? (char *) alloca(strlen(_dname) + 1) : NULL);
  1068. BAIL_IF_MACRO(dname == NULL, ERR_INVALID_ARGUMENT, 0);
  1069. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_dname, dname), NULL, 0);
  1070. __PHYSFS_platformGrabMutex(stateLock);
  1071. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1072. h = writeDir;
  1073. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &dname, 1), NULL, stateLock, 0);
  1074. start = dname;
  1075. while (1)
  1076. {
  1077. end = strchr(start, '/');
  1078. if (end != NULL)
  1079. *end = '\0';
  1080. /* only check for existance if all parent dirs existed, too... */
  1081. if (exists)
  1082. retval = h->funcs->isDirectory(h->opaque, dname, &exists);
  1083. if (!exists)
  1084. retval = h->funcs->mkdir(h->opaque, dname);
  1085. if (!retval)
  1086. break;
  1087. if (end == NULL)
  1088. break;
  1089. *end = '/';
  1090. start = end + 1;
  1091. } /* while */
  1092. __PHYSFS_platformReleaseMutex(stateLock);
  1093. return(retval);
  1094. } /* PHYSFS_mkdir */
  1095. int PHYSFS_delete(const char *_fname)
  1096. {
  1097. int retval;
  1098. DirHandle *h;
  1099. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1100. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1101. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1102. __PHYSFS_platformGrabMutex(stateLock);
  1103. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1104. h = writeDir;
  1105. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, 0);
  1106. retval = h->funcs->remove(h->opaque, fname);
  1107. __PHYSFS_platformReleaseMutex(stateLock);
  1108. return(retval);
  1109. } /* PHYSFS_delete */
  1110. const char *PHYSFS_getRealDir(const char *_fname)
  1111. {
  1112. DirHandle *i;
  1113. const char *retval = NULL;
  1114. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1115. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1116. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, NULL);
  1117. __PHYSFS_platformGrabMutex(stateLock);
  1118. for (i = searchPath; ((i != NULL) && (retval == NULL)); i = i->next)
  1119. {
  1120. char *arcfname = fname;
  1121. if (partOfMountPoint(i, arcfname))
  1122. retval = i->dirName;
  1123. else if (verifyPath(i, &arcfname, 0))
  1124. {
  1125. if (i->funcs->exists(i->opaque, arcfname))
  1126. retval = i->dirName;
  1127. } /* if */
  1128. } /* for */
  1129. __PHYSFS_platformReleaseMutex(stateLock);
  1130. return(retval);
  1131. } /* PHYSFS_getRealDir */
  1132. static int locateInStringList(const char *str,
  1133. char **list,
  1134. PHYSFS_uint32 *pos)
  1135. {
  1136. PHYSFS_uint32 len = *pos;
  1137. PHYSFS_uint32 half_len;
  1138. PHYSFS_uint32 lo = 0;
  1139. PHYSFS_uint32 middle;
  1140. int cmp;
  1141. while (len > 0)
  1142. {
  1143. half_len = len >> 1;
  1144. middle = lo + half_len;
  1145. cmp = strcmp(list[middle], str);
  1146. if (cmp == 0) /* it's in the list already. */
  1147. return(1);
  1148. else if (cmp > 0)
  1149. len = half_len;
  1150. else
  1151. {
  1152. lo = middle + 1;
  1153. len -= half_len + 1;
  1154. } /* else */
  1155. } /* while */
  1156. *pos = lo;
  1157. return(0);
  1158. } /* locateInStringList */
  1159. static void enumFilesCallback(void *data, const char *origdir, const char *str)
  1160. {
  1161. PHYSFS_uint32 pos;
  1162. void *ptr;
  1163. char *newstr;
  1164. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1165. /*
  1166. * See if file is in the list already, and if not, insert it in there
  1167. * alphabetically...
  1168. */
  1169. pos = pecd->size;
  1170. if (locateInStringList(str, pecd->list, &pos))
  1171. return; /* already in the list. */
  1172. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1173. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1174. if (ptr != NULL)
  1175. pecd->list = (char **) ptr;
  1176. if ((ptr == NULL) || (newstr == NULL))
  1177. return; /* better luck next time. */
  1178. strcpy(newstr, str);
  1179. if (pos != pecd->size)
  1180. {
  1181. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1182. sizeof (char *) * ((pecd->size) - pos));
  1183. } /* if */
  1184. pecd->list[pos] = newstr;
  1185. pecd->size++;
  1186. } /* enumFilesCallback */
  1187. char **PHYSFS_enumerateFiles(const char *path)
  1188. {
  1189. EnumStringListCallbackData ecd;
  1190. memset(&ecd, '\0', sizeof (ecd));
  1191. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1192. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  1193. PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
  1194. ecd.list[ecd.size] = NULL;
  1195. return(ecd.list);
  1196. } /* PHYSFS_enumerateFiles */
  1197. /*
  1198. * Broke out to seperate function so we can use alloca() gratuitously.
  1199. */
  1200. static void enumerateFromMountPoint(DirHandle *i, const char *arcfname,
  1201. PHYSFS_EnumFilesCallback callback,
  1202. const char *_fname, void *data)
  1203. {
  1204. size_t len = strlen(arcfname);
  1205. char *ptr = NULL;
  1206. char *end = NULL;
  1207. char *mountPoint = (char *) alloca(strlen(i->mountPoint) + 1);
  1208. strcpy(mountPoint, i->mountPoint);
  1209. ptr = mountPoint + ((len) ? len + 1 : 0);
  1210. end = strchr(ptr, '/');
  1211. assert(end); /* should always find a terminating '/'. */
  1212. *end = '\0';
  1213. callback(data, _fname, ptr);
  1214. } /* enumerateFromMountPoint */
  1215. void PHYSFS_enumerateFilesCallback(const char *_fname,
  1216. PHYSFS_EnumFilesCallback callback,
  1217. void *data)
  1218. {
  1219. DirHandle *i;
  1220. int noSyms;
  1221. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1222. if ((fname == NULL) || (callback == NULL))
  1223. return; /* oh well. */
  1224. if (!sanitizePlatformIndependentPath(_fname, fname))
  1225. return;
  1226. __PHYSFS_platformGrabMutex(stateLock);
  1227. noSyms = !allowSymLinks;
  1228. for (i = searchPath; i != NULL; i = i->next)
  1229. {
  1230. char *arcfname = fname;
  1231. if (partOfMountPoint(i, arcfname))
  1232. enumerateFromMountPoint(i, arcfname, callback, _fname, data);
  1233. else if (verifyPath(i, &arcfname, 0))
  1234. {
  1235. i->funcs->enumerateFiles(i->opaque, arcfname, noSyms,
  1236. callback, _fname, data);
  1237. } /* else if */
  1238. } /* for */
  1239. __PHYSFS_platformReleaseMutex(stateLock);
  1240. } /* PHYSFS_enumerateFilesCallback */
  1241. int PHYSFS_exists(const char *fname)
  1242. {
  1243. return(PHYSFS_getRealDir(fname) != NULL);
  1244. } /* PHYSFS_exists */
  1245. PHYSFS_sint64 PHYSFS_getLastModTime(const char *_fname)
  1246. {
  1247. DirHandle *i;
  1248. PHYSFS_sint64 retval = -1;
  1249. int fileExists = 0;
  1250. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1251. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1252. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1253. if (*fname == '\0') /* eh...punt if it's the root dir. */
  1254. return(1); /* !!! FIXME: Maybe this should be an error? */
  1255. __PHYSFS_platformGrabMutex(stateLock);
  1256. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1257. {
  1258. char *arcfname = fname;
  1259. fileExists = partOfMountPoint(i, arcfname);
  1260. if (fileExists)
  1261. retval = 1; /* !!! FIXME: What's the right value? */
  1262. else if (verifyPath(i, &arcfname, 0))
  1263. retval = i->funcs->getLastModTime(i->opaque,arcfname,&fileExists);
  1264. } /* for */
  1265. __PHYSFS_platformReleaseMutex(stateLock);
  1266. return(retval);
  1267. } /* PHYSFS_getLastModTime */
  1268. int PHYSFS_isDirectory(const char *_fname)
  1269. {
  1270. DirHandle *i;
  1271. int retval = 0;
  1272. int fileExists = 0;
  1273. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1274. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1275. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1276. BAIL_IF_MACRO(*fname == '\0', NULL, 1); /* Root is always a dir. :) */
  1277. __PHYSFS_platformGrabMutex(stateLock);
  1278. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1279. {
  1280. char *arcfname = fname;
  1281. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1282. retval = 1;
  1283. else if (verifyPath(i, &arcfname, 0))
  1284. retval = i->funcs->isDirectory(i->opaque, arcfname, &fileExists);
  1285. } /* for */
  1286. __PHYSFS_platformReleaseMutex(stateLock);
  1287. return(retval);
  1288. } /* PHYSFS_isDirectory */
  1289. int PHYSFS_isSymbolicLink(const char *_fname)
  1290. {
  1291. DirHandle *i;
  1292. int retval = 0;
  1293. int fileExists = 0;
  1294. char *fname;
  1295. BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
  1296. fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1297. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1298. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1299. BAIL_IF_MACRO(*fname == '\0', NULL, 0); /* Root is never a symlink */
  1300. __PHYSFS_platformGrabMutex(stateLock);
  1301. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1302. {
  1303. char *arcfname = fname;
  1304. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1305. retval = 0; /* virtual dir...not a symlink. */
  1306. else if (verifyPath(i, &arcfname, 0))
  1307. retval = i->funcs->isSymLink(i->opaque, arcfname, &fileExists);
  1308. } /* for */
  1309. __PHYSFS_platformReleaseMutex(stateLock);
  1310. return(retval);
  1311. } /* PHYSFS_isSymbolicLink */
  1312. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  1313. {
  1314. void *opaque = NULL;
  1315. FileHandle *fh = NULL;
  1316. DirHandle *h = NULL;
  1317. const PHYSFS_Archiver *f;
  1318. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1319. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1320. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1321. __PHYSFS_platformGrabMutex(stateLock);
  1322. BAIL_IF_MACRO_MUTEX(!writeDir, ERR_NO_WRITE_DIR, stateLock, NULL);
  1323. h = writeDir;
  1324. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, NULL);
  1325. f = h->funcs;
  1326. if (appending)
  1327. opaque = f->openAppend(h->opaque, fname);
  1328. else
  1329. opaque = f->openWrite(h->opaque, fname);
  1330. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1331. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1332. if (fh == NULL)
  1333. {
  1334. f->fileClose(opaque);
  1335. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1336. } /* if */
  1337. else
  1338. {
  1339. memset(fh, '\0', sizeof (FileHandle));
  1340. fh->opaque = opaque;
  1341. fh->dirHandle = h;
  1342. fh->funcs = h->funcs;
  1343. fh->next = openWriteList;
  1344. openWriteList = fh;
  1345. } /* else */
  1346. __PHYSFS_platformReleaseMutex(stateLock);
  1347. return((PHYSFS_File *) fh);
  1348. } /* doOpenWrite */
  1349. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1350. {
  1351. return(doOpenWrite(filename, 0));
  1352. } /* PHYSFS_openWrite */
  1353. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1354. {
  1355. return(doOpenWrite(filename, 1));
  1356. } /* PHYSFS_openAppend */
  1357. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  1358. {
  1359. FileHandle *fh = NULL;
  1360. int fileExists = 0;
  1361. DirHandle *i = NULL;
  1362. fvoid *opaque = NULL;
  1363. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1364. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1365. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1366. __PHYSFS_platformGrabMutex(stateLock);
  1367. BAIL_IF_MACRO_MUTEX(!searchPath, ERR_NO_SUCH_PATH, stateLock, NULL);
  1368. /* !!! FIXME: Why aren't we using a for loop here? */
  1369. i = searchPath;
  1370. do
  1371. {
  1372. char *arcfname = fname;
  1373. if (verifyPath(i, &arcfname, 0))
  1374. {
  1375. opaque = i->funcs->openRead(i->opaque, arcfname, &fileExists);
  1376. if (opaque)
  1377. break;
  1378. } /* if */
  1379. i = i->next;
  1380. } while ((i != NULL) && (!fileExists));
  1381. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1382. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1383. if (fh == NULL)
  1384. {
  1385. i->funcs->fileClose(opaque);
  1386. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1387. } /* if */
  1388. memset(fh, '\0', sizeof (FileHandle));
  1389. fh->opaque = opaque;
  1390. fh->forReading = 1;
  1391. fh->dirHandle = i;
  1392. fh->funcs = i->funcs;
  1393. fh->next = openReadList;
  1394. openReadList = fh;
  1395. __PHYSFS_platformReleaseMutex(stateLock);
  1396. return((PHYSFS_File *) fh);
  1397. } /* PHYSFS_openRead */
  1398. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  1399. {
  1400. FileHandle *prev = NULL;
  1401. FileHandle *i;
  1402. int rc = 1;
  1403. for (i = *list; i != NULL; i = i->next)
  1404. {
  1405. if (i == handle) /* handle is in this list? */
  1406. {
  1407. PHYSFS_uint8 *tmp = handle->buffer;
  1408. rc = PHYSFS_flush((PHYSFS_File *) handle);
  1409. if (rc)
  1410. rc = handle->funcs->fileClose(handle->opaque);
  1411. if (!rc)
  1412. return(-1);
  1413. if (tmp != NULL) /* free any associated buffer. */
  1414. allocator.Free(tmp);
  1415. if (prev == NULL)
  1416. *list = handle->next;
  1417. else
  1418. prev->next = handle->next;
  1419. allocator.Free(handle);
  1420. return(1);
  1421. } /* if */
  1422. prev = i;
  1423. } /* for */
  1424. return(0);
  1425. } /* closeHandleInOpenList */
  1426. int PHYSFS_close(PHYSFS_File *_handle)
  1427. {
  1428. FileHandle *handle = (FileHandle *) _handle;
  1429. int rc;
  1430. __PHYSFS_platformGrabMutex(stateLock);
  1431. /* -1 == close failure. 0 == not found. 1 == success. */
  1432. rc = closeHandleInOpenList(&openReadList, handle);
  1433. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1434. if (!rc)
  1435. {
  1436. rc = closeHandleInOpenList(&openWriteList, handle);
  1437. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1438. } /* if */
  1439. __PHYSFS_platformReleaseMutex(stateLock);
  1440. BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
  1441. return(1);
  1442. } /* PHYSFS_close */
  1443. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
  1444. PHYSFS_uint32 objSize,
  1445. PHYSFS_uint32 objCount)
  1446. {
  1447. PHYSFS_sint64 retval = 0;
  1448. PHYSFS_uint32 remainder = 0;
  1449. while (objCount > 0)
  1450. {
  1451. PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
  1452. PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
  1453. PHYSFS_uint32 copied;
  1454. if (buffered == 0) /* need to refill buffer? */
  1455. {
  1456. PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
  1457. 1, fh->bufsize);
  1458. if (rc <= 0)
  1459. {
  1460. fh->bufpos -= remainder;
  1461. return(((rc == -1) && (retval == 0)) ? -1 : retval);
  1462. } /* if */
  1463. buffered = fh->buffill = (PHYSFS_uint32) rc;
  1464. fh->bufpos = 0;
  1465. } /* if */
  1466. if (buffered > mustread)
  1467. buffered = (PHYSFS_uint32) mustread;
  1468. memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
  1469. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  1470. fh->bufpos += buffered;
  1471. buffered += remainder; /* take remainder into account. */
  1472. copied = (buffered / objSize);
  1473. remainder = (buffered % objSize);
  1474. retval += copied;
  1475. objCount -= copied;
  1476. } /* while */
  1477. return(retval);
  1478. } /* doBufferedRead */
  1479. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  1480. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1481. {
  1482. FileHandle *fh = (FileHandle *) handle;
  1483. BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
  1484. if (fh->buffer != NULL)
  1485. return(doBufferedRead(fh, buffer, objSize, objCount));
  1486. return(fh->funcs->read(fh->opaque, buffer, objSize, objCount));
  1487. } /* PHYSFS_read */
  1488. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  1489. PHYSFS_uint32 objSize,
  1490. PHYSFS_uint32 objCount)
  1491. {
  1492. FileHandle *fh = (FileHandle *) handle;
  1493. /* whole thing fits in the buffer? */
  1494. if (fh->buffill + (objSize * objCount) < fh->bufsize)
  1495. {
  1496. memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
  1497. fh->buffill += (objSize * objCount);
  1498. return(objCount);
  1499. } /* if */
  1500. /* would overflow buffer. Flush and then write the new objects, too. */
  1501. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
  1502. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1503. } /* doBufferedWrite */
  1504. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  1505. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1506. {
  1507. FileHandle *fh = (FileHandle *) handle;
  1508. BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
  1509. if (fh->buffer != NULL)
  1510. return(doBufferedWrite(handle, buffer, objSize, objCount));
  1511. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1512. } /* PHYSFS_write */
  1513. int PHYSFS_eof(PHYSFS_File *handle)
  1514. {
  1515. FileHandle *fh = (FileHandle *) handle;
  1516. if (!fh->forReading) /* never EOF on files opened for write/append. */
  1517. return(0);
  1518. /* eof if buffer is empty and archiver says so. */
  1519. return((fh->bufpos == fh->buffill) && (fh->funcs->eof(fh->opaque)));
  1520. } /* PHYSFS_eof */
  1521. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  1522. {
  1523. FileHandle *fh = (FileHandle *) handle;
  1524. PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
  1525. PHYSFS_sint64 retval = fh->forReading ?
  1526. (pos - fh->buffill) + fh->bufpos :
  1527. (pos + fh->buffill);
  1528. return(retval);
  1529. } /* PHYSFS_tell */
  1530. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  1531. {
  1532. FileHandle *fh = (FileHandle *) handle;
  1533. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1534. if (fh->buffer && fh->forReading)
  1535. {
  1536. /* avoid throwing away our precious buffer if seeking within it. */
  1537. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  1538. if ( /* seeking within the already-buffered range? */
  1539. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  1540. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  1541. {
  1542. fh->bufpos += (PHYSFS_uint32) offset;
  1543. return(1); /* successful seek */
  1544. } /* if */
  1545. } /* if */
  1546. /* we have to fall back to a 'raw' seek. */
  1547. fh->buffill = fh->bufpos = 0;
  1548. return(fh->funcs->seek(fh->opaque, pos));
  1549. } /* PHYSFS_seek */
  1550. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  1551. {
  1552. FileHandle *fh = (FileHandle *) handle;
  1553. return(fh->funcs->fileLength(fh->opaque));
  1554. } /* PHYSFS_filelength */
  1555. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  1556. {
  1557. FileHandle *fh = (FileHandle *) handle;
  1558. PHYSFS_uint32 bufsize;
  1559. /* !!! FIXME: Unlocalized string. */
  1560. BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
  1561. bufsize = (PHYSFS_uint32) _bufsize;
  1562. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1563. /*
  1564. * For reads, we need to move the file pointer to where it would be
  1565. * if we weren't buffering, so that the next read will get the
  1566. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  1567. */
  1568. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  1569. {
  1570. PHYSFS_uint64 pos;
  1571. PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
  1572. BAIL_IF_MACRO(curpos == -1, NULL, 0);
  1573. pos = ((curpos - fh->buffill) + fh->bufpos);
  1574. BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
  1575. } /* if */
  1576. if (bufsize == 0) /* delete existing buffer. */
  1577. {
  1578. if (fh->buffer != NULL)
  1579. {
  1580. allocator.Free(fh->buffer);
  1581. fh->buffer = NULL;
  1582. } /* if */
  1583. } /* if */
  1584. else
  1585. {
  1586. PHYSFS_uint8 *newbuf;
  1587. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  1588. BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
  1589. fh->buffer = newbuf;
  1590. } /* else */
  1591. fh->bufsize = bufsize;
  1592. fh->buffill = fh->bufpos = 0;
  1593. return(1);
  1594. } /* PHYSFS_setBuffer */
  1595. int PHYSFS_flush(PHYSFS_File *handle)
  1596. {
  1597. FileHandle *fh = (FileHandle *) handle;
  1598. PHYSFS_sint64 rc;
  1599. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  1600. return(1); /* open for read or buffer empty are successful no-ops. */
  1601. /* dump buffer to disk. */
  1602. rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
  1603. fh->buffill - fh->bufpos, 1);
  1604. BAIL_IF_MACRO(rc <= 0, NULL, 0);
  1605. fh->bufpos = fh->buffill = 0;
  1606. return(1);
  1607. } /* PHYSFS_flush */
  1608. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  1609. {
  1610. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  1611. externalAllocator = (a != NULL);
  1612. if (externalAllocator)
  1613. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  1614. return(1);
  1615. } /* PHYSFS_setAllocator */
  1616. static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
  1617. {
  1618. BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
  1619. #undef malloc
  1620. return(malloc((size_t) s));
  1621. } /* mallocAllocatorMalloc */
  1622. static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
  1623. {
  1624. BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
  1625. #undef realloc
  1626. return(realloc(ptr, (size_t) s));
  1627. } /* mallocAllocatorRealloc */
  1628. static void mallocAllocatorFree(void *ptr)
  1629. {
  1630. #undef free
  1631. free(ptr);
  1632. } /* mallocAllocatorFree */
  1633. static void setDefaultAllocator(void)
  1634. {
  1635. assert(!externalAllocator);
  1636. if (!__PHYSFS_platformSetDefaultAllocator(&allocator))
  1637. {
  1638. allocator.Init = NULL;
  1639. allocator.Deinit = NULL;
  1640. allocator.Malloc = mallocAllocatorMalloc;
  1641. allocator.Realloc = mallocAllocatorRealloc;
  1642. allocator.Free = mallocAllocatorFree;
  1643. } /* if */
  1644. } /* setDefaultAllocator */
  1645. /* end of physfs.c ... */